Prune the source tree to the Release 2 build closure

Keep only what the Release 2 scope (46 targets) compiles and the build
pipeline needs, derived from the run-5 build.ninja closure (46 targets +
transitive deps) and a header scan resolved against the real -I roots of
the compile rules:

- 14133 tracked files removed (1.25 GB), incl. include/ArcGIS (1.03 GB),
  include/rti stubs (identical copies of the external RTI headers),
  out-of-scope Lts/Application, Lts/Viewer, Lts/Services/*, Lts/Tools
  generators, src/, tests/, specs/, translations/, external/
- kept: the 46 scope modules + their transitive service deps, codegen
  inputs (.xml, .grantlee), doxygen/ (configure_file at configure time),
  include/GeographicLib (libGeographicLib.so linked from the source tree),
  the 12 referenced include/ stub headers, pipeline files
  (new_docker_build_release2.sh, rpmbuild/, jenkins-ci-rme/, cmake/)
- 7 CMakeLists updated: drop add_subdirectory calls of the removed dirs
  (tests, translations, Lts/Plugins/ProjectDataManagement, qav, scripts,
  CommonUnitTestsPlaceholder, httq, LtsRestClient, LtsWebSocket,
  TopicEditorBase, ConnectDialog, StyleManager, Routing, DdsUnitTests,
  DdsUnitTestsPlaceholder, Light, Dark, Test, ExerciseManagement,
  ParticipantManagement, the 3 tools generators)

Result: 2157 tracked files (was 16290).
This commit is contained in:
berrux-dev committed 2026-11-13 23:33:32 +01:00
1 parent 2b1c3dc241
commit 7fc6f66649
14140 files changed
+8 -2803418

No files matched your search

@@ -4,11 +4,8 @@
# $Author$
#
# Release 2 Common modules (S set: 16 modules)
# Mock library for unit tests (CoordTrans mocks)
ADD_SUBDIRECTORY(CommonUnitTestsPlaceholder)
# Release 2 Common modules (S set: 15 modules)
ADD_SUBDIRECTORY(CodeGen)
ADD_SUBDIRECTORY(httq)
ADD_SUBDIRECTORY(LtsAppDescriptor)
ADD_SUBDIRECTORY(LtsCommandLineParser)
ADD_SUBDIRECTORY(LtsCoordTrans)
@@ -19,13 +16,10 @@ ADD_SUBDIRECTORY(LtsLicence)
ADD_SUBDIRECTORY(LtsNotification)
ADD_SUBDIRECTORY(LtsPluginManager)
ADD_SUBDIRECTORY(LtsSession)
ADD_SUBDIRECTORY(LtsRestClient)
ADD_SUBDIRECTORY(LtsSerialPortQuerry)
ADD_SUBDIRECTORY(LtsUtils)
ADD_SUBDIRECTORY(LtsWebSocket)
ADD_SUBDIRECTORY(LtsWidgets)
ADD_SUBDIRECTORY(ProjectConfig)
ADD_SUBDIRECTORY(TopicEditorBase)
# LtsMultiMonitor and PluginInterfaces required by LtsSession for Release 2a
ADD_SUBDIRECTORY(LtsMultiMonitor)
ADD_SUBDIRECTORY(PluginInterfaces)
@@ -1,34 +0,0 @@
cmake_minimum_required(VERSION 3.16)
project(CommonUnitTestsPlaceholder)
include(FetchContent)
option(BUILD_SMOKE_TESTS "Build QtTest smoke tests" OFF)
option(BUILD_GTEST_SMOKE "Build GTest smoke tests" OFF)
add_subdirectory(mocks)
if(BUILD_SMOKE_TESTS)
if(NOT TARGET Qt6::Test)
find_package(Qt6 REQUIRED COMPONENTS Test)
endif()
add_executable(coordTransTests_smoke coordTransTests_smoke.cpp)
target_link_libraries(coordTransTests_smoke PRIVATE Qt6::Test MockCoordTrans::MockCoordTrans)
add_test(NAME coordTransTests_smoke COMMAND coordTransTests_smoke)
endif()
if(BUILD_GTEST_SMOKE)
find_package(GTest QUIET)
if(NOT GTest_FOUND)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.12.1
)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
endif()
add_executable(coordTransTests_gtest coordTransTests_gtest.cpp)
target_link_libraries(coordTransTests_gtest PRIVATE GTest::gtest_main MockCoordTrans::MockCoordTrans)
add_test(NAME coordTransTests_gtest COMMAND coordTransTests_gtest)
endif()
@@ -1,11 +0,0 @@
// Stub GTest smoke test for coordTrans
#include <gtest/gtest.h>
TEST(CoordTransSmokeTest, StubTest) {
EXPECT_TRUE(true);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -1,14 +0,0 @@
// Stub QtTest smoke test for coordTrans
#include <QTest>
class CoordTransSmokeTest : public QObject
{
Q_OBJECT
private slots:
void stubTest() {
QVERIFY(true);
}
};
QTEST_APPLESS_MAIN(CoordTransSmokeTest)
@@ -1,5 +0,0 @@
add_library(MockCoordTrans STATIC MockCoordTrans.h)
target_include_directories(MockCoordTrans PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
# Export header-only semantics by providing an interface target
add_library(MockCoordTrans::MockCoordTrans ALIAS MockCoordTrans)
@@ -1,19 +0,0 @@
// MockCoordTrans.h - Stub mock for CoordTrans functionality
// This is a placeholder to allow builds without full CoordTrans implementation
#ifndef MOCK_COORD_TRANS_H
#define MOCK_COORD_TRANS_H
#include <QtCore/QString>
#include <QtCore/QPointF>
// Minimal stub to satisfy linker requirements
namespace LtsCoordTrans {
// Placeholder types
struct UtmCoordinate {
static UtmCoordinate fromMgrs(const QString&) { return UtmCoordinate(); }
QPointF geographic() const { return QPointF(); }
};
}
#endif // MOCK_COORD_TRANS_H
@@ -1,32 +0,0 @@
#include "app.h"
#include "AppChooser/app_chooser_model.h"
#include "ui_app.h"
namespace LtsAppManager
{
CustomViewApp::CustomViewApp(QWidget* parent) : AbstractDisplayWidget(parent), m_ui(new Ui::CustomViewApp)
{
m_ui->setupUi(this);
m_ui->image->setMenuEnabled(false);
}
CustomViewApp::~CustomViewApp()
{
delete m_ui;
}
bool CustomViewApp::init(const QModelIndex& idx)
{
if (!idx.isValid())
return false;
m_ui->lbAppName->setText(rowData(idx, AppChooserModel::Name).toString());
return true;
}
} // namespace LtsAppManager
@@ -1,28 +0,0 @@
#pragma once
#include <QtCore/QObject>
#include <Viewer/LtsDataView/abstract_display_widget.h>
namespace Ui
{
class CustomViewApp;
}
namespace LtsAppManager
{
class CustomViewApp final : public LtsDataView::AbstractDisplayWidget
{
Q_OBJECT
public:
explicit CustomViewApp(QWidget* parent = nullptr);
~CustomViewApp();
bool init(const QModelIndex& idx) override;
private:
Ui::CustomViewApp* m_ui;
};
} // namespace LtsAppManager
@@ -1,108 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CustomViewApp</class>
<widget class="QWidget" name="CustomViewApp">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>300</width>
<height>150</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string/>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="LtsWidgets::LtsImageEditor" name="image">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>128</width>
<height>128</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>128</width>
<height>128</height>
</size>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="lbAppName">
<property name="text">
<string notr="true">&lt;App Name&gt;</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="lbDescription">
<property name="text">
<string notr="true">&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&amp;lt;Description with wordwrap&amp;gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsWidgets::LtsImageEditor</class>
<extends>QWidget</extends>
<header>LtsWidgets/lts_image_editor.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,80 +0,0 @@
#include "AppChooser/app_chooser.h"
#include "AppChooser/CustomViews/app.h"
#include "AppChooser/app_chooser_model.h"
#include "lts_app_manager.h"
#include "ui_app_chooser.h"
#include <QtGui/QCloseEvent>
#include <QtCore/QDebug>
namespace LtsAppManager
{
AppChooser::AppChooser() : QWidget(nullptr), m_ui(new Ui::AppChooser), m_model(), m_madeSelection(false)
{
m_ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalDoubleClicked, this,
&AppChooser::slotAppSelected);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalEnterPressed, this,
&AppChooser::slotAppSelected);
connect(m_ui->widget, &LtsDataView::LtsDataView::LtsDataView::signalSelectionChanged, this, &AppChooser::enaDisa);
connect(m_ui->pbQuit, &QPushButton::clicked, this, &QWidget::close);
connect(m_ui->pbSelect, &QPushButton::clicked, this, &AppChooser::slotAppSelected);
m_model = new AppChooserModel(this);
m_model->initModel(LtsAppManager::getInstance()->getAvailableApps());
m_ui->widget->seamless();
m_ui->widget->setModel(m_model);
m_ui->widget->hideColumn(AppChooserModel::Columns::Visible);
}
AppChooser::~AppChooser()
{
delete m_ui;
}
void AppChooser::slotQuit()
{
if (m_alreadyCloseEmitted)
return;
m_alreadyCloseEmitted = true;
emit signalLogout();
}
void AppChooser::closeEvent(QCloseEvent*)
{
if (!m_madeSelection)
slotQuit();
}
void AppChooser::slotAppSelected()
{
const QModelIndex idx = m_ui->widget->currentIndex();
const LtsAppDescriptor::AppDescription app = m_model->getRowData(idx.row());
if (!app.active)
return;
hide();
m_madeSelection = true;
emit signalAppSelected(app.id);
close();
}
void AppChooser::enaDisa()
{
const QModelIndexList selectedRows = m_ui->widget->selectedRows();
const int cntSelectedRows = selectedRows.size();
m_ui->pbSelect->setEnabled(cntSelectedRows == 1);
}
} // namespace LtsAppManager
@@ -1,45 +0,0 @@
#pragma once
#include <LtsAppDescriptor/lts_app_descriptor.h>
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace Ui
{
class AppChooser;
}
namespace LtsAppManager
{
class AppChooserModel;
class AppChooser : public QWidget
{
Q_OBJECT
public:
AppChooser();
~AppChooser();
private:
Ui::AppChooser* m_ui;
AppChooserModel* m_model;
bool m_madeSelection;
bool m_alreadyCloseEmitted{false};
void enaDisa();
protected:
void closeEvent(QCloseEvent*);
signals:
void signalAppSelected(LtsAppDescriptor::App appId);
void signalLogout();
private slots:
void slotAppSelected();
void slotQuit();
};
} // namespace LtsAppManager
@@ -1,92 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AppChooser</class>
<widget class="QWidget" name="AppChooser">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>400</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="windowTitle">
<string>App Chooser</string>
</property>
<property name="windowIcon">
<iconset resource="../../LtsWidgets/resources/lts_resources.qrc">
<normaloff>:/rde_icon_256.png</normaloff>:/rde_icon_256.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Select App:</string>
</property>
</widget>
</item>
<item>
<widget class="LtsDataView::LtsDataView" name="widget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="pbQuit">
<property name="text">
<string>Quit</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pbSelect">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Select</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsDataView::LtsDataView</class>
<extends>QWidget</extends>
<header location="global">Viewer/LtsDataView/lts_data_view.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources>
<include location="../../LtsWidgets/resources/lts_resources.qrc"/>
</resources>
<connections/>
</ui>
@@ -1,48 +0,0 @@
#include "app_chooser_model.h"
#include <LtsSession/lts_session.h>
namespace LtsAppManager
{
AppChooserModel::AppChooserModel(QObject* parent)
: LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription>({tr("Name")}, parent)
{
}
bool AppChooserModel::initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps)
{
for (auto i = availableApps.constBegin(); i != availableApps.constEnd(); ++i)
{
const LtsAppDescriptor::AppDescription& appDesc = *i;
if (!appDesc.visible)
continue;
insertRow(appDesc);
}
return true;
}
QVariant AppChooserModel::data(const QModelIndex& index, int role) const
{
if (role != Qt::DisplayRole || !indexIsValid(index))
return QVariant();
const LtsAppDescriptor::AppDescription& ad = m_vecData.at(index.row());
switch (index.column())
{
case Name:
return LtsSession::LtsSession::appToString(ad.id);
case Visible:
return ad.visible;
}
return QVariant();
}
} // namespace LtsAppManager
@@ -1,25 +0,0 @@
#pragma once
#include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsWidgets/lts_abstract_table_model.h>
#include <QtCore/QObject>
namespace LtsAppManager
{
class AppChooserModel final : public LtsWidgets::LtsAbstractTableModel<LtsAppDescriptor::AppDescription>
{
Q_OBJECT
public:
enum Columns {
Name = 0,
Visible,
};
explicit AppChooserModel(QObject* parent = nullptr);
bool initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps);
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final;
};
} // namespace LtsAppManager
@@ -1,71 +0,0 @@
# Make ${Qt6_Gui} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Gui)
set(Qt6_Gui ${Qt6_Gui})
else()
set(Qt6_Gui "")
endif()
# Make ${Qt6_Widgets} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Widgets)
set(Qt6_Widgets ${Qt6_Widgets})
else()
set(Qt6_Widgets "")
endif()
#
# $Id$
# $HeadURL$
# $Author$
# Created by Mike Wille, SLSE, 2016-10-27
#
# LtsAppManager
set(LtsAppManager_SRCS
lts_app_manager.cpp
AppChooser/app_chooser.cpp
AppChooser/app_chooser_model.cpp
AppChooser/CustomViews/app.cpp
)
NGL_WRAP_UI(LtsAppManager_SRCS
AppChooser/app_chooser.ui
AppChooser/CustomViews/app.ui
)
IF(BUILD_RTI)
NGL_ADD_LIBRARY2(WS LtsAppManager SHARED ${LtsAppManager_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsAppManager
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_CURRENT_SOURCE_DIR}/AppChooser/
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(LtsAppManager
PRIVATE
NGLLogger
LtsDataView
LtsWidgets
LtsLogin
LtsPluginManager
LtsSession
LtsSessionData
LtsUtilsSettings
LtsMultiMonitor
ProjectConfig
${Qt6_Gui}
${Qt6_Widgets}
Qt6::Network # debug server
OpmSettingsGuiPluginInterface
LtsPluginLoader
PUBLIC
Qt6::Core
LtsAppDescriptor
)
endif()
NGL_INSTALL_TARGET(LtsAppManager)
ENDIF(BUILD_RTI)
@@ -1,963 +0,0 @@
#include "lts_app_manager.h"
#include "AppChooser/app_chooser.h"
#include <LtsLogin/lts_login.h>
#include <LtsMultiMonitor/lts_multi_monitor.h>
#include <LtsPluginManager/lts_plugin_manager.h>
#include <LtsSession/lts_session.h>
#include <LtsSession/lts_session_data.h>
#include <LtsSession/lts_session_manager.h>
#include <LtsUtilsSettings/settings.h>
#include <LtsWidgets/lts_events.h>
#include <LtsWidgets/lts_global_wait_dialog.h>
#include <OperatorManagement/opm_settings_gui_plugin_interface.h>
#include <PluginInterfaces/gui_plugin_interface.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonValue>
#include <QtWidgets/QMessageBox>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QtCore/QTimer>
#include <QtCore/QUuid>
#include <utility>
#ifndef LTS_VERSION_MAJOR
#define LTS_VERSION_MAJOR "undefined"
#endif
#ifndef LTS_VERSION_MINOR
#define LTS_VERSION_MINOR "undefined"
#endif
#ifndef LTS_VERSION_PATCH
#define LTS_VERSION_PATCH "undefined"
#endif
#ifndef JENKINS_BUILD_NUMBER
#define JENKINS_BUILD_NUMBER "unknown"
#endif
static const char ver_major[] = LTS_VERSION_MAJOR;
static const char ver_minor[] = LTS_VERSION_MINOR;
static const char ver_patch[] = LTS_VERSION_PATCH;
static const char ver_jenkins[] = JENKINS_BUILD_NUMBER;
namespace LtsAppManager
{
struct LtsAppManagerHandler
{
LtsAppManager ltsAppManager;
};
Q_GLOBAL_STATIC(LtsAppManagerHandler, s_ltsAppManager)
LtsAppManager* LtsAppManager::getInstance()
{
return &s_ltsAppManager->ltsAppManager;
}
LtsAppManager::LtsAppManager() : m_login(nullptr)
{
qRegisterMetaType<LtsAppDescriptor::App>("LtsAppDescriptor::App");
slotStartDebugServer();
connect(qApp, &QCoreApplication::aboutToQuit, this, [this] {
delete m_login;
m_login = nullptr;
});
}
LtsAppManager::~LtsAppManager()
{
delete m_login;
m_login = nullptr;
}
void LtsAppManager::setAvailableApps(const LtsAppDescriptor::AppDescriptionVector& availableApps)
{
m_availableApps = availableApps;
#ifndef LTS_DEBUG
if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(
QStringLiteral("PluginManager.CheckAppRequirements")) == QVariant(true))
{
QMessageBox::information(nullptr, QStringLiteral("LtsAppManager"),
QStringLiteral("Checking App Requirements now"));
#else
{
#endif
QStringList errors;
LtsPluginManager::LtsPluginLoader::getInstance()->checkPlugins(availableApps, errors);
if (!errors.isEmpty())
QMessageBox::critical(
nullptr, QStringLiteral("LtsAppManager"),
QStringLiteral("App Requirements check failed!<br> - %1").arg(errors.join(QStringLiteral("<br> - "))));
}
if (m_availableApps.isEmpty())
{
QMessageBox::critical(nullptr, tr("App Manager"),
tr("There are no apps available for this project.\nPlease contact Support."));
abort();
}
}
void LtsAppManager::slotStartDebugServer()
{
QTcpServer* debugServer = new QTcpServer(this);
if (!debugServer->listen(QHostAddress::Any, 20000))
{
debugServer->deleteLater();
const int waitTryAgain = 5;
#ifdef LTS_DEBUG
#endif
QTimer::singleShot(waitTryAgain * 1000, this, &LtsAppManager::slotStartDebugServer);
return;
}
connect(debugServer, &QTcpServer::newConnection, this, [this]() {
QTcpServer* server = qobject_cast<QTcpServer*>(sender());
if (server == nullptr)
return;
QTcpSocket* client = server->nextPendingConnection();
if (client == nullptr)
return;
connect(client, &QTcpSocket::readyRead, this, [this]() {
QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());
if (client == nullptr)
return;
QString commandStr(
QString::fromUtf8(client->readLine(100)).remove(QStringLiteral("\r")).remove(QStringLiteral("\n")));
QStringList argList = commandStr.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (argList.count() < 1)
return;
const QString& command = argList.at(0);
LtsSessionData::LtsSessionData* sessionData = LtsSessionData::LtsSessionData::getInstance();
static QStringList commands;
commands << QStringLiteral("showSessions") << QStringLiteral("operator") << QStringLiteral("help")
<< QStringLiteral("logout") << QStringLiteral("flag") << QStringLiteral("setFlag")
<< QStringLiteral("start") << QStringLiteral("voiceCommand") << QStringLiteral("ftcmock");
switch (commands.indexOf(command))
{
case 0: {
sessionData->setDebugFlagValue(QStringLiteral("DeveloperTools.ShowSessionsOnce"), true);
client->write("K");
break;
}
case 1: {
QString operatorName(sessionData->getOperatorName());
if (operatorName.isEmpty())
operatorName = QStringLiteral("(none)");
QString result(QStringLiteral("%1").arg(operatorName));
client->write(result.toUtf8());
break;
}
case 2: {
QString result(QStringLiteral("Available Commands: %1").arg(commands.join(QStringLiteral(", "))));
client->write(result.toUtf8());
break;
}
case 3: {
client->write("...");
slotLogout();
client->write("\r\nK");
break;
}
case 4: {
if (argList.count() != 2)
{
client->write("Usage: flag <flag name>");
break;
}
const QString& debugFlagName = argList.at(1);
if (!sessionData->hasDebugFlag(debugFlagName))
{
client->write("(unknown)");
break;
}
client->write(sessionData->debugFlagValue(argList.at(1)).toString().toUtf8());
break;
}
case 5: {
if (argList.count() < 3)
{
client->write("Usage: setFlag <flag name> <flag type> <value>\r\nFlag types: int, string (no "
"spaces allowed yet), boolean, double");
break;
}
static QStringList flagTypes;
flagTypes << QStringLiteral("int") << QStringLiteral("string") << QStringLiteral("boolean")
<< QStringLiteral("double");
const QString& flagType = argList.at(2);
bool k = false;
const QString& flagName = argList.at(1);
switch (flagTypes.indexOf(flagType))
{
case 0: {
int value = argList.at(3).toInt(&k);
if (k)
sessionData->setDebugFlagValue(flagName, value);
else
client->write("cannot convert value to integer");
break;
}
case 1: {
sessionData->setDebugFlagValue(flagName, argList.at(3));
break;
}
case 2: {
QString value(argList.at(3).toLower().simplified());
if (value == QStringLiteral("true"))
sessionData->setDebugFlagValue(flagName, true);
else if (value == QStringLiteral("false"))
sessionData->setDebugFlagValue(flagName, false);
else
client->write("cannot convert value to boolean");
break;
}
case 3: {
double value = argList.at(3).toDouble(&k);
if (k)
sessionData->setDebugFlagValue(flagName, value);
else
client->write("cannot convert value to double");
break;
}
default: {
client->write("unknown flag type");
break;
}
}
break;
}
case 6: {
if (argList.count() < 3)
{
client->write("Usage: start <app id> <domain id> ");
break;
}
client->write("not implemented yet");
break;
}
case 7: {
if (argList.count() < 2)
{
client->write("Usage: voiceCommand <keyword> <optional description>");
break;
}
static QStringList keywords;
keywords << QStringLiteral("AddMarker") << QStringLiteral("SetMarker")
<< QStringLiteral("AddSnapshot") << QStringLiteral("SaveSnapshot");
const QString& keyword = argList.at(1);
switch (keywords.indexOf(keyword))
{
case 0: {
auto ev = new LtsWidgets::AddMarkerEvent;
ev->setAccepted(false);
sessionData->setDebugFlagValue(command, keyword);
QCoreApplication::postEvent(qApp, ev);
break;
}
case 1: {
auto ev = new LtsWidgets::SetMarkerEvent(QString());
if (argList.size() > 2)
ev->setDescription(argList.at(2));
ev->setAccepted(false);
sessionData->setDebugFlagValue(command, keyword);
QCoreApplication::postEvent(qApp, ev);
break;
}
case 2: {
auto ev = new LtsWidgets::AddSnapshotEvent;
ev->setAccepted(false);
sessionData->setDebugFlagValue(command, keyword);
QCoreApplication::postEvent(qApp, ev);
break;
}
case 3: {
auto ev = new LtsWidgets::SaveSnapshotEvent(QString());
if (argList.size() > 2)
ev->setDescription(argList.at(2));
ev->setAccepted(false);
sessionData->setDebugFlagValue(command, keyword);
QCoreApplication::postEvent(qApp, ev);
break;
}
default:
break;
}
if (!sessionData->hasDebugFlag(command))
{
client->write("(unknown)");
break;
}
client->write(sessionData->debugFlagValue(argList.at(1)).toString().toUtf8());
break;
}
case 8: {
auto usage = [client]() {
client->write("Usage: ftcmock start <sessionId> <min ms> <max ms> <timer count> - See 'Session "
"id' in DevDialog "
"\nftcmock stop <sessionId>");
};
if (argList.count() < 3)
{
usage();
break;
}
bool k = false;
switch (QStringList({QStringLiteral("start"), QStringLiteral("stop")}).indexOf(argList.at(1)))
{
case 0: {
if (argList.count() < 6)
{
usage();
return;
}
const int min = argList.at(3).toInt(&k);
if (!k || min < 0)
{
client->write("min must be a positive integer!");
return;
}
const int max = argList.at(4).toInt(&k);
if (!k || max < 0)
{
client->write("max must be a positive integer!");
return;
}
const int timers = argList.at(5).toInt(&k);
if (!k || timers < 1)
{
client->write("'timer count' must be a positive integer and greater than 0!");
return;
}
break;
}
case 1: {
break;
}
default: {
usage();
return;
}
}
const int sessionId = argList.at(2).toInt(&k);
if (!k || sessionId < 0)
{
client->write("sessionId must be a positive integer!");
return;
}
emit signalCommand(client, argList);
break;
}
default: {
QString result(QStringLiteral("Unknown command '%1'").arg(command));
client->write(result.toUtf8());
break;
}
}
client->write("\r\n> ");
});
QString versionString = QStringLiteral("%1.%2-%3 (rev: %4)")
.arg(QString::fromLatin1(ver_major), QString::fromLatin1(ver_minor),
QString::fromLatin1(ver_jenkins), QString::fromLatin1(ver_patch));
QString motd(QStringLiteral("\r\nOperatorApplication - Version %1").arg(versionString));
client->write(motd.toUtf8());
client->write("\r\n> ");
});
}
void LtsAppManager::showLogin()
{
QTimer::singleShot(0, this, &LtsAppManager::slotShowLogin);
}
void LtsAppManager::slotShowLogin()
{
if (m_login == nullptr)
{
m_login = new LtsLogin::LtsLogin;
connect(m_login, &LtsLogin::LtsLogin::signalLoginDone, this, [&] {
#ifdef LTS_DEBUG
#endif
if (m_appList.isEmpty())
if (!startAppOrLetUserChoose(m_app, {}))
QTimer::singleShot(100, this, &LtsAppManager::slotLogout);
});
connect(m_login, &LtsLogin::LtsLogin::signalLogoffDone, this, &LtsAppManager::signalLogoffDone);
connect(m_login, &LtsLogin::LtsLogin::signalLogoffDone, this, &LtsAppManager::slotShowLogin,
Qt::QueuedConnection);
connect(m_login, &LtsLogin::LtsLogin::signalLogout, this, &LtsAppManager::slotLogout);
m_login->setLoginPlugin(m_loginPluginIid);
}
m_login->login();
}
bool LtsAppManager::hasRightForApp(const LtsAppDescriptor::AppDescription& appDescription) const
{
const QSet<int>& acls = LtsSessionData::LtsSessionData::getInstance()->getOperatorRights();
for (int reqRight : appDescription.requiredAcls)
{
if (!acls.contains(reqRight))
{
QMessageBox::critical(
nullptr, tr("App Manager"),
tr("The minimal required operator rights are not met. Therefore, the app cannot be started."));
return false;
}
}
return true;
}
void LtsAppManager::taskSwitch(QObject* _caller)
{
LtsSession::LtsSession* caller = qobject_cast<LtsSession::LtsSession*>(_caller);
if (caller == nullptr)
{
Q_ASSERT(false);
return;
}
QVector<LtsSession::LtsSession*> sessions;
for (const LtsPluginManager::LtsPluginManager* app : m_appList)
sessions += app->sessions();
if (sessions.isEmpty())
return;
int sessionCount = sessions.count();
if (sessionCount < 2)
return;
auto sessionIt = std::find_if(sessions.begin(), sessions.end(),
[caller](const LtsSession::LtsSession* session) { return (session == caller); });
if (sessionIt == sessions.end())
{
return;
}
auto it = ++sessionIt;
int x = 0;
do
{
if (x > 100)
{
return;
}
x++;
if (it == sessions.end())
{
if (sessions.begin() == sessionIt)
{
return;
}
it = sessions.begin();
}
LtsSession::LtsSession* session = *it;
QWidget* blw = session->baseLayoutWidget();
if (blw == nullptr || session->isForeverInvisible() || session == caller)
{
continue;
}
caller->baseLayoutWidget()->hide();
blw->showFullScreen();
return;
}
while (++it != sessionIt);
}
void LtsAppManager::hideAllOtherBLWs(QObject* _caller)
{
if (!LtsSessionData::LtsSessionData::getInstance()->isTablet())
return;
LtsSession::LtsSession* caller = qobject_cast<LtsSession::LtsSession*>(_caller);
QVector<LtsSession::LtsSession*> sessions;
for (const LtsPluginManager::LtsPluginManager* app : m_appList)
sessions += app->sessions();
for (LtsSession::LtsSession* session : sessions)
{
QWidget* blw = session->baseLayoutWidget();
if (blw != nullptr && !session->isForeverInvisible() && session != caller)
{
blw->hide();
}
}
if (caller != nullptr)
return;
for (LtsSession::LtsSession* session : sessions)
{
QWidget* blw = session->baseLayoutWidget();
if (blw == nullptr || session->isForeverInvisible())
{
continue;
}
blw->showFullScreen();
return;
}
}
bool LtsAppManager::startAppOrLetUserChoose(LtsAppDescriptor::App appId,
const LtsSession::DdsConnectionParams& connParams, bool force)
{
return startAppOrLetUserChoose(getApp(appId), connParams, force);
}
bool LtsAppManager::startAppOrLetUserChoose(const LtsAppDescriptor::AppDescription& appDescription,
const LtsSession::DdsConnectionParams& connParams, bool force)
{
if (!appDescription.active && !force)
{
AppChooser* appChooser = new AppChooser();
appChooser->setAttribute(Qt::WA_DeleteOnClose);
connect(appChooser, &AppChooser::signalLogout, this, &LtsAppManager::slotLogout);
connect(
appChooser, &AppChooser::signalAppSelected, this,
[this, connParams](LtsAppDescriptor::App appId) {
if (createApp(appId, connParams) == nullptr)
QTimer::singleShot(100, this, &LtsAppManager::slotLogout);
},
Qt::QueuedConnection);
appChooser->show();
return true;
}
if (createApp(appDescription, connParams, {}, false, force) == nullptr)
{
QMessageBox::critical(nullptr, tr("App Manager"), tr("Could not create app.\nPlease contact support."));
return false;
}
return true;
}
LtsPluginManager::LtsPluginManager* LtsAppManager::createApp(LtsAppDescriptor::App appId,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId, bool hidden, bool force)
{
return createApp(getApp(appId), connParams, workspaceId, hidden, force);
}
LtsPluginManager::LtsPluginManager* LtsAppManager::createApp(const LtsAppDescriptor::AppDescription& appDescription,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId, bool hidden, bool force)
{
if (!appDescription.isValid())
{
return nullptr;
}
if (!hasRightForApp(appDescription) && !force)
return nullptr;
const bool bDesiredAppHasSituationMapInstance =
LtsPluginManager::LtsPluginManager::hasSituationMapInstance(appDescription, true);
if (bDesiredAppHasSituationMapInstance)
{
const int curInstances = getNumberOfSituationMapInstances();
if (curInstances >= 3 && !force)
{
if (QMessageBox::Yes !=
QMessageBox::question(nullptr, tr("App Manager"),
tr("Are you sure you want to launch another resource-intensive app? <br />"
"Please note that you are currently running three apps containing the "
"resource-intensive map componment. <br />"
"It may lead to potential performance issues.")))
{
return nullptr;
}
}
}
auto* pluginManager = new LtsPluginManager::LtsPluginManager();
connect(pluginManager, &LtsPluginManager::LtsPluginManager::signalQuit, this, &LtsAppManager::slotQuit);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::signalSoftQuit, this, &LtsAppManager::slotSoftQuit);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::signalLogout, this, &LtsAppManager::slotLogout);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this,
&LtsAppManager::signalInitializationFinished);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::destroyed, this, &LtsAppManager::slotAppDestroyed);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::hideAllOtherBLWs, this,
&LtsAppManager::hideAllOtherBLWs);
connect(pluginManager, &LtsPluginManager::LtsPluginManager::taskSwitch, this, &LtsAppManager::taskSwitch);
#ifdef LTS_DEBUG
connect(pluginManager, &LtsPluginManager::LtsPluginManager::signalStillAlive, this, [this]() {
auto* app = qobject_cast<LtsPluginManager::LtsPluginManager*>(sender());
if (!app)
return;
for (auto i = m_appList.constBegin(); i != m_appList.constEnd(); ++i)
{
if (*i == app)
return;
}
});
#endif
if (!pluginManager->startApp(appDescription, false, connParams, workspaceId, hidden))
{
QMessageBox::critical(
nullptr, tr("App Manager"),
tr("The Plugin Manager failed to start the app due to plugin errors.\nPlease contact support."));
pluginManager->deleteLater();
return nullptr;
}
m_appList.append(pluginManager);
return pluginManager;
}
bool LtsAppManager::hasApp(LtsAppDescriptor::App appId) const
{
return (std::find_if(m_availableApps.constBegin(), m_availableApps.constEnd(),
[appId](const LtsAppDescriptor::AppDescription& app) {
bool ret = (app.id == appId);
return ret;
}) != m_availableApps.constEnd());
}
int LtsAppManager::getNumberOfSituationMapInstances() const
{
int numberOfSituationMapInstances = 0;
for (const LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList))
{
if (!app)
continue;
if (app->hasSituationMapInstance())
++numberOfSituationMapInstances;
}
return numberOfSituationMapInstances;
}
LtsAppDescriptor::AppDescription LtsAppManager::getApp(LtsAppDescriptor::App appId) const
{
for (const LtsAppDescriptor::AppDescription& app : m_availableApps)
{
if (app.id == appId)
return app;
}
return LtsAppDescriptor::AppDescription();
}
void LtsAppManager::setMainApp(LtsAppDescriptor::App appId)
{
m_app = getApp(appId);
}
void LtsAppManager::saveState()
{
if (LtsSessionData::LtsSessionData::getInstance()->getOperatorId() == 0)
return;
QStringList unsavedWorkspaces =
LtsUtils::OperatorSettings::getInstance()->identifiers(QStringLiteral("UnsavedWorkspace"));
for (auto i = unsavedWorkspaces.constBegin(); i != unsavedWorkspaces.constEnd(); ++i)
LtsUtils::OperatorSettings::getInstance()->removeValue(QStringLiteral("UnsavedWorkspace"), *i);
QStringList unsavedFilterPreset =
LtsUtils::OperatorSettings::getInstance()->identifiers(QStringLiteral("UnsavedFilterPreset"));
for (auto i = unsavedFilterPreset.constBegin(); i != unsavedFilterPreset.constEnd(); ++i)
LtsUtils::OperatorSettings::getInstance()->removeValue(QStringLiteral("UnsavedFilterPreset"), *i);
QJsonArray root;
for (const LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList))
{
const QVector<LtsSession::LtsSession*> sessions = app->sessions();
const auto appId = app->appDescription().id;
if (appId == LtsAppDescriptor::App::Login || sessions.count() < 1)
continue;
QJsonObject appState;
appState[QStringLiteral("id")] = static_cast<int>(appId);
QJsonArray sessionStates;
for (LtsSession::LtsSession* session : sessions)
{
if (session->baseLayout() != nullptr && session->baseLayout()->isSecondaryWidget())
continue;
QJsonObject sessionState;
int screenId = session->screenId();
int screenContainerId = session->screenContainerId();
sessionState[QStringLiteral("screenId")] = screenId;
sessionState[QStringLiteral("screenContainerId")] = screenContainerId;
sessionState[QStringLiteral("exerciseId")] = session->exerciseId();
sessionState[QStringLiteral("partitionId")] = session->partitionId();
sessionState[QStringLiteral("partitionType")] = int(session->partitionType());
sessionState[QStringLiteral("savegame")] = session->getSavegame();
const QString newId(QUuid::createUuid().toString());
sessionState[QStringLiteral("workspaceId")] = newId;
std::shared_ptr<OperatorManagement::ForeignSettingsGuiInterface> ifcOpm;
if (session->getForeignGuiInterface<OperatorManagement::ForeignSettingsGuiInterface>(ifcOpm))
{
ifcOpm->callWorkspaceSaveUnsaved(newId);
}
sessionStates.append(sessionState);
}
if (!sessionStates.isEmpty())
{
appState[QStringLiteral("sessions")] = sessionStates;
root.append(appState);
}
}
QJsonDocument doc(root);
LtsUtils::OperatorSettings::getInstance()->setValue(QStringLiteral("app"), QStringLiteral("LastAppStates"),
doc.toJson(QJsonDocument::Compact));
}
void LtsAppManager::slotLogout()
{
for (LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList))
{
const QVector<LtsSession::LtsSession*> sessions = app->sessions();
for (LtsSession::LtsSession* session : sessions)
{
if (session->notifyUnsavedChanges() == false)
return;
}
}
saveState();
const QVector<LtsPluginManager::LtsPluginManager*> apps = m_appList;
if (apps.isEmpty() && m_login != nullptr)
m_login->logoff();
for (LtsPluginManager::LtsPluginManager* app : apps)
app->deleteLater();
}
void LtsAppManager::slotAppDestroyed()
{
LtsPluginManager::LtsPluginManager* app = static_cast<LtsPluginManager::LtsPluginManager*>(sender());
m_appList.removeOne(app);
if (m_appList.isEmpty() && m_login != nullptr)
{
m_login->logoff();
}
}
void LtsAppManager::slotQuit()
{
QObject* object = sender();
if (!object)
qCritical()
<< "ERROR: LtsAppManager: slot called without object - so it cannot be deleted from the app assignments!";
LtsPluginManager::LtsPluginManager* app = qobject_cast<LtsPluginManager::LtsPluginManager*>(object);
if (app == nullptr)
{
qCritical() << "ERROR: LtsAppManager: quit requested for invalid app";
return;
}
if (m_appList.count() == 1)
{
m_appList.removeAll(app);
saveState();
}
app->deleteLater();
}
void LtsAppManager::slotSoftQuit()
{
QObject* object = sender();
LtsPluginManager::LtsPluginManager* app = qobject_cast<LtsPluginManager::LtsPluginManager*>(object);
if (app == nullptr)
{
qCritical() << "ERROR: LtsAppManager: quit requested for invalid app";
return;
}
app->_softQuit();
if (m_appList.count() == 1)
{
m_appList.removeAll(app);
saveState();
}
}
bool LtsAppManager::otherSessionsResponsibility(LtsSession::LtsSession* thisSession,
const QVector<LtsAppDescriptor::App>& requiredAppTypes,
const QVector<IDL::PartitionType>& requiredPartitionTypes,
const QString& menuGroup, const QString& identifier,
LtsWidgets::LayoutArea area)
{
const QVector<LtsPluginManager::LtsPluginManager*> apps = LtsAppManager::LtsAppManager::getInstance()->getAppList();
QVector<LtsPluginManager::LtsPluginManager*> worthyApps;
for (LtsPluginManager::LtsPluginManager* app : apps)
{
if (!requiredAppTypes.contains(static_cast<LtsAppDescriptor::App>(app->appDescription().id)))
continue;
worthyApps.append(app);
}
for (const LtsPluginManager::LtsPluginManager* app : std::as_const(worthyApps))
{
const QVector<LtsSession::LtsSession*> sessions = app->sessions();
for (const LtsSession::LtsSession* session : sessions)
{
if (session->widgetExists(menuGroup, identifier, area))
return true;
}
}
LtsMultiMonitor::LtsMultiMonitor* mm = LtsMultiMonitor::LtsMultiMonitor::getInstance();
LtsMultiMonitor::LtsScreenBase* mainScreen = mm->mainScreen();
for (const LtsPluginManager::LtsPluginManager* app : std::as_const(worthyApps))
{
const QVector<LtsSession::LtsSession*> sessions = app->sessions();
for (LtsSession::LtsSession* session : sessions)
{
if (session != thisSession && mm->widgetsScreen(session->baseLayoutWidget()) == mainScreen &&
requiredPartitionTypes.contains(session->partitionType()))
return true;
}
}
return false;
}
} // namespace LtsAppManager
@@ -1,136 +0,0 @@
#pragma once
#include <Lts/Common/ProjectConfig/project_defines.h>
#include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsSession/lts_session.h>
#include <LtsWidgets/lts_base_layout_widget.h>
#include <LtsWidgets/lts_dialog.h>
#include <QtCore/QObject>
#include <QtCore/QVector>
#include <memory>
#ifndef LTSAPPMANAGER_EXPORT
#ifdef BUILD_STATIC_LIBRARIES
#define LTSAPPMANAGER_EXPORT
#else
#if defined(MAKE_LTSAPPMANAGER_LIB)
#define LTSAPPMANAGER_EXPORT Q_DECL_EXPORT
#else
#define LTSAPPMANAGER_EXPORT Q_DECL_IMPORT
#endif
#endif
#endif
namespace LtsPluginManager
{
class LtsPluginManager;
}
namespace LtsLogin
{
class LtsLogin;
}
namespace LtsSession
{
class LtsSession;
struct DdsConnectionParams;
} // namespace LtsSession
namespace DeveloperTools
{
class DevDialog;
}
class QTcpSocket;
namespace LtsAppManager
{
class LTSAPPMANAGER_EXPORT LtsAppManager : public QObject
{
Q_OBJECT
public:
static LtsAppManager* getInstance();
void showLogin();
LtsPluginManager::LtsPluginManager* createApp(LtsAppDescriptor::App appId,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId = QString(), bool hidden = false,
bool force = false);
bool startAppOrLetUserChoose(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams& connParams,
bool force = false);
void setLoginPluginIid(const QString& loginPluginIid)
{
m_loginPluginIid = loginPluginIid;
}
void setMainApp(LtsAppDescriptor::App appId = LtsAppDescriptor::App::Login);
QVector<LtsPluginManager::LtsPluginManager*> getAppList() const
{
return m_appList;
}
LtsAppDescriptor::AppDescriptionVector getAvailableApps() const
{
return m_availableApps;
}
void setAvailableApps(const LtsAppDescriptor::AppDescriptionVector& availableApps);
bool hasRightForApp(const LtsAppDescriptor::AppDescription& appDescription) const;
LtsAppDescriptor::AppDescription getApp(LtsAppDescriptor::App appId) const;
bool hasApp(LtsAppDescriptor::App appId) const;
int getNumberOfSituationMapInstances() const;
void debugSendMessage(const QString& msg);
bool otherSessionsResponsibility(LtsSession::LtsSession* thisSession,
const QVector<LtsAppDescriptor::App>& requiredAppTypes,
const QVector<IDL::PartitionType>& requiredPartitionTypes,
const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area);
private:
friend struct LtsAppManagerHandler;
friend class DeveloperTools::DevDialog;
LtsAppManager();
~LtsAppManager();
bool startAppOrLetUserChoose(const LtsAppDescriptor::AppDescription& appDescription,
const LtsSession::DdsConnectionParams& connParams, bool force = false);
LtsPluginManager::LtsPluginManager* createApp(const LtsAppDescriptor::AppDescription& appDescription,
const LtsSession::DdsConnectionParams& connParams,
const QString& workspaceId = QString(), bool hidden = false,
bool force = false);
void saveState();
LtsAppDescriptor::AppDescriptionVector m_availableApps;
QVector<LtsPluginManager::LtsPluginManager*> m_appList;
LtsLogin::LtsLogin* m_login;
LtsAppDescriptor::AppDescription m_app;
QString m_loginPluginIid;
public slots:
void slotLogout();
private slots:
void slotQuit();
void slotSoftQuit();
void slotShowLogin();
void slotAppDestroyed();
void slotStartDebugServer();
void hideAllOtherBLWs(QObject* _caller);
void taskSwitch(QObject* _caller);
signals:
void signalLoginDone();
void signalLogoffDone();
void signalShowLogin();
void signalInitializationFinished();
void signalCommand(QTcpSocket* client, const QStringList argList);
};
} // namespace LtsAppManager
@@ -1,12 +0,0 @@
find_package(Botan2)
if (BOTAN_FOUND AND CMAKE_VERSION VERSION_GREATER 3.15.9) # botan doesn't use cmake, make it a cmake target | imported targets don't work correctly with 3.10
add_library(LtsBotan STATIC IMPORTED GLOBAL)
set_target_properties(LtsBotan PROPERTIES IMPORTED_LOCATION ${BOTAN_LIBRARIES})
set_target_properties(LtsBotan PROPERTIES INCLUDE_DIRECTORIES ${BOTAN_INCLUDE_DIRS})
target_compile_definitions(LtsBotan INTERFACE BOTAN_FOUND)
target_include_directories(LtsBotan SYSTEM INTERFACE ${BOTAN_INCLUDE_DIRS})
set(LTS_BOTAN LtsBotan)
message(STATUS "BOTAN_INCLUDE_DIRS = ${BOTAN_INCLUDE_DIRS}, BOTAN_LIBRARIES = ${BOTAN_LIBRARIES}, LTS_BOTAN = ${LTS_BOTAN}")
endif()
@@ -1,52 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
#
# Make ${Qt6_Gui} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Gui)
set(Qt6_Gui ${Qt6_Gui})
else()
set(Qt6_Gui "")
endif()
NGL_ADD_LIBRARY2(WS SV HLA LtsElevation SHARED
lts_elevation_manager.cpp
lts_elevation_manager.h
logger.cpp
logger.h
)
NGL_TARGET_INCLUDE_DIRECTORIES(LtsElevation
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
${CMAKE_SOURCE_DIR}/Lts/Common
${CMAKE_SOURCE_DIR}/Lts/Common/LtsUtils
${CMAKE_SOURCE_DIR}/Lts/Viewer/SituationMap
${CMAKE_SOURCE_DIR}/Lts/Viewer/SituationMap/Common
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(LtsElevation
PRIVATE
NGLLogger
## LtsSessionDataDds
PUBLIC
LtsUtilsCoreHeaderOnly
Qt6::Core
${Qt6_Gui}
)
endif()
if(BUILD_RTI)
# All ElevationMapManager / resource_path / exm-dtc usages live inside
# #ifdef BUILD_RTI in lts_elevation_manager.cpp (Qt5 dependencies restored).
target_link_libraries(LtsElevation PRIVATE
AsmDataPluginInterface
ExmDataPluginInterface
situationMapCommon
situationMapElevationMap
)
endif()
ADD_SUBDIRECTORY(UnitTest_Elevation)
@@ -1,33 +0,0 @@
# Make ${Qt6_Gui} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Gui)
set(Qt6_Gui ${Qt6_Gui})
else()
set(Qt6_Gui "")
endif()
#
# @RDE_HEADER@
# $Id$
# $HeadURL$
# $Author$
#
# External dependency - missing: situationMapCommon, situationMapElevationMap
# Test disabled until external dependencies are available
# IF(BUILD_TESTING AND TARGET LtsElevation)
# ADD_EXECUTABLE(commenUnitTestElevation ${LinkedSources} ${UnitTestSources} )
#
# TARGET_LINK_LIBRARIES(commenUnitTestElevation
# NGLLogger
# nglcoreapplication
# LtsElevation
# LtsCoordTrans
# situationMapCommon
# situationMapElevationMap
# Qt6::Core
# ${Qt6_Gui}
# Qt6::Test)
#
# ADD_TEST(NAME commenUnitTestElevation COMMAND $<TARGET_FILE:commenUnitTestElevation>)
# ENDIF()
@@ -1,198 +0,0 @@
#include "elevation_unit_test.h"
#include <ElevationMap/elevation_map_manager.h>
#include <LtsCoordTrans/lts_coord_trans.h>
#include <NGLLogger/NGLLoggerBootstrap.h>
#include <QtTest/QTest>
#include <nglapplication/nglcoreapplication.h>
Q_DECLARE_METATYPE(LtsUtils::QPoint3D);
Q_DECLARE_METATYPE(LtsElevation::LineOfSight);
#include <iostream>
static const int s_id{4711};
static LtsElevation::LtsElevationManager* s_eleMgr{nullptr};
class MyLtsElevationManagerBootstrap : public LtsElevation::LtsElevationManager
{
using BaseClass = LtsElevation::LtsElevationManager;
public:
static LtsElevationManager* createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine)
{
return BaseClass::createInstanceUnitTest(id, filePaths_rough_to_fine);
}
};
UnitTestElevation::UnitTestElevation()
: m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestElevation"))
{
}
void UnitTestElevation::initTestCase()
{
QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif"));
s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath});
const bool bIsValid = s_eleMgr->isValid();
std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl;
{
s_eleMgr->waitForInitialization();
const bool bIsValid = s_eleMgr->isValid();
std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl;
}
}
void UnitTestElevation::init()
{
QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist");
}
void UnitTestElevation::test_elevation_data()
{
QTest::addColumn<QPointF>("lonLat");
QTest::addColumn<double>("elevationRef");
QTest::newRow("elevation 1 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic() << 75.0;
QTest::newRow("elevation 2 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 72000 13000")).geographic() << 80.0;
QTest::newRow("elevation 3 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 76925 18625")).geographic() << 92.0;
}
void UnitTestElevation::test_elevation()
{
QFETCH(QPointF, lonLat);
QFETCH(double, elevationRef);
double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y());
QVERIFY2(qFuzzyCompare(elevationRef, elevation), " got wrong elevation result");
}
void UnitTestElevation::test_elevation_isCovered()
{
const QPointF& lonLat1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic();
const QPointF& lonLat2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U MD 60000 10000")).geographic();
const double defaultElevationValue = -123;
{
bool bIsCovered = false;
s_eleMgr->elevation(lonLat1.x(), lonLat1.y(), defaultElevationValue, &bIsCovered);
QVERIFY2(bIsCovered, " error on bIsCovered");
}
{
bool bIsCovered = true;
s_eleMgr->elevation(lonLat2.x(), lonLat2.y(), defaultElevationValue, &bIsCovered);
QVERIFY2(!bIsCovered, " error on bIsCovered");
}
}
void UnitTestElevation::test_elevation_defaultValue()
{
const QPointF& lonLat = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic();
double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y());
QVERIFY2(qFuzzyCompare(elevation, std::numeric_limits<double>::min()), " error on defaultValue");
{
const double defaultValue = 100;
elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue);
QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue");
}
{
const double defaultValue = std::numeric_limits<double>::max();
elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue);
QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue");
}
}
void UnitTestElevation::test_lineOfSightCalculation_data()
{
QTest::addColumn<QPointF>("startGeo2D");
QTest::addColumn<double>("startObjH");
QTest::addColumn<QPointF>("endGeo2D");
QTest::addColumn<double>("endObjH");
QTest::addColumn<LtsElevation::LineOfSight>("expectedResult");
QTest::newRow("losDataset 1 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 10000")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 60000 60000")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 2 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_INVISIBLE;
QTest::newRow("losDataset 3 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 20.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 20.0
<< LtsElevation::LineOfSight::LOS_VISIBLE;
QTest::newRow("losDataset 4 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << -1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 5 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 1.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << -1.0
<< LtsElevation::LineOfSight::LOS_ERROR;
QTest::newRow("losDataset 6 ")
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77200 17600")).geographic() << 0.0
<< LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 77600 17600")).geographic() << 0.0
<< LtsElevation::LineOfSight::LOS_INVISIBLE;
}
void UnitTestElevation::test_lineOfSightCalculation()
{
QFETCH(QPointF, startGeo2D);
QFETCH(double, startObjH);
QFETCH(QPointF, endGeo2D);
QFETCH(double, endObjH);
QFETCH(LtsElevation::LineOfSight, expectedResult);
LtsUtils::QPoint3D start3D = LtsUtils::QPoint3D::fromQPointF(startGeo2D);
start3D.rz() = startObjH;
start3D.rz() += s_eleMgr->elevation(start3D.x(), start3D.y());
LtsUtils::QPoint3D end3D = LtsUtils::QPoint3D::fromQPointF(endGeo2D);
end3D.rz() = endObjH;
end3D.rz() += s_eleMgr->elevation(end3D.x(), end3D.y());
LtsElevation::LineOfSight los = s_eleMgr->lineOfSightCalculation(start3D, end3D);
NOTICE_LOG(m_logger) << "los = " << los;
{
LtsElevation::LineOfSight los2 = s_eleMgr->lineOfSightCalculation(startGeo2D, startObjH, endGeo2D, endObjH);
QVERIFY2(los == los2, " got different lineOfSightCalculation result");
}
QVERIFY2(los == expectedResult, " got lineOfSightCalculation result");
}
int main(int argc, char* argv[])
{
NGLCoreApplication app(argc, argv);
app.createLogger("UnitTestElevation", "log4cxxElevationUnitTest.props");
UnitTestElevation tc;
int ret = QTest::qExec(&tc, argc, argv);
if (s_eleMgr)
{
s_eleMgr->cleanupAll();
}
return ret;
}
@@ -1,38 +0,0 @@
#pragma once
#include <ElevationMap/elevation_map_manager.h>
#include <LtsElevation/lts_elevation_manager.h>
#include <NGLLogger/INGLLogger.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QObject>
#include <QtTest/QTest>
using LOGGER_T = NGL::INGLLogger&;
class UnitTestElevation : public QObject
{
Q_OBJECT
public:
UnitTestElevation();
private Q_SLOTS:
void initTestCase();
void init();
void test_elevation_data();
void test_elevation();
void test_elevation_isCovered();
void test_elevation_defaultValue();
void test_lineOfSightCalculation_data();
void test_lineOfSightCalculation();
private:
NGL::INGLLogger& m_logger;
};
@@ -1,30 +0,0 @@
#include "logger.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
namespace LtsElevation
{
LOGGER_T getLogger(const char* name)
{
static const char ns[] = "Lts.Elevation.";
std::string loggerName;
const size_t len = strlen(name);
loggerName.reserve(sizeof(ns) + len);
loggerName.append(ns, sizeof(ns) - 1);
loggerName.append(name, len);
try
{
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName);
}
catch (const std::exception& ex)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
}
}
} // namespace LtsElevation
@@ -1,17 +0,0 @@
#pragma once
#include <NGLLogger/INGLLogger.h>
namespace LtsElevation
{
typedef NGL::INGLLogger& LOGGER_T;
LOGGER_T getLogger(const char* name);
inline LOGGER_T getLogger(const QString& loggerName)
{
return getLogger(loggerName.toUtf8().constData());
}
} // namespace LtsElevation
@@ -1,587 +0,0 @@
#include "lts_elevation_manager.h"
#ifdef BUILD_RTI
#include <AssetManagement/asm_data_plugin_interface.h>
#include <ExerciseManagement/exm_data_plugin_interface.h>
#include <Viewer/SituationMap/ElevationMap/elevation_map_manager.h>
#include <Viewer/SituationMap/Common/resource_path.h>
#include <QDir>
#include <QHash>
#include <QSharedPointer>
#include <QUrl>
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_UNDEFINED ==
(int)LtsElevation::LineOfSight::LOS_UNDEFINED,
"LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_ERROR ==
(int)LtsElevation::LineOfSight::LOS_ERROR,
"LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_VISIBLE ==
(int)LtsElevation::LineOfSight::LOS_VISIBLE,
"LineOfSight mismatch");
static_assert((int)SituationMap::ElevationMapManager::LineOfSight::LOS_INVISIBLE ==
(int)LtsElevation::LineOfSight::LOS_INVISIBLE,
"LineOfSight mismatch");
#endif
namespace LtsElevation
{
class LtsElevationManager;
using LtsElevatioMgrMapTrainingAreaId = QMap<int, LTS_ELEVATION_MANAGER_TYPE>;
static LtsElevatioMgrMapTrainingAreaId& ltsElevatioMgrMapTrainingAreaId()
{
static LtsElevatioMgrMapTrainingAreaId s_ltsElevatioMgrMapTrainingAreaId;
return s_ltsElevatioMgrMapTrainingAreaId;
}
static void cleanupLtsElevatioMgrMapTrainingAreaId()
{
qDeleteAll(ltsElevatioMgrMapTrainingAreaId());
ltsElevatioMgrMapTrainingAreaId().clear();
}
LtsElevatioMgrMapTrainingAreaId& getLtsElevationMgrMapTrainingAreaId()
{
if (ltsElevatioMgrMapTrainingAreaId().isEmpty())
qAddPostRoutine(cleanupLtsElevatioMgrMapTrainingAreaId);
return ltsElevatioMgrMapTrainingAreaId();
}
static long s_counter{0};
class LtsElevationManager::Private
{
public:
Private() = default;
~Private()
{
#ifdef BUILD_RTI
delete m_elevationManager;
#endif
}
std::shared_ptr<ExerciseManagement::Interface::Dtc> m_exmDtc;
#ifdef BUILD_RTI
std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
SituationMap::ElevationMapManager* m_elevationManager{nullptr};
#endif
QStringList m_filePaths_rough_to_fine;
};
LtsElevationManager::LtsElevationManager()
: QObject(nullptr)
, d(new Private)
, m_logger(getLogger("LtsElevationManager"))
{
++s_counter;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this;
}
LtsElevationManager::~LtsElevationManager()
{
--s_counter;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, s_counter=" << s_counter << " this=" << this;
delete d;
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END, s_counter=" << s_counter << " this=" << this;
}
LTS_ELEVATION_MANAGER_TYPE
LtsElevationManager::createInstance(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
#ifdef BUILD_RTI
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc
#else
const std::shared_ptr<void>& asmDtc
#endif
)
{
LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START, exerciseId=" << exerciseId;
if (exerciseId < 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " exerciseId invalid, exerciseId=" << exerciseId;
return nullptr;
}
// Qt5 logic restored (the qt6 port had dropped the exerciseId->trainingAreaId
// caching and always returned nullptr here).
#ifdef BUILD_RTI
int trainingAreaId = -1;
// remember for future calls
// (so createInstance should work WITHOUT dtcs)
// Idea: MainHandler: createInstance with exerciseId and valid dtcs
// Plugin or simular: createInstance with exerciseId and no dtcs
static QHash<int, int> s_exIdToTaIdStore;
const auto exTaIt = s_exIdToTaIdStore.find(exerciseId);
if (exTaIt != s_exIdToTaIdStore.end())
{
// CASE 1:
// already created:
trainingAreaId = *exTaIt;
}
else
{
// CASE 2:
// ... or create on demand:
if (!exmDtc || !asmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for exerciseId=" << exerciseId
<< ", asmDtc=" << asmDtc
<< ", exmDtc=" << exmDtc;
return nullptr;
}
// exId to taId
trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, exmDtc);
if (trainingAreaId <= 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId
<< ", trainingAreaId=" << trainingAreaId;
return nullptr;
}
// store and remember:
s_exIdToTaIdStore[exerciseId] = trainingAreaId;
}
// CASE 1: Following should work even with invalid asmDtc:
LTS_ELEVATION_MANAGER_TYPE temp = createInstanceForTrainingAreaId(trainingAreaId, asmDtc);
if (!temp)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on createInstanceForTrainingAreaId"
<< ", exerciseId=" << exerciseId
<< ", trainingAreaId=" << trainingAreaId;
return nullptr;
}
// add exmDtc
temp->initDDS(exmDtc, asmDtc);
TRACE_LOG(logger) << Q_FUNC_INFO << " END, exerciseId=" << exerciseId;
return temp;
#else
Q_UNUSED(exmDtc);
Q_UNUSED(asmDtc);
ERROR_LOG(logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, cannot create instance";
return nullptr;
#endif
}
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::getInstance(int exerciseId)
{
return LtsElevationManager::createInstance(exerciseId);
}
#ifdef BUILD_RTI
LTS_ELEVATION_MANAGER_TYPE
LtsElevationManager::createInstanceForTrainingAreaId(int trainingAreaId,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc)
{
LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START, trainingAreaId=" << trainingAreaId;
if (trainingAreaId < 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " trainingAreaId invalid, trainingAreaId=" << trainingAreaId;
return nullptr;
}
LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId();
QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(trainingAreaId);
if (it != map.end())
{
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
if (!asmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for trainingAreaId=" << trainingAreaId << ", asmDtc=" << asmDtc;
return nullptr;
}
LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager();
temp->initDDS(nullptr, asmDtc);
const QStringList& filenames = temp->getFilenamesForTrainingArea(trainingAreaId);
if (filenames.isEmpty())
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no filenames for trainingAreaId=" << trainingAreaId;
delete temp;
return nullptr;
}
bool bInitFilenames = temp->init(filenames);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for trainingAreaId=" << trainingAreaId;
delete temp;
return nullptr;
}
map.insert(trainingAreaId, temp);
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << trainingAreaId;
return map[trainingAreaId];
}
#endif
LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceUnitTest(int id,
const QStringList& filePaths_rough_to_fine)
{
LOGGER_T logger = getLogger("LtsElevationManager");
LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId();
QMap<int, LTS_ELEVATION_MANAGER_TYPE>::iterator it = map.find(id);
if (it != map.end())
{
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size();
return it.value();
}
LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager();
bool bInitFilenames = temp->init(filePaths_rough_to_fine);
if (!bInitFilenames)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " bInitFilenames failed for id=" << id;
delete temp;
return nullptr;
}
map.insert(id, temp);
DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size();
TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << id;
return map[id];
}
void LtsElevationManager::cleanupAll()
{
LOGGER_T logger = getLogger("LtsElevationManager");
TRACE_LOG(logger) << Q_FUNC_INFO << " START";
cleanupLtsElevatioMgrMapTrainingAreaId();
TRACE_LOG(logger) << Q_FUNC_INFO << " END";
}
#ifdef BUILD_RTI
void LtsElevationManager::initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc)
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
d->m_exmDtc = exmDtc;
if (d->m_exmDtc)
d->m_exmDtc->waitForHistoricalDataExercise(1000);
d->m_asmDtc = asmDtc;
if (d->m_asmDtc)
d->m_asmDtc->waitForHistoricalDataTrainingArea(1000);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END";
}
#else
void LtsElevationManager::initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
const std::shared_ptr<void>& asmDtc)
{
Q_UNUSED(exmDtc);
Q_UNUSED(asmDtc);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START (BUILD_RTI=OFF, no DDS init)";
// BUILD_RTI=OFF: No DDS initialization
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END";
}
#endif
#ifdef BUILD_RTI
QStringList LtsElevationManager::getFilenamesForExercise(int exerciseId)
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
if (!d->m_exmDtc || !d->m_asmDtc)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs"
<< ", exerciseId=" << exerciseId;
return {};
}
int trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, d->m_exmDtc);
if (trainingAreaId <= 0)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return {};
}
QStringList filePaths_rough_to_fine = getFilenamesForTrainingArea(trainingAreaId);
TRACE_LOG(m_logger) << Q_FUNC_INFO
<< " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";"));
return filePaths_rough_to_fine;
}
QStringList LtsElevationManager::getFilenamesForTrainingArea(int trainingAreaId)
{
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START";
if (!d->m_asmDtc)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs"
<< ", trainingAreaId=" << trainingAreaId;
return {};
}
QStringList filePaths_rough_to_fine;
{
d->m_asmDtc->waitForHistoricalDataTrainingArea(1000);
const AssetManagement::TrainingArea& ta = d->m_asmDtc->trainingArea(trainingAreaId);
if (ta.id != trainingAreaId)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error on s_asmDtc->trainingArea"
<< ", trainingAreaId=" << trainingAreaId;
return {};
}
const std::vector<AssetManagement::MapDescription>& mdVec = ta.elevation;
filePaths_rough_to_fine.reserve(mdVec.size());
for (const AssetManagement::MapDescription& md : std::as_const(mdVec))
{
QUrl url(QString::fromStdString(md.url));
QString filePathAbs = url.toLocalFile();
if (QDir::isRelativePath(filePathAbs))
filePathAbs = SituationMap::getResourcePath() + QStringLiteral("/elevation/") + filePathAbs;
filePaths_rough_to_fine.append(filePathAbs);
}
}
TRACE_LOG(m_logger) << Q_FUNC_INFO
<< " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";"));
return filePaths_rough_to_fine;
}
#else
QStringList LtsElevationManager::getFilenamesForExercise(int /*exerciseId*/)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, getFilenamesForExercise not available";
return {};
}
QStringList LtsElevationManager::getFilenamesForTrainingArea(int /*trainingAreaId*/)
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, getFilenamesForTrainingArea not available";
return {};
}
#endif
bool LtsElevationManager::init(const QStringList& filePaths_rough_to_fine)
{
#ifdef BUILD_RTI
delete d->m_elevationManager;
d->m_elevationManager = new SituationMap::ElevationMapManager();
int cnt = d->m_elevationManager->init(filePaths_rough_to_fine);
if (cnt != filePaths_rough_to_fine.size())
{
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!";
return false;
}
return true;
#else
Q_UNUSED(filePaths_rough_to_fine);
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, init not available";
return false;
#endif
}
#ifdef BUILD_RTI
int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId,
const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc)
{
LOGGER_T logger = getLogger("LtsElevationManager");
if (!exmDtc)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs"
<< ", exerciseId=" << exerciseId;
return -1;
}
int trainingAreaId = -1;
{
exmDtc->waitForHistoricalDataExercise(1000);
const ExerciseManagement::Exercise& exm = exmDtc->exercise(exerciseId);
if (exm.id != exerciseId)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error on m_exmDtc->exercise"
<< ", exerciseId=" << exerciseId;
return -1;
}
trainingAreaId = exm.trainingAreaId;
if (trainingAreaId <= 0)
{
ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId"
<< ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId;
return -1;
}
}
return trainingAreaId;
}
#else
int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId,
const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc)
{
Q_UNUSED(exerciseId);
Q_UNUSED(exmDtc);
LOGGER_T logger = getLogger("LtsElevationManager");
ERROR_LOG(logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, cannot convert exerciseId to trainingAreaId";
return -1;
}
#endif
bool LtsElevationManager::waitForInitialization()
{
#ifdef BUILD_RTI
if (!d->m_elevationManager)
return false;
return d->m_elevationManager->waitForInitialization();
#else
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, waitForInitialization not available";
return false;
#endif
}
bool LtsElevationManager::isValid() const
{
#ifdef BUILD_RTI
if (!d->m_elevationManager)
return false;
return d->m_elevationManager->isValid();
#else
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, isValid not available";
return false;
#endif
}
double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool* bIsCovered) const
{
#ifdef BUILD_RTI
if (!d->m_elevationManager)
return defaultValue;
return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered);
#else
Q_UNUSED(lon_rad);
Q_UNUSED(lat_rad);
Q_UNUSED(bIsCovered);
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, elevation not available";
return defaultValue;
#endif
}
LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ,
const LtsUtils::QPoint3D& endPointGeo_absZ)
{
#ifdef BUILD_RTI
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< ", startPointGeo_absZ = " << startPointGeo_absZ
<< ", endPointGeo_absZ = " << endPointGeo_absZ;
if (!isValid())
{
ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error, LtsElevationManager not valid";
return LineOfSight::LOS_ERROR;
}
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult =
d->m_elevationManager->lineOfSightCalculation(startPointGeo_absZ, endPointGeo_absZ);
LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"
<< ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ
<< " -> LineOfSight " << result;
return result;
#else
Q_UNUSED(startPointGeo_absZ);
Q_UNUSED(endPointGeo_absZ);
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, lineOfSightCalculation not available";
return LineOfSight::LOS_ERROR;
#endif
}
LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF& startPointGeo, double startHat,
const QPointF& endPointGeo, double endHat)
{
#ifdef BUILD_RTI
TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"
<< ", startPointGeo = " << startPointGeo << ", startHat = " << startHat
<< ", endPointGeo = " << endPointGeo << ", endHat = " << endHat;
SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult =
d->m_elevationManager->lineOfSightCalculation(startPointGeo, startHat, endPointGeo, endHat);
LtsElevation::LineOfSight result = static_cast<LtsElevation::LineOfSight>(eleMapMgrResult);
TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"
<< ", startPointGeo = " << startPointGeo << ", startHat = " << startHat
<< ", endPointGeo = " << endPointGeo << ", endHat = " << endHat << " -> LineOfSight "
<< static_cast<int>(eleMapMgrResult);
return result;
#else
Q_UNUSED(startPointGeo);
Q_UNUSED(startHat);
Q_UNUSED(endPointGeo);
Q_UNUSED(endHat);
ERROR_LOG(m_logger) << Q_FUNC_INFO << " BUILD_RTI=OFF, lineOfSightCalculation not available";
return LineOfSight::LOS_ERROR;
#endif
}
const QString toString(const LineOfSight& value)
{
switch (value)
{
case LineOfSight::LOS_UNDEFINED:
return QStringLiteral("LOS_UNDEFINED");
case LineOfSight::LOS_ERROR:
return QStringLiteral("LOS_ERROR");
case LineOfSight::LOS_VISIBLE:
return QStringLiteral("LOS_VISIBLE");
case LineOfSight::LOS_INVISIBLE:
return QStringLiteral("LOS_INVISIBLE");
}
Q_ASSERT(false);
return QStringLiteral("LineOfSightERROR");
}
std::ostream& operator<<(std::ostream& stream, const LineOfSight value)
{
stream << toString(value).toStdString();
return stream;
}
} // namespace LtsElevation
@@ -1,113 +0,0 @@
#pragma once
#include "logger.h"
#include "ltselevation_export.h"
#include <LtsUtils/LtsUtilsCore/qpoint3d.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QMap>
#include <QtCore/QObject>
#include <QtCore/QPointer>
#include <QtCore/QStringList>
#include <iosfwd>
#include <memory>
namespace LtsSession
{
class LtsSessionDataDds;
}
namespace ExerciseManagement
{
namespace Interface
{
class Dtc;
}
} // namespace ExerciseManagement
#ifdef BUILD_RTI
namespace AssetManagement
{
namespace Interface
{
class Dtc;
}
} // namespace AssetManagement
#endif
namespace LtsElevation
{
enum class LineOfSight { LOS_UNDEFINED, LOS_ERROR, LOS_VISIBLE, LOS_INVISIBLE };
class LtsElevationManager;
using LTS_ELEVATION_MANAGER_TYPE = QPointer<LtsElevationManager>;
class LTSELEVATION_EXPORT LtsElevationManager : public QObject
{
public:
static LTS_ELEVATION_MANAGER_TYPE
createInstance(int exerciseId, const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc = {},
#ifdef BUILD_RTI
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc = {}
#else
const std::shared_ptr<void>& asmDtc = {}
#endif
);
static LTS_ELEVATION_MANAGER_TYPE getInstance(int exerciseId);
#ifdef BUILD_RTI
static LTS_ELEVATION_MANAGER_TYPE
createInstanceForTrainingAreaId(int trainingAreaId,
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc = nullptr);
#endif
static void cleanupAll();
virtual ~LtsElevationManager();
bool waitForInitialization();
bool isValid() const;
double elevation(double lon_rad, double lat_rad, double defaultValue = std::numeric_limits<double>::min(),
bool* bIsCovered = nullptr) const;
LineOfSight lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ,
const LtsUtils::QPoint3D& endPointGeo_absZ);
LineOfSight lineOfSightCalculation(const QPointF& startPointGeo, double startHat, const QPointF& endPointGeo,
double endHat);
protected:
explicit LtsElevationManager();
void initDDS(const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc,
#ifdef BUILD_RTI
const std::shared_ptr<AssetManagement::Interface::Dtc>& asmDtc
#else
const std::shared_ptr<void>& asmDtc
#endif
);
bool init(const QStringList& filePaths_rough_to_fine);
static int exerciseIdToTrainingAreaId(int exerciseId,
const std::shared_ptr<ExerciseManagement::Interface::Dtc>& exmDtc);
QStringList getFilenamesForExercise(int exerciseId);
QStringList getFilenamesForTrainingArea(int trainingAreaId);
static LTS_ELEVATION_MANAGER_TYPE createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine);
private:
class Private;
Private* d;
LOGGER_T m_logger;
};
LTSELEVATION_EXPORT const QString toString(const LtsElevation::LineOfSight& value);
LTSELEVATION_EXPORT std::ostream& operator<<(std::ostream& stream, const LtsElevation::LineOfSight value);
} // namespace LtsElevation
@@ -1,44 +0,0 @@
#
# Library which automatically provides Login/Logoff so that user data (rights for apps, etc.) is available before any app is started
#
# $Id$
# $HeadURL$
# $Author$
# Created by Mike Wille, SLSE, 2016-10-27
#
# LtsLogin
set(LtsLogin_SRCS
lts_login.cpp
logout_info_dialog.cpp
)
NGL_WRAP_UI(LtsLogin_SRCS
logout_info_dialog.ui
)
IF(BUILD_RTI)
NGL_ADD_LIBRARY2(WS LtsLogin SHARED ${LtsLogin_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsLogin
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
NGL_TARGET_LINK_LIBRARIES(LtsLogin
PRIVATE
LtsAppDescriptor
LtsPluginManager
LtsSession
LtsSessionData
LtsWidgets
LtsUtilsSettings
LtsUtilsCoreHeaderOnly
PUBLIC
OpmDataPluginInterface
SrmDataPluginInterface
AsmDataPluginInterface
Qt6::Core
)
ENDIF(BUILD_RTI)
@@ -1,92 +0,0 @@
#include "logout_info_dialog.h"
#include "ui_logout_info_dialog.h"
#include <QtCore/QTimer>
namespace LtsLogin
{
LogoutInformationDialog::LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction,
QWidget* parent)
: LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_ui(new Ui::LogoutInformationDialog),
m_timer(new QTimer(this)), m_timeOut(timeOut), m_secsLeft(timeOut)
{
m_ui->setupUi(this);
QString actionText;
switch (shutdownAction)
{
case AssetManagement::ShutdownAction::NoAction:
case AssetManagement::ShutdownAction::Logout:
actionText = tr("logout");
break;
case AssetManagement::ShutdownAction::Shutdown:
actionText = tr("shutdown");
break;
case AssetManagement::ShutdownAction::Reboot:
actionText = tr("reboot");
break;
}
setText(tr("A %1 was triggered by a remote workstation.").arg(actionText));
connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this,
&LogoutInformationDialog::acceptClicked);
connect(m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this,
&LogoutInformationDialog::closeClicked);
connect(m_timer, &QTimer::timeout, this, &LogoutInformationDialog::onTimerTimeout);
m_timer->setInterval(1000);
}
LogoutInformationDialog::~LogoutInformationDialog()
{
delete m_ui;
}
void LogoutInformationDialog::setText(const QString& text)
{
m_ui->lblLogoutText->setText(text);
}
void LogoutInformationDialog::onTimerTimeout()
{
if (m_secsLeft > 0)
{
m_secsLeft--;
setCloseButtonText(m_secsLeft);
}
else
{
acceptClicked();
}
}
void LogoutInformationDialog::acceptClicked()
{
m_timer->stop();
accept();
}
void LogoutInformationDialog::closeClicked()
{
m_timer->stop();
reject();
}
void LogoutInformationDialog::setCloseButtonText(int secsLeft)
{
m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort [%1]").arg(secsLeft));
}
void LogoutInformationDialog::showEvent(QShowEvent* event)
{
m_secsLeft = m_timeOut;
setCloseButtonText(m_secsLeft);
m_timer->start();
LtsWidgets::LtsFramelessDialog::showEvent(event);
}
} // namespace LtsLogin
@@ -1,44 +0,0 @@
#pragma once
#include <AssetManagement/asm.hpp>
#include <LtsWidgets/lts_frameless_dialog.h>
#include <QtCore/QObject>
class QTimer;
namespace Ui
{
class LogoutInformationDialog;
}
namespace LtsLogin
{
class LogoutInformationDialog : public LtsWidgets::LtsFramelessDialog
{
Q_OBJECT
public:
LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget* parent = nullptr);
~LogoutInformationDialog();
private slots:
void onTimerTimeout();
void acceptClicked();
void closeClicked();
private:
void setText(const QString& text);
void setCloseButtonText(int secsLeft);
Ui::LogoutInformationDialog* m_ui;
QTimer* m_timer;
int m_timeOut;
int m_secsLeft;
protected:
void showEvent(QShowEvent* event) override final;
};
} // namespace LtsLogin
@@ -1,76 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LogoutInformationDialog</class>
<widget class="QWidget" name="LogoutInformationDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>165</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QFrame" name="frame">
<property name="frameShape">
<enum>QFrame::NoFrame</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Raised</enum>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QLabel" name="lblLogoutText">
<property name="text">
<string notr="true">&lt;logout information text&gt;</string>
</property>
<property name="textFormat">
<enum>Qt::AutoText</enum>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<widget class="LtsWidgets::LtsDialogButtonBox" name="buttonBox"/>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsWidgets::LtsDialogButtonBox</class>
<extends>QWidget</extends>
<header>LtsWidgets/lts_dialog_button_box.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,282 +0,0 @@
#include "lts_login.h"
#include "logout_info_dialog.h"
#include <LtsAppDescriptor/lts_app_descriptor.h>
#include <LtsPluginManager/lts_plugin_manager.h>
#include <LtsSession/lts_session.h>
#include <LtsSession/lts_session_data.h>
#include <LtsSession/lts_session_manager.h>
#include <LtsUtils/LtsUtilsCore/dds_vector.h>
#include <LtsUtilsSettings/settings.h>
#include <LtsWidgets/lts_wait_dialog.h>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtWidgets/QMessageBox>
#include <QtCore/QProcess>
namespace LtsLogin
{
const int logoutShutdownTimeout = 2 * 60;
LtsLogin::LtsLogin()
: m_loginApp(nullptr), m_shutdownAction(AssetManagement::ShutdownAction::NoAction), m_isInLogoutDialog(false)
{
}
LtsLogin::~LtsLogin()
{
delete m_loginApp;
m_loginApp = nullptr;
}
void LtsLogin::login()
{
LtsAppDescriptor::PluginInfo opmDataPlugin;
opmDataPlugin.iid = QStringLiteral("opm");
opmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo pdmDataPlugin;
pdmDataPlugin.iid = QStringLiteral("pdm");
pdmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo asmDataPlugin;
asmDataPlugin.iid = QStringLiteral("asm");
asmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo srmDataPlugin;
srmDataPlugin.iid = QStringLiteral("srm");
srmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA;
LtsAppDescriptor::PluginInfo guiPlugin;
guiPlugin.iid = m_loginPluginIid;
guiPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI;
guiPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD;
QVector<LtsAppDescriptor::PluginInfo> plugins;
plugins.append(opmDataPlugin);
plugins.append(pdmDataPlugin);
plugins.append(asmDataPlugin);
plugins.append(srmDataPlugin);
plugins.append(guiPlugin);
LtsAppDescriptor::AppDescription app;
app.active = true;
app.appName = QStringLiteral("Login");
app.pluginInfos = plugins;
LtsSession::DdsConnectionParams connParams;
connParams.domainId = LtsSessionData::LtsSessionData::getInstance()->getDomainIdPreset();
connParams.tcpConnectionUrl = LtsSessionData::LtsSessionData::getInstance()->getTcpConnectionUrl();
connParams.partitionType = IDL::PartitionType::Global;
connParams.partitionId = 0;
m_loginApp = new LtsPluginManager::LtsPluginManager();
bool result = m_loginApp->startApp(app, true, connParams);
if (!result)
{
qWarning() << "no login plugin - probably an offline project";
emit signalLoginDone();
return;
}
connect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this, [this]() {
disconnect(m_loginApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this, nullptr);
LtsSession::LtsSession* session = getAdminSession();
if (!session)
{
qCritical() << "I cannot find the Admin Session :( - abort!";
QMessageBox::critical(nullptr, tr("Error loading login app"), tr("Could not load login app - abort."));
abort();
}
if (session->isInitializationDone())
QMetaObject::invokeMethod(this, &LtsLogin::slotLoginDone);
else
connect(session, &LtsSession::LtsSession::signalDoneInitializingSession, this, &LtsLogin::slotLoginDone,
Qt::UniqueConnection);
});
}
void LtsLogin::slotLoginDone()
{
LtsSession::LtsSession* session = getAdminSession();
if (session != nullptr)
{
disconnect(session, &LtsSession::LtsSession::signalDoneInitializingSession, this, &LtsLogin::slotLoginDone);
if (session->getDtc<AssetManagement::DataInterface>(m_asmDtc))
{
m_asmDtc->enableWorkstationLogout();
connect(m_asmDtc.get(), &AssetManagement::Interface::Dtc::workstationLogoutChanged, this,
&LtsLogin::slotLogoutShutdown);
}
else
qWarning() << "LtsLogin: no asm dtc, no remote logout/shutdown!";
}
else
{
qCritical() << "LtsLogin: no admin session for login!!";
QMessageBox::critical(nullptr, tr("Login error"), tr("Could not finalize login - abort."));
abort();
}
emit signalLoginDone();
}
void LtsLogin::showLogoutInformationDialog(AssetManagement::ShutdownAction action)
{
LogoutInformationDialog* lid = new LogoutInformationDialog(logoutShutdownTimeout, action, nullptr);
connect(lid, &LogoutInformationDialog::accepted, this, [this, action]() {
m_shutdownAction = action;
m_isInLogoutDialog = false;
emit signalLogout();
});
connect(lid, &LogoutInformationDialog::rejected, this, [this]() { m_isInLogoutDialog = false; });
lid->show();
}
void LtsLogin::slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType)
{
if (m_isInLogoutDialog)
return;
if (m_asmDtc == nullptr || modType != DataModification::eAdded)
return;
if (!m_asmDtc->isAssetEnabled())
m_asmDtc->enableAsset();
for (int id : data.ids)
{
if (QString::fromStdString(m_asmDtc->asset(id).name)
.compare(LtsSession::LtsSession::workstationName(), Qt::CaseInsensitive) == 0)
{
m_isInLogoutDialog = true;
showLogoutInformationDialog(data.shutdownAction);
break;
}
}
}
LtsSession::LtsSession* LtsLogin::getAdminSession()
{
return m_loginApp->m_sessionManager->getSession(IDL::PartitionType::Global, 0);
}
void LtsLogin::logoff()
{
if (m_loginApp == nullptr)
{
qCritical() << "LtsLogin::logoff: missing login app!";
return;
}
LtsSession::LtsSession* datSession = getAdminSession();
if (!datSession)
{
qCritical() << "LtsLogin::logoff: no admin session for logout!";
abort();
}
int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId();
int workstationId = LtsSessionData::LtsSessionData::getInstance()->getWorkstationId();
LtsSessionData::LtsSessionData::getInstance()->clear();
std::shared_ptr<OperatorManagement::Interface::Ftc> opmFtc;
if (operatorId == -1 || !datSession->getFtc<OperatorManagement::DataInterface>(opmFtc))
{
}
else
{
try
{
LtsUtils::OperatorSettings* os = LtsUtils::OperatorSettings::getInstance();
const QByteArray settings = os->exportSettings();
const auto vec(LtsUtils::convert<std::vector<uint8_t>>(settings));
os->clear();
opmFtc->operatorGetSetSettingsRequest(OperatorManagement::OperatorGetSetSettingsRequest(operatorId, vec));
}
catch (const std::runtime_error& err)
{
qCritical() << "Saving operator settings failed!" << err.what();
}
std::shared_ptr<SituationReplayManagement::ForeignDataInterface> srmIfc;
if (datSession->getForeignDataInterface<SituationReplayManagement::DataInterface>(srmIfc))
{
try
{
srmIfc->removeReplayPartitionsWorkstation(workstationId);
}
catch (const std::runtime_error& err)
{
qCritical() << "Removing reply partitions from this workstation failed!" << err.what();
}
try
{
srmIfc->removeReplayPartitionsOperator(operatorId);
}
catch (const std::runtime_error& err)
{
qCritical() << "Removing reply partitions from this operator failed!" << err.what();
}
}
try
{
opmFtc->operatorLogoutRequest(OperatorManagement::OperatorLogoutRequest(operatorId));
}
catch (const std::runtime_error& err)
{
qCritical() << "Logout failed!" << err.what();
}
}
m_loginApp->deleteLater();
m_loginApp = nullptr;
QString cmd;
switch (m_shutdownAction)
{
case AssetManagement::ShutdownAction::Shutdown:
#ifdef LTS_DEBUG
cmd = QStringLiteral("xeyes");
#else
cmd = QStringLiteral("systemctl poweroff");
#endif
break;
case AssetManagement::ShutdownAction::Reboot:
#ifdef LTS_DEBUG
cmd = QStringLiteral("kcalc");
#else
cmd = QStringLiteral("systemctl reboot");
#endif
break;
case AssetManagement::ShutdownAction::Logout:
case AssetManagement::ShutdownAction::NoAction:
emit signalLogoffDone();
break;
}
if (!cmd.isEmpty())
{
QProcess::startDetached(cmd);
QCoreApplication::quit();
}
}
} // namespace LtsLogin
@@ -1,71 +0,0 @@
#pragma once
#include <AssetManagement/asm_data_plugin_interface.h>
#include <OperatorManagement/opm_data_plugin_interface.h>
#include <SituationReplayManagement/srm_data_plugin_interface.h>
#include <QtCore/QObject>
#include <ltslogin_export.h>
namespace LtsPluginManager
{
class LtsPluginManager;
}
namespace LtsUtils
{
class RequestHelper;
}
namespace LtsSession
{
class LtsSession;
}
namespace DeveloperTools
{
class DevDialog;
}
namespace LtsLogin
{
class LTSLOGIN_EXPORT LtsLogin : public QObject
{
Q_OBJECT
public:
LtsLogin();
~LtsLogin();
void login();
void logoff();
void setLoginPlugin(const QString& loginPluginIid)
{
m_loginPluginIid = loginPluginIid;
}
private:
friend class DeveloperTools::DevDialog;
LtsSession::LtsSession* getAdminSession();
void showLogoutInformationDialog(AssetManagement::ShutdownAction action);
LtsPluginManager::LtsPluginManager* m_loginApp;
AssetManagement::ShutdownAction m_shutdownAction;
std::shared_ptr<AssetManagement::Interface::Dtc> m_asmDtc;
QString m_loginPluginIid;
bool m_isInLogoutDialog;
private slots:
void slotLoginDone();
void slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType);
signals:
void signalLogout();
void signalStopBlock();
void signalLoginDone();
void signalLogoffDone();
};
} // namespace LtsLogin
@@ -1,50 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
#
# Created by Christian Ehrlicher, SLSE, 2017-12-05
#
if(QT6_GUI_AVAILABLE)
find_package(KDReports QUIET)
endif()
SET(SRCS
printing_base.cpp
printing_base.h
printing.cpp
printing.h
)
# Legacy always built the real LtsPrinting when KDReports was available
# (FIND_PACKAGE(KDReports REQUIRED)); it is a common lib consumed by many
# targets (e.g. SitmapGuiPlugin::doPrint -> LtsPrinting::printImage), so it must
# NOT be gated on the BUILD_CODIFICATION product flag (which only bundles the
# CodificationManagement/ReportViewer plugins). Build the real lib whenever
# KDReports is found; keep the stub only as a KDReports-absent fallback.
if (KDReports_FOUND AND QT6_GUI_AVAILABLE)
NGL_ADD_LIBRARY2(WS LtsPrinting SHARED ${SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsPrinting
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(LtsPrinting
PRIVATE
KDReports::KDReports
LtsSessionData
LtsSession
nglsettings
ngltools
PUBLIC
Qt6::PrintSupport
Qt6::Core
)
endif()
NGL_INSTALL_TARGET(LtsPrinting)
else()
message(STATUS "KDReports not found or Qt6 GUI unavailable; building LtsPrinting stub (link-only, no printing symbols)")
add_library(LtsPrinting SHARED lts_printing_stub.cpp)
NGL_INSTALL_TARGET(LtsPrinting)
endif()
@@ -1,14 +0,0 @@
// LtsPrinting link stub for the Qt6 migration.
//
// The real LtsPrinting library requires KDReports (a Qt5/KDE print-reporting
// library that is not available in the Qt6 toolchain). When KDReports is not
// found the real library is skipped (see CMakeLists.txt); this stub provides a
// linkable `LtsPrinting` target so that consumers referencing the target name
// (e.g. SmoCheckButtonHandler) still link. It exports no printing symbols.
namespace lts_printing_stub
{
int lts_printing_stub_marker()
{
return 0;
}
}
@@ -1,386 +0,0 @@
#include "printing.h"
#include "printing_base.h"
#include <KDReports/KDReportsReport>
#include <LtsSession/lts_session.h>
#include <LtsSession/lts_session_data.h>
#include <LtsWidgets/lts_base_layout_widget.h>
#include <QtCore/QAbstractItemModel>
#include <QtCore/QDebug>
#include <QtGui/QImage>
#include <QtWidgets/QLabel>
#include <QtWidgets/QListView>
#include <QtGui/QPainter>
#include <QPrintDialog>
#include <QPrinter>
#include <QtCore/QString>
#include <QtWidgets/QTableView>
#include <QtWidgets/QTableWidget>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocument>
#include <QtWidgets/QTextEdit>
#include <QTextTable>
#include <QtWidgets/QTreeView>
namespace LtsPrinting
{
bool itemsHaveNoChildren(const QTreeView* view)
{
const QAbstractItemModel* itemModel = view->model();
int rowCount = itemModel->rowCount();
for (int row = 0; row < rowCount; ++row)
{
if (itemModel->hasChildren(itemModel->index(row, 0)))
return false;
}
return true;
}
void setNameOfExerciseAndOperator(LtsSession::LtsSession* session, LtsPrinting::Base& nglPrinter)
{
if (session->exerciseId() != 0)
nglPrinter.setCurrentExerciseName(
QObject::tr("Exercise: %1 %2").arg(session->exerciseData()->exName, session->exerciseData()->phName));
else
nglPrinter.setCurrentExerciseName(QObject::tr("Exercise: Administration"));
LtsSessionData::LtsSessionData* sessionData = LtsSessionData::LtsSessionData::getInstance();
nglPrinter.setOperatorName(sessionData->getOperatorName());
}
void printView(LtsSession::LtsSession* session, QWidget* dialogParent, const QAbstractItemView* view,
const QString& headingHtml)
{
const QTableView* tableView = dynamic_cast<const QTableView*>(view);
const QTreeView* treeView = dynamic_cast<const QTreeView*>(view);
QSet<int> hiddenCols;
int switchNum = 0;
if (tableView != nullptr)
{
switchNum = 1;
hiddenCols = LtsPrinting::Base::getHiddenCols(tableView);
}
else if (treeView != nullptr)
{
switchNum = 2;
hiddenCols = LtsPrinting::Base::getHiddenCols(treeView);
if (itemsHaveNoChildren(treeView))
switchNum = 1;
}
else if (dynamic_cast<const QListView*>(view) != nullptr)
switchNum = 3;
else
{
return;
}
QTextDocument doc;
QTextCursor cursor(&doc);
doc.setMetaInformation(QTextDocument::DocumentTitle, dialogParent->windowTitle());
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(dialogParent->windowTitle()),
dialogParent->windowTitle(), QPageSize(QPageSize::A4), QPageLayout::Landscape);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
cursor.movePosition(QTextCursor::End);
QString htmlStr;
switch (switchNum)
{
case 1:
nglPrinter.printTableData(htmlStr, view, QString(), hiddenCols);
break;
case 2:
nglPrinter.printTreeData(htmlStr, view, QString(), hiddenCols);
break;
case 3:
nglPrinter.printListData(htmlStr, view, QString());
break;
}
cursor.insertHtml(headingHtml);
cursor.insertHtml(htmlStr);
nglPrinter.print(&doc);
}
void printView(LtsSession::LtsSession* session, QWidget* dialogParent, QAbstractItemView* view,
const QString& headingHtml)
{
const QAbstractItemView* itemView = static_cast<const QAbstractItemView*>(view);
printView(session, dialogParent, itemView, headingHtml);
}
void printImage(LtsSession::LtsSession* session, QWidget* dialogParent, const QImage& image, const QString& imageTitle,
const QString& description, const QPageSize& pageSize,
const QPageLayout::Orientation& pageOrientation)
{
QTextDocument doc;
QTextCursor cursor(&doc);
QString windowTitle = dialogParent->windowTitle();
doc.setMetaInformation(QTextDocument::DocumentTitle, dialogParent->windowTitle());
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(windowTitle), windowTitle, pageSize,
pageOrientation);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
cursor.movePosition(QTextCursor::End);
nglPrinter.printDocImage(doc, image, imageTitle, description);
nglPrinter.print(&doc);
}
void printImages(LtsSession::LtsSession* session, QWidget* dialogParent, const QString& docName,
QVector<QImage>& images, QVector<QString>& imageTitles, QVector<QString>& descriptions,
const QPageSize& pageSize, const QPageLayout::Orientation& pageOrientation)
{
QTextDocument doc;
QTextCursor cursor(&doc);
doc.setMetaInformation(QTextDocument::DocumentTitle, docName);
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(docName), docName, pageSize,
pageOrientation);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
cursor.movePosition(QTextCursor::End);
for (int i = 0; i < images.size(); i++)
{
QString imageTitle, imageDescription;
if (imageTitles.size() > i && imageTitles[i].size() > 0)
imageTitle = imageTitles[i];
if (descriptions.size() > i && descriptions[i].size() > 0)
imageDescription = descriptions[i];
nglPrinter.printDocImage(doc, images[i], imageTitle, imageDescription);
nglPrinter.printSinglePage(&doc);
doc.clear();
if (i != images.size() - 1)
nglPrinter.newPage();
}
nglPrinter.printDone();
}
void printPDFImages(QWidget* dialogParent, const QString& docName, const QString& printPath, QVector<QImage>& images)
{
QPrinter printer;
printer.setColorMode(QPrinter::ColorMode::Color);
printer.setPageOrientation(QPageLayout::Portrait);
printer.setPageSize(QPageSize(QPageSize::A4));
QString fn = docName;
fn = fn.remove(QLatin1Char(' '));
fn = fn.remove(QLatin1String(".."));
fn = fn.remove(QLatin1Char('/'));
fn = printPath + fn;
if (!fn.endsWith(QLatin1String(".pdf"), Qt::CaseInsensitive))
fn += QLatin1String(".pdf");
#ifndef WIN32
printer.setOutputFileName(fn);
#endif
printer.setOutputFormat(QPrinter::NativeFormat);
QPrintDialog* dialog = new QPrintDialog(&printer, dialogParent);
dialog->setWindowTitle(QObject::tr("Print %1").arg(docName));
if (dialog->exec() != QDialog::Accepted)
return;
QPainter painter;
painter.begin(&printer);
int lastItem = images.size() - 1;
for (int i = 0; i < images.size(); ++i)
{
QRect rect = painter.viewport();
QSize size = images.at(i).size();
size.scale(rect.size(), Qt::KeepAspectRatio);
painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
painter.setWindow(images.at(i).rect());
painter.drawImage(0, 0, images.at(i));
if (i != lastItem)
printer.newPage();
}
painter.end();
}
void printReport(LtsSession::LtsSession* session, QWidget* dialogParent, KDReports::Report& report)
{
QTextDocument doc;
QTextCursor cursor(&doc);
doc.setMetaInformation(QTextDocument::DocumentTitle, dialogParent->windowTitle());
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(dialogParent->windowTitle()),
dialogParent->windowTitle(), QPageSize(QPageSize::A3), QPageLayout::Landscape);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
cursor.movePosition(QTextCursor::End);
report.setWidthForEndlessPrinter(0);
report.setPageSize(QPageSize::A3);
report.setPageOrientation(QPageLayout::Landscape);
LtsPrinting::Base::printReportData(doc, report);
nglPrinter.print(&doc);
}
void printWidget(LtsSession::LtsSession* session, QWidget* dialogParent, QWidget* widget, const QString& title)
{
QTextDocument doc;
QTextCursor cursor(&doc);
QImage image(widget->size(), QImage::Format_ARGB32);
widget->render(&image);
QString windowTitle = dialogParent->windowTitle();
doc.setMetaInformation(QTextDocument::DocumentTitle, dialogParent->windowTitle());
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(windowTitle), windowTitle,
QPageSize(QPageSize::A3), QPageLayout::Landscape);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
cursor.movePosition(QTextCursor::End);
nglPrinter.printDocImage(doc, image, title);
nglPrinter.print(&doc);
}
void printMessage(LtsSession::LtsSession* session, QWidget* dialogParent, const QString& subject,
const QString& subjectContent, const QString& from, const QString& fromContent, const QString& to,
const QString& toContent, const QString& msgTextContent, const QString& time,
const QString& timeContent)
{
QTextDocument doc;
QString windowTitle = subject;
doc.setMetaInformation(QTextDocument::DocumentTitle, subject);
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(windowTitle), windowTitle,
QPageSize(QPageSize::A4), QPageLayout::Portrait);
QString str = QString(QStringLiteral("<H2><strong>%1</strong> %2 </H2>")).arg(subject).arg(subjectContent);
str.append(QString(QStringLiteral("<strong>%1</strong> %2<br>")).arg(time).arg(timeContent));
str.append(QString(QStringLiteral("<strong>%1</strong> %2<br>")).arg(from).arg(fromContent));
str.append(QString(QStringLiteral("<strong>%1</strong> %2<hr>")).arg(to).arg(toContent));
str.append(QString(QStringLiteral("%1")).arg(msgTextContent));
doc.setHtml(str);
if (!nglPrinter.printer())
return;
setNameOfExerciseAndOperator(session, nglPrinter);
nglPrinter.print(&doc);
}
void printStoryboard(LtsSession::LtsSession* session, QWidget* dialogParent, QAbstractItemView* view,
const QString& headingHtml)
{
QTableWidget* tbl = dynamic_cast<QTableWidget*>(view);
QTextDocument doc;
QTextCursor cursor(&doc);
QTextBlockFormat tbfFormat;
tbfFormat.setPageBreakPolicy(QTextFormat::PageBreakFlag::PageBreak_Auto);
QString windowTitle = dialogParent->windowTitle();
doc.setMetaInformation(QTextDocument::DocumentTitle, dialogParent->windowTitle());
LtsPrinting::Base nglPrinter(doc, dialogParent, QObject::tr("Print %1").arg(windowTitle), windowTitle,
QPageSize(QPageSize::A4), QPageLayout::Portrait);
if (!nglPrinter.printer())
return;
const int rows = tbl->rowCount();
cursor.insertHtml(headingHtml);
double currentHeight = 0;
double previousPagesHeight = 0;
QString htmlStr;
for (int rowCounter = 0; rowCounter < rows; rowCounter++)
{
htmlStr.append(QStringLiteral("<table>"));
QTextEdit* labelForFirstCell = (QTextEdit*)tbl->cellWidget(rowCounter, 0);
QString stringFirstColumn = labelForFirstCell->toHtml();
QTextEdit* labelSecondColumn = (QTextEdit*)tbl->cellWidget(rowCounter, 1);
QString stringSecondColumn = labelSecondColumn->toHtml();
QTextEdit* labelThirdColumn = (QTextEdit*)tbl->cellWidget(rowCounter, 2);
QString stringThirdColumn = labelThirdColumn->toHtml();
for (int rowInCellCounter = 0; rowInCellCounter < stringSecondColumn.split(QStringLiteral("<br>")).size();
++rowInCellCounter)
{
htmlStr.append(QStringLiteral("<tr>"));
if (rowInCellCounter < stringFirstColumn.split(QStringLiteral("<br>")).size())
{
htmlStr.append(QStringLiteral("<td width = \"25%\">"));
htmlStr.append(stringFirstColumn.split(QStringLiteral("<br>"))[rowInCellCounter]);
htmlStr.append(QStringLiteral("</td>"));
}
else
{
htmlStr.append(QStringLiteral("<td width = \"25%\"> "));
htmlStr.append(QStringLiteral("</td>"));
}
QString currentTextSecond = stringSecondColumn.split(QStringLiteral("<br>"))[rowInCellCounter];
htmlStr.append(QStringLiteral("<td width = \"37%\">"));
htmlStr.append(currentTextSecond);
htmlStr.append(QStringLiteral("</td>"));
QString currentTextThird = stringThirdColumn.split(QStringLiteral("<br>"))[rowInCellCounter];
htmlStr.append(QStringLiteral("<td width = \"37%\">"));
htmlStr.append(currentTextThird);
htmlStr.append(QStringLiteral("</td>"));
htmlStr.append(QStringLiteral("</tr>"));
}
QTextDocument tempDoc;
tempDoc.setPageSize(doc.pageSize());
tempDoc.setHtml(htmlStr);
currentHeight = doc.size().height() - previousPagesHeight;
if (currentHeight + tempDoc.size().height() > nglPrinter.pageSizeInMM().height())
{
tbfFormat.setPageBreakPolicy(QTextFormat::PageBreakFlag::PageBreak_AlwaysBefore);
cursor.insertBlock(tbfFormat);
previousPagesHeight = doc.size().height();
currentHeight = doc.size().height() - previousPagesHeight;
}
else
{
tbfFormat.setPageBreakPolicy(QTextFormat::PageBreakFlag::PageBreak_Auto);
currentHeight = doc.size().height() - previousPagesHeight;
}
cursor.insertHtml(htmlStr);
htmlStr.clear();
}
htmlStr.append(QStringLiteral("</table>"));
cursor.insertHtml(htmlStr);
cursor.movePosition(QTextCursor::End);
setNameOfExerciseAndOperator(session, nglPrinter);
nglPrinter.print(&doc);
}
} // namespace LtsPrinting
@@ -1,68 +0,0 @@
#pragma once
#include <QtPrintSupport/QPrinter>
#include <QtGui/QPageSize>
#include <QtGui/QPageLayout>
#ifndef LTSPRINTING_EXPORT
#ifdef BUILD_STATIC_LIBRARIES
#define LTSPRINTING_EXPORT
#else
#if defined(MAKE_LTSPRINTING_LIB)
#define LTSPRINTING_EXPORT Q_DECL_EXPORT
#else
#define LTSPRINTING_EXPORT Q_DECL_IMPORT
#endif
#endif
#endif
class QWidget;
class QAbstractItemView;
class QImage;
namespace LtsSession
{
class LtsSession;
}
namespace KDReports
{
class Report;
}
namespace LtsPrinting
{
LTSPRINTING_EXPORT void printView(LtsSession::LtsSession* session, QWidget* dialogParent, const QAbstractItemView* view,
const QString& headingHtml = QString());
LTSPRINTING_EXPORT void printView(LtsSession::LtsSession* session, QWidget* dialogParent, QAbstractItemView* view,
const QString& headingHtml = QString());
LTSPRINTING_EXPORT void printStoryboard(LtsSession::LtsSession* session, QWidget* dialogParent, QAbstractItemView* view,
const QString& headingHtml = QString());
LTSPRINTING_EXPORT void printImage(LtsSession::LtsSession* session, QWidget* dialogParent, const QImage& image,
const QString& imageTitle, const QString& description,
const QPageSize& pageSize = QPageSize(QPageSize::A3),
const QPageLayout::Orientation& pageOrientation = QPageLayout::Landscape);
LTSPRINTING_EXPORT void printImages(LtsSession::LtsSession* session, QWidget* dialogParent, const QString& docName,
QVector<QImage>& images, QVector<QString>& imageTitles,
QVector<QString>& descriptions, const QPageSize& pageSize = QPageSize(QPageSize::A3),
const QPageLayout::Orientation& pageOrientation = QPageLayout::Landscape);
LTSPRINTING_EXPORT void printPDFImages(QWidget* dialogParent, const QString& docName, const QString& printPath,
QVector<QImage>& images);
LTSPRINTING_EXPORT void printReport(LtsSession::LtsSession* session, QWidget* dialogParent, KDReports::Report& report);
LTSPRINTING_EXPORT void printWidget(LtsSession::LtsSession* session, QWidget* dialogParent, QWidget* widget,
const QString& title);
LTSPRINTING_EXPORT void printMessage(LtsSession::LtsSession* session, QWidget* dialogParent, const QString& subject,
const QString& subjectContent, const QString& from, const QString& fromContent,
const QString& to, const QString& toContent, const QString& msgTextContent,
const QString& time, const QString& timeContent);
} // namespace LtsPrinting
File diff suppressed because it is too large. Load diff
@@ -1,231 +0,0 @@
#pragma once
#include <QtCore/QSet>
#include <QtPrintSupport/QPrinter>
#include <QtGui/QPageSize>
#include <QtGui/QPageLayout>
namespace NGL
{
class INGLLogger;
class Settings;
} // namespace NGL
namespace KDReports
{
class Report;
}
class QPainter;
class QAbstractItemView;
class QAbstractItemModel;
class QModelIndex;
class QTextDocument;
namespace LtsPrinting
{
static constexpr int DECORATION_EXTENT = 50;
static constexpr int DOC_MARGIN = 60;
static constexpr int ProjectIconHeight = 40;
static const QLatin1String
HeaderText("<table width=\"100%\">"
" <tr>"
" <td align=\"left\" valign=\"bottom\">&exercise;</td>"
" <td align=\"center\" valign=\"bottom\">&title;</td>"
" <td align=\"right\" valign=\"top\"><img src=\"&logo;\" height=\"&logoHeight;\" alt=\"Logo\" /></td>"
" </tr>"
"</table>");
static const QLatin1String FooterText("<table width=\"100%\">"
" <tr>"
" <td align=\"left\">&date; -- &user;</td>"
" <td align=\"center\" valign=\"bottom\">&footertitle;</td>"
" <td align=\"right\">&page;</td>"
" </tr>"
"</table>");
class Base
{
public:
Base(QTextDocument& doc, QWidget* dialogParent, const QString& dialogTitle, const QString& _fn,
QPageSize _ps = QPageSize(QPageSize::A4), QPageLayout::Orientation _or = QPageLayout::Portrait,
QPrinter::ColorMode _cm = QPrinter::Color);
virtual ~Base();
QPrinter* printer();
static void setPrintToFile(bool printToFile);
static QString styleSheet();
QPageSize pageSize() const;
void setPageSize(QPageSize size);
QPageLayout::Orientation orientation() const;
void setOrientation(QPageLayout::Orientation orientation);
bool newPage();
double leftMargin() const;
void setLeftMargin(double margin);
double rightMargin() const;
void setRightMargin(double margin);
double topMargin() const;
void setTopMargin(double margin);
double bottomMargin() const;
void setBottomMargin(double margin);
void setMargins(double margin);
double spacing() const;
void setSpacing(double spacing);
double headerSize() const;
void setHeaderSize(double size);
double headerRule() const;
void setHeaderRule(double pointsize);
const QString& headerText() const;
void setHeaderText(const QString& text);
double footerSize() const;
void setFooterSize(double size);
double footerRule() const;
void setFooterRule(double pointsize);
const QString& footerText() const;
void setFooterText(const QString& text);
void setFooterTitle(const QString& footertitle)
{
footertitle_ = footertitle;
}
void setItemFontSize(int itemFontSize);
static void printTitleData(QString& htmlStr, const QString& title, const QString& heading = QStringLiteral("h3"));
bool printListData(QString& str, const QAbstractItemView* view, const QString& title, bool asIcons = false,
int iconExtent = DECORATION_EXTENT);
bool printTableData(QString& str, const QAbstractItemView* view, const QString& title = QString(),
const QSet<int>& suppressCols = QSet<int>(), int iconExtent = DECORATION_EXTENT);
bool printTreeData(QString& str, const QAbstractItemView* view, const QString& title = QString(),
const QSet<int>& suppressCols = QSet<int>(), int iconExtent = DECORATION_EXTENT,
const QList<QString>& tabtexts = QList<QString>());
static bool printDocTextBlock(QTextDocument& doc, const QString& text, const QString& title = QString());
bool printDocImage(QTextDocument& doc, const QImage& image, const QString& title = QString(),
const QString& description = QString(), const qreal alreadyUsedHeight = 0) const;
static bool printReportData(QTextDocument& doc, KDReports::Report& report);
virtual void print(QTextDocument* doc);
virtual void printSinglePage(QTextDocument* doc);
virtual void printDone();
template <class T> static QSet<int> getHiddenCols(T* view)
{
QSet<int> hiddenCols;
int colCount = view->model()->columnCount();
for (int i = 0; i < colCount; ++i)
{
if (view->isColumnHidden(i))
hiddenCols += i;
}
return hiddenCols;
}
void setCurrentExerciseName(const QString& exerciseName);
void setOperatorName(const QString& operatorName);
void paintPage(QTextDocument* document, int pagenum);
QSize pageSizeInMM();
protected:
NGL::INGLLogger& m_logger;
bool printTableItemData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi, int rowSpanSize,
int columnSpanSize, int iconExtent = DECORATION_EXTENT);
bool printItemData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi,
int iconExtent = DECORATION_EXTENT);
void printDecorationData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi,
int iconExtent = DECORATION_EXTENT);
void printListPoint(QString& str, const QAbstractItemView* view, const QAbstractItemModel* vm,
const QModelIndex& miColumn0, const QSet<int>& suppressCols = QSet<int>(),
int iconExtent = DECORATION_EXTENT);
static int hierarchyCount(const QModelIndex& child);
QString iconFilename(int nr) const;
QSize printerPageSize() const;
QSize contentPageSize() const;
QString currentExerciseName() const;
QString operatorName() const;
QRectF paperRect(QPaintDevice* device);
QRectF contentRect(QPaintDevice* device);
QRectF headerRect(QPaintDevice* device);
QRectF footerRect(QPaintDevice* device);
void printSinglePage();
void print();
private:
QPrinter* m_printer;
QPainter* m_painter;
static bool m_printToFile;
int m_iconFilenameNr;
QTextDocument* m_tempdoc;
double leftmargin_;
double rightmargin_;
double topmargin_;
double bottommargin_;
double spacing_;
double headersize_;
double headerrule_;
QString headertext_;
double footersize_;
double footerrule_;
QString footertext_;
QString footertitle_;
int itemFontSize_;
private:
NGL::Settings* m_settings;
QString m_exerciseName;
QString m_operatorName;
int m_currentPage;
};
} // namespace LtsPrinting
@@ -1,57 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
# Created by Christian Roeskens, NLSE, 2018-03-02
# Make ${Qt6_Gui} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Gui)
set(Qt6_Gui ${Qt6_Gui})
else()
set(Qt6_Gui "")
endif()
SET(LtsProjectionWorkstation_SRCS
lts_projection_workstation.h
lts_projection_workstation.cpp
lts_projection_workstation_export.h
vnc_server_manager.h
vnc_server_manager.cpp
logger.cpp
logger.h
WebSocket/json_keys.h
WebSocket/messages.h
WebSocket/messages.cpp
WebSocket/message_factory.h
WebSocket/message_factory.cpp
)
NGL_ADD_LIBRARY2(WS LtsProjectionWorkstation SHARED ${LtsProjectionWorkstation_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsProjectionWorkstation
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(LtsProjectionWorkstation
PUBLIC
Qt6::Core
PRIVATE
${Qt6_Gui}
NGLLogger
nglsettings
LtsWebSocketServer
LtsSession
LtsSessionData
)
endif()
NGL_INSTALL_TARGET(LtsProjectionWorkstation)
@@ -1,56 +0,0 @@
#include "client_message.h"
#include "json_keys.h"
#include "message_handler.h"
namespace LtsProjectionWorkstation
{
LtsWebSocket::AbstractClientMessage* ClientMessageFactory::createMessage(LtsWebSocket::ReplyHandler* client,
const QString& message)
{
LtsWebSocket::AbstractClientMessage* result = checkAttributes(client, message);
if (result)
return result;
if (m_type == JsonKeys::LOGIN_REQUEST())
result = new LoginRequest(m_messageHandler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::LOGOUT_REQUEST())
result = new LoginRequest(m_messageHandler, client, m_type, m_uuid, m_data);
return checkResult(client, message, result);
}
void LoginRequest::process()
{
if (hasValidData())
{
int userId = m_data.toObject().value(JsonKeys::USER_ID()).toInt(-1),
userPriority = m_data.toObject().value(JsonKeys::USER_PRIORITY()).toInt(-1),
exerciseId = m_data.toObject().value(JsonKeys::EXERCISE_ID()).toInt(-1);
m_client->addReply(m_messageHandler->handleLoginRequest(userId, userPriority, exerciseId));
}
}
bool LoginRequest::hasValidData() const
{
return m_data.isObject() && m_data.toObject().value(JsonKeys::USER_ID()).toInt(-1) > -1 &&
m_data.toObject().value(JsonKeys::USER_PRIORITY()).toInt(-1) > -1 &&
m_data.toObject().value(JsonKeys::EXERCISE_ID()).toInt(-1) > -1;
}
void LogoutRequest::process()
{
m_client->addReply(m_messageHandler->handleLogoutRequest());
}
bool LogoutRequest::hasValidData() const
{
return true;
}
} // namespace LtsProjectionWorkstation
@@ -1,68 +0,0 @@
#pragma once
#include "logger.h"
#include <LtsWebSocket/client_message_factory.h>
namespace LtsProjectionWorkstation
{
class MessageHandler;
class ClientMessageFactory : public LtsWebSocket::AbstractClientMessageFactory
{
public:
explicit ClientMessageFactory(MessageHandler* messageHandler)
: LtsWebSocket::AbstractClientMessageFactory(getLogger("ClientMessageFactory")),
m_messageHandler(messageHandler)
{
}
LtsWebSocket::AbstractClientMessage* createMessage(LtsWebSocket::ReplyHandler* client,
const QString& message) override final;
private:
MessageHandler* m_messageHandler;
};
class ClientMessage : public LtsWebSocket::AbstractClientMessage
{
public:
explicit ClientMessage(MessageHandler* messageHandler, LtsWebSocket::ReplyHandler* client, const QString& type,
const QString& uuid, const QJsonValue& data)
: AbstractClientMessage(client, type, uuid, data), m_messageHandler(messageHandler)
{
}
protected:
MessageHandler* m_messageHandler;
};
class LoginRequest : public ClientMessage
{
public:
explicit LoginRequest(MessageHandler* messageHandler, LtsWebSocket::ReplyHandler* client, const QString& type,
const QString& uuid, const QJsonValue& data)
: ClientMessage(messageHandler, client, type, uuid, data)
{
}
void process();
bool hasValidData() const;
};
class LogoutRequest : public ClientMessage
{
public:
explicit LogoutRequest(MessageHandler* messageHandler, LtsWebSocket::ReplyHandler* client, const QString& type,
const QString& uuid, const QJsonValue& data)
: ClientMessage(messageHandler, client, type, uuid, data)
{
}
void process();
bool hasValidData() const;
};
} // namespace LtsProjectionWorkstation
@@ -1,100 +0,0 @@
#pragma once
#include <QtCore/QString>
namespace LtsProjectionWorkstation::JsonKeys
{
inline QString ERROR_MESSAGE()
{
return QStringLiteral("errorMessage");
}
inline QString LOGIN_REQUEST()
{
return QStringLiteral("loginRequest");
}
inline QString LOGOUT_REQUEST()
{
return QStringLiteral("logoutRequest");
}
inline QString DISCONNECT_REQUEST()
{
return QStringLiteral("disconnectRequest");
}
inline QString LOGIN_REPLY()
{
return QStringLiteral("loginReply");
}
inline QString LOGOUT_REPLY()
{
return QStringLiteral("logoutReply");
}
inline QString DEDICAED_DISCONNECT()
{
return QStringLiteral("dedicatedDisconnect");
}
inline QString USER_ID()
{
return QStringLiteral("userId");
}
inline QString USER_PRIORITY()
{
return QStringLiteral("userPriority");
}
inline QString EXERCISE_ID()
{
return QStringLiteral("exerciseId");
}
inline QString NAME()
{
return QStringLiteral("name");
}
inline QString PORT()
{
return QStringLiteral("port");
}
inline QString WIDTH()
{
return QStringLiteral("width");
}
inline QString HEIGHT()
{
return QStringLiteral("height");
}
inline QString REASON()
{
return QStringLiteral("reason");
}
inline QString SUCCESS()
{
return QStringLiteral("success");
}
inline QString SCREENS()
{
return QStringLiteral("screens");
}
inline QString SETTINGS_DATA()
{
return QStringLiteral("settingsData");
}
} // namespace LtsProjectionWorkstation::JsonKeys
@@ -1,53 +0,0 @@
#include "message_factory.h"
#include "json_keys.h"
#include "messages.h"
#include <LtsWebSocket/client_message.h>
#include <LtsWebSocket/json_keys.h>
#include <QtCore/QUuid>
namespace LtsProjectionWorkstation
{
LtsWebSocket::AbstractClientMessage* MessageFactory::createMessage(LtsWebSocket::ReplyHandler* client,
const QString& message)
{
if (m_uuid.isEmpty())
{
WARNING_LOG(m_logger) << "Got message without uuid: " << message << "'";
WARNING_LOG(m_logger) << "Created UUID for error message!";
return new ErrorMessage(QUuid::createUuid().toString(), QStringLiteral("Got message without uuid"));
}
LtsWebSocket::AbstractClientMessage* result = checkAttributes(client, message);
if (result)
return result;
if (m_type == JsonKeys::DEDICAED_DISCONNECT())
result = new STC::DedicatedDisconnect(m_handler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::LOGIN_REPLY())
result = new STC::LoginRequestReply(m_handler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::LOGOUT_REPLY())
result = new STC::LoginRequestReply(m_handler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::LOGIN_REQUEST())
result = new CTS::LoginRequest(m_handler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::LOGOUT_REQUEST())
result = new CTS::LogoutRequest(m_handler, client, m_type, m_uuid, m_data);
if (m_type == JsonKeys::DISCONNECT_REQUEST())
result = new CTS::DisconnectRequest(m_handler, client, m_type, m_uuid, m_data);
if (m_type == LtsWebSocket::JsonKeys::ERROR_())
return nullptr;
return checkResult(client, message, result);
}
} // namespace LtsProjectionWorkstation
@@ -1,29 +0,0 @@
#pragma once
#include "ltsprojectionworkstation_export.h"
#include <LtsProjectionWorkstation/logger.h>
#include <LtsWebSocket/client_message_factory.h>
namespace LtsProjectionWorkstation
{
class AbstractMessageHandler;
class LTSPROJECTIONWORKSTATION_EXPORT MessageFactory : public LtsWebSocket::AbstractClientMessageFactory
{
public:
MessageFactory(AbstractMessageHandler* handler, LOGGER_T& logger)
: LtsWebSocket::AbstractClientMessageFactory(logger), m_handler(handler)
{
}
LtsWebSocket::AbstractClientMessage* createMessage(LtsWebSocket::ReplyHandler* client,
const QString& message) override final;
private:
AbstractMessageHandler* m_handler;
};
} // namespace LtsProjectionWorkstation
@@ -1,211 +0,0 @@
#include "messages.h"
#include <QtCore/QDebug>
#include <QtCore/QJsonArray>
namespace LtsProjectionWorkstation
{
STC::LoginRequestReply::LoginRequestReply(const QString& uuid, Reason reason, int reasonUserId,
const QVector<VncScreen>& screens)
: Message(nullptr, nullptr, JsonKeys::LOGIN_REPLY(), uuid, QJsonValue()), m_screens(screens),
m_reasonUserId(reasonUserId), m_reason(reason)
{
QJsonObject result;
QJsonArray arr;
for (const VncScreen& vncScreen : screens)
{
QJsonObject screen;
screen.insert(JsonKeys::NAME(), vncScreen.name);
screen.insert(JsonKeys::PORT(), vncScreen.port);
screen.insert(JsonKeys::WIDTH(), vncScreen.geometry.width());
screen.insert(JsonKeys::HEIGHT(), vncScreen.geometry.height());
arr.append(screen);
}
result.insert(JsonKeys::REASON(), reason);
result.insert(JsonKeys::USER_ID(), reasonUserId);
result.insert(JsonKeys::SCREENS(), arr);
m_replyData = QJsonValue(result);
}
void STC::LoginRequestReply::process()
{
if (!m_handler || !m_client)
return;
QJsonObject dataObj = m_data.toObject();
m_reason = Reason(dataObj.value(JsonKeys::REASON()).toInt());
m_reasonUserId = dataObj.value(JsonKeys::USER_ID()).toInt();
const auto arr = dataObj.value(JsonKeys::SCREENS()).toArray();
for (const QJsonValue& val : arr)
{
const QJsonObject obj(val.toObject());
VncScreen screen;
screen.name = obj.value(JsonKeys::NAME()).toString(QStringLiteral("err"));
screen.port = obj.value(JsonKeys::PORT()).toInt(-1);
screen.geometry = QRect(0, 0, obj.value(JsonKeys::WIDTH()).toInt(-1), obj.value(JsonKeys::HEIGHT()).toInt(-1));
m_screens.append(std::move(screen));
}
m_handler->handleMessage(this);
}
bool STC::LoginRequestReply::hasValidData() const
{
if (!m_handler || !m_client)
return false;
QJsonObject obj = m_data.toObject();
if (obj.value(JsonKeys::REASON()).isUndefined())
return false;
if (obj.value(JsonKeys::USER_ID()).isUndefined())
return false;
if (obj.value(JsonKeys::SCREENS()).isUndefined())
return false;
return true;
}
STC::DedicatedDisconnect::DedicatedDisconnect(const QString& uuid, int userId)
: Message(nullptr, nullptr, JsonKeys::DEDICAED_DISCONNECT(), uuid, QJsonValue()), m_userId(userId)
{
QJsonObject result;
result.insert(JsonKeys::USER_ID(), m_userId);
m_replyData = result;
}
void STC::DedicatedDisconnect::process()
{
if (!m_handler || !m_client)
return;
QJsonObject obj = m_data.toObject();
m_userId = obj.value(JsonKeys::USER_ID()).toInt(-1);
m_handler->handleMessage(this);
}
bool STC::DedicatedDisconnect::hasValidData() const
{
if (!m_handler || !m_client)
return false;
QJsonObject obj = m_data.toObject();
if (obj.value(JsonKeys::USER_ID()).isUndefined())
return false;
return true;
}
CTS::LoginRequest::LoginRequest(const QString& uuid, int userId, int priority, int exerciseId,
const QByteArray& settingsData)
: Message(nullptr, nullptr, JsonKeys::LOGIN_REQUEST(), uuid, QJsonValue()), m_settingsData(settingsData),
m_userId(userId), m_priority(priority), m_exerciseId(exerciseId)
{
QJsonObject result;
result.insert(JsonKeys::USER_ID(), m_userId);
result.insert(JsonKeys::USER_PRIORITY(), m_priority);
result.insert(JsonKeys::EXERCISE_ID(), m_exerciseId);
result.insert(JsonKeys::SETTINGS_DATA(), QString::fromLatin1(m_settingsData.toBase64()));
m_replyData = result;
}
void CTS::LoginRequest::process()
{
if (!m_handler || !m_client)
return;
QJsonObject obj = m_data.toObject();
m_userId = obj.value(JsonKeys::USER_ID()).toInt(-1);
m_priority = obj.value(JsonKeys::USER_PRIORITY()).toInt(-1);
m_exerciseId = obj.value(JsonKeys::EXERCISE_ID()).toInt(-1);
m_settingsData = QByteArray::fromBase64(obj.value(JsonKeys::SETTINGS_DATA()).toString().toLatin1());
m_handler->handleMessage(this);
}
bool CTS::LoginRequest::hasValidData() const
{
if (!m_handler || !m_client)
return false;
QJsonObject obj = m_data.toObject();
if (obj.value(JsonKeys::USER_ID()).isUndefined())
return false;
if (obj.value(JsonKeys::EXERCISE_ID()).isUndefined())
return false;
if (obj.value(JsonKeys::USER_PRIORITY()).isUndefined())
return false;
if (obj.value(JsonKeys::SETTINGS_DATA()).isUndefined())
return false;
return true;
}
void CTS::LogoutRequest::process()
{
if (!m_handler || !m_client)
return;
m_handler->handleMessage(this);
}
bool CTS::LogoutRequest::hasValidData() const
{
if (!m_handler || !m_client)
return false;
return true;
}
CTS::DisconnectRequest::DisconnectRequest(const QString& uuid, int userId)
: Message(nullptr, nullptr, JsonKeys::DISCONNECT_REQUEST(), uuid, QJsonValue()), m_userId(userId)
{
qDebug() << " 1 m_userId = " << m_userId;
QJsonObject result;
result.insert(JsonKeys::USER_ID(), m_userId);
m_replyData = result;
}
void CTS::DisconnectRequest::process()
{
if (!m_handler || !m_client)
return;
QJsonObject obj = m_data.toObject();
m_userId = obj.value(JsonKeys::USER_ID()).toInt(-1);
qDebug() << " 2 m_userId = " << m_userId;
m_handler->handleMessage(this);
}
bool CTS::DisconnectRequest::hasValidData() const
{
if (!m_handler || !m_client)
return false;
QJsonObject obj = m_data.toObject();
if (obj.value(JsonKeys::USER_ID()).isUndefined())
return false;
return true;
}
// Unqualified: we are already inside namespace LtsProjectionWorkstation, and the unity
// build concatenates lts_projection_workstation.cpp (which declares
// class LtsProjectionWorkstation in this same namespace) into this TU, so
// "LtsProjectionWorkstation::ErrorMessage" would resolve to the class (which has no
// such member) instead of the namespace. In a separate TU (legacy structure) the
// class is not visible here and the qualified name resolved to the namespace.
ErrorMessage::ErrorMessage(const QString& uuid, const QString& reason)
: Message(nullptr, nullptr, JsonKeys::ERROR_MESSAGE(), uuid, QJsonValue()), m_reason(reason)
{
QJsonObject result;
result.insert(JsonKeys::REASON(), m_reason);
m_replyData = result;
}
void ErrorMessage::process()
{
if (!m_handler || !m_client)
return;
QJsonObject obj = m_data.toObject();
m_reason = obj.value(JsonKeys::REASON()).toString(QStringLiteral("err"));
m_handler->handleMessage(this);
}
bool ErrorMessage::hasValidData() const
{
if (!m_handler || !m_client)
return false;
QJsonObject obj = m_data.toObject();
if (obj.value(JsonKeys::REASON()).isUndefined())
return false;
return true;
}
} // namespace LtsProjectionWorkstation
@@ -1,209 +0,0 @@
#pragma once
#include "json_keys.h"
#include "LtsProjectionWorkstation/ltsprojectionworkstation_export.h"
#include <LtsProjectionWorkstation/vnc_server_manager.h>
#include <LtsWebSocket/client_message.h>
#include <LtsWebSocket/json_keys.h>
#include <QtCore/QVector>
namespace LtsWebSocket
{
class ReplyHandler;
}
namespace LtsProjectionWorkstation
{
class AbstractMessageHandler
{
public:
virtual ~AbstractMessageHandler() = default;
virtual void handleMessage(LtsWebSocket::AbstractClientMessage* message) = 0;
};
class Reply : public LtsWebSocket::ReplyMessage
{
public:
Reply(const QString& type, const int typeId, const QString& uuid, const QJsonObject& data)
: LtsWebSocket::ReplyMessage(type, typeId, uuid)
{
m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data);
}
};
class Message : public LtsWebSocket::AbstractClientMessage
{
public:
Message(AbstractMessageHandler* handler, LtsWebSocket::ReplyHandler* client, const QString& type,
const QString& uuid, const QJsonValue& data = QJsonValue())
: LtsWebSocket::AbstractClientMessage(client, type, 1, uuid, data), m_handler(handler)
{
}
LtsWebSocket::ReplyMessage* toReplyMessage() const
{
if (!m_handler || !m_client)
return new Reply(m_type, m_typeId, m_uuid, m_replyData.toObject());
return nullptr;
}
void addReply(LtsWebSocket::ReplyMessage* reply)
{
if (m_client)
m_client->addReply(reply);
}
protected:
AbstractMessageHandler* m_handler;
QJsonValue m_replyData;
};
class LTSPROJECTIONWORKSTATION_EXPORT ErrorMessage : public Message
{
public:
using Message::Message;
ErrorMessage(const QString& uuid, const QString& reason);
void process() override final;
bool hasValidData() const override final;
private:
QString m_reason;
};
namespace STC
{
class LTSPROJECTIONWORKSTATION_EXPORT LoginRequestReply : public Message
{
public:
enum Reason {
LoginSuccessful,
OtherUser,
};
using Message::Message;
LoginRequestReply(const QString& uuid, Reason reason, int reasonUserId, const QVector<VncScreen>& screens);
void process() override final;
bool hasValidData() const override final;
int reasonUserId() const
{
return m_reasonUserId;
}
Reason reason() const
{
return m_reason;
}
const QVector<VncScreen>& screens() const
{
return m_screens;
}
private:
QVector<VncScreen> m_screens;
int m_reasonUserId = -1;
Reason m_reason = LoginSuccessful;
};
class LTSPROJECTIONWORKSTATION_EXPORT DedicatedDisconnect : public Message
{
public:
using Message::Message;
DedicatedDisconnect(const QString& uuid, int userId);
void process() override final;
bool hasValidData() const override final;
int userid() const
{
return m_userId;
}
private:
int m_userId = -1;
};
} // namespace STC
namespace CTS
{
class LTSPROJECTIONWORKSTATION_EXPORT LoginRequest : public Message
{
public:
using Message::Message;
LoginRequest(const QString& uuid, int userId, int priority, int exerciseId, const QByteArray& settingsData);
void process() override final;
bool hasValidData() const override final;
int userId() const
{
return m_userId;
}
int priority() const
{
return m_priority;
}
int exerciseId() const
{
return m_exerciseId;
}
const QByteArray& settingsData() const
{
return m_settingsData;
}
private:
QByteArray m_settingsData;
int m_userId = 0;
int m_priority = 0;
int m_exerciseId = 0;
};
class LTSPROJECTIONWORKSTATION_EXPORT LogoutRequest : public Message
{
public:
using Message::Message;
explicit LogoutRequest(const QString& uuid)
: Message(nullptr, nullptr, JsonKeys::LOGOUT_REQUEST(), uuid, QJsonValue())
{
}
void process() override final;
bool hasValidData() const override final;
};
class LTSPROJECTIONWORKSTATION_EXPORT DisconnectRequest : public Message
{
public:
using Message::Message;
explicit DisconnectRequest(const QString& uuid, int userId);
void process() override final;
bool hasValidData() const override final;
int userId() const
{
return m_userId;
}
private:
int m_userId{0};
};
} // namespace CTS
} // namespace LtsProjectionWorkstation
@@ -1,20 +0,0 @@
#include "reply_message.h"
namespace LtsProjectionWorkstation
{
LoginReply::LoginReply(const QJsonObject& data, const QString& uuid)
: LtsWebSocket::ReplyMessage(JsonKeys::LOGIN_REPLY(), uuid)
{
m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data);
}
LogoutReply::LogoutReply(const QJsonObject& data, const QString& uuid)
: LtsWebSocket::ReplyMessage(JsonKeys::LOGOUT_REPLY(), uuid)
{
m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data);
}
} // namespace LtsProjectionWorkstation
@@ -1,23 +0,0 @@
#include "json_keys.h"
#include <LtsWebSocket/json_keys.h>
#include <LtsWebSocket/reply_message.h>
namespace LtsProjectionWorkstation
{
class LoginReply : public LtsWebSocket::ReplyMessage
{
public:
explicit LoginReply(const QJsonObject& data, const QString& uuid);
};
class LogoutReply : public LtsWebSocket::ReplyMessage
{
public:
explicit LogoutReply(const QJsonObject& data, const QString& uuid);
};
} // namespace LtsProjectionWorkstation
@@ -1,30 +0,0 @@
#include "logger.h"
#include <NGLLogger/NGLLoggerBootstrap.h>
namespace LtsProjectionWorkstation
{
LOGGER_T getLogger(const char* name)
{
static const char ns[] = "PWS.";
std::string loggerName;
const size_t len = strlen(name);
loggerName.reserve(sizeof(ns) + len);
loggerName.append(ns, sizeof(ns) - 1);
loggerName.append(name, len);
try
{
return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName);
}
catch (const std::exception& ex)
{
fprintf(stderr, "Error retrieving logger: %s", ex.what());
abort();
}
}
} // namespace LtsProjectionWorkstation
@@ -1,19 +0,0 @@
#pragma once
#include <Lts/Common/LtsProjectionWorkstation/ltsprojectionworkstation_export.h>
#include <NGLLogger/INGLLogger.h>
namespace LtsProjectionWorkstation
{
using LOGGER_T = NGL::INGLLogger&;
LTSPROJECTIONWORKSTATION_EXPORT LOGGER_T getLogger(const char* name);
inline LOGGER_T getLogger(const QString& loggerName)
{
return getLogger(loggerName.toUtf8().constData());
}
} // namespace LtsProjectionWorkstation
@@ -1,226 +0,0 @@
#include "lts_projection_workstation.h"
#include "WebSocket/json_keys.h"
#include "WebSocket/message_factory.h"
#include <LtsSession/lts_session_data.h>
#include <LtsWebSocket/lts_web_socket_server.h>
#include <QtGui/QGuiApplication>
#include <QtCore/QTimer>
#include <QtCore/QUuid>
#include <QtWebSockets/QWebSocket>
#include <nglsettings/nglsettings_connections.h>
#include <utility>
namespace LtsProjectionWorkstation
{
static LtsProjectionWorkstation* s_ltsProjectionWorkstation = nullptr;
LtsProjectionWorkstation* LtsProjectionWorkstation::getInstance()
{
if (!s_ltsProjectionWorkstation)
{
s_ltsProjectionWorkstation = new LtsProjectionWorkstation;
qAddPostRoutine(&cleanupLtsProjectionWorkstation);
}
return s_ltsProjectionWorkstation;
}
void LtsProjectionWorkstation::cleanupLtsProjectionWorkstation()
{
delete s_ltsProjectionWorkstation;
s_ltsProjectionWorkstation = nullptr;
}
bool LtsProjectionWorkstation::hasInstance()
{
return !!s_ltsProjectionWorkstation;
}
LtsProjectionWorkstation::LtsProjectionWorkstation(QObject* parent)
: QObject(parent), m_logger(getLogger("LtsProjectionWorkstation")),
m_messageFactory(new MessageFactory(this, m_logger)),
m_webSocketServer(new LtsWebSocket::LtsWebSocketServer(m_messageFactory, this)), m_pendingLoginRequest(nullptr),
m_vncManager(new VncServerManager(m_logger, this))
{
connect(m_webSocketServer, &LtsWebSocket::LtsWebSocketServer::clientDisconnected, this,
&LtsProjectionWorkstation::clientDisconnected);
connect(m_webSocketServer, &LtsWebSocket::LtsWebSocketServer::clientConnected, this,
&LtsProjectionWorkstation::clientConnected);
int port = NGL::Connections::port(NGL::Connections::eConnection::PWS_WEBSOCKET);
if (m_webSocketServer->init(QStringLiteral("LtsProjectionWorkstation"), port))
{
if (m_vncManager->init(qApp->screens()))
m_vncManager->startScreens();
}
}
LtsProjectionWorkstation::~LtsProjectionWorkstation()
{
delete m_vncManager;
delete m_messageFactory;
delete m_webSocketServer;
}
LoginInformation LtsProjectionWorkstation::pendingLoginRequest()
{
if (!m_pendingLoginRequest)
return {};
LoginInformation result = *m_pendingLoginRequest;
INFO_LOG(m_logger) << " reset pendingLoginRequest..";
delete m_pendingLoginRequest;
m_pendingLoginRequest = nullptr;
return result;
}
void LtsProjectionWorkstation::handleMessage(LtsWebSocket::AbstractClientMessage* message)
{
CTS::LoginRequest* login = dynamic_cast<CTS::LoginRequest*>(message);
if (login)
{
INFO_LOG(m_logger) << "Login request received!"
<< ", login->userId()=" << login->userId() << " with login->priority()=" << login->priority()
<< " ;;; m_lastLoginRequest.m_userId=" << m_lastLoginRequest.m_userId
<< ", m_priority=" << m_lastLoginRequest.m_priority;
if (login->userId() > 0 && login->priority() > 0 && login->exerciseId() > 0)
{
if (login->userId() == m_lastLoginRequest.m_userId || (login->priority() > m_lastLoginRequest.m_priority))
{
m_webSocketServer->sendToAllClients(
(new STC::DedicatedDisconnect(QUuid::createUuid().toString(), login->userId()))->toReplyMessage());
DEBUG_LOG(m_logger)
<< "Login request received and DedicatedDisconnect distributed, wait some seconds...";
int i = 0;
while (i < 20)
{
DEBUG_LOG(m_logger)
<< "Login request received and DedicatedDisconnect distributed, wait some seconds...i=" << i;
qApp->processEvents(QEventLoop::AllEvents, 50);
QThread::msleep(50);
++i;
}
INFO_LOG(m_logger)
<< "Login request received and DedicatedDisconnect distributed, wait some seconds... done";
login->addReply(
(new STC::LoginRequestReply(QUuid::createUuid().toString(), STC::LoginRequestReply::LoginSuccessful,
login->userId(), m_vncManager->screens()))
->toReplyMessage());
m_lastLoginRequest.m_userId = login->userId();
m_lastLoginRequest.m_priority = login->priority();
m_lastLoginRequest.m_exerciseId = login->exerciseId();
m_lastLoginRequest.m_settingsData = login->settingsData();
slotLoginRequestReceived(login->userId(), login->exerciseId());
INFO_LOG(m_logger) << "Valid login request received -> userId: " << login->userId()
<< " priority: " << login->priority() << " exerciseId: " << login->exerciseId();
DEBUG_LOG(m_logger) << "Logging in now!";
}
else
{
login->addReply(
(new STC::LoginRequestReply(QUuid::createUuid().toString(), STC::LoginRequestReply::OtherUser,
m_lastLoginRequest.m_userId, QVector<VncScreen>()))
->toReplyMessage());
DEBUG_LOG(m_logger) << "Higher prioritized login received -> userId: " << login->userId()
<< " priority: " << login->priority() << " exerciseId: " << login->exerciseId();
DEBUG_LOG(m_logger) << "Last login data was -> userId: " << m_lastLoginRequest.m_userId
<< " priority: " << m_lastLoginRequest.m_priority
<< " exerciseId: " << m_lastLoginRequest.m_exerciseId;
}
}
else
ERROR_LOG(m_logger) << "invalid login request received -> userId: " << login->userId()
<< " priority: " << login->priority() << " exerciseId: " << login->exerciseId();
return;
}
CTS::LogoutRequest* logout = dynamic_cast<CTS::LogoutRequest*>(message);
if (logout)
{
DEBUG_LOG(m_logger) << "Logging out now!";
slotLogoutRequestReceived();
return;
}
CTS::DisconnectRequest* discon = dynamic_cast<CTS::DisconnectRequest*>(message);
if (discon)
{
int disconnectingUserId = discon->userId();
INFO_LOG(m_logger) << "Disconnecting now! "
<< ", disconnectingUserId=" << disconnectingUserId
<< ", m_pendingLoginRequest=" << m_pendingLoginRequest;
m_lastLoginRequest = LoginInformation();
return;
}
}
void LtsProjectionWorkstation::slotLoginRequestReceived(int userId, int exerciseId)
{
INFO_LOG(m_logger) << "slotLoginRequestReceived.."
<< ", userId=" << userId << ", exerciseId=" << exerciseId;
delete m_pendingLoginRequest;
m_pendingLoginRequest = new LoginInformation(m_lastLoginRequest);
emit signalLoginRequestReceived(userId, exerciseId);
}
void LtsProjectionWorkstation::slotLogoutRequestReceived()
{
emit signalLogoutRequestReceived();
}
void LtsProjectionWorkstation::slotLogoffDone()
{
if (hasPendingLoginRequest())
return;
for (LtsWebSocket::ClientConnection* con : std::as_const(m_connections))
con->webSocket()->close();
}
void LtsProjectionWorkstation::clientDisconnected(LtsWebSocket::ClientConnection* client)
{
INFO_LOG(m_logger) << Q_FUNC_INFO << " START"
<< ", m_connections.size = " << m_connections.size();
m_connections.removeOne(client);
if (m_connections.size() == 0 && (m_lastLoginRequest.m_userId != 0 || m_lastLoginRequest.m_priority != 0))
{
INFO_LOG(m_logger) << Q_FUNC_INFO << " reset m_lastLoginRequest";
m_lastLoginRequest = LoginInformation();
}
INFO_LOG(m_logger) << Q_FUNC_INFO << " END"
<< ", m_connections.size = " << m_connections.size();
}
void LtsProjectionWorkstation::clientConnected(LtsWebSocket::ClientConnection* client)
{
m_connections.append(client);
}
void LtsProjectionWorkstation::setProjectionOperatorPreset(const QString& operatorName, const QString& operatorPassword)
{
m_projectionOperatorPreset.first = operatorName;
m_projectionOperatorPreset.second = operatorPassword;
}
} // namespace LtsProjectionWorkstation
@@ -1,101 +0,0 @@
#pragma once
#include "WebSocket/messages.h"
#include "logger.h"
#include <LtsProjectionWorkstation/ltsprojectionworkstation_export.h>
#include "vnc_server_manager.h"
#include <LtsWebSocket/client_connection.h>
#include <QtCore/QObject>
#include <QtCore/QPair>
namespace LtsWebSocket
{
class LtsWebSocketServer;
}
namespace LtsProjectionWorkstation
{
struct LoginInformation
{
LoginInformation() = default;
LoginInformation(int userId, int priority, int exerciseId, const QByteArray& settingsData)
: m_settingsData(settingsData), m_userId(userId), m_priority(priority), m_exerciseId(exerciseId)
{
}
QByteArray m_settingsData;
int m_userId = 0;
int m_priority = 0;
int m_exerciseId = 0;
};
class MessageFactory;
class LTSPROJECTIONWORKSTATION_EXPORT LtsProjectionWorkstation : public QObject, public AbstractMessageHandler
{
Q_OBJECT
public:
static LtsProjectionWorkstation* getInstance();
static bool hasInstance();
const LoginInformation& lastLoginRequest() const
{
return m_lastLoginRequest;
}
LoginInformation pendingLoginRequest();
bool hasPendingLoginRequest() const
{
return !!m_pendingLoginRequest;
}
void setProjectionOperatorPreset(const QString& operatorName, const QString& operatorPassword);
const QPair<QString, QString>& projectionOperatorPreset() const
{
return m_projectionOperatorPreset;
}
void handleMessage(LtsWebSocket::AbstractClientMessage* message) override final;
public slots:
void slotLoginRequestReceived(int userId, int exerciseId);
void slotLogoutRequestReceived();
void slotLogoffDone();
signals:
void signalLoginRequestReceived(int userId, int exerciseId);
void signalLogoutRequestReceived();
private slots:
void clientDisconnected(LtsWebSocket::ClientConnection* client);
void clientConnected(LtsWebSocket::ClientConnection* client);
private:
explicit LtsProjectionWorkstation(QObject* parent = nullptr);
~LtsProjectionWorkstation();
static void cleanupLtsProjectionWorkstation();
LOGGER_T m_logger;
MessageFactory* m_messageFactory;
LtsWebSocket::LtsWebSocketServer* m_webSocketServer;
LoginInformation m_lastLoginRequest;
LoginInformation* m_pendingLoginRequest;
QPair<QString, QString> m_projectionOperatorPreset;
QVector<LtsWebSocket::ClientConnection*> m_connections;
VncServerManager* m_vncManager;
};
} // namespace LtsProjectionWorkstation
@@ -1,17 +0,0 @@
#pragma once
#include <QtCore/qglobal.h>
#ifndef LTSPROJECTIONWORKSTATION_EXPORT
#ifdef BUILD_STATIC_LIBRARIES
#define LTSPROJECTIONWORKSTATION_EXPORT
#else
#if defined(MAKE_LTSPROJECTIONWORKSTATION_LIB)
#define LTSPROJECTIONWORKSTATION_EXPORT Q_DECL_EXPORT
#else
#define LTSPROJECTIONWORKSTATION_EXPORT Q_DECL_IMPORT
#endif
#endif
#endif
@@ -1,179 +0,0 @@
#include "vnc_server_manager.h"
#include <QtCore/QDir>
#include <QtCore/QRegularExpression>
#include <QtGui/QScreen>
#include <utility>
namespace LtsProjectionWorkstation
{
VncServerManager::VncServerManager(LOGGER_T& logger, QObject* parent) : QObject(parent), m_logger(logger) {}
VncServerManager::~VncServerManager()
{
stopScreens();
}
QList<QScreen*> sortScreen(const QList<QScreen*>& screens)
{
auto ret(screens);
auto doSortScreens = [](const QScreen* s1, const QScreen* s2) -> bool {
const auto tl1 = s1->geometry().topLeft();
const auto tl2 = s2->geometry().topLeft();
if (tl1.y() > tl2.y())
return true;
if (tl1.y() < tl2.y())
return false;
return tl1.x() < tl2.x();
};
std::sort(ret.begin(), ret.end(), doSortScreens);
return ret;
}
bool VncServerManager::init(const QList<QScreen*>& screens)
{
killScreens();
createPwdFile();
const auto sortedScreens = sortScreen(screens);
DEBUG_LOG(m_logger) << "Setup VNCScreens with " << screens.size() << " screens";
int count = 1;
static constexpr char VNC_START_ARGS[] =
"-rfbauth,%1/.vnc/passwd,-clip,%2x%3+%4+%5,-loop100,-forever,-display,:0,-threads,-noxdamage";
for (QScreen* screen : sortedScreens)
{
VncScreen vncScreen;
vncScreen.geometry = screen->geometry();
vncScreen.name = QStringLiteral("Display%1").arg(count);
vncScreen.proc = new QProcess(this);
QString startArgs = QString::fromLatin1(VNC_START_ARGS)
.arg(QDir::home().absolutePath())
.arg(screen->geometry().width())
.arg(screen->geometry().height())
.arg(screen->geometry().x())
.arg(screen->geometry().y());
vncScreen.proc->setProgram(QStringLiteral("x11vnc"));
vncScreen.proc->setArguments(startArgs.split(QLatin1Char(',')));
NOTICE_LOG(m_logger) << "Started VNC for Screen " << count << " with geometry " << screen->geometry().width()
<< "," << screen->geometry().height() << "+" << screen->geometry().x() << "+"
<< screen->geometry().y();
m_vncScreens.push_back(vncScreen);
count++;
}
DEBUG_LOG(m_logger) << m_vncScreens.size() << " VNCScreen(s) created - Setup completed.";
return true;
}
void VncServerManager::startScreens()
{
DEBUG_LOG(m_logger) << "Starting " << m_vncScreens.size() << " VNCScreen(s) ... ";
for (const VncScreen& s : std::as_const(m_vncScreens))
{
connect(s.proc, &QProcess::readyReadStandardOutput, this, &VncServerManager::slotReadStandardOutput,
Qt::UniqueConnection);
connect(s.proc, &QProcess::errorOccurred, this, &VncServerManager::slotErrorOccured, Qt::UniqueConnection);
s.proc->start();
}
for (const VncScreen& s : std::as_const(m_vncScreens))
{
if (!s.proc->waitForStarted(2000))
ERROR_LOG(m_logger) << "Can not start process '" << s.proc->program() << "': " << s.proc->errorString();
}
DEBUG_LOG(m_logger) << "Done";
}
void VncServerManager::stopScreens()
{
DEBUG_LOG(m_logger) << "Stopping " << m_vncScreens.size() << " VNCScreen(s) ...";
for (const VncScreen& s : std::as_const(m_vncScreens))
{
s.proc->disconnect(this);
s.proc->terminate();
}
for (const VncScreen& s : std::as_const(m_vncScreens))
{
if (!s.proc->waitForFinished(2000))
s.proc->kill();
}
DEBUG_LOG(m_logger) << "Done";
}
void VncServerManager::killScreens()
{
DEBUG_LOG(m_logger) << "Killing all exisiting x11vnc processes ...";
SingleShotProcess ssp(QStringLiteral("killall x11vnc"));
ssp.execute();
DEBUG_LOG(m_logger) << "Done";
}
void VncServerManager::createPwdFile()
{
DEBUG_LOG(m_logger) << "(Re)creating x11vnc password-file ...";
SingleShotProcess ssp(
QStringLiteral("x11vnc -storepasswd ctc11de %1/.vnc/passwd").arg(QDir::home().absolutePath()));
ssp.execute();
DEBUG_LOG(m_logger) << "Done";
}
void VncServerManager::slotReadStandardOutput()
{
QProcess* p = qobject_cast<QProcess*>(QObject::sender());
if (!p)
return;
QString stdOut = QString::fromLocal8Bit(p->readAllStandardOutput());
QRegularExpressionMatch match = QRegularExpression(QStringLiteral("PORT=(.*?)\\s")).match(stdOut);
if (!match.hasMatch())
{
WARNING_LOG(m_logger) << "Could not retrieve port information from stdout of " << p->program();
return;
}
const quint16 port = match.captured(1).toInt();
if (port == 0)
return;
for (VncScreen& screen : m_vncScreens)
{
if (screen.proc != p)
continue;
screen.port = port;
disconnect(screen.proc, &QProcess::readyReadStandardOutput, nullptr, nullptr);
break;
}
}
void VncServerManager::slotErrorOccured()
{
QProcess* p = qobject_cast<QProcess*>(QObject::sender());
if (p)
ERROR_LOG(m_logger) << p->errorString();
}
SingleShotProcess::SingleShotProcess(const QString& cmd, bool startImmediatly) : m_cmd(cmd)
{
if (startImmediatly)
execute();
}
bool SingleShotProcess::execute()
{
m_process.start(m_cmd);
return m_process.waitForFinished();
}
} // namespace LtsProjectionWorkstation
@@ -1,67 +0,0 @@
#pragma once
#include "logger.h"
#include <QtCore/QObject>
#include <QtCore/QProcess>
#include <QtCore/QRect>
#include <QtCore/QString>
#include <QtCore/QVector>
class QScreen;
namespace LtsProjectionWorkstation
{
class SingleShotProcess
{
public:
explicit SingleShotProcess(const QString& cmd, bool startImmediatly = false);
bool execute();
private:
QProcess m_process;
QString m_cmd;
};
struct VncScreen
{
QString name;
QProcess* proc = nullptr;
QRect geometry;
quint16 port = 0;
};
class VncServerManager : public QObject
{
Q_OBJECT
public:
explicit VncServerManager(LOGGER_T& logger, QObject* parent = nullptr);
~VncServerManager();
bool init(const QList<QScreen*>& screens);
const QVector<VncScreen>& screens() const
{
return m_vncScreens;
}
void startScreens();
void stopScreens();
void killScreens();
void createPwdFile();
private slots:
void slotReadStandardOutput();
void slotErrorOccured();
private:
QVector<VncScreen> m_vncScreens;
LOGGER_T& m_logger;
};
} // namespace LtsProjectionWorkstation
@@ -1,27 +0,0 @@
#
# Lightweight REST Client Framework
# $Id$
# $HeadURL$
# $Author$
# Created by Hannes Fritsche, ESZS, 2026-08-21
#
# --- Library LtsRestClient --------------------------------------------------------------------------------
#
SET(LtsRestClient_SRCS
lts_rest_client.cpp
lts_rest_client.h
)
NGL_ADD_LIBRARY2(ALL LtsRestClient SHARED ${LtsRestClient_SRCS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsRestClient
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
NGL_TARGET_LINK_LIBRARIES(LtsRestClient
PUBLIC
Qt6::Core
Qt6::Network
)
@@ -1,172 +0,0 @@
/**
* Lightweight REST Client Framework
* $Id$
* $HeadURL$
* $Author$
* Created by Hannes Fritsche, ESZS, 2026-08-21
*/
#include "lts_rest_client.h"
#include <QTimer>
#include <QUrl>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
namespace LtsCommon
{
LtsRestClient::LtsRestClient(const QString &baseUrl, QObject *parent)
: QObject(parent)
, m_baseUrl(baseUrl)
, m_manager(new QNetworkAccessManager(this))
{
}
void LtsRestClient::ping(PingSuccessCallback onSuccess, ErrorCallback onError, int timeoutMs)
{
const QNetworkRequest request((QUrl(m_baseUrl)));
QNetworkReply *reply = m_manager->head(request);
if (!reply)
{
if (onError)
onError(QStringLiteral("Failed to initiate ping."));
return;
}
// 1. Setup the timer (parented to reply for auto-cleanup)
QTimer *timeoutTimer = new QTimer(reply);
timeoutTimer->setSingleShot(true);
// 2. Connect the timeout signal to abort the request
connect(timeoutTimer, &QTimer::timeout, this, [reply]()
{
if (reply && reply->isRunning())
reply->abort(); // Triggers finished() with OperationCanceledError
});
// 3. Connect the finished signal to handle the response
connect(reply,
&QNetworkReply::finished,
this,
[reply, timeoutTimer, onSuccess, onError]()
{
timeoutTimer->stop();
reply->deleteLater();
if (reply->error() != QNetworkReply::NoError)
{
if (onError)
{
if (reply->error() == QNetworkReply::OperationCanceledError)
onError(QStringLiteral("Ping timed out."));
else
onError(reply->errorString());
}
return;
}
const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (onSuccess)
onSuccess(statusCode);
});
// 4. Start the timer only after all connections are successfully established
timeoutTimer->start(timeoutMs);
}
void LtsRestClient::get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError)
{
sendRequest(QStringLiteral("GET"), endpoint, QByteArray(), onSuccess, onError);
}
void LtsRestClient::post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError)
{
sendRequest(QStringLiteral("POST"), endpoint, json.toJson(), onSuccess, onError);
}
void LtsRestClient::put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError)
{
sendRequest(QStringLiteral("PUT"), endpoint, json.toJson(), onSuccess, onError);
}
void LtsRestClient::del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError)
{
sendRequest(QStringLiteral("DELETE"), endpoint, QByteArray(), onSuccess, onError);
}
void LtsRestClient::sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError)
{
QUrl url(m_baseUrl);
url.setPath(url.path() + endpoint);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
QNetworkReply *reply = nullptr;
if (method == QStringLiteral("GET"))
reply = m_manager->get(request);
else if (method == QStringLiteral("POST"))
reply = m_manager->post(request, data);
else if (method == QStringLiteral("PUT"))
reply = m_manager->put(request, data);
else if (method == QStringLiteral("DELETE"))
reply = m_manager->deleteResource(request);
if (!reply)
{
if (onError)
onError(QStringLiteral("Failed to initiate request."));
return;
}
connect(reply,
&QNetworkReply::finished,
this,
[reply, onSuccess, onError]()
{
reply->deleteLater();
// Handle network errors
if (reply->error() != QNetworkReply::NoError)
{
if (onError)
onError(reply->errorString());
return;
}
// Handle HTTP errors
const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (statusCode >= 400)
{
if (onError)
onError(QStringLiteral("HTTP Error %1").arg(statusCode));
return;
}
// Parse JSON safely
QJsonParseError parseError;
const QJsonDocument doc = QJsonDocument::fromJson(reply->readAll(), &parseError);
if (parseError.error != QJsonParseError::NoError)
{
if (onError)
onError(QStringLiteral("JSON Parse Error: ") + parseError.errorString());
return;
}
if (onSuccess)
onSuccess(doc);
});
}
} // namespace LtsCommon
@@ -1,51 +0,0 @@
/**
* Lightweight REST Client Framework
* $Id$
* $HeadURL$
* $Author$
* Created by Hannes Fritsche, ESZS, 2026-08-21
*/
// Short documentation on how to use it can be found at https://confluence-classified.rh-int.de/spaces/LEG/pages/207915647/HOWTO+LtsRestClient
#pragma once
#include <QJsonDocument>
#include <QObject>
#include <QString>
#include <functional>
#include <LtsRestClient/ltsrestclient_export.h>
class QNetworkAccessManager;
namespace LtsCommon
{
class LTSRESTCLIENT_EXPORT LtsRestClient : public QObject
{
Q_OBJECT
public:
explicit LtsRestClient(const QString &baseUrl, QObject *parent = nullptr);
// type aliases
using PingSuccessCallback = std::function<void(int statusCode)>;
using SuccessCallback = std::function<void(const QJsonDocument &)>;
using ErrorCallback = std::function<void(const QString &)>;
// HTTP Header Ping to m_baseUrl to check server availability
void ping(PingSuccessCallback onSuccess, ErrorCallback onError = nullptr, int timeoutMs = 3000);
// HTTP Methods
void get(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr);
void post(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr);
void put(const QString &endpoint, const QJsonDocument &json, SuccessCallback onSuccess, ErrorCallback onError = nullptr);
void del(const QString &endpoint, SuccessCallback onSuccess, ErrorCallback onError = nullptr);
private:
void sendRequest(const QString &method, const QString &endpoint, const QByteArray &data, SuccessCallback onSuccess, ErrorCallback onError);
QString m_baseUrl;
QNetworkAccessManager *m_manager;
}; // class RestClient
} // namespace LtsCommon
@@ -1,84 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
#
# Created by Mike Wille, SLSE, 2017-03-15
#
# Test
#ADD_SUBDIRECTORY(Test) Not needed anymore + old 'api'
# Library
# Make ${Qt6_Widgets} optional
if(QT6_GUI_AVAILABLE AND TARGET Qt6::Widgets)
set(Qt6_Widgets ${Qt6_Widgets})
else()
set(Qt6_Widgets "")
endif()
SET(LtsScriptTimeline_SRCS
tools.h
tools.cpp
indicator.h
indicator.cpp
script_timeline.h
script_timeline.cpp
track_content_widget.h
track_content_widget.cpp
track_entry.h
track_entry_painters.h
track_entry_painters.cpp
track_entry_previewer.h
track_entry_previewer.cpp
track_entry_preview_widget.h
track_entry_preview_widget.cpp
track_select_handler.h
track_select_handler.cpp
track_resize_handler.cpp
track_resize_handler.h
track_drag_handler.h
track_drag_handler.cpp
track_widget.h
track_widget.cpp
track_header.h
track_header.cpp
filter_track_widget.h
filter_track_widget.cpp
filter_background_widget.h
filter_background_widget.cpp
temporary_pointer_vector.h
)
SET(LtsScriptTimeline_UICS
Ui/indicator.ui
Ui/script_timeline.ui
Ui/track_widget.ui
Ui/filter_track_widget.ui
Ui/track_entry_preview_widget.ui
)
NGL_WRAP_UI(LtsScriptTimeline_SRCS ${LtsScriptTimeline_UICS})
SET(CMAKE_AUTOUIC_SEARCH_PATHS ${CMAKE_CURRENT_SOURCE_DIR}/Ui)
IF(BUILD_RTI)
NGL_ADD_LIBRARY2(WS LtsScriptTimeline SHARED ${LtsScriptTimeline_SRCS} ${LtsScriptTimeline_UICS})
NGL_TARGET_INCLUDE_DIRECTORIES(LtsScriptTimeline
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/../
)
if(QT6_GUI_AVAILABLE)
NGL_TARGET_LINK_LIBRARIES(LtsScriptTimeline
Qt6::Core
${Qt6_Widgets}
LtsWidgets
LtsSessionData
)
endif()
ENDIF(BUILD_RTI)
@@ -1,24 +0,0 @@
#
# $Id$
# $HeadURL$
# $Author$
#
# Created by Mike Wille, SLSE, 2017-03-15
#
# Test-Executable
SET(LtsScriptTimelineTest_SRCS
main.cpp
mainwindow.h
mainwindow.cpp
)
SET(LtsScriptTimelineTest_UICS
mainwindow.ui
)
NGL_WRAP_UI(LtsScriptTimelineTest_SRCS ${LtsScriptTimelineTest_UICS})
NGL_ADD_EXECUTABLE(TOOLSWS LtsScriptTimelineTest ${LtsScriptTimelineTest_SRCS})
NGL_TARGET_LINK_LIBRARIES(LtsScriptTimelineTest LtsScriptTimeline)
@@ -1,12 +0,0 @@
#include "mainwindow.h"
#include <QtWidgets/QApplication>
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
@@ -1,86 +0,0 @@
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <LtsScriptTimeline/track_entry.h>
#include <QtWidgets/QDialog>
#include <QtWidgets/QLabel>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent), ui(new Ui::MainWindow), m_selectedTe(nullptr), m_currentNewTopicEditor(nullptr),
m_currentEditTopicEditor(nullptr)
{
ui->setupUi(this);
ui->masterSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->masterSplitter), 20);
ui->masterSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->toolBox), 0);
ui->detailSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->scriptTimeline), 20);
ui->detailSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->detailLayout), 0);
connect(ui->scriptTimeline, &LtsScriptTimeline::ScriptTimeline::signalTrackEntrySelectionChanged, this,
&MainWindow::slotTrackEntrySelectionChanged);
connect(ui->pbTopicAddAudio, &QPushButton::clicked, this, [this]() {
LtsScriptTimeline::TrackEntry* te = new LtsScriptTimeline::TrackEntry(LtsScriptTimeline::TrackEntryType::Audio);
te->time = -1;
te->length = 30;
te->topicId = 3;
if (m_currentNewTopicEditor)
delete m_currentNewTopicEditor;
LtsScriptTimeline::AudioTopicEditor* ate = new LtsScriptTimeline::AudioTopicEditor(te);
connect(ate, &LtsScriptTimeline::AudioTopicEditor::destroyed, this,
[this]() { m_currentNewTopicEditor = nullptr; });
m_currentNewTopicEditor = ate;
ui->newTopicTab->layout()->addWidget(ate);
ui->detailLayout->setCurrentWidget(ui->newTopicTab);
});
ui->scriptTimeline->addTrack(ui->scriptTimeline->newTrackName());
qCritical() << "THIS EXAMPLE NO LONGER WORKS!";
}
void MainWindow::disconnectTrackEntry()
{
if (!m_selectedTe)
return;
m_selectedTe = nullptr;
if (m_currentEditTopicEditor)
{
delete m_currentEditTopicEditor;
m_currentEditTopicEditor = nullptr;
ui->lblNoTopicSelected->setVisible(true);
}
ui->lblNoTopicSelected->setVisible(true);
}
void MainWindow::slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry* te)
{
qDeleteAll(ui->topicEditorTab->layout()->children());
disconnectTrackEntry();
if (!te)
return;
ui->lblNoTopicSelected->setVisible(false);
m_selectedTe = te;
LtsScriptTimeline::AudioTopicEditor* ate = new LtsScriptTimeline::AudioTopicEditor(te);
connect(ate, &LtsScriptTimeline::AudioTopicEditor::destroyed, this,
[this]() { m_currentEditTopicEditor = nullptr; });
m_currentEditTopicEditor = ate;
ui->topicEditorTab->layout()->addWidget(ate);
}
MainWindow::~MainWindow()
{
delete ui;
}
@@ -1,33 +0,0 @@
#pragma once
#include <QtWidgets/QMainWindow>
#include <QtCore/QObject>
namespace Ui
{
class MainWindow;
}
namespace LtsScriptTimeline
{
class TrackEntry;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
private:
Ui::MainWindow* ui;
LtsScriptTimeline::TrackEntry* m_selectedTe;
QWidget* m_currentNewTopicEditor;
QWidget* m_currentEditTopicEditor;
void disconnectTrackEntry();
private slots:
void slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry* te);
};
@@ -1,564 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1084</width>
<height>834</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralWidget">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QSplitter" name="masterSplitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QSplitter" name="detailSplitter">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="LtsScriptTimeline::ScriptTimeline" name="scriptTimeline" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
<widget class="QTabWidget" name="detailLayout">
<property name="currentIndex">
<number>1</number>
</property>
<widget class="QWidget" name="newTopicTab">
<attribute name="title">
<string>New Topic</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_4"/>
</widget>
<widget class="QWidget" name="topicEditorTab">
<attribute name="title">
<string>Topic Editor</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item alignment="Qt::AlignTop">
<widget class="QLabel" name="lblNoTopicSelected">
<property name="text">
<string>No Topic selected.</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="layoutEditorTab">
<attribute name="title">
<string>Layout Editor</string>
</attribute>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QGroupBox" name="previewGroupBox">
<property name="palette">
<palette>
<active>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Light">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Midlight">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>212</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Dark">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Mid">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>113</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="BrightText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Shadow">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="AlternateBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>212</red>
<green>127</green>
<blue>127</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>220</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
</active>
<inactive>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Light">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Midlight">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>212</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Dark">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Mid">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>113</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="BrightText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Shadow">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="AlternateBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>212</red>
<green>127</green>
<blue>127</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>220</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
</inactive>
<disabled>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Light">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Midlight">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>212</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Dark">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Mid">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>113</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="BrightText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>85</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Shadow">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="AlternateBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>170</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipBase">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>220</blue>
</color>
</brush>
</colorrole>
<colorrole role="ToolTipText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
</disabled>
</palette>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</widget>
<widget class="QToolBox" name="toolBox">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="page_2">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>453</width>
<height>782</height>
</rect>
</property>
<attribute name="label">
<string>Add Topics</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QPushButton" name="pbTopicAddAudio">
<property name="text">
<string>Add Audio Topic</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</widget>
</widget>
</item>
</layout>
</widget>
</widget>
<layoutdefault spacing="6" margin="11"/>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::ScriptTimeline</class>
<extends>QWidget</extends>
<header location="global">LtsScriptTimeline/script_timeline.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,126 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>FilterTrackWidget</class>
<widget class="QWidget" name="FilterTrackWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>828</width>
<height>43</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QWidget" name="left" native="true">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Filters</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="cbSelect">
<property name="text">
<string/>
</property>
<property name="const" stdset="0">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbDelete">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Delete</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="LtsScriptTimeline::FilterBackgroundWidget" name="fbw" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>40</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>40</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::FilterBackgroundWidget</class>
<extends>QWidget</extends>
<header>filter_background_widget.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Indicator</class>
<widget class="QWidget" name="Indicator">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>822</width>
<height>88</height>
</rect>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QSplitter" name="splitter">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QWidget" name="m_widgetTrackLabel" native="true">
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string notr="true">Tracks</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="LtsScriptTimeline::TrackHeader" name="m_widgetTrackHeader" native="true"/>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::TrackHeader</class>
<extends>QWidget</extends>
<header>track_header.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,205 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ScriptTimeline</class>
<widget class="QWidget" name="ScriptTimeline">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>570</width>
<height>397</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="0,0">
<property name="spacing">
<number>8</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QScrollArea" name="trackScrollArea">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>568</width>
<height>370</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<layout class="QVBoxLayout" name="trackLayout">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="LtsScriptTimeline::Indicator" name="indicator" native="true">
<property name="minimumSize">
<size>
<width>0</width>
<height>50</height>
</size>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout" stretch="0,0,0,0,1">
<item>
<widget class="QLabel" name="lbPortrait">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string notr="true">P</string>
</property>
</widget>
</item>
<item>
<widget class="QSlider" name="zoomSlider">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>6</number>
</property>
<property name="pageStep">
<number>1</number>
</property>
<property name="value">
<number>1</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="invertedAppearance">
<bool>true</bool>
</property>
<property name="invertedControls">
<bool>false</bool>
</property>
<property name="const" stdset="0">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lbLandscape">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string notr="true">L</string>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="wordWrap">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="Line" name="line">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
</widget>
</item>
<item>
<widget class="QScrollBar" name="trackScrollBar">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="const" stdset="0">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::Indicator</class>
<extends>QWidget</extends>
<header>indicator.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,99 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>TrackEntryPreviewWidget</class>
<widget class="QWidget" name="TrackEntryPreviewWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>296</width>
<height>78</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2" stretch="0">
<property name="spacing">
<number>6</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="0">
<widget class="QLabel" name="lblDnD">
<property name="text">
<string>Drag &amp; Drop:</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblTopicId">
<property name="text">
<string>[Topic id:]</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="LtsScriptTimeline::TrackEntryPreviewer" name="widget" native="true">
<property name="minimumSize">
<size>
<width>200</width>
<height>50</height>
</size>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLabel" name="lbTopicId">
<property name="text">
<string notr="true">?</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="lblLen">
<property name="text">
<string>[Topic length:]</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="lbLen">
<property name="text">
<string>?</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::TrackEntryPreviewer</class>
<extends>QWidget</extends>
<header location="global">LtsScriptTimeline/track_entry_previewer.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,245 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>TrackWidget</class>
<widget class="QWidget" name="TrackWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>925</width>
<height>120</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string notr="true">Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2" stretch="0,0">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QWidget" name="mainWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QWidget" name="mainLeft" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>300</width>
<height>0</height>
</size>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QCheckBox" name="chkSelect">
<property name="text">
<string notr="true"/>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblTrackName">
<property name="text">
<string>Name of Track:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="leName">
<property name="maxLength">
<number>128</number>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbEditName">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Edit</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbApply">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Apply</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbCancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbExpand">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>More</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pbAddFilter">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Add filter track</string>
</property>
<property name="text">
<string>+</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="LtsScriptTimeline::TrackContentWidget" name="mainTrack" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>40</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>40</height>
</size>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QWidget" name="filtersWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>40</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
</layout>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>LtsScriptTimeline::TrackContentWidget</class>
<extends>QWidget</extends>
<header>track_content_widget.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>
@@ -1,163 +0,0 @@
#include "filter_background_widget.h"
#include "script_timeline.h"
#include "tools.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include <QtGui/QPainter>
namespace LtsScriptTimeline
{
FilterBackgroundWidget::FilterBackgroundWidget(QWidget* parent)
: QWidget(parent), m_readonly(false), m_scriptTimeline(nullptr), m_tools(nullptr), m_trackWidget(nullptr)
{
}
void FilterBackgroundWidget::setReadonly(bool readonly)
{
m_readonly = readonly;
for (auto i = m_filterContentWidgets.begin(); i != m_filterContentWidgets.end(); ++i)
{
TrackContentWidget* tcw = *i;
tcw->setReadonly(readonly);
}
}
void FilterBackgroundWidget::paintEvent(QPaintEvent* event)
{
(void)event;
QPainter painter(this);
painter.save();
painter.setBrush(QColor("lightgray"));
painter.drawRect(rect());
painter.restore();
}
void FilterBackgroundWidget::setTools(Tools* tools)
{
m_tools = tools;
}
void FilterBackgroundWidget::adjustFilterContentWidgets(const TrackEntry* te)
{
TrackContentWidget* tcw = m_filterContentWidgets.value(te->m_topicId, nullptr);
if (tcw == nullptr)
{
trackEntryAdded(te);
return;
}
QRect currentGeo = tcw->geometry();
int currentX = currentGeo.x();
int currentWidth = currentGeo.width();
int x = m_tools->getPos(te->m_startTime);
int width = m_tools->getLength(te->m_startTime, te->m_length);
if (currentX != x || currentWidth != width)
{
tcw->setGeometry(x, currentGeo.y(), width, currentGeo.height());
}
else
{
}
}
void FilterBackgroundWidget::slotChangesMade()
{
QObject* tcwObj = sender();
TrackContentWidget* tcw = qobject_cast<TrackContentWidget*>(tcwObj);
if (tcw == nullptr)
{
return;
}
int topicId = m_filterContentWidgets.key(tcw, -1);
if (topicId == -1)
{
return;
}
emit signalChangesMade(topicId);
}
void FilterBackgroundWidget::trackEntryDeleted(const int topicId)
{
auto fcwI = m_filterContentWidgets.find(topicId);
if (fcwI != m_filterContentWidgets.end())
{
TrackContentWidget* tcw = *fcwI;
m_filterContentWidgets.erase(fcwI);
tcw->deleteLater();
}
}
void FilterBackgroundWidget::addFilterEntry(TrackEntry* main, TrackEntry* filter)
{
auto fcwI = m_filterContentWidgets.find(main->m_topicId);
if (fcwI != m_filterContentWidgets.end())
{
TrackContentWidget* tcw = *fcwI;
tcw->addTrackEntry(filter, false);
emit tcw->signalChangesMade();
}
}
void FilterBackgroundWidget::trackEntryAdded(const TrackEntry* te)
{
auto fcwI = m_filterContentWidgets.find(te->m_topicId);
if (fcwI == m_filterContentWidgets.end())
{
TrackContentWidget* tcw = new TrackContentWidget(this, true, m_tools, te->m_topicId);
tcw->setTrackWidget(m_trackWidget);
tcw->setReadonly(m_readonly);
tcw->setScriptTimeline(m_scriptTimeline);
tcw->setGeometry(-1, 0, 0, height());
tcw->show();
connect(tcw, &TrackContentWidget::signalChangesMade, this, &FilterBackgroundWidget::slotChangesMade);
connect(tcw, &TrackContentWidget::signalUnselectAll, this, &FilterBackgroundWidget::signalUnselectAll);
connect(tcw, &TrackContentWidget::signalTrackEntrySelectionChanged, this,
&FilterBackgroundWidget::signalTrackEntrySelectionChanged);
connect(tcw, &TrackContentWidget::signalTrackEntryDeleted, this,
&FilterBackgroundWidget::signalTrackEntryDeleted);
connect(tcw, &TrackContentWidget::signalEditEntry, this, &FilterBackgroundWidget::signalEditEntry);
connect(tcw, &TrackContentWidget::signalStartRubberband, m_scriptTimeline,
&ScriptTimeline::slotStartRubberband);
connect(tcw, &TrackContentWidget::signalModifyRubberband, m_scriptTimeline,
&ScriptTimeline::slotModifyRubberband);
connect(tcw, &TrackContentWidget::signalEscapeRubberband, m_scriptTimeline,
&ScriptTimeline::slotEscapeRubberband);
connect(tcw, &TrackContentWidget::signalStopRubberband, m_scriptTimeline, &ScriptTimeline::slotStopRubberband);
connect(tcw, &TrackContentWidget::signalSelectAllGlobal, m_scriptTimeline, &ScriptTimeline::selectAll);
connect(tcw, &TrackContentWidget::signalCopyTopics, m_scriptTimeline, &ScriptTimeline::slotCopyTopics);
connect(tcw, &TrackContentWidget::signalPasteTopics, m_scriptTimeline, &ScriptTimeline::slotPasteTopics);
connect(tcw, &TrackContentWidget::signalCutTopics, m_scriptTimeline, &ScriptTimeline::slotCutTopics);
connect(tcw, &TrackContentWidget::signalDeleteSelectedTopics, m_scriptTimeline,
&ScriptTimeline::slotDeleteSelectedTopics);
connect(tcw, &TrackContentWidget::signalSave, m_scriptTimeline, &ScriptTimeline::signalSave);
connect(tcw, &TrackContentWidget::signalMoveAll, m_scriptTimeline, &ScriptTimeline::slotMoveAll);
m_filterContentWidgets.insert(te->m_topicId, tcw);
}
adjustFilterContentWidgets(te);
}
} // namespace LtsScriptTimeline
@@ -1,65 +0,0 @@
#pragma once
#include "track_content_widget.h"
#include <QtCore/QMap>
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace LtsScriptTimeline
{
class TrackEntry;
class ScriptTimeline;
class Tools;
class FilterBackgroundWidget : public QWidget
{
Q_OBJECT
public:
explicit FilterBackgroundWidget(QWidget* parent = nullptr);
const QMap<int, TrackContentWidget*>& filterContentWidgets() const
{
return m_filterContentWidgets;
}
void adjustFilterContentWidgets(const TrackEntry* te);
void trackEntryAdded(const TrackEntry* te);
void trackEntryDeleted(const int topicId);
void addFilterEntry(TrackEntry* main, TrackEntry* filter);
void setReadonly(bool readonly);
void setScriptTimeline(ScriptTimeline* scriptTimeline)
{
m_scriptTimeline = scriptTimeline;
}
void setTools(Tools* tools);
void setTrackWidget(TrackWidget* trackWidget)
{
m_trackWidget = trackWidget;
}
signals:
void signalChangesMade(int topicId);
void signalUnselectAll();
void signalTrackEntrySelectionChanged(TrackEntry* te);
void signalTrackEntryDeleted(const int topicId);
void signalEditEntry(const int topicId);
private slots:
void slotChangesMade();
private:
QMap<int, TrackContentWidget*> m_filterContentWidgets;
bool m_readonly;
ScriptTimeline* m_scriptTimeline;
Tools* m_tools;
TrackWidget* m_trackWidget;
protected:
void paintEvent(QPaintEvent* event);
};
} // namespace LtsScriptTimeline
@@ -1,107 +0,0 @@
#include "filter_track_widget.h"
#include "script_timeline.h"
#include "track_entry.h"
#include "ui_filter_track_widget.h"
#include <QtGui/QBrush>
#include <QtGui/QColor>
#include <QtGui/QPainter>
#include <QtGui/QPen>
namespace LtsScriptTimeline
{
FilterTrackWidget::FilterTrackWidget(int baseWidth, bool readonly, QWidget* parent)
: QWidget(parent), ui(new Ui::FilterTrackWidget), m_baseWidth(baseWidth), m_readonly(readonly), m_tools(nullptr),
m_trackWidget(nullptr)
{
ui->setupUi(this);
ui->cbSelect->hide();
setReadonly(readonly);
setBaseWidth(baseWidth);
connect(ui->pbDelete, &QPushButton::clicked, this, &FilterTrackWidget::signalDeleteMe);
connect(ui->fbw, &FilterBackgroundWidget::signalChangesMade, this, &FilterTrackWidget::signalChangesMade);
connect(ui->fbw, &FilterBackgroundWidget::signalUnselectAll, this, &FilterTrackWidget::signalUnselectAll);
connect(ui->fbw, &FilterBackgroundWidget::signalTrackEntrySelectionChanged, this,
&FilterTrackWidget::signalTrackEntrySelectionChanged);
connect(ui->fbw, &FilterBackgroundWidget::signalEditEntry, this, &FilterTrackWidget::signalEditEntry);
connect(ui->fbw, &FilterBackgroundWidget::signalTrackEntryDeleted, this,
&FilterTrackWidget::signalTrackEntryDeleted);
}
FilterTrackWidget::~FilterTrackWidget()
{
delete ui;
}
void FilterTrackWidget::setTrackWidget(TrackWidget* trackWidget)
{
m_trackWidget = trackWidget;
ui->fbw->setTrackWidget(trackWidget);
}
void FilterTrackWidget::setReadonly(bool readonly)
{
m_readonly = readonly;
ui->pbDelete->setVisible(!readonly);
ui->fbw->setReadonly(readonly);
}
void FilterTrackWidget::setTools(Tools* tools)
{
m_tools = tools;
ui->fbw->setTools(tools);
}
void FilterTrackWidget::setScriptTimeline(ScriptTimeline* scriptTimeline)
{
m_scriptTimeline = scriptTimeline;
ui->fbw->setScriptTimeline(m_scriptTimeline);
}
FilterBackgroundWidget* FilterTrackWidget::fbw()
{
return ui->fbw;
}
const FilterBackgroundWidget* FilterTrackWidget::fbw() const
{
return ui->fbw;
}
void FilterTrackWidget::setBaseWidth(int width)
{
ui->left->setMinimumWidth(width);
ui->left->setMaximumWidth(width);
}
void FilterTrackWidget::addFilterEntry(TrackEntry* main, TrackEntry* filter)
{
filter->m_topicId = m_scriptTimeline->nextUniqueId();
ui->fbw->addFilterEntry(main, filter);
}
bool FilterTrackWidget::isSelected() const
{
return (ui->cbSelect->checkState() == Qt::CheckState::Checked);
}
void FilterTrackWidget::unselectAll() {}
void FilterTrackWidget::updateMe()
{
update();
}
void FilterTrackWidget::paintEvent(QPaintEvent* event)
{
QWidget::paintEvent(event);
}
} // namespace LtsScriptTimeline
@@ -1,68 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include "track_entry_painters.h"
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace Ui
{
class FilterTrackWidget;
}
namespace LtsScriptTimeline
{
class TrackEntry;
class TrackContentWidget;
class FilterBackgroundWidget;
class ScriptTimeline;
class Tools;
class TrackWidget;
class LTSSCRIPTTIMELINE_EXPORT FilterTrackWidget : public QWidget
{
Q_OBJECT
public:
explicit FilterTrackWidget(int baseWidth, bool readonly = false, QWidget* parent = nullptr);
~FilterTrackWidget();
FilterBackgroundWidget* fbw();
const FilterBackgroundWidget* fbw() const;
void setReadonly(bool readonly);
void updateMe();
void unselectAll();
bool isSelected() const;
QString trackName() const;
void addFilterEntry(TrackEntry* main, TrackEntry* filter);
void setTrackName(const QString& name);
void setBaseWidth(int width);
void setScriptTimeline(ScriptTimeline* scriptTimeline);
void setTools(Tools* tools);
void setTrackWidget(TrackWidget* trackWidget);
private:
Ui::FilterTrackWidget* ui;
int m_baseWidth;
bool m_readonly;
ScriptTimeline* m_scriptTimeline;
Tools* m_tools;
TrackWidget* m_trackWidget;
protected:
void paintEvent(QPaintEvent* event);
signals:
void signalUnselectAll();
void signalSelectTrack();
void signalTrackEntrySelectionChanged(TrackEntry* te);
void signalChangesMade(int topicId);
void signalDeleteMe();
void signalEditEntry(const int topicId);
void signalTrackEntryDeleted(const int topicId);
};
} // namespace LtsScriptTimeline
@@ -1,73 +0,0 @@
#include "indicator.h"
#include "ui_indicator.h"
#include <QtCore/QTimer>
namespace LtsScriptTimeline
{
Indicator::Indicator(QWidget* parent) : QWidget(parent), ui(new Ui::Indicator)
{
ui->setupUi(this);
connect(ui->splitter, &QSplitter::splitterMoved, this, &Indicator::slotSplitterMoved);
connect(ui->m_widgetTrackHeader, &TrackHeader::signalHeaderIndicatorTimeChanged, this,
&Indicator::signalHeaderIndicatorTimeChanged);
connect(ui->m_widgetTrackHeader, &TrackHeader::signalHeaderIndicatorTimeUserChanged, this,
&Indicator::signalHeaderIndicatorTimeUserChanged);
QList<int> sizes;
sizes << 100 << 900;
ui->splitter->setSizes(sizes);
QTimer::singleShot(500, this, [this]() {
slotSplitterMoved();
emit signalHeaderIndicatorTimeUserChanged(ui->m_widgetTrackHeader->indicatorTime());
ui->m_widgetTrackHeader->recreatePositionLabels();
});
}
Indicator::~Indicator()
{
delete ui;
}
void Indicator::setTools(Tools* tools)
{
ui->m_widgetTrackHeader->setTools(tools);
}
void Indicator::lockIndicator(bool lock)
{
ui->m_widgetTrackHeader->lockIndicator(lock);
}
void Indicator::setIndicatorTime(int time)
{
ui->m_widgetTrackHeader->setIndicatorTime(time);
}
void Indicator::updateMe()
{
ui->m_widgetTrackHeader->updateMe();
update();
}
void Indicator::resizeEvent(QResizeEvent*)
{
slotSplitterMoved();
}
void Indicator::slotSplitterMoved()
{
int newSize = ui->m_widgetTrackLabel->width() + ui->splitter->handleWidth();
if (newSize < 0)
newSize = 0;
emit signalHandleResized(newSize);
}
} // namespace LtsScriptTimeline
@@ -1,41 +0,0 @@
#pragma once
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace Ui
{
class Indicator;
}
namespace LtsScriptTimeline
{
class Tools;
class Indicator : public QWidget
{
Q_OBJECT
public:
explicit Indicator(QWidget* parent = nullptr);
~Indicator();
void updateMe();
void setIndicatorTime(int time);
void lockIndicator(bool lock = true);
void setTools(Tools* tools);
private:
void resizeEvent(QResizeEvent* event);
Ui::Indicator* ui;
signals:
void signalHandleResized(int width);
void signalHeaderIndicatorTimeChanged(int time);
void signalHeaderIndicatorTimeUserChanged(int time);
private slots:
void slotSplitterMoved();
};
} // namespace LtsScriptTimeline
@@ -1,12 +0,0 @@
#ifndef LTSSCRIPTTIMELINE_EXPORT_H
#define LTSSCRIPTTIMELINE_EXPORT_H
#include <QtCore/qglobal.h>
#if defined(LTSSCRIPTTIMELINE_LIBRARY)
# define LTSSCRIPTTIMELINE_EXPORT Q_DECL_EXPORT
#else
# define LTSSCRIPTTIMELINE_EXPORT Q_DECL_IMPORT
#endif
#endif // LTSSCRIPTTIMELINE_EXPORT_H
File diff suppressed because it is too large. Load diff
@@ -1,136 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include "track_entry_painters.h"
#include <QtGui/QKeyEvent>
#include <QtCore/QObject>
#include <QtCore/QPointer>
#include <QtWidgets/QWidget>
namespace Ui
{
class ScriptTimeline;
}
class QRubberBand;
namespace LtsScriptTimeline
{
class TrackContentWidget;
class TrackWidget;
class TrackEntry;
class Tools;
class LTSSCRIPTTIMELINE_EXPORT ScriptTimeline : public QWidget
{
Q_OBJECT
public:
explicit ScriptTimeline(QWidget* parent = nullptr);
~ScriptTimeline();
TrackWidget* addTrack(const QString& name, bool filtersAllowed = true);
void setScriptId(int scriptId)
{
m_scriptId = scriptId;
}
bool addTopic(TrackEntry* te);
QString newTrackName() const;
int nextUniqueId()
{
return ++m_uniqueId;
}
void setUniqueIdCounter(int uniqueId)
{
m_uniqueId = uniqueId;
}
QVector<TrackEntry*> getTrackEntriesWithFiltersAsEntries(bool selectedEntriesOnly = false) const;
QMap<QString, QVector<TrackEntry*>> getTrackEntriesWithFilters(bool selectedEntriesOnly = false) const;
QVector<TrackEntry*> getTrackEntries(bool selectedEntriesOnly = false) const;
QVector<TrackEntry*> getSelectedEntriesWithFilterEntries() const;
QVector<TrackEntry*> getSelectedFilterEntries() const;
TrackEntry* getTrackEntry(int topicId);
TrackEntry* getTrackEntryWithFiltersAsEntries(int topicId);
void setIndicatorTime(int time);
int getCurrentScriptEndTime();
void updateEverything();
void clear();
void setReadonly(bool readonly);
QList<TrackWidget*> getTrackWidgets() const;
void lockIndicator(bool lock = true);
int getFilterTrackEntryRealTime(TrackEntry* te);
bool checkNewLength(TrackEntry* te, int newLength);
bool importTrackEntries(const QVector<LtsScriptTimeline::TrackEntry*>& importTes);
protected:
void keyPressEvent(QKeyEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent*) override;
void mouseReleaseEvent(QMouseEvent*) override;
private:
Ui::ScriptTimeline* ui;
int m_uniqueId;
int m_scriptId;
int m_baseTrackWidgetWidth;
QVector<TrackEntry*> m_clipboard;
bool m_readonly;
int m_time;
Tools* m_tools;
TrackContentWidget* m_mlmsMaster;
QHash<TrackContentWidget*, bool> m_mlmsTCWStates;
bool m_ignoreChanges;
QHash<TrackWidget*, QByteArray> m_copyTopics;
struct RubberbandAction
{
QPoint origin;
QPointer<QRubberBand> rubberBand;
} m_rubberbandAction;
void resizeEvent(QResizeEvent* event) override;
void updateAllTracks();
signals:
void signalTrackEntrySelectionChanged(TrackEntry* te);
void signalChangesMade();
void signalHeaderIndicatorTimeChanged(int time);
void signalHeaderIndicatorTimeUserChanged(int time);
void signalEditEntry(const int topicId);
void signalTrackEntryDeleted(const int topicId);
void signalTrackEntryAdded(TrackEntry* te);
void signalSave();
public slots:
void slotUnselectAll();
void slotEscapeRubberband();
void slotStopRubberband();
void slotStartRubberband(const QPoint& pos);
void slotModifyRubberband();
void selectAll();
void slotCopyTopics();
void slotCutTopics();
void slotPasteTopics();
void slotDeleteSelectedTopics();
void slotMoveAll(int direction);
void slotScroll(int incr);
private slots:
void slotScrollbarValueChanged();
void slotZoomValueChanged(int value);
void slotDeleteTracks();
void slotSelectTrack();
void slotHeaderHandleResized(int newSize);
void slotHeaderIndicatorTimeChanged(int time);
void slotTrackEntrySelectionChanged(TrackEntry* te);
void slotSetNewScrollBarMaximum();
};
} // namespace LtsScriptTimeline
@@ -1,43 +0,0 @@
#pragma once
#include <QtCore/QDebug>
#include <QtCore/QVector>
namespace LtsScriptTimeline
{
template <typename T> class TemporaryPointerVector : public QVector<T>
{
static_assert(std::is_pointer<T>::value, "Type must be of pointer type");
public:
TemporaryPointerVector() = default;
explicit TemporaryPointerVector(const QVector<T>& other)
{
discard();
this->append(other);
}
~TemporaryPointerVector()
{
discard();
}
void setDiscardable(bool discardable)
{
m_discard = discardable;
}
private:
bool m_discard = true;
void discard()
{
if (m_discard)
qDeleteAll(this->begin(), this->end());
this->clear();
}
};
} // namespace LtsScriptTimeline
@@ -1,75 +0,0 @@
#include "tools.h"
#include <math.h>
namespace LtsScriptTimeline
{
int Tools::getLength(int startTime, int duration)
{
return (getPos(startTime + duration) - getPos(startTime));
}
int Tools::getDuration(int duration)
{
double max = Tools::m_timelineLength;
max /= Tools::m_zoomFactor;
int paintWidth = m_paintWidth;
double x = duration;
x /= paintWidth;
x *= max;
return lrint(x);
}
int Tools::getTime(int pos, bool neutral)
{
double visibleMax = Tools::m_timelineLength;
visibleMax /= Tools::m_zoomFactor;
if (!neutral)
visibleMax += Tools::m_scrollPos;
int visibleMin = 0;
if (!neutral)
visibleMin = Tools::m_scrollPos;
double diff = visibleMax - visibleMin;
int paintWidth = m_paintWidth;
double x = pos;
x /= paintWidth;
x *= diff;
x += visibleMin;
return lrint(x);
}
int Tools::getPos(int time, bool neutral)
{
double visibleMax = Tools::m_timelineLength;
visibleMax /= Tools::m_zoomFactor;
if (!neutral)
visibleMax += Tools::m_scrollPos;
int visibleMin = 0;
if (!neutral)
visibleMin = Tools::m_scrollPos;
double diff = visibleMax - visibleMin;
int paintWidth = m_paintWidth;
double x = time;
x -= visibleMin;
x /= diff;
x *= paintWidth;
return lrint(x);
}
} // namespace LtsScriptTimeline
@@ -1,29 +0,0 @@
#pragma once
#include <QtCore/QObject>
namespace LtsScriptTimeline
{
class Tools : public QObject
{
Q_OBJECT
public:
explicit Tools(QObject* parent)
: QObject(parent), m_timelineLength(5 * 60), m_zoomFactor(1), m_scrollPos(0), m_paintWidth(1)
{
}
int m_timelineLength;
float m_zoomFactor;
int m_scrollPos;
int m_paintWidth;
int getDuration(int duration);
int getTime(int pos, bool neutral = false);
int getPos(int time, bool neutral = false);
int getLength(int startTime, int duration);
};
} // namespace LtsScriptTimeline
@@ -1,243 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace LtsScriptTimeline
{
class TrackEntry;
enum class TrackEntryType;
class TrackWidget;
class ScriptTimeline;
class Tools;
class DragHandler;
class ResizeHandler;
class SelectHandler;
LTSSCRIPTTIMELINE_EXPORT QDataStream& operator<<(QDataStream& ds, const TrackEntry& te);
LTSSCRIPTTIMELINE_EXPORT QDataStream& operator>>(QDataStream& ds, TrackEntry& te);
LTSSCRIPTTIMELINE_EXPORT bool isCollision(int start_s, int end_s, int toCompare_start_s, int toCompare_end_s);
LTSSCRIPTTIMELINE_EXPORT bool isCollision2(int startPreview_s, int endPreview_s, const TrackEntry* pTrackEntry);
class LTSSCRIPTTIMELINE_EXPORT TrackContentWidget : public QWidget
{
Q_OBJECT
public:
explicit TrackContentWidget(QWidget* parent = nullptr, bool isFilter = false, Tools* tools = nullptr,
int mainTopicId = -1);
~TrackContentWidget() override;
bool addTrackEntry(TrackEntry* te, bool selectTrackEntry);
void removeTrackEntryByTopicId(TrackEntry* te);
void selectAll();
void unselectAll();
const QVector<TrackEntry*>& getTrackEntries() const
{
return m_entryList;
}
const QVector<TrackEntry*>& getSelectedEntries() const
{
return m_selected;
}
void setIndicatorTime(int time);
void setTrackName(const QString& trackName);
void deleteSelectedTopics();
void selectEntry(int topicId);
void setTopicFilterId(int id)
{
m_topicFilterId = id;
}
int topicFilterId() const
{
return m_topicFilterId;
}
void setReadonly(bool readonly);
void addAllowedType(const TrackEntryType& tet)
{
m_allowedTypes.append(tet);
}
void addDisallowedType(const TrackEntryType& tet)
{
m_disallowedTypes.append(tet);
}
void setTrackWidget(TrackWidget* trackWidget);
void setScriptTimeline(ScriptTimeline* scriptTimeline)
{
m_scriptTimeline = scriptTimeline;
}
void setTools(Tools* tools);
void addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget);
static QString parallelError();
bool isMultiLineMultiSelectionMode() const
{
return m_isMultiLineMultiSelectionMode;
}
void setMultiLineMultiSelectionMode(bool active)
{
m_isMultiLineMultiSelectionMode = active;
}
bool isDragPossible() const
{
return (!m_isMultiLineMultiSelectionMode || m_dragPossible);
}
void selectEntriesAtPositions(int fromPos, int toPos);
void forceLocalUnselect();
static bool checkForParallelTopics(const TrackContentWidget* pTCW,
const QVector<TrackEntry*>& vecPreviewTrackEntries, int dropTime_s,
bool hack = false);
static bool checkForParallelTopics(const TrackContentWidget* tcw, const QVector<TrackEntry*>& preview,
int dropTime_s, QVector<TrackEntry*>& vecParallelTopics,
bool ignoreSelectedTopics = false, bool hack = false);
static bool checkForCollisions(const TrackContentWidget* tcw, const QVector<TrackEntry*>& preview, int dropTime_s,
QVector<TrackEntry*>& vecCollisions, bool ignoreSelected = false,
bool ignoreSelfCheck = false);
static bool checkForCollisions(const TrackContentWidget* pTCW, const QVector<TrackEntry*>& vecPreviewTrackEntries,
int dropTime_s);
bool checkForCollisionsSimple(const TrackEntry& previewEntry) const;
QByteArray selectedItemsToData(int dragPosTime = 0, bool calculateFirstTeTime = true);
static QByteArray itemsToData(const QVector<TrackEntry*>& items, int dragPosTime = 0,
bool calculateFirstTeTime = true);
static QVector<TrackEntry*> dataToItems(const QByteArray& data, int& offset);
bool canPasteTopics(const QVector<TrackEntry*>& topics, int offsetTime, int pasteTime) const;
void forcePasteTopics(const QVector<TrackEntry*>& topics, int offsetTime, int pasteTime);
bool canMoveAll(int offset) const;
void forceMoveAll(int offset);
bool setDescriptionForSelected();
static QString mime;
void dragEnd();
void setDragPossible(bool possible);
void dragLeave();
bool dragEnter(const QByteArray& itemData);
bool dragMove(int pos);
bool dragDrop(int pos);
void clearDrag();
int getDropPos() const;
TrackWidget* trackWidget()
{
return m_trackWidget;
}
TrackEntry* trackEntryAtPos(int x) const;
void keyPressEvent(QKeyEvent* event) override;
protected:
void paintEvent(QPaintEvent* event) override;
void dragEnterEvent(QDragEnterEvent* event) override;
void dragLeaveEvent(QDragLeaveEvent* event) override;
void dropEvent(QDropEvent* event) override;
void dragMoveEvent(QDragMoveEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseMoveEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
private:
TrackEntry* getTrackEntryOnPos(QPoint globalPos);
bool allowedByType(const TrackEntry* te) const;
TrackEntry* getParentTopicOfFilter(TrackEntry* filterTe) const;
int m_topicFilterId = -1;
friend class SelectHandler;
SelectHandler* m_selectHandler;
friend class ResizeHandler;
ResizeHandler* m_resizeHandler;
friend class DragHandler;
DragHandler* m_dragHandler;
void selectEntry(TrackEntry* te);
void addFilterType(const TrackEntryType& tet);
void unselect();
void moveAll(int offset);
bool handleResize(int cursorTime, bool leftButton);
bool handleDrag(int cursorTime, bool leftButton);
void cancelResize();
TrackEntry* getTrackEntryAt(int clickedTime);
void clearPreview();
int dragPos() const
{
return m_dragPos;
}
int m_dragOffsetTime;
int m_dragPos;
QVector<TrackEntry*> m_entryList;
QVector<TrackEntry*> m_selected;
TrackEntry* m_mainSelected;
QVector<TrackEntry*> m_preview;
int m_width;
bool m_cursorSet;
int m_oldEntryLength;
bool m_unselectAllImmune;
int m_indicatorTime;
QString m_trackName;
QVector<TrackEntryType> m_allowedTypes;
QVector<TrackEntryType> m_disallowedTypes;
bool m_isFilter;
bool m_readonly;
TrackWidget* m_trackWidget;
ScriptTimeline* m_scriptTimeline;
Tools* m_tools;
QVector<TrackContentWidget*> m_tcwCorresponding;
bool m_isMultiLineMultiSelectionMode;
bool m_multiLineMultiSelectionOkay;
bool m_dragPossible;
bool m_moveValid;
int m_mainTopicId;
signals:
void signalUnselectAll();
void signalTrackEntrySelectionChanged(TrackEntry*);
void signalChangesMade();
void signalTrackEntryAdded(TrackEntry* te);
void signalTrackEntryDeleted(const int topicId);
void signalEditEntry(const int topicId);
void signalMultiLineMultiSelectionFailed();
void signalMultiLineMultiSelectionOkay();
void signalMultiLineMultiSelectionDone(int dropPos);
void signalMultiLineMultiSelectionStart(int dragPosTime);
void signalMultiLineMultiSelectionMove(int x);
void signalStartRubberband(QPoint pos);
void signalStopRubberband();
void signalEscapeRubberband();
void signalModifyRubberband();
void signalSelectAllGlobal();
void signalCopyTopics();
void signalPasteTopics();
void signalCutTopics();
void signalDeleteSelectedTopics();
void signalSave();
void signalMoveAll(int offset);
void signalScroll(int incr);
};
} // namespace LtsScriptTimeline
@@ -1,164 +0,0 @@
#include "track_drag_handler.h"
#include "script_timeline.h"
#include "tools.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include "track_widget.h"
#include <LtsWidgets/lts_message_dialog.h>
#include <QtWidgets/QApplication>
#include <QtCore/QDebug>
#include <QDrag>
#include <QtGui/QDragEnterEvent>
#include <QtGui/QDropEvent>
#include <QtGui/QGuiApplication>
#include <QMimeData>
#include <utility>
namespace LtsScriptTimeline
{
void DragHandler::dragEnterEvent(QDragEnterEvent* event)
{
if (m_tcw->isMultiLineMultiSelectionMode())
{
if (event->source() != m_tcw)
{
event->ignore();
return;
}
else
{
for (const auto& tcw : std::as_const(m_tcwCorresponding))
tcw->dragEnter(tcw->selectedItemsToData(tcw->m_tools->getTime(m_dragStartPos.x())));
}
}
m_tcw->dragEnd();
if (!event->mimeData()->hasFormat(TrackContentWidget::mime))
return;
if (m_tcw->dragEnter(event->mimeData()->data(TrackContentWidget::mime)))
event->acceptProposedAction();
}
void DragHandler::dragLeaveEvent(QDragLeaveEvent* event)
{
if (m_tcw->isMultiLineMultiSelectionMode())
{
event->ignore();
for (const auto& tcw : std::as_const(m_tcwCorresponding))
tcw->dragEnd();
}
m_tcw->dragEnd();
}
void DragHandler::dropEvent(QDropEvent* event)
{
int dropPos = event->position().toPoint().x();
int dropTime = m_tcw->m_tools->getTime(dropPos, m_tcw->m_isFilter) - m_tcw->m_dragOffsetTime;
for (const auto& tcw : std::as_const(m_tcwCorresponding))
{
bool hasParallelTopicsOfSameType = TrackContentWidget::checkForParallelTopics(tcw, m_tcw->m_preview, dropTime);
if (hasParallelTopicsOfSameType)
{
new LtsWidgets::LtsMessageDialogNew(m_tcw, TrackContentWidget::parallelError(), QObject::tr("Error"));
break;
}
}
if (m_tcw->dragDrop(dropPos))
event->acceptProposedAction();
else
emit m_tcw->signalMultiLineMultiSelectionDone(0);
}
void DragHandler::dragMoveEvent(QDragMoveEvent* event)
{
int pos = event->position().toPoint().x();
if (m_tcw->dragMove(pos))
event->acceptProposedAction();
if (m_tcw->isMultiLineMultiSelectionMode())
emit m_tcw->signalMultiLineMultiSelectionMove(pos);
}
void DragHandler::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() != Qt::LeftButton)
return;
m_dragStartPos = event->pos();
}
void DragHandler::mouseMoveEvent(QMouseEvent* event)
{
if (event->buttons() != Qt::LeftButton)
return;
QPoint cursorPos = m_tcw->mapFromGlobal(event->globalPosition().toPoint());
if (!m_tcw->m_mainSelected || ((cursorPos - m_dragStartPos).manhattanLength() < QApplication::startDragDistance() &&
(m_dragStartPos - cursorPos).manhattanLength() < QApplication::startDragDistance()))
return;
QVector<TrackEntry*> selected = m_tcw->getSelectedEntries();
if (selected.isEmpty())
return;
int cursorPosTime = m_tcw->m_tools->getTime(m_dragStartPos.x());
QMimeData* mimeData = new QMimeData();
mimeData->setData(TrackContentWidget::mime, m_tcw->selectedItemsToData(cursorPosTime));
QDrag* drag = new QDrag(m_tcw);
drag->setMimeData(mimeData);
if (m_tcw->isMultiLineMultiSelectionMode())
emit m_tcw->signalMultiLineMultiSelectionStart(cursorPosTime);
QVector<TrackEntry*> selectedOld = m_tcw->m_selected;
if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
{
if (!m_tcw->isMultiLineMultiSelectionMode())
{
for (auto i = selectedOld.begin(); i != selectedOld.end(); ++i)
emit m_tcw->signalTrackEntryDeleted((*i)->m_topicId);
qDeleteAll(selectedOld);
}
}
else
{
emit m_tcw->signalMultiLineMultiSelectionDone(-1);
}
}
void DragHandler::keyPressEvent(QKeyEvent* event)
{
switch (event->key())
{
case Qt::Key_Left: {
emit m_tcw->signalMoveAll(-1);
break;
}
case Qt::Key_Right: {
emit m_tcw->signalMoveAll(1);
break;
}
default: {
break;
}
}
}
} // namespace LtsScriptTimeline
@@ -1,32 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <QtWidgets/QWidget>
namespace LtsScriptTimeline
{
class TrackContentWidget;
class TrackEntry;
class LTSSCRIPTTIMELINE_EXPORT DragHandler
{
public:
explicit DragHandler(TrackContentWidget* _tcw) : m_tcw(_tcw), m_dropPos(-1) {}
void dragEnterEvent(QDragEnterEvent* event);
void dragLeaveEvent(QDragLeaveEvent* event);
void dropEvent(QDropEvent* event);
void dragMoveEvent(QDragMoveEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent* event);
TrackContentWidget* m_tcw;
QVector<TrackContentWidget*> m_tcwCorresponding;
QPoint m_dragStartPos;
QVector<TrackEntry*> m_vecCollisions, m_vecParallel;
int m_dropPos;
};
} // namespace LtsScriptTimeline
@@ -1,131 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include "track_entry_painters.h"
#include <QtCore/QJsonObject>
#include <QtCore/QObject>
namespace LtsScriptTimeline
{
class LTSSCRIPTTIMELINE_EXPORT TrackEntry : public QObject
{
Q_OBJECT
public:
explicit TrackEntry(const TrackEntryType& tet = TrackEntryType::INVALID)
: QObject(), m_topicId(-1), m_startTime(-1), m_length(-1), m_type(tet), isSet(false), index(-1), x(-1), y(-1),
h(-1), w(-1)
{
}
explicit TrackEntry(int topicId, int startTime, int length, LtsScriptTimeline::TrackEntryType type,
const QJsonObject& detailData, const QString& channelName, const QString& description)
: QObject(), m_topicId(topicId), m_startTime(startTime), m_length(length), m_type(type), isSet(false),
index(-1), x(-1), y(-1), h(-1), w(-1), m_detailData(detailData), m_channelName(channelName)
,
m_description(description)
{
}
explicit TrackEntry(const TrackEntry& te)
: QObject(), m_topicId(te.m_topicId), m_startTime(te.m_startTime), m_length(te.m_length), m_type(te.m_type),
isSet(te.isSet), index(te.index), x(te.x), y(te.y), h(te.h), w(te.w), m_detailData(te.m_detailData),
m_channelName(te.m_channelName), m_description(te.m_description),
m_filterParentChannel(te.m_filterParentChannel)
{
}
explicit TrackEntry(TrackEntry* te)
: QObject(), m_topicId(te->m_topicId), m_startTime(te->m_startTime), m_length(te->m_length), m_type(te->m_type),
isSet(te->isSet), index(te->index), x(te->x), y(te->y), h(te->h), w(te->w), m_detailData(te->m_detailData),
m_channelName(te->m_channelName), m_description(te->m_description),
m_filterParentChannel(te->m_filterParentChannel)
{
}
TrackEntry(const TrackEntryType& tet, int length)
: QObject(), m_topicId(-1), m_startTime(-1), m_length(length), m_type(tet), isSet(false), index(-1), x(-1),
y(-1), h(-1), w(-1)
{
}
~TrackEntry() {}
TrackEntry& operator=(const TrackEntry& other)
{
this->m_topicId = other.m_topicId;
this->m_startTime = other.m_startTime;
this->m_length = other.m_length;
this->m_type = other.m_type;
this->isSet = other.isSet;
this->index = other.index;
this->x = other.x;
this->y = other.y;
this->h = other.h;
this->w = other.w;
this->m_detailData = other.m_detailData;
this->m_channelName = other.m_channelName;
this->m_filterParentChannel = other.m_filterParentChannel;
this->m_description = other.m_description;
return *this;
}
int m_topicId;
int m_startTime;
int m_length;
TrackEntryType m_type;
bool isSet;
int index;
double x;
double y;
double h;
double w;
QJsonObject m_detailData;
QString m_channelName;
QString m_description;
QString m_filterParentChannel;
QJsonObject toJson() const
{
return QJsonObject({{QStringLiteral("topicId"), m_topicId},
{QStringLiteral("startTime"), m_startTime},
{QStringLiteral("length"), m_length},
{QStringLiteral("type"), static_cast<int>(m_type)},
{QStringLiteral("isSet"), isSet},
{QStringLiteral("index"), index},
{QStringLiteral("x"), x},
{QStringLiteral("y"), y},
{QStringLiteral("w"), w},
{QStringLiteral("h"), h},
{QStringLiteral("detailData"), m_detailData},
{QStringLiteral("channelName"), m_channelName},
{QStringLiteral("description"), m_description},
{QStringLiteral("filterParentChannel"), m_filterParentChannel}});
}
void fromJson(const QJsonObject& obj)
{
m_topicId = obj[QStringLiteral("topicId")].toInt();
m_startTime = obj[QStringLiteral("startTime")].toInt(-1);
m_length = obj[QStringLiteral("length")].toInt(-1);
m_type = static_cast<TrackEntryType>(obj[QStringLiteral("type")].toInt());
isSet = obj[QStringLiteral("isSet")].toBool();
index = obj[QStringLiteral("index")].toInt();
x = obj[QStringLiteral("x")].toDouble();
y = obj[QStringLiteral("y")].toDouble();
w = obj[QStringLiteral("w")].toDouble();
h = obj[QStringLiteral("h")].toDouble();
m_detailData = obj[QStringLiteral("detailData")].toObject();
m_channelName = obj[QStringLiteral("channelName")].toString();
m_description = obj[QStringLiteral("description")].toString();
m_filterParentChannel = obj[QStringLiteral("filterParentChannel")].toString();
}
};
} // namespace LtsScriptTimeline
@@ -1,328 +0,0 @@
#include "track_entry_painters.h"
#include "track_entry.h"
#include <QtCore/QDebug>
#include <QtCore/QObject>
namespace LtsScriptTimeline
{
QString translateTrackEntryType(const TrackEntryType& tet)
{
switch (tet)
{
case TrackEntryType::INVALID:
return QObject::tr("<unknown>");
case TrackEntryType::SituationMap:
return QObject::tr("Map");
case TrackEntryType::Situation:
return QObject::tr("Situation");
case TrackEntryType::SituationReplay:
return QObject::tr("Replay");
case TrackEntryType::Snapshot:
return QObject::tr("Snapshot");
case TrackEntryType::Image:
return QObject::tr("Image");
case TrackEntryType::Text:
return QObject::tr("Text");
case TrackEntryType::Pdf:
return QObject::tr("Pdf");
case TrackEntryType::Xml:
return QObject::tr("Xml");
case TrackEntryType::MSOffice:
return QObject::tr("MS Office");
case TrackEntryType::OpenOffice:
return QObject::tr("Open Office");
case TrackEntryType::Audio:
return QObject::tr("Audio");
case TrackEntryType::Video:
return QObject::tr("Video");
case TrackEntryType::Building:
return QObject::tr("Building");
case TrackEntryType::Evaluation:
return QObject::tr("Evaluation");
case TrackEntryType::Report:
return QObject::tr("Report");
case TrackEntryType::TacticalPlan:
return QObject::tr("Tactical Plan Map Filter");
case TrackEntryType::SituationMapFilter:
return QObject::tr("Map Filter");
}
return QString();
}
QString trackEntryTypeName(const TrackEntryType& tet)
{
switch (tet)
{
case TrackEntryType::INVALID:
return QStringLiteral("<unknown>");
case TrackEntryType::SituationMap:
return QStringLiteral("SituationMap");
case TrackEntryType::Situation:
return QStringLiteral("SituationReplayAndMap");
case TrackEntryType::SituationReplay:
return QStringLiteral("SituationReplay");
case TrackEntryType::Image:
return QStringLiteral("Image");
case TrackEntryType::Text:
return QStringLiteral("Text");
case TrackEntryType::Pdf:
return QStringLiteral("Pdf");
case TrackEntryType::Xml:
return QStringLiteral("Xml");
case TrackEntryType::TacticalPlan:
return QStringLiteral("TacticalPlan");
case TrackEntryType::MSOffice:
return QStringLiteral("MSOffice");
case TrackEntryType::OpenOffice:
return QStringLiteral("OpenOffice");
case TrackEntryType::Audio:
return QStringLiteral("Audio");
case TrackEntryType::Video:
return QStringLiteral("Video");
case TrackEntryType::Building:
return QStringLiteral("Building");
case TrackEntryType::SituationMapFilter:
return QStringLiteral("SituationMapFilter");
case TrackEntryType::Snapshot:
return QStringLiteral("Snapshot");
case TrackEntryType::Evaluation:
return QStringLiteral("Evaluation");
case TrackEntryType::Report:
return QStringLiteral("Report");
}
return QString();
}
QIcon appToIcon(const TrackEntryType type)
{
switch (type)
{
case LtsScriptTimeline::TrackEntryType::INVALID:
return QIcon();
case LtsScriptTimeline::TrackEntryType::SituationMap:
return QIcon(QLatin1String("icon:add_situation.svg"));
case LtsScriptTimeline::TrackEntryType::Situation:
return QIcon(QLatin1String("icon:add_situation_combined.svg"));
case LtsScriptTimeline::TrackEntryType::SituationReplay:
return QIcon(QLatin1String("icon:add_restart.svg"));
case LtsScriptTimeline::TrackEntryType::Image:
return QIcon(QLatin1String("icon:create_image_topic.svg"));
case LtsScriptTimeline::TrackEntryType::Text:
return QIcon(QLatin1String("icon:document-new-txt.svg"));
case LtsScriptTimeline::TrackEntryType::Pdf:
return QIcon(QLatin1String("icon:create_pdf_topic.svg"));
case LtsScriptTimeline::TrackEntryType::Xml:
return QIcon(QLatin1String("icon:document-new-xml.svg"));
case LtsScriptTimeline::TrackEntryType::TacticalPlan:
return QIcon(QLatin1String("icon:tactical_organization.svg"));
case LtsScriptTimeline::TrackEntryType::MSOffice:
return QIcon(QLatin1String("icon:ms_office.svg"));
case LtsScriptTimeline::TrackEntryType::OpenOffice:
return QIcon(QLatin1String("icon:documents.svg"));
case LtsScriptTimeline::TrackEntryType::Audio:
return QIcon(QLatin1String("icon:create_lecture_topic.svg"));
case LtsScriptTimeline::TrackEntryType::Video:
return QIcon(QLatin1String("icon:add_video_menu.svg"));
case LtsScriptTimeline::TrackEntryType::Building:
return QIcon(QLatin1String("icon:configure_buildings.svg"));
case LtsScriptTimeline::TrackEntryType::SituationMapFilter:
return QIcon(QLatin1String("icon:filter_player.svg"));
case LtsScriptTimeline::TrackEntryType::Snapshot:
return QIcon(QLatin1String("icon:create_snapshot.svg"));
case LtsScriptTimeline::TrackEntryType::Evaluation:
return QIcon(QLatin1String("icon:add_evaluation_elements.svg"));
case LtsScriptTimeline::TrackEntryType::Report:
return QIcon(QLatin1String("icon:add_reports_display.svg"));
}
return QIcon();
}
TrackEntryPainter* getTrackEntryPainter(const TrackEntryType& type)
{
TrackEntryPainter* trackEntryPainter = nullptr;
static TrackEntryPainter painter;
switch (type)
{
case TrackEntryType::SituationMap: {
painter = TrackEntryPainter(QColor(QStringLiteral("#b1cbbb")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Situation: {
painter = TrackEntryPainter(QColor(QStringLiteral("#b1c1cb")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::SituationReplay: {
painter = TrackEntryPainter(QColor(QStringLiteral("#c94c4c")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Audio: {
painter = TrackEntryPainter(QColor(QStringLiteral("#034f84")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Video: {
painter = TrackEntryPainter(QColor(QStringLiteral("#618685")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Image: {
painter = TrackEntryPainter(QColor(QStringLiteral("#fefbd8")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Evaluation: {
painter = TrackEntryPainter(QColor(QStringLiteral("#d6cbd3")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Pdf: {
painter = TrackEntryPainter(QColor(QStringLiteral("#80ced6")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Text: {
painter = TrackEntryPainter(QColor(QStringLiteral("#92a8d1")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Xml: {
painter = TrackEntryPainter(QColor(QStringLiteral("#eea29a")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::TacticalPlan: {
painter = TrackEntryPainter(QColor(QStringLiteral("#dac292")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::MSOffice: {
painter = TrackEntryPainter(QColor(QStringLiteral("#f7cac9")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::OpenOffice: {
painter = TrackEntryPainter(QColor(QStringLiteral("#b2b2b2")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Building: {
painter = TrackEntryPainter(QColor(QStringLiteral("#c6bcb6")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::SituationMapFilter: {
painter = TrackEntryPainter(QColor(QStringLiteral("#36486b")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Snapshot: {
painter = TrackEntryPainter(QColor(QStringLiteral("#f18973")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
case TrackEntryType::Report: {
painter = TrackEntryPainter(QColor(QStringLiteral("#feb236")), translateTrackEntryType(type));
trackEntryPainter = static_cast<TrackEntryPainter*>(&painter);
break;
}
default: {
qWarning() << "no painter found for type" << (int)type;
trackEntryPainter = nullptr;
break;
}
}
return trackEntryPainter;
}
void drawTrackEntry(TrackEntry* te, QPainter& painter, const QRect& trackRect, bool isSelected, bool isEnabled)
{
TrackEntryPainter* trackEntryPainter = getTrackEntryPainter(te->m_type);
if (!trackEntryPainter)
return;
QColor trackEntryBgColor = trackEntryPainter->bgColor();
if (isSelected)
{
int r = trackEntryBgColor.red();
int g = trackEntryBgColor.green();
int b = trackEntryBgColor.blue();
trackEntryBgColor = trackEntryBgColor.lighter();
painter.setPen(QColor(255 - r, 255 - g, 255 - b));
}
else if (!isEnabled)
{
trackEntryBgColor = QColor(200, 200, 200);
painter.setPen(QColor("white"));
}
else
painter.setPen(QColor(36, 36, 36));
painter.setBrush(trackEntryBgColor);
painter.drawRect(trackRect);
if (trackRect.width() < 20)
return;
QRect trackEntryPainterRect(trackRect.adjusted(1, 1, -1, -1));
painter.save();
painter.setClipping(true);
painter.setClipRect(trackEntryPainterRect, Qt::ReplaceClip);
trackEntryPainter->paintEvent(painter, trackEntryPainterRect);
painter.drawText(trackEntryPainterRect.adjusted(3, 16, 5000, 0), te->m_description);
painter.restore();
if (trackRect.width() < 12)
return;
int trackRectEnd = trackRect.right();
int gradientLength = 12;
QRect gradientRect(trackRectEnd - gradientLength, 2, gradientLength, trackRect.height() - 2);
QLinearGradient gradient(gradientRect.bottomRight(), gradientRect.bottomLeft());
int r = trackEntryBgColor.red();
int g = trackEntryBgColor.green();
int b = trackEntryBgColor.blue();
gradient.setColorAt(0, QColor(r, g, b, 255));
gradient.setColorAt(1, QColor(r, g, b, 0));
painter.fillRect(gradientRect, gradient);
}
} // namespace LtsScriptTimeline
@@ -1,89 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <QtGui/QColor>
#include <QtGui/QIcon>
#include <QtGui/QPainter>
#include <QtGui/QPen>
#include <QtCore/QRect>
namespace LtsScriptTimeline
{
class TrackEntry;
enum class TrackEntryType {
INVALID,
SituationMap,
SituationReplay,
Image,
Text,
Pdf,
Xml,
TacticalPlan,
MSOffice,
OpenOffice,
Audio,
Video,
Building,
SituationMapFilter,
Snapshot,
Evaluation,
Report,
Situation
};
LTSSCRIPTTIMELINE_EXPORT QString translateTrackEntryType(const TrackEntryType& tet);
LTSSCRIPTTIMELINE_EXPORT QString trackEntryTypeName(const TrackEntryType& tet);
LTSSCRIPTTIMELINE_EXPORT QIcon appToIcon(const TrackEntryType type);
inline std::ostream& operator<<(std::ostream& stream, const TrackEntryType tet)
{
return stream << trackEntryTypeName(tet).toStdString();
}
class LTSSCRIPTTIMELINE_EXPORT TrackEntryPainter
{
public:
explicit TrackEntryPainter(const QColor& bgColor = QColor(0, 0, 0),
const QString& trackEntryType = QStringLiteral("INVALID"))
: m_bgColor(bgColor), m_trackEntryType(trackEntryType)
{
}
void paintEvent(QPainter& painter, const QRect& rect)
{
painter.setPen(QPen(Qt::black));
painter.drawText(rect.adjusted(3, 0, 5000, 0), m_trackEntryType);
}
QColor bgColor() const
{
return m_bgColor;
}
void setBgColor(const QColor& bgColor)
{
m_bgColor = bgColor;
}
const QString& trackEntryType() const
{
return m_trackEntryType;
}
void setTrackEntryType(const QString& trackEntryType)
{
m_trackEntryType = trackEntryType;
}
protected:
QColor m_bgColor;
QString m_trackEntryType;
};
void drawTrackEntry(TrackEntry* te, QPainter& painter, const QRect& trackRect, bool isSelected, bool isEnabled = true);
TrackEntryPainter* getTrackEntryPainter(const TrackEntryType& type);
} // namespace LtsScriptTimeline
@@ -1,89 +0,0 @@
#include "track_entry_preview_widget.h"
#include "track_entry.h"
#include "ui_track_entry_preview_widget.h"
#include <LtsSession/lts_session_data.h>
#include <LtsWidgets/lts_message_dialog.h>
#include <QtGui/QContextMenuEvent>
#include <QtCore/QJsonDocument>
#include <QtWidgets/QMenu>
#include <QtWidgets/QTextEdit>
namespace LtsScriptTimeline
{
TrackEntryPreviewWidget::TrackEntryPreviewWidget(QWidget* parent)
: QWidget(parent), m_ui(new Ui::TrackEntryPreviewWidget)
{
m_ui->setupUi(this);
#ifndef LTS_DEBUG
m_ui->lbTopicId->hide();
m_ui->lblTopicId->hide();
m_ui->lbLen->hide();
m_ui->lblLen->hide();
#endif
connect(m_ui->widget, &TrackEntryPreviewer::signalDelete, this, &TrackEntryPreviewWidget::signalDelete);
connect(m_ui->widget, &TrackEntryPreviewer::signalStartDrag, this, &TrackEntryPreviewWidget::signalStartDrag);
connect(m_ui->widget, &TrackEntryPreviewer::signalStopDrag, this, &TrackEntryPreviewWidget::signalStopDrag);
}
TrackEntryPreviewWidget::~TrackEntryPreviewWidget()
{
delete m_ui;
}
void TrackEntryPreviewWidget::contextMenuEvent(QContextMenuEvent* event)
{
#ifndef LTS_DEBUG
if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(
QStringLiteral("TrackEntryPreviewWidget.DebugMenu")) == QVariant(true))
#endif
{
QMenu* m = new QMenu(this);
m->setAttribute(Qt::WA_DeleteOnClose);
QPoint p = mapToGlobal(m->pos());
m->setGeometry(QRect(p, QPoint(event->x(), event->y())));
m->addAction(QStringLiteral("enable"), this, [this]() { setTopicEnabled(true); });
m->addAction(QStringLiteral("disable"), this, [this]() { setTopicEnabled(false); });
m->addAction(QStringLiteral("show detail data"), this, [this]() {
TrackEntry* te = m_ui->widget->trackEntry();
if (te == nullptr)
{
LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("no te was set"));
return;
}
QTextEdit* ted = new QTextEdit(nullptr);
ted->setAttribute(Qt::WA_DeleteOnClose);
ted->setWindowTitle(QStringLiteral("Track Entry #%1 - Detail Data string").arg(te->m_topicId));
ted->setText(QString::fromUtf8(QJsonDocument(te->m_detailData).toJson()));
ted->setReadOnly(true);
ted->show();
});
m->show();
}
}
void TrackEntryPreviewWidget::setTopicEnabled(bool enabled)
{
m_ui->widget->setEnabled(enabled);
}
void TrackEntryPreviewWidget::setTrackEntry(TrackEntry* te)
{
m_ui->lblDnD->setVisible(!te->isSet);
m_ui->widget->setVisible(!te->isSet);
m_ui->lbTopicId->setText(QString::number(te->m_topicId));
m_ui->lbLen->setText(QString::number(te->m_length));
m_ui->widget->setTrackEntry(te);
}
} // namespace LtsScriptTimeline
@@ -1,39 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace Ui
{
class TrackEntryPreviewWidget;
}
namespace LtsScriptTimeline
{
class TrackEntry;
class LTSSCRIPTTIMELINE_EXPORT TrackEntryPreviewWidget : public QWidget
{
Q_OBJECT
public:
explicit TrackEntryPreviewWidget(QWidget* parent = nullptr);
~TrackEntryPreviewWidget();
void setTrackEntry(TrackEntry* te);
void setTopicEnabled(bool enabled);
private:
Ui::TrackEntryPreviewWidget* m_ui;
void contextMenuEvent(QContextMenuEvent* event);
signals:
void signalStartDrag();
void signalStopDrag();
void signalDelete();
};
} // namespace LtsScriptTimeline
@@ -1,76 +0,0 @@
#include "track_entry_previewer.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include "track_entry_painters.h"
#include <QDrag>
#include <QMimeData>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
namespace LtsScriptTimeline
{
QDataStream& operator<<(QDataStream& ds, const TrackEntry& te);
QDataStream& operator>>(QDataStream& ds, TrackEntry& te);
TrackEntryPreviewer::TrackEntryPreviewer(QWidget* parent) : QWidget(parent), m_te(nullptr)
{
setVisible(false);
}
TrackEntryPreviewer::~TrackEntryPreviewer() {}
void TrackEntryPreviewer::setTrackEntry(TrackEntry* te)
{
m_te = te;
if (m_te->isSet)
return;
connect(m_te, &TrackEntry::destroyed, this, [this]() {
m_te = nullptr;
emit signalDelete();
});
}
void TrackEntryPreviewer::mousePressEvent(QMouseEvent* event)
{
if (!m_te || event->buttons() != Qt::LeftButton)
return;
m_te->isSet = true;
QByteArray itemData(TrackContentWidget::itemsToData({m_te}, 0));
m_te->isSet = false;
QMimeData* mimeData = new QMimeData;
mimeData->setData(TrackContentWidget::mime, itemData);
QDrag* drag = new QDrag(this);
drag->setDragCursor(QPixmap(), Qt::CopyAction);
drag->setMimeData(mimeData);
emit signalStartDrag();
if (drag->exec(Qt::CopyAction) == Qt::CopyAction)
emit signalDelete();
emit signalStopDrag();
}
void TrackEntryPreviewer::paintEvent(QPaintEvent* event)
{
QWidget::paintEvent(event);
QPainter painter(this);
if (!m_te)
return;
drawTrackEntry(m_te, painter, rect().adjusted(0, 0, -1, -1), false, isEnabled());
}
} // namespace LtsScriptTimeline
@@ -1,37 +0,0 @@
#pragma once
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace LtsScriptTimeline
{
class TrackEntry;
class TrackEntryPreviewer : public QWidget
{
Q_OBJECT
public:
explicit TrackEntryPreviewer(QWidget* parent = nullptr);
~TrackEntryPreviewer();
void setTrackEntry(TrackEntry* te);
TrackEntry* trackEntry() const
{
return m_te;
}
protected:
void paintEvent(QPaintEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
private:
TrackEntry* m_te;
signals:
void signalDelete();
void signalStartDrag();
void signalStopDrag();
};
} // namespace LtsScriptTimeline
@@ -1,158 +0,0 @@
#include "track_header.h"
#include "tools.h"
#include <QtWidgets/QApplication>
#include <QtGui/QBrush>
#include <QtGui/QColor>
#include <QCursor>
#include <QtCore/QDebug>
#include <QtGui/QFont>
#include <QFontMetrics>
#include <QtGui/QMouseEvent>
#include <QtGui/QPainter>
#include <QtGui/QPen>
#include <QtCore/QTime>
namespace LtsScriptTimeline
{
TrackHeader::TrackHeader(QWidget* parent)
: QWidget(parent), m_indicatorTime(-1), m_textMargin(12), m_textSpacing(10), m_indicatorLock(false),
m_tools(nullptr)
{
setCursor(Qt::IBeamCursor);
m_timeFormat = QStringLiteral("HH:mm:ss");
}
void TrackHeader::setTools(Tools* tools)
{
m_tools = tools;
}
void TrackHeader::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() != Qt::LeftButton)
return;
if (!m_indicatorLock)
{
setIndicatorTime(m_tools->getTime(event->position().toPoint().x()));
emit signalHeaderIndicatorTimeUserChanged(m_indicatorTime);
}
}
void TrackHeader::setIndicatorTime(int time)
{
m_indicatorTime = time;
emit signalHeaderIndicatorTimeChanged(m_indicatorTime);
update();
}
void TrackHeader::recreatePositionLabels()
{
QTime t;
t.setHMS(23, 59, 59);
QFontMetrics fm(QApplication::font());
#if QT_VERSION < QT_VERSION_CHECK(5, 11, 0)
int currentTextWidth = fm.width(t.toString());
#else
int currentTextWidth = fm.horizontalAdvance(t.toString());
#endif
if (currentTextWidth < 1)
{
qCritical() << "TrackHeader::recreatePositionLabels: invalid text size";
return;
}
int currentTextWidthTime = m_tools->getDuration(currentTextWidth);
int time = m_tools->getDuration(m_textMargin);
int end = (m_tools->m_timelineLength * 2) + currentTextWidthTime;
int paintStartTime = m_tools->getTime(0) - currentTextWidthTime;
int paintEndTime = m_tools->getTime(width() * 2);
int count = 0;
m_positionMarkers.clear();
int textSpacingTime = m_tools->getDuration(m_textSpacing);
while (time < end && count < 5000)
{
if (time >= paintStartTime && time <= paintEndTime)
{
m_positionMarkers.append(m_tools->getPos(time));
}
time += currentTextWidthTime + textSpacingTime;
count++;
}
update();
}
void TrackHeader::resizeEvent(QResizeEvent* event)
{
recreatePositionLabels();
QWidget::resizeEvent(event);
}
void TrackHeader::updateMe()
{
recreatePositionLabels();
update();
}
void TrackHeader::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
QWidget::paintEvent(event);
painter.save();
painter.setPen(QGuiApplication::palette().windowText().color());
painter.setBrush(QGuiApplication::palette().window().color());
painter.drawRect(rect().adjusted(0, 0, -1, -1));
int h = height();
if (m_indicatorTime > -1 && m_indicatorTime <= m_tools->getTime(width()))
{
painter.setPen(QColor("cyan"));
int indicatorPos = m_tools->getPos(m_indicatorTime);
painter.drawLine(indicatorPos, h - (h / 4), indicatorPos, h);
}
painter.setPen(QGuiApplication::palette().windowText().color());
for (auto i = m_positionMarkers.constBegin(); i != m_positionMarkers.constEnd(); ++i)
{
int pos = *i;
int time = m_tools->getTime(pos);
QTime t = QTime::fromMSecsSinceStartOfDay(time * 1000);
QString x = t.toString(m_timeFormat);
painter.drawText(pos, h / 2, x);
painter.save();
painter.setPen(QGuiApplication::palette().link().color());
painter.drawLine(pos, (h / 2) + 2, pos, h);
painter.restore();
}
painter.restore();
}
} // namespace LtsScriptTimeline
@@ -1,50 +0,0 @@
#pragma once
#include <QtCore/QObject>
#include <QtWidgets/QWidget>
namespace LtsScriptTimeline
{
class Tools;
class TrackHeader : public QWidget
{
Q_OBJECT
public:
explicit TrackHeader(QWidget* parent = nullptr);
void recreatePositionLabels();
void updateMe();
void setIndicatorTime(int time);
void lockIndicator(bool lock = true)
{
m_indicatorLock = lock;
}
void setTools(Tools* tools);
int indicatorTime() const
{
return m_indicatorTime;
}
private:
void resizeEvent(QResizeEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
int m_indicatorTime;
int m_textMargin;
int m_textSpacing;
QString m_timeFormat;
QVector<int> m_positionMarkers;
bool m_indicatorLock;
Tools* m_tools;
signals:
void signalHeaderIndicatorTimeChanged(int time);
void signalHeaderIndicatorTimeUserChanged(qint64 time);
};
} // namespace LtsScriptTimeline
@@ -1,183 +0,0 @@
#include "track_resize_handler.h"
#include "filter_background_widget.h"
#include "filter_track_widget.h"
#include "tools.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include "track_widget.h"
#include <LtsWidgets/lts_message_dialog.h>
#include <QtCore/QDebug>
#include <QtGui/QMouseEvent>
#include <utility>
namespace LtsScriptTimeline
{
void ResizeHandler::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() != Qt::LeftButton || !m_possible)
return;
TrackEntry* te = m_trackContentWidget->getTrackEntryOnPos(event->globalPosition().toPoint());
if (te == nullptr)
return;
m_oldLength = te->m_length;
m_resizing = true;
}
void ResizeHandler::mouseReleaseEvent(QMouseEvent*)
{
m_resizing = false;
if (!m_trackContentWidget->m_mainSelected)
return;
QVector<TrackEntry*> vecPreviewTrackEntries = {m_trackContentWidget->m_mainSelected};
bool msg = true;
for (TrackContentWidget* tcw : std::as_const(m_tcwCorresponding))
{
if (TrackContentWidget::checkForParallelTopics(tcw, vecPreviewTrackEntries,
m_trackContentWidget->m_mainSelected->m_startTime))
{
if (msg)
{
LtsWidgets::LtsMessageDialog::showMessage(m_trackContentWidget, TrackContentWidget::parallelError(),
QObject::tr("Error"));
msg = false;
}
m_trackContentWidget->m_mainSelected->m_length = m_oldLength;
}
}
}
bool ResizeHandler::isCollision(int newLength) const
{
int startTime = m_trackContentWidget->m_mainSelected->m_startTime;
int endTime = startTime + newLength;
for (auto i = m_trackContentWidget->m_entryList.constBegin(); i != m_trackContentWidget->m_entryList.constEnd();
++i)
{
const TrackEntry* trackEntry = *i;
if (!trackEntry || trackEntry == m_trackContentWidget->m_mainSelected)
continue;
if (LtsScriptTimeline::isCollision2(startTime, endTime, trackEntry))
return true;
}
const QVector<FilterTrackWidget*>& filterTrackWidgets = m_trackContentWidget->trackWidget()->filterLines();
for (const FilterTrackWidget* filterTrackWidget : std::as_const(filterTrackWidgets))
{
for (auto iFilterContentWidget = filterTrackWidget->fbw()->filterContentWidgets().begin();
iFilterContentWidget != filterTrackWidget->fbw()->filterContentWidgets().end(); ++iFilterContentWidget)
{
int filterContentWidgetTopicId = iFilterContentWidget.key();
if (m_trackContentWidget->m_mainSelected->m_topicId != filterContentWidgetTopicId)
continue;
TrackContentWidget* filterContentWidget = iFilterContentWidget.value();
for (auto iTrackEntry = filterContentWidget->m_entryList.constBegin();
iTrackEntry != filterContentWidget->m_entryList.end(); ++iTrackEntry)
{
const TrackEntry* trackEntry = *iTrackEntry;
if (!trackEntry || trackEntry == m_trackContentWidget->m_mainSelected)
continue;
if (endTime < startTime + trackEntry->m_startTime + trackEntry->m_length)
return true;
}
}
}
return false;
}
bool ResizeHandler::mouseMoveEvent(QMouseEvent* event)
{
QPoint pos = m_trackContentWidget->mapFromGlobal(event->globalPosition().toPoint());
int posX = pos.x();
int cursorTime = m_trackContentWidget->m_tools->getTime(posX, m_trackContentWidget->m_isFilter);
if (m_resizing && m_trackContentWidget->m_mainSelected)
{
int newLength = cursorTime - m_trackContentWidget->m_mainSelected->m_startTime;
int cursorY = pos.y();
if (cursorY < 0 || cursorY > m_trackContentWidget->height() || newLength < 1 ||
(m_mainTeLength != -1 && newLength > m_mainTeLength) || isCollision(newLength))
{
newLength = m_oldLength;
m_trackContentWidget->setCursor(Qt::ForbiddenCursor);
}
else
{
m_trackContentWidget->setCursor(m_cursor);
}
m_trackContentWidget->m_mainSelected->m_length = newLength;
m_trackContentWidget->update();
emit m_trackContentWidget->signalChangesMade();
return true;
}
else
{
TrackEntry* te = m_trackContentWidget->getTrackEntryOnPos(event->globalPosition().toPoint());
if (m_trackContentWidget->m_isFilter)
{
TrackEntry* mainTe = m_trackContentWidget->getParentTopicOfFilter(te);
if (mainTe != nullptr)
m_mainTeLength = mainTe->m_length;
else
m_mainTeLength = -1;
}
if (te && (te->m_type == LtsScriptTimeline::TrackEntryType::Audio ||
te->m_type == LtsScriptTimeline::TrackEntryType::Video))
{
m_possible = false;
m_trackContentWidget->setCursor(m_cursor = Qt::ArrowCursor);
m_trackContentWidget->update();
}
else if (te && m_trackContentWidget->m_mainSelected && te == m_trackContentWidget->m_mainSelected &&
m_trackContentWidget->m_selected.count() == 1 &&
(cursorTime >= (m_trackContentWidget->m_mainSelected->m_startTime +
m_trackContentWidget->m_mainSelected->m_length - 4) &&
cursorTime <= (m_trackContentWidget->m_mainSelected->m_startTime +
m_trackContentWidget->m_mainSelected->m_length)))
{
m_possible = true;
m_trackContentWidget->setCursor(m_cursor = Qt::SizeHorCursor);
m_trackContentWidget->update();
}
else if (!m_resizing)
{
m_possible = false;
m_trackContentWidget->setCursor(m_cursor = Qt::ArrowCursor);
m_trackContentWidget->update();
}
}
return false;
}
void ResizeHandler::keyPressEvent(QKeyEvent* event)
{
if (m_trackContentWidget->m_mainSelected && event->key() == Qt::Key_Escape && m_resizing)
{
m_trackContentWidget->m_mainSelected->m_length = m_oldLength;
m_resizing = false;
m_possible = false;
m_trackContentWidget->setCursor(Qt::ArrowCursor);
m_trackContentWidget->update();
}
}
} // namespace LtsScriptTimeline
@@ -1,38 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <LtsScriptTimeline/track_content_widget.h>
#include <QCursor>
class QMouseEvent;
class QKeyEvent;
namespace LtsScriptTimeline
{
class LTSSCRIPTTIMELINE_EXPORT ResizeHandler
{
public:
explicit ResizeHandler(TrackContentWidget* _tcw)
: m_trackContentWidget(_tcw), m_resizing(false), m_possible(false), m_oldLength(-1), m_mainTeLength(-1)
{
}
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
bool mouseMoveEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent* event);
TrackContentWidget* m_trackContentWidget;
QVector<TrackContentWidget*> m_tcwCorresponding;
bool m_resizing;
bool m_possible;
int m_oldLength;
int m_mainTeLength;
Qt::CursorShape m_cursor;
private:
bool isCollision(int newLength) const;
};
} // namespace LtsScriptTimeline
@@ -1,169 +0,0 @@
#include "track_select_handler.h"
#include "tools.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtGui/QGuiApplication>
#include <QtWidgets/QInputDialog>
#include <QtGui/QKeyEvent>
#include <QtWidgets/QMenu>
#include <QtGui/QMouseEvent>
namespace LtsScriptTimeline
{
void SelectHandler::slotSetDescription()
{
if (m_pressedEntry == nullptr)
return;
bool ok;
QString iniDescription = m_pressedEntry->m_description;
QString text =
QInputDialog::getText(tcw, tr("Operator Application"), tr("Topic Description:"), QLineEdit::Normal,
iniDescription, &ok, Qt::Popup | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
if (ok)
{
m_pressedEntry->m_description = text;
emit tcw->signalChangesMade();
}
}
void SelectHandler::mouseDoubleClick(QMouseEvent* event)
{
if (m_pressedEntry != nullptr && tcw->m_selected.count() == 1 && !tcw->m_isMultiLineMultiSelectionMode &&
event->buttons() == Qt::LeftButton)
emit tcw->signalEditEntry(m_pressedEntry->m_topicId);
}
void SelectHandler::mousePressEvent(QMouseEvent* event)
{
if (event->buttons() == Qt::LeftButton)
{
m_pressedEntry = nullptr;
QPoint clickedPos = tcw->mapFromGlobal(event->globalPosition().toPoint());
int clickedPosY = clickedPos.y();
int clickedPosX = clickedPos.x();
if (clickedPosY < 0 || clickedPosY > tcw->height())
return;
int clickedTime = tcw->m_tools->getTime(clickedPosX, tcw->m_isFilter);
m_pressedEntry = tcw->getTrackEntryAt(clickedTime);
}
else if (event->buttons() == Qt::RightButton)
{
QMenu* contextMenu = new QMenu(tcw);
contextMenu->setAttribute(Qt::WA_DeleteOnClose);
contextMenu->addSection(tr("All tracks"));
{
QAction* action = new QAction(tr("Set topic description"), tcw);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_D));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:document-edit.svg")));
action->setEnabled(m_pressedEntry);
if (!m_pressedEntry)
action->setToolTip(tr("Right click directly on a single Topic to edit its description."));
connect(action, &QAction::triggered, this, &SelectHandler::slotSetDescription);
contextMenu->addAction(action);
}
{
QAction* action = new QAction(tr("Remove selected Topic(s)"), tcw);
action->setShortcut(QKeySequence(Qt::Key_Delete));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:delete.svg")));
connect(action, &QAction::triggered, tcw, &TrackContentWidget::signalDeleteSelectedTopics);
contextMenu->addAction(action);
}
contextMenu->addSection(tr("Main track only"));
{
QAction* action = new QAction(tr("Select all topics"), tcw);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_A));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:selection_rec.svg")));
connect(action, &QAction::triggered, tcw, &TrackContentWidget::signalSelectAllGlobal);
contextMenu->addAction(action);
}
{
QAction* action = new QAction(tr("Cut selected topic(s)"), tcw);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_X));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:edit-cut.svg")));
connect(action, &QAction::triggered, tcw, &TrackContentWidget::signalCutTopics);
contextMenu->addAction(action);
}
{
QAction* action = new QAction(tr("Copy selected topic(s)"), tcw);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:edit-copy.svg")));
connect(action, &QAction::triggered, tcw, &TrackContentWidget::signalCopyTopics);
contextMenu->addAction(action);
}
{
QAction* action = new QAction(tr("Paste topic(s) at indicator position"), tcw);
action->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_V));
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
action->setShortcutVisibleInContextMenu(true);
#endif
action->setIcon(QIcon(QStringLiteral("icon:edit-paste.svg")));
connect(action, &QAction::triggered, tcw, &TrackContentWidget::signalPasteTopics);
contextMenu->addAction(action);
}
contextMenu->popup(event->globalPosition().toPoint());
}
}
void SelectHandler::mouseReleaseEvent(QMouseEvent* event)
{
QPoint clickedPos = tcw->mapFromGlobal(event->globalPosition().toPoint());
int clickedPosX = clickedPos.x();
int clickedTime = tcw->m_tools->getTime(clickedPosX, tcw->m_isFilter);
TrackEntry* releasedEntry = tcw->getTrackEntryAt(clickedTime);
if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && (!m_pressedEntry || !releasedEntry))
{
emit tcw->signalUnselectAll();
emit tcw->signalTrackEntrySelectionChanged(nullptr);
}
else
{
if (m_pressedEntry == releasedEntry)
tcw->selectEntry(releasedEntry);
}
}
void SelectHandler::keyPressEvent(QKeyEvent* event)
{
if (event->key() == Qt::Key_Escape)
{
m_pressedEntry = nullptr;
emit tcw->signalUnselectAll();
emit tcw->signalTrackEntrySelectionChanged(nullptr);
}
}
} // namespace LtsScriptTimeline
@@ -1,33 +0,0 @@
#pragma once
#include "ltsscripttimeline_export.h"
#include <QtCore/QObject>
class QMouseEvent;
class QKeyEvent;
namespace LtsScriptTimeline
{
class TrackContentWidget;
class TrackEntry;
class LTSSCRIPTTIMELINE_EXPORT SelectHandler : public QObject
{
Q_OBJECT
public:
explicit SelectHandler(TrackContentWidget* _tcw) : QObject(nullptr), tcw(_tcw), m_pressedEntry(nullptr) {}
void mouseDoubleClick(QMouseEvent* event);
void mousePressEvent(QMouseEvent* event);
void mouseReleaseEvent(QMouseEvent* event);
void keyPressEvent(QKeyEvent* event);
TrackContentWidget* tcw;
TrackEntry* m_pressedEntry;
public slots:
void slotSetDescription();
};
} // namespace LtsScriptTimeline
@@ -1,476 +0,0 @@
#include "track_widget.h"
#include "filter_background_widget.h"
#include "filter_track_widget.h"
#include "tools.h"
#include "track_content_widget.h"
#include "track_entry.h"
#include "ui_track_widget.h"
#include <QtGui/QBrush>
#include <QtGui/QColor>
#include <QtCore/QDebug>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonValue>
#include <QtGui/QPainter>
#include <QtGui/QPen>
#include <utility>
namespace LtsScriptTimeline
{
TrackWidget::TrackWidget(int baseWidth, bool readonly, Tools* tools, bool filtersAllowed, QWidget* parent)
: QWidget(parent), ui(new Ui::TrackWidget), m_baseWidth(baseWidth), m_readonly(readonly), m_tools(tools)
{
Q_ASSERT(m_tools != nullptr);
ui->setupUi(this);
ui->mainTrack->setTrackWidget(this);
ui->mainTrack->setTools(tools);
ui->chkSelect->hide();
ui->filtersWidget->hide();
ui->leName->hide();
ui->pbApply->hide();
ui->pbCancel->hide();
ui->pbEditName->hide();
if (!filtersAllowed)
ui->pbExpand->hide();
ui->pbAddFilter->hide();
setBaseWidth(baseWidth);
setReadonly(readonly);
connect(ui->mainTrack, &TrackContentWidget::signalUnselectAll, this, &TrackWidget::signalUnselectAll);
connect(ui->mainTrack, &TrackContentWidget::signalTrackEntrySelectionChanged, this,
&TrackWidget::signalTrackEntrySelectionChanged);
connect(ui->mainTrack, &TrackContentWidget::signalChangesMade, this, &TrackWidget::signalChangesMade);
connect(ui->mainTrack, &TrackContentWidget::signalChangesMade, this, &TrackWidget::slotMainChangesMade);
connect(ui->mainTrack, &TrackContentWidget::signalTrackEntryAdded, this, &TrackWidget::slotTrackEntryAdded);
connect(ui->mainTrack, &TrackContentWidget::signalTrackEntryDeleted, this, &TrackWidget::slotTrackEntryDeleted);
connect(ui->mainTrack, &TrackContentWidget::signalEditEntry, this, &TrackWidget::signalEditEntry);
connect(ui->chkSelect, &QCheckBox::checkStateChanged, this, &TrackWidget::signalSelectTrack);
connect(ui->pbExpand, &QPushButton::clicked, this, &TrackWidget::slotExpand);
connect(ui->pbAddFilter, &QPushButton::clicked, this, &TrackWidget::slotAddFilter);
}
TrackWidget::~TrackWidget()
{
m_filterLines.clear();
delete ui;
}
void TrackWidget::setReadonly(bool readonly)
{
m_readonly = readonly;
ui->mainTrack->setReadonly(readonly);
if (readonly)
ui->pbAddFilter->hide();
else if (ui->filtersWidget->isVisible())
ui->pbAddFilter->show();
for (auto i3 = m_filterLines.begin(); i3 != m_filterLines.end(); ++i3)
{
FilterTrackWidget* ftw = *i3;
ftw->setReadonly(readonly);
}
}
void TrackWidget::setScriptTimeline(ScriptTimeline* scriptTimeline)
{
m_scriptTimeline = scriptTimeline;
ui->mainTrack->setScriptTimeline(m_scriptTimeline);
}
void TrackWidget::keyPressEvent(QKeyEvent* event)
{
getTrackContentWidget()->keyPressEvent(event);
}
QVector<TrackEntry*> TrackWidget::getSelectedFilterEntries() const
{
QVector<TrackEntry*> result;
const QVector<FilterTrackWidget*>& ftws = filterLines();
for (const FilterTrackWidget* ftw : std::as_const(ftws))
{
const FilterBackgroundWidget* fbw = ftw->fbw();
const QMap<int, TrackContentWidget*>& fcws = fbw->filterContentWidgets();
for (auto i = fcws.constBegin(); i != fcws.constEnd(); ++i)
{
TrackContentWidget* tcw = i.value();
result += tcw->getSelectedEntries();
}
}
return result;
}
const QVector<TrackEntry*>& TrackWidget::getSelectedEntries() const
{
return ui->mainTrack->getSelectedEntries();
}
void TrackWidget::slotAddFilter()
{
FilterTrackWidget* ftw = new FilterTrackWidget(m_baseWidth, m_readonly);
ftw->setTrackWidget(this);
ftw->setTools(m_tools);
ftw->setScriptTimeline(m_scriptTimeline);
ui->filtersWidget->layout()->addWidget(ftw);
m_filterLines.append(ftw);
connect(ftw, &FilterTrackWidget::signalChangesMade, this, &TrackWidget::signalChangesMade);
connect(ftw, &FilterTrackWidget::signalUnselectAll, this, &TrackWidget::signalUnselectAll);
connect(ftw, &FilterTrackWidget::signalTrackEntrySelectionChanged, this,
&TrackWidget::signalTrackEntrySelectionChanged);
connect(ftw, &FilterTrackWidget::signalEditEntry, this, &TrackWidget::signalEditEntry);
connect(ftw, &FilterTrackWidget::signalTrackEntryDeleted, this, &TrackWidget::signalTrackEntryDeleted);
connect(ftw, &FilterTrackWidget::signalDeleteMe, this, [this]() {
m_filterLines.removeAll(qobject_cast<FilterTrackWidget*>(sender()));
sender()->deleteLater();
emit signalChangesMade();
});
emit signalChangesMade();
slotMainChangesMade();
}
void TrackWidget::slotMainChangesMade()
{
const QVector<TrackEntry*> trackEntries = ui->mainTrack->getTrackEntries();
for (auto i1 = trackEntries.constBegin(); i1 != trackEntries.constEnd(); ++i1)
{
const TrackEntry* te = *i1;
for (auto i3 = m_filterLines.begin(); i3 != m_filterLines.end(); ++i3)
{
FilterTrackWidget* ftw = *i3;
ftw->fbw()->adjustFilterContentWidgets(te);
}
}
}
void TrackWidget::slotTrackEntryAdded(TrackEntry* te)
{
for (FilterTrackWidget* ftw : std::as_const(m_filterLines))
ftw->fbw()->trackEntryAdded(te);
emit signalTrackEntryAdded(te);
}
void TrackWidget::slotTrackEntryDeleted(const int topicId)
{
for (FilterTrackWidget* ftw : std::as_const(m_filterLines))
ftw->fbw()->trackEntryDeleted(topicId);
emit signalTrackEntryDeleted(topicId);
}
void TrackWidget::slotExpand()
{
if (ui->filtersWidget->isVisible())
{
ui->pbExpand->setText(tr("More"));
ui->pbAddFilter->hide();
ui->filtersWidget->hide();
}
else
{
ui->pbExpand->setText(tr("Less"));
if (!m_readonly)
ui->pbAddFilter->show();
ui->filtersWidget->show();
slotMainChangesMade();
}
}
void TrackWidget::selectEntry(int topicId)
{
ui->mainTrack->selectEntry(topicId);
}
int TrackWidget::getParentTopicIdOfFilter(const TrackEntry* te) const
{
for (const FilterTrackWidget* ftw : m_filterLines)
{
const FilterBackgroundWidget* fbw = ftw->fbw();
const QMap<int, TrackContentWidget*>& filterContentWidgets = fbw->filterContentWidgets();
for (auto i = filterContentWidgets.constBegin(); i != filterContentWidgets.constEnd(); ++i)
{
int parentTopicId = i.key();
const TrackContentWidget* datWidget = i.value();
const QVector<TrackEntry*>& filterEntries = datWidget->getTrackEntries();
for (const TrackEntry* filterTE : filterEntries)
{
if (filterTE == te)
return parentTopicId;
}
}
}
return -1;
}
QVector<TrackEntry*> TrackWidget::getTrackEntriesWithFilters(bool selectedEntriesOnly) const
{
QVector<TrackEntry*> result;
const QVector<TrackEntry*> trackEntryList = ui->mainTrack->getTrackEntries();
for (TrackEntry* te : trackEntryList)
{
if (selectedEntriesOnly && !ui->mainTrack->getSelectedEntries().contains(te))
continue;
result += te;
QJsonArray jsonFilterLines;
for (const FilterTrackWidget* ftw : std::as_const(m_filterLines))
{
const FilterBackgroundWidget* fbw = ftw->fbw();
const QMap<int, TrackContentWidget*>& filterContentWidgets = fbw->filterContentWidgets();
const TrackContentWidget* datWidget = filterContentWidgets.value(te->m_topicId);
if (datWidget == nullptr)
continue;
const QVector<TrackEntry*>& filterEntries = datWidget->getTrackEntries();
if (filterEntries.isEmpty())
continue;
QJsonArray jsonFilterLine;
for (const TrackEntry* fte : filterEntries)
jsonFilterLine.append(fte->toJson());
jsonFilterLines.append(jsonFilterLine);
}
te->m_detailData[QStringLiteral("Filters")] = jsonFilterLines;
}
return result;
}
QVector<TrackEntry*> TrackWidget::getTrackEntriesFiltersAsEntries(bool selectedEntriesOnly) const
{
QVector<TrackEntry*> result;
const QVector<TrackEntry*> trackEntryList = ui->mainTrack->getTrackEntries();
for (TrackEntry* te : trackEntryList)
{
if (selectedEntriesOnly && !ui->mainTrack->getSelectedEntries().contains(te))
continue;
result += te;
for (FilterTrackWidget* ftw : m_filterLines)
{
const QMap<int, TrackContentWidget*>& filterContentWidgets = ftw->fbw()->filterContentWidgets();
for (auto i1 = filterContentWidgets.constBegin(); i1 != filterContentWidgets.constEnd(); ++i1)
{
TrackContentWidget* tcw = i1.value();
result += tcw->getTrackEntries();
}
}
}
return result;
}
QVector<TrackEntry*> TrackWidget::getTrackEntries(bool selectedEntriesOnly) const
{
QVector<TrackEntry*> result;
const QVector<TrackEntry*> trackEntryList = ui->mainTrack->getTrackEntries();
if (selectedEntriesOnly)
{
for (TrackEntry* te : trackEntryList)
{
if (!ui->mainTrack->getSelectedEntries().contains(te))
continue;
result += te;
}
}
else
{
return trackEntryList;
}
return result;
}
void TrackWidget::setBaseWidth(int width)
{
m_baseWidth = width;
ui->mainLeft->setMinimumWidth(width);
ui->mainLeft->setMaximumWidth(width);
for (FilterTrackWidget* ftw : std::as_const(m_filterLines))
ftw->setBaseWidth(m_baseWidth);
}
void TrackWidget::addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget)
{
ui->mainTrack->addCorrespondingTrackWidget(pCorrespondingTrackWidget);
}
TrackContentWidget* TrackWidget::getTrackContentWidget() const
{
return ui->mainTrack;
}
void TrackWidget::setInternalName(const QString& name)
{
m_internalName = name;
ui->mainTrack->setTrackName(name);
}
void TrackWidget::setTrackName(const QString& name)
{
ui->lblTrackName->setText(name);
}
bool TrackWidget::addTrackEntry(TrackEntry* te, bool selectTrackEntry)
{
if (!ui->mainTrack->addTrackEntry(te, selectTrackEntry))
return false;
const QJsonObject detailData = te->m_detailData;
if (detailData.isEmpty())
{
return true;
}
const QJsonArray filterLines = detailData[QStringLiteral("Filters")].toArray();
if (filterLines.isEmpty())
return true;
int missingFilterLines = filterLines.count() - m_filterLines.count();
while (missingFilterLines > 0)
{
slotAddFilter();
missingFilterLines--;
}
for (int i1 = 0; i1 != filterLines.count(); i1++)
{
const QJsonArray filterLine = filterLines.at(i1).toArray();
for (const QJsonValue& filter : filterLine)
{
TrackEntry* filterTe = new TrackEntry;
filterTe->fromJson(filter.toObject());
m_filterLines.at(i1)->addFilterEntry(te, filterTe);
}
}
emit signalChangesMade();
return true;
}
QString TrackWidget::trackName() const
{
return m_internalName;
}
bool TrackWidget::isSelected() const
{
return (ui->chkSelect->checkState() == Qt::CheckState::Checked);
}
void TrackWidget::unselectAll()
{
ui->mainTrack->unselectAll();
for (FilterTrackWidget* ftw : std::as_const(m_filterLines))
{
const auto fcw = ftw->fbw()->filterContentWidgets();
for (TrackContentWidget* tcw : fcw)
tcw->unselectAll();
}
}
void TrackWidget::updateMe()
{
update();
ui->mainTrack->update();
slotMainChangesMade();
}
void TrackWidget::setIndicatorTime(int time)
{
ui->mainTrack->setIndicatorTime(time);
for (FilterTrackWidget* ftw : std::as_const(m_filterLines))
{
const auto filterContentWidgets = ftw->fbw()->filterContentWidgets();
for (auto i1 = filterContentWidgets.begin(); i1 != filterContentWidgets.end(); ++i1)
{
int mainTeId = i1.key();
int mainTeStart = 0;
const QVector<TrackEntry*>& tes = ui->mainTrack->getTrackEntries();
for (const TrackEntry* te : tes)
{
if (te->m_topicId == mainTeId)
{
mainTeStart = te->m_startTime;
break;
}
}
TrackContentWidget* filterTcw = i1.value();
filterTcw->setIndicatorTime(time - mainTeStart);
}
}
}
void TrackWidget::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.save();
painter.setPen(QGuiApplication::palette().windowText().color());
painter.setBrush(QGuiApplication::palette().window().color());
painter.drawRect(rect());
painter.restore();
}
} // namespace LtsScriptTimeline
Loaded 100 of 14140 files, more files were not shown because too many files have changed in this diff. Show more