diff --git a/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_dtc.h b/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_dtc.h index f2053458c..53d8cdb02 100644 --- a/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_dtc.h +++ b/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AreaEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_enums.hpp b/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_enums.hpp index 050c7d259..7dc7ece03 100644 --- a/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/AreaEffectSimulation/aes_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AreaEffectSimulation { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/AssetManagement/asm_dtc.h b/qt6-after/qt6-migrated-legatus/AssetManagement/asm_dtc.h index b2e40ee30..085fecaf1 100644 --- a/qt6-after/qt6-migrated-legatus/AssetManagement/asm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/AssetManagement/asm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AssetManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/AssetManagement/asm_enums.hpp b/qt6-after/qt6-migrated-legatus/AssetManagement/asm_enums.hpp index 69ea7aa9b..d4ac88b4e 100644 --- a/qt6-after/qt6-migrated-legatus/AssetManagement/asm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/AssetManagement/asm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AssetManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_dtc.h b/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_dtc.h index 5bcb2e6e6..6ebbe52b0 100644 --- a/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AudioVideoManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_enums.hpp b/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_enums.hpp index 81e092b64..c4a2a16af 100644 --- a/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/AudioVideoManagement/avm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AudioVideoManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Buildings/bld_dtc.h b/qt6-after/qt6-migrated-legatus/Buildings/bld_dtc.h index 4544b5be1..1a97ff37a 100644 --- a/qt6-after/qt6-migrated-legatus/Buildings/bld_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Buildings/bld_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Buildings { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Buildings/bld_enums.hpp b/qt6-after/qt6-migrated-legatus/Buildings/bld_enums.hpp index 9341ea232..e3f3ac39c 100644 --- a/qt6-after/qt6-migrated-legatus/Buildings/bld_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Buildings/bld_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace Buildings { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/CentralEffectSimulation/ces_dtc.h b/qt6-after/qt6-migrated-legatus/CentralEffectSimulation/ces_dtc.h index f5df78efd..afdb06c40 100644 --- a/qt6-after/qt6-migrated-legatus/CentralEffectSimulation/ces_dtc.h +++ b/qt6-after/qt6-migrated-legatus/CentralEffectSimulation/ces_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace CentralEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/CodificationManagement/cod_dtc.h b/qt6-after/qt6-migrated-legatus/CodificationManagement/cod_dtc.h index b86da2200..0aad572f6 100644 --- a/qt6-after/qt6-migrated-legatus/CodificationManagement/cod_dtc.h +++ b/qt6-after/qt6-migrated-legatus/CodificationManagement/cod_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace CodificationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/ComponentMonitor/cmo_dtc.h b/qt6-after/qt6-migrated-legatus/ComponentMonitor/cmo_dtc.h index 9ce661211..451073155 100644 --- a/qt6-after/qt6-migrated-legatus/ComponentMonitor/cmo_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ComponentMonitor/cmo_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ComponentMonitor { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ComponentMonitor diff --git a/qt6-after/qt6-migrated-legatus/Core/core_dtc.h b/qt6-after/qt6-migrated-legatus/Core/core_dtc.h index 0a13b7ce3..a2fa8e814 100644 --- a/qt6-after/qt6-migrated-legatus/Core/core_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Core/core_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Core { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/Core/core_enums.hpp b/qt6-after/qt6-migrated-legatus/Core/core_enums.hpp index 620e6c95e..7cf5e6fee 100644 --- a/qt6-after/qt6-migrated-legatus/Core/core_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Core/core_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace Core { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/DDS/Core/core_dtc.h b/qt6-after/qt6-migrated-legatus/DDS/Core/core_dtc.h index 0a13b7ce3..a2fa8e814 100644 --- a/qt6-after/qt6-migrated-legatus/DDS/Core/core_dtc.h +++ b/qt6-after/qt6-migrated-legatus/DDS/Core/core_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Core { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/DDS/Core/core_enums.hpp b/qt6-after/qt6-migrated-legatus/DDS/Core/core_enums.hpp index 620e6c95e..7cf5e6fee 100644 --- a/qt6-after/qt6-migrated-legatus/DDS/Core/core_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/DDS/Core/core_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace Core { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/DDS/DTC/generic_dtc.h b/qt6-after/qt6-migrated-legatus/DDS/DTC/generic_dtc.h index 787f7f1cb..9c3aa6d57 100644 --- a/qt6-after/qt6-migrated-legatus/DDS/DTC/generic_dtc.h +++ b/qt6-after/qt6-migrated-legatus/DDS/DTC/generic_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace DDS { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace DDS diff --git a/qt6-after/qt6-migrated-legatus/EffectShowClient/esc_dtc.h b/qt6-after/qt6-migrated-legatus/EffectShowClient/esc_dtc.h index bf5409eb5..d91be8274 100644 --- a/qt6-after/qt6-migrated-legatus/EffectShowClient/esc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/EffectShowClient/esc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowClient { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/EffectShowManagement/esm_dtc.h b/qt6-after/qt6-migrated-legatus/EffectShowManagement/esm_dtc.h index 15dfc2d81..d73623e87 100644 --- a/qt6-after/qt6-migrated-legatus/EffectShowManagement/esm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/EffectShowManagement/esm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Evaluations/evl_dtc.h b/qt6-after/qt6-migrated-legatus/Evaluations/evl_dtc.h index 589171637..89207e684 100644 --- a/qt6-after/qt6-migrated-legatus/Evaluations/evl_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Evaluations/evl_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Evaluations { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/ExerciseEventManagement/eem_dtc.h b/qt6-after/qt6-migrated-legatus/ExerciseEventManagement/eem_dtc.h index 35b8fc6bf..ce5c860f8 100644 --- a/qt6-after/qt6-migrated-legatus/ExerciseEventManagement/eem_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ExerciseEventManagement/eem_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ExerciseEventManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ExerciseEventManagement diff --git a/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_dtc.h b/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_dtc.h index d7f5e5ac9..d9f59111e 100644 --- a/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ExerciseManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_enums.hpp b/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_enums.hpp index 97c15d67f..63217d29f 100644 --- a/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/ExerciseManagement/exm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ExerciseManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/FileManagement/flm_dtc.h b/qt6-after/qt6-migrated-legatus/FileManagement/flm_dtc.h index 83888f40a..9a997306f 100644 --- a/qt6-after/qt6-migrated-legatus/FileManagement/flm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/FileManagement/flm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace FileManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/FileManagement/flm_enums.hpp b/qt6-after/qt6-migrated-legatus/FileManagement/flm_enums.hpp index b773bcb54..9bef20c39 100644 --- a/qt6-after/qt6-migrated-legatus/FileManagement/flm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/FileManagement/flm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace FileManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/GuezIedManagement/gim_dtc.h b/qt6-after/qt6-migrated-legatus/GuezIedManagement/gim_dtc.h index fc33757be..1f16e4e83 100644 --- a/qt6-after/qt6-migrated-legatus/GuezIedManagement/gim_dtc.h +++ b/qt6-after/qt6-migrated-legatus/GuezIedManagement/gim_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace GuezIedManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace GuezIedManagement diff --git a/qt6-after/qt6-migrated-legatus/GuezNasat/gna_dtc.h b/qt6-after/qt6-migrated-legatus/GuezNasat/gna_dtc.h index 5bb435ce5..47d51ae59 100644 --- a/qt6-after/qt6-migrated-legatus/GuezNasat/gna_dtc.h +++ b/qt6-after/qt6-migrated-legatus/GuezNasat/gna_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace GuezNasat { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace GuezNasat diff --git a/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_dtc.h b/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_dtc.h index 726a7a246..b62a281ef 100644 --- a/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_dtc.h +++ b/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace InfrastructureManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_enums.hpp b/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_enums.hpp index 21423f23b..369f0caa3 100644 --- a/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/InfrastructureManagement/ism_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace InfrastructureManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.cpp old mode 100755 new mode 100644 index f729e9d9f..4a18de39f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.cpp @@ -1,10 +1,11 @@ - #include "CppTopicGeneratorGrantlee.h" + #include "StructBuilder.h" -#include + #include +#include #include #ifdef RTI_HEADER_AVAILABLE @@ -13,341 +14,317 @@ using namespace CodeGen; -CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee() - : GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee") -{} +CppTopicGeneratorGrantlee::CppTopicGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.CppTopicGeneratorGrantlee") {} -bool CppTopicGeneratorGrantlee::init(const XmlReader *reader, StructBuilder *structBuilder) +bool CppTopicGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder) { - m_reader = reader; - if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) - return false; + m_reader = reader; + if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) + return false; - addCustomFunctions(reader->getCustomFunctions()); + addCustomFunctions(reader->getCustomFunctions()); - return initDataTopics() && initFunctionTopics() && initIdlStructs(); + return initDataTopics() && initFunctionTopics() && initIdlStructs(); } - - bool CppTopicGeneratorGrantlee::initDataTopics() { - DataTopicsWrapper *dataTopicsWrapper = new DataTopicsWrapper(QString(), this); - const auto dataTopics = m_reader->getIdlStructInformation(); - QVector keyColumns; - QVector trColumns; - for (const CodeGen::TopicTypeInformation &tti : dataTopics) - { - if (!tti.isDataObject) - continue; - - keyColumns.clear(); - trColumns.clear(); - const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name); - if (!ctti.isValid()) + DataTopicsWrapper* dataTopicsWrapper = new DataTopicsWrapper(QString(), this); + const auto dataTopics = m_reader->getIdlStructInformation(); + QVector keyColumns; + QVector trColumns; + for (const CodeGen::TopicTypeInformation& tti : dataTopics) { - ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name; - continue; + if (!tti.isDataObject) + continue; + + keyColumns.clear(); + trColumns.clear(); + const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(tti.name); + if (!ctti.isValid()) + { + ERROR_LOG(m_logger) << "could not find informations for struct " << tti.name; + continue; + } + DataTopicWrapper* dtw = dataTopicsWrapper->addDataTopic(ctti); + getSpecialColumns(ctti, keyColumns, trColumns); + if (keyColumns.size() == 1) + dtw->setKeyColumnData(keyColumns.first()); + dtw->setTrColumns(trColumns); + if (ctti.recordTopic) + { + const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name)); + if (!cti.isEmpty()) + dtw->setRecordTableInformation(cti); + } + else + { + if (ctti.isDataObject) + m_structBuilder->buildJSonStructureInformationFromIdlData(ctti); + } } - DataTopicWrapper *dtw = dataTopicsWrapper->addDataTopic(ctti); - getSpecialColumns(ctti, keyColumns, trColumns); - if (keyColumns.size() == 1) - dtw->setKeyColumnData(keyColumns.first()); - dtw->setTrColumns(trColumns); - if (ctti.recordTopic) + m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper); + + QSet exportedSubTopics; + DataTopicsWrapper* subTopicsWrapper = new DataTopicsWrapper(QString(), this); + const QVector> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics(); + for (const QSharedPointer& dti : serializeTopics) { - const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name)); - if (!cti.isEmpty()) - dtw->setRecordTableInformation(cti); + if (exportedSubTopics.contains(dti->idlType())) + continue; + if (dti->isStructure()) + { + const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType()); + if (!ctti.isValid()) + { + ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType(); + continue; + } + const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name)); + if (cti.isEmpty()) + { + ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType(); + continue; + } + DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name; + DataTopicWrapper* dtw = subTopicsWrapper->addDataTopic(ctti); + dtw->setRecordTableInformation(cti); + exportedSubTopics += dti->idlType(); + } } - else + m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper); + + QVector jsonTopics; + const QMap> jsonExport = m_structBuilder->jsonStructureInformation(); + for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it) { - if (ctti.isDataObject) - m_structBuilder->buildJSonStructureInformationFromIdlData(ctti); + MemberInformationListWrapper* mil = new MemberInformationListWrapper(it.key(), it.value(), this); + jsonTopics += mil; } - } - m_ctx->insert(QStringLiteral("dataTopics"), dataTopicsWrapper); + m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics)); - QSet exportedSubTopics; - DataTopicsWrapper *subTopicsWrapper = new DataTopicsWrapper(QString(), this); - const QVector> serializeTopics = m_structBuilder->getSerializeFromToJsonTopics(); - for (const QSharedPointer &dti : serializeTopics) - { - if (exportedSubTopics.contains(dti->idlType())) - continue; - if (dti->isStructure()) - { - const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(dti->idlType()); - if (!ctti.isValid()) - { - ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType(); - continue; - } - const CompleteTableInformation cti(m_structBuilder->getRecordingTopicTable(ctti.name)); - if (cti.isEmpty()) - { - ERROR_LOG(m_logger) << "could not find informations for struct " << dti->idlType(); - continue; - } - DEBUG_LOG(m_logger) << "Adding substruct topic " << ctti.name; - DataTopicWrapper *dtw = subTopicsWrapper->addDataTopic(ctti); - dtw->setRecordTableInformation(cti); - exportedSubTopics += dti->idlType(); - } - } - m_ctx->insert(QStringLiteral("serializeTopics"), subTopicsWrapper); - - QVector jsonTopics; - const QMap> jsonExport = m_structBuilder->jsonStructureInformation(); - for (auto it = jsonExport.begin(); it != jsonExport.end(); ++it) - { - MemberInformationListWrapper *mil = new MemberInformationListWrapper(it.key(), it.value(), this); - jsonTopics += mil; - - } - m_ctx->insert(QStringLiteral("jsonTopics"), QVariant::fromValue(jsonTopics)); - - return true; -} - -bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation &tti, - QVector &keyColumns, - QVector &trColumns) const -{ - DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType; - if (!tti.isValid()) - { - ERROR_LOG(m_logger) << "tti is not valid ..."; - return false; - } - for (const IdlData &ci : tti.members) - { - if (ci.isKey) - keyColumns += ci; - if (ci.isTranslatable) - trColumns += ci; - } - if (tti.baseValueType.isEmpty()) return true; - return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns); } - +bool CppTopicGeneratorGrantlee::getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector& keyColumns, + QVector& trColumns) const +{ + DEBUG_LOG(m_logger) << "Get special columns for " << tti.name << " - base is " << tti.baseValueType; + if (!tti.isValid()) + { + ERROR_LOG(m_logger) << "tti is not valid ..."; + return false; + } + for (const IdlData& ci : tti.members) + { + if (ci.isKey) + keyColumns += ci; + if (ci.isTranslatable) + trColumns += ci; + } + if (tti.baseValueType.isEmpty()) + return true; + return getSpecialColumns(topicTypeInformationByDerivedTopic(tti), keyColumns, trColumns); +} bool CppTopicGeneratorGrantlee::initFunctionTopics() { - - const QVector functionTopics = m_reader->getFunctionTopics(); - FunctionTopicsWrapper *functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this)); - for (const FunctionTopic &ft : functionTopics) - { - if (!handleStruct(ft, functionTopicsWrapper)) - return false; - } - m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper); - return true; -} - -bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic &ft, - FunctionTopicsWrapper *functionTopicsWrapper) -{ - DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name; - - const CompleteTopicTypeInformation siRequest = m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType); - if (!siRequest.isValid()) - { - WARNING_LOG(m_logger) << "Could not get topic informations about request topic " - << ft.requestTopicName; - return false; - } - - const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType); - if (!siReply.isValid()) - { - WARNING_LOG(m_logger) << "Could not get topic informations about reply topic " - << ft.replyTopicType; - return false; - } - - FunctionTopicWrapper *ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply); - const QByteArray hash = QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16); - ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL")); - if (!addRequesterRequestParams(ft.name, siRequest, ftw) || - !addRequesterReplyParams(ft.name, siReply, ftw)) - return false; - - return true; -} - -bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString &request_name, - const CompleteTopicTypeInformation &request, - FunctionTopicWrapper *ftw) -{ - if (request.hasBaseValue()) - { - const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(request.baseValueType); - if (!siBase.isValid()) + const QVector functionTopics = m_reader->getFunctionTopics(); + FunctionTopicsWrapper* functionTopicsWrapper(new FunctionTopicsWrapper(QStringLiteral("functionTopics"), this)); + for (const FunctionTopic& ft : functionTopics) { - WARNING_LOG(m_logger) << "Could not get topic informations about base request topic " - << request.baseValueType; - return false; + if (!handleStruct(ft, functionTopicsWrapper)) + return false; } - if (!addRequesterRequestParams(request_name, siBase, ftw)) - return false; - } - ftw->addRequestParams(request.members); - - return true; + m_ctx->insert(QStringLiteral("functionTopics"), functionTopicsWrapper); + return true; } -bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString &request_name, - const CompleteTopicTypeInformation &reply, - FunctionTopicWrapper *ftw) +bool CppTopicGeneratorGrantlee::handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper) { - if (reply.hasBaseValue()) - { - const CompleteTopicTypeInformation siBase = m_structBuilder->topicTypeInformationByStructType(reply.baseValueType); - if (!siBase.isValid()) + DEBUG_LOG(m_logger) << "handling FunctionTopic: " << ft.name; + + const CompleteTopicTypeInformation siRequest = + m_structBuilder->topicTypeInformationByStructType(ft.requestTopicType); + if (!siRequest.isValid()) { - WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic " - << reply.baseValueType; - return false; + WARNING_LOG(m_logger) << "Could not get topic informations about request topic " << ft.requestTopicName; + return false; } - if (!addRequesterReplyParams(request_name, siBase, ftw)) - return false; - } - ftw->addReplyParams(reply.members); + const CompleteTopicTypeInformation siReply = m_structBuilder->topicTypeInformationByStructType(ft.replyTopicType); + if (!siReply.isValid()) + { + WARNING_LOG(m_logger) << "Could not get topic informations about reply topic " << ft.replyTopicType; + return false; + } - return true; + FunctionTopicWrapper* ftw = functionTopicsWrapper->addFunctionTopic(ft, siRequest, siReply); + const QByteArray hash = + QCryptographicHash::hash(ft.requestTopicName.toUtf8(), QCryptographicHash::Sha3_512).toHex().left(16); + ftw->setReplyHandlerHash(QStringLiteral("0x") + QString::fromLatin1(hash) + QStringLiteral("LL")); + if (!addRequesterRequestParams(ft.name, siRequest, ftw) || !addRequesterReplyParams(ft.name, siReply, ftw)) + return false; + + return true; } - - -bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation &csi, - QSet &idlStructNames, - QVector &idlStructs) +bool CppTopicGeneratorGrantlee::addRequesterRequestParams(const QString& request_name, + const CompleteTopicTypeInformation& request, + FunctionTopicWrapper* ftw) { - if (!csi.isValid()) - return true; - - if (idlStructNames.contains(csi.name)) - return true; - - - - - if (csi.hasBaseValue()) - { - const CompleteTopicTypeInformation ctti = m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false); - if (ctti.isValid()) + if (request.hasBaseValue()) { + const CompleteTopicTypeInformation siBase = + m_structBuilder->topicTypeInformationByStructType(request.baseValueType); + if (!siBase.isValid()) + { + WARNING_LOG(m_logger) << "Could not get topic informations about base request topic " + << request.baseValueType; + return false; + } + + if (!addRequesterRequestParams(request_name, siBase, ftw)) + return false; + } + ftw->addRequestParams(request.members); + + return true; +} + +bool CppTopicGeneratorGrantlee::addRequesterReplyParams(const QString& request_name, + const CompleteTopicTypeInformation& reply, + FunctionTopicWrapper* ftw) +{ + if (reply.hasBaseValue()) + { + const CompleteTopicTypeInformation siBase = + m_structBuilder->topicTypeInformationByStructType(reply.baseValueType); + if (!siBase.isValid()) + { + WARNING_LOG(m_logger) << "Could not get topic informations about base reply topic " << reply.baseValueType; + return false; + } + + if (!addRequesterReplyParams(request_name, siBase, ftw)) + return false; + } + ftw->addReplyParams(reply.members); + + return true; +} + +bool CppTopicGeneratorGrantlee::handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet& idlStructNames, + QVector& idlStructs) +{ + if (!csi.isValid()) + return true; + + if (idlStructNames.contains(csi.name)) + return true; + + if (csi.hasBaseValue()) + { + const CompleteTopicTypeInformation ctti = + m_structBuilder->topicTypeInformationByStructType(csi.baseValueType, false); + if (ctti.isValid()) + { #ifdef RTI_HEADER_AVAILABLE - if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL) - { - ERROR_LOG(m_logger) << "Base struct (" << ctti.name - << ") has final extensibility - this is not allowed"; - return false; - } + if (ctti.extensibility == dds::core::xtypes::ExtensibilityKind_def::FINAL) + { + ERROR_LOG(m_logger) << "Base struct (" << ctti.name + << ") has final extensibility - this is not allowed"; + return false; + } #else - // RTI not available - skip extensibility check (assume EXTENSIBLE) - Q_UNUSED(ctti.extensibility); + // RTI not available - skip extensibility check (assume EXTENSIBLE) + Q_UNUSED(ctti.extensibility); #endif - if (!idlStructNames.contains(csi.baseValueType)) - { - if (!handleIdlStruct(ctti, idlStructNames, idlStructs)) - return false; - } + if (!idlStructNames.contains(csi.baseValueType)) + { + if (!handleIdlStruct(ctti, idlStructNames, idlStructs)) + return false; + } + } + else + { + const int idx = csi.baseValueType.indexOf(QLatin1String("::")); + if (idx < 0) + { + ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType << "' not found in idl-file"; + return false; + } + } } - else + + for (const IdlData& idlData : csi.members) { - const int idx = csi.baseValueType.indexOf(QLatin1String("::")); - if (idx < 0) - { - ERROR_LOG(m_logger) << "idlStruct '" << csi.baseValueType - << "' not found in idl-file"; - return false; - } + QString idlType; + DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name << " " + << idlData.dataTypeInfo->isStructure() << " " << idlData.dataTypeInfo->isSequence(); + if (idlData.dataTypeInfo->isStructure()) + idlType = idlData.dataTypeInfo->idlType(); + else if (idlData.dataTypeInfo->isSequence()) + { + if (idlData.dataTypeInfo->innerDataType()->isStructure()) + idlType = idlData.dataTypeInfo->innerDataType()->idlType(); + } + if (idlType.isEmpty()) + continue; + if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType, false), idlStructNames, + idlStructs)) + return false; } - } - - for (const IdlData &idlData : csi.members) - { - QString idlType; - DEBUG_LOG(m_logger) << "member: " << idlData.type << " - " << idlData.name - << " " << idlData.dataTypeInfo->isStructure() - << " " << idlData.dataTypeInfo->isSequence(); - if (idlData.dataTypeInfo->isStructure()) - idlType = idlData.dataTypeInfo->idlType(); - else if (idlData.dataTypeInfo->isSequence()) - { - if (idlData.dataTypeInfo->innerDataType()->isStructure()) - idlType = idlData.dataTypeInfo->innerDataType()->idlType(); - } - if (idlType.isEmpty()) - continue; - if (!handleIdlStruct(m_structBuilder->topicTypeInformationByStructType(idlType, - false), - idlStructNames, - idlStructs)) - return false; - } + DEBUG_LOG(m_logger) << "Current structName: " << csi.name; + idlStructs += new IdlStructWrapper(csi, this); - - DEBUG_LOG(m_logger) << "Current structName: " << csi.name; - idlStructs += new IdlStructWrapper(csi, this); + idlStructNames.insert(csi.name); - - idlStructNames.insert(csi.name); - - return true; + return true; } bool CppTopicGeneratorGrantlee::initIdlStructs() { - - const QVector csiData = m_structBuilder->topicTypeInformations(); - QSet idlStructNames; - QVector idlStructs; - idlStructs.reserve(csiData.size()); - for (const CompleteTopicTypeInformation &csi : csiData) - { - if (!handleIdlStruct(csi, idlStructNames, idlStructs)) - return false; - } - - m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs)); + const QVector csiData = m_structBuilder->topicTypeInformations(); - const QVector enumerations = m_structBuilder->enumInformations(); - QVector idlEnumerations; - idlEnumerations.reserve(enumerations.size()); - for (const EnumInformation &ei : enumerations) - idlEnumerations += new IdlEnumWrapper(ei, this); - m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations)); + QSet idlStructNames; + QVector idlStructs; + idlStructs.reserve(csiData.size()); + for (const CompleteTopicTypeInformation& csi : csiData) + { + if (!handleIdlStruct(csi, idlStructNames, idlStructs)) + return false; + } - - exportUsedServices(m_reader); - return true; + m_ctx->insert(QStringLiteral("idl_structs"), QVariant::fromValue(idlStructs)); + + const QVector enumerations = m_structBuilder->enumInformations(); + QVector idlEnumerations; + idlEnumerations.reserve(enumerations.size()); + for (const EnumInformation& ei : enumerations) + idlEnumerations += new IdlEnumWrapper(ei, this); + m_ctx->insert(QStringLiteral("idl_enums"), QVariant::fromValue(idlEnumerations)); + + exportUsedServices(m_reader); + return true; } - -CompleteTopicTypeInformation CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const +CompleteTopicTypeInformation +CppTopicGeneratorGrantlee::topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const { - if (tti.baseValueType.isEmpty()) - return CompleteTopicTypeInformation(); - QString baseValueType = tti.baseValueType; - - - if (tti.name.contains(QLatin1String("::")) && - !tti.baseValueType.contains(QLatin1String("::"))) - { - const QStringList sl = tti.name.split(QStringLiteral("::")); - baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType; - } - DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")"; - return m_structBuilder->topicTypeInformationByStructType(baseValueType); + if (tti.baseValueType.isEmpty()) + return CompleteTopicTypeInformation(); + QString baseValueType = tti.baseValueType; + + if (tti.name.contains(QLatin1String("::")) && !tti.baseValueType.contains(QLatin1String("::"))) + { + const QStringList sl = tti.name.split(QStringLiteral("::")); + baseValueType = sl.at(0) + QLatin1String("::") + tti.baseValueType; + } + DEBUG_LOG(m_logger) << "topicTypeInformationByStructName(" << baseValueType << ")"; + return m_structBuilder->topicTypeInformationByStructType(baseValueType); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.h old mode 100755 new mode 100644 index 34282bbb9..5f5f44d83 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/CppTopicGeneratorGrantlee.h @@ -1,47 +1,41 @@ #pragma once -#include - #include "GeneratorGrantleeBase.h" -#include "StructBuilder.h" #include "GrantleeWrappers.h" +#include "StructBuilder.h" + +#include namespace CodeGen { class CppTopicGeneratorGrantlee final : public GeneratorGrantleeBase { - Q_OBJECT -public: - explicit CppTopicGeneratorGrantlee(); + Q_OBJECT + public: + explicit CppTopicGeneratorGrantlee(); - bool init(const XmlReader *reader, StructBuilder *structBuilder) override; + bool init(const XmlReader* reader, StructBuilder* structBuilder) override; -private: - - bool initDataTopics(); - bool getSpecialColumns(const CompleteTopicTypeInformation &tti, - QVector &keyColumns, - QVector &trColumns) const; - - bool initFunctionTopics(); - bool handleStruct(const FunctionTopic &ft, - FunctionTopicsWrapper *functionTopicsWrapper); - bool addRequesterRequestParams(const QString &request_name, - const CompleteTopicTypeInformation &request, - FunctionTopicWrapper *ftw); - bool addRequesterReplyParams(const QString &request_name, - const CompleteTopicTypeInformation &reply, - FunctionTopicWrapper *ftw); - - bool handleIdlStruct(const CompleteTopicTypeInformation &csi, - QSet &idlStructNames, - QVector &idlStructs); - bool initIdlStructs(); - - CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation &tti) const; + private: + bool initDataTopics(); + bool getSpecialColumns(const CompleteTopicTypeInformation& tti, QVector& keyColumns, + QVector& trColumns) const; - const XmlReader *m_reader = nullptr; + bool initFunctionTopics(); + bool handleStruct(const FunctionTopic& ft, FunctionTopicsWrapper* functionTopicsWrapper); + bool addRequesterRequestParams(const QString& request_name, const CompleteTopicTypeInformation& request, + FunctionTopicWrapper* ftw); + bool addRequesterReplyParams(const QString& request_name, const CompleteTopicTypeInformation& reply, + FunctionTopicWrapper* ftw); + + bool handleIdlStruct(const CompleteTopicTypeInformation& csi, QSet& idlStructNames, + QVector& idlStructs); + bool initIdlStructs(); + + CompleteTopicTypeInformation topicTypeInformationByDerivedTopic(const CompleteTopicTypeInformation& tti) const; + + const XmlReader* m_reader = nullptr; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.cpp old mode 100755 new mode 100644 index 2397892db..aa19aeea8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.cpp @@ -1,57 +1,54 @@ - #include "DaoGeneratorGrantlee.h" + #include "StructBuilder.h" + #include #include using namespace CodeGen; -DaoGeneratorGrantlee::DaoGeneratorGrantlee() - : GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee") -{} +DaoGeneratorGrantlee::DaoGeneratorGrantlee() : GeneratorGrantleeBase("CodeGen.DaoGeneratorGrantlee") {} -bool DaoGeneratorGrantlee::init(const XmlReader *reader, - StructBuilder *structBuilder) +bool DaoGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder) { - if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) - return false; + if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) + return false; - - if (reader->isServiceExerciseIndependent()) - m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); + if (reader->isServiceExerciseIndependent()) + m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); - bool bHasDbNotifications = false; - QVector vlServiceStructs; - QVector vlStaticDataStructs; - const QVector csiData = structBuilder->structInformations(); - vlServiceStructs.reserve(csiData.size()); - vlStaticDataStructs.reserve(csiData.size()); - for (const CompleteStructInformation &csi : csiData) - { - DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this)); + bool bHasDbNotifications = false; + QVector vlServiceStructs; + QVector vlStaticDataStructs; + const QVector csiData = structBuilder->structInformations(); + vlServiceStructs.reserve(csiData.size()); + vlStaticDataStructs.reserve(csiData.size()); + for (const CompleteStructInformation& csi : csiData) + { + DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this)); - if (csi.hasStaticContent) - vlStaticDataStructs += dbStructWrapper; - else - vlServiceStructs += dbStructWrapper; - if (!csi.dbNotifications.isEmpty()) - bHasDbNotifications = true; - } + if (csi.hasStaticContent) + vlStaticDataStructs += dbStructWrapper; + else + vlServiceStructs += dbStructWrapper; + if (!csi.dbNotifications.isEmpty()) + bHasDbNotifications = true; + } - if (structBuilder->needPoint3d()) - m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1")); - if (structBuilder->needPgArrayInclude()) - m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1")); - m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs)); - m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs)); - if (bHasDbNotifications) - m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1")); + if (structBuilder->needPoint3d()) + m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1")); + if (structBuilder->needPgArrayInclude()) + m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1")); + m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs)); + m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs)); + if (bHasDbNotifications) + m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1")); - m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON")); + m_ctx->insert(QStringLiteral("library_target"), QStringLiteral("COMMON")); - exportUsedServices(reader); + exportUsedServices(reader); - return true; + return true; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.h old mode 100755 new mode 100644 index b1ff86dce..1ab45436d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DaoGeneratorGrantlee.h @@ -1,11 +1,11 @@ #pragma once -#include - #include "GeneratorGrantleeBase.h" -#include "StructBuilder.h" #include "GrantleeWrappers.h" +#include "StructBuilder.h" + +#include namespace CodeGen { @@ -13,13 +13,12 @@ struct CompleteStructInformation; class StructBuilder; class XmlReader; - class DaoGeneratorGrantlee final : public GeneratorGrantleeBase { - Q_OBJECT -public: - explicit DaoGeneratorGrantlee(); + Q_OBJECT + public: + explicit DaoGeneratorGrantlee(); - bool init(const XmlReader *reader, StructBuilder *structBuilder) override; + bool init(const XmlReader* reader, StructBuilder* structBuilder) override; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.cpp old mode 100755 new mode 100644 index 53a472082..9857d842a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.cpp @@ -1,59 +1,59 @@ - #include "DatabaseGeneratorGrantlee.h" + #include "StructBuilder.h" + #include #include using namespace CodeGen; DatabaseGeneratorGrantlee::DatabaseGeneratorGrantlee(bool targetIsServer) - : GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee") - , m_targetIsServer(targetIsServer) -{} - -bool DatabaseGeneratorGrantlee::init(const XmlReader *reader, - StructBuilder *structBuilder) + : GeneratorGrantleeBase("CodeGen.CppStructGeneratorGrantlee"), m_targetIsServer(targetIsServer) { - if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) - return false; - - - if (reader->isServiceExerciseIndependent()) - m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); - - bool bHasDbNotifications = false; - QVector vlServiceStructs; - QVector vlStaticDataStructs; - const QVector csiData = structBuilder->structInformations(); - vlServiceStructs.reserve(csiData.size()); - vlStaticDataStructs.reserve(csiData.size()); - for (const CompleteStructInformation &csi : csiData) - { - DbStructWrapper *dbStructWrapper(new DbStructWrapper(csi, this)); - - if (csi.hasStaticContent) - vlStaticDataStructs += dbStructWrapper; - else - vlServiceStructs += dbStructWrapper; - if (!csi.dbNotifications.isEmpty()) - bHasDbNotifications = true; - } - addCustomFunctions(reader->getCustomFunctions()); - - if (structBuilder->needPoint3d()) - m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1")); - if (structBuilder->needPgArrayInclude()) - m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1")); - m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs)); - m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs)); - if (bHasDbNotifications) - m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1")); - - m_ctx->insert(QStringLiteral("library_target"), m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON")); - - exportUsedServices(reader); - - return true; +} + +bool DatabaseGeneratorGrantlee::init(const XmlReader* reader, StructBuilder* structBuilder) +{ + if (!GeneratorGrantleeBase::initInternal(reader, structBuilder)) + return false; + + if (reader->isServiceExerciseIndependent()) + m_ctx->insert(QStringLiteral("isExerciseIndependent"), QLatin1String("1")); + + bool bHasDbNotifications = false; + QVector vlServiceStructs; + QVector vlStaticDataStructs; + const QVector csiData = structBuilder->structInformations(); + vlServiceStructs.reserve(csiData.size()); + vlStaticDataStructs.reserve(csiData.size()); + for (const CompleteStructInformation& csi : csiData) + { + DbStructWrapper* dbStructWrapper(new DbStructWrapper(csi, this)); + + if (csi.hasStaticContent) + vlStaticDataStructs += dbStructWrapper; + else + vlServiceStructs += dbStructWrapper; + if (!csi.dbNotifications.isEmpty()) + bHasDbNotifications = true; + } + addCustomFunctions(reader->getCustomFunctions()); + + if (structBuilder->needPoint3d()) + m_ctx->insert(QStringLiteral("need_point3d"), QLatin1String("1")); + if (structBuilder->needPgArrayInclude()) + m_ctx->insert(QStringLiteral("need_pgarray"), QLatin1String("1")); + m_ctx->insert(QStringLiteral("cpp_structs"), QVariant::fromValue(vlServiceStructs)); + m_ctx->insert(QStringLiteral("data_structs"), QVariant::fromValue(vlStaticDataStructs)); + if (bHasDbNotifications) + m_ctx->insert(QStringLiteral("has_db_notifications"), QLatin1String("1")); + + m_ctx->insert(QStringLiteral("library_target"), + m_targetIsServer ? QStringLiteral("SERVER") : QStringLiteral("COMMON")); + + exportUsedServices(reader); + + return true; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.h old mode 100755 new mode 100644 index cac90c380..16903ea4b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/DatabaseGeneratorGrantlee.h @@ -1,11 +1,11 @@ #pragma once -#include - #include "GeneratorGrantleeBase.h" -#include "StructBuilder.h" #include "GrantleeWrappers.h" +#include "StructBuilder.h" + +#include namespace CodeGen { @@ -13,15 +13,15 @@ struct CompleteStructInformation; class StructBuilder; class XmlReader; - class DatabaseGeneratorGrantlee final : public GeneratorGrantleeBase { - Q_OBJECT -public: - explicit DatabaseGeneratorGrantlee(bool targetIsServer); + Q_OBJECT + public: + explicit DatabaseGeneratorGrantlee(bool targetIsServer); - bool init(const XmlReader *reader, StructBuilder *structBuilder) override; -private: - bool m_targetIsServer; + bool init(const XmlReader* reader, StructBuilder* structBuilder) override; + + private: + bool m_targetIsServer; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.cpp old mode 100755 new mode 100644 index d825f5b23..54eb537a8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.cpp @@ -1,9 +1,10 @@ - #include "GeneratorGrantleeBase.h" -#include "XmlReader.h" + #include "GrantleeWrappers.h" +#include "XmlReader.h" + #include #include #include @@ -11,190 +12,187 @@ #include using namespace CodeGen; + GeneratorGrantleeBase::GeneratorGrantleeBase(const char *loggerName) : m_engine(new Grantlee::Engine) , m_ctx(new Grantlee::Context) , m_structBuilder(nullptr) .getNGLLogger(loggerName)), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ } GeneratorGrantleeBase::~GeneratorGrantleeBase() { - delete m_engine; - delete m_ctx; + delete m_engine; + delete m_ctx; } -bool GeneratorGrantleeBase::initInternal(const XmlReader *reader, StructBuilder *structBuilder) +bool GeneratorGrantleeBase::initInternal(const XmlReader* reader, StructBuilder* structBuilder) { - m_structBuilder = structBuilder; + m_structBuilder = structBuilder; - if (reader) - { - m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace()); - m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower()); - m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper()); - if (reader->getServiceNamespace() == QLatin1String("Core")) - m_ctx->insert(QStringLiteral("include_prefix"), QStringLiteral("DDS/%1").arg(reader->getServiceNamespace())); - else - m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace()); - m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin()); - } - return true; + if (reader) + { + m_ctx->insert(QStringLiteral("namespace"), reader->getServiceNamespace()); + m_ctx->insert(QStringLiteral("namespace_abbr"), reader->getServiceAbbr().toLower()); + m_ctx->insert(QStringLiteral("namespace_abbr_upper"), reader->getServiceAbbr().toUpper()); + if (reader->getServiceNamespace() == QLatin1String("Core")) + m_ctx->insert(QStringLiteral("include_prefix"), + QStringLiteral("DDS/%1").arg(reader->getServiceNamespace())); + else + m_ctx->insert(QStringLiteral("include_prefix"), reader->getServiceNamespace()); + m_ctx->insert(QStringLiteral("custom_record_replay"), reader->hasCustomRecordReplayPlugin()); + } + return true; } -bool GeneratorGrantleeBase::setTemplate(const QString &templateName, const QString &tmpl) +bool GeneratorGrantleeBase::setTemplate(const QString& templateName, const QString& tmpl) { - m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate")); - if (m_template->error()) - { - WARNING_LOG(m_logger) << "Error parsing template '" << templateName - << "': " << m_template->errorString(); - return false; - } - return true; + m_template = m_engine->newTemplate(tmpl, QStringLiteral("myTemplate")); + if (m_template->error()) + { + WARNING_LOG(m_logger) << "Error parsing template '" << templateName << "': " << m_template->errorString(); + return false; + } + return true; } QString GeneratorGrantleeBase::render() const { - QString out = m_template->render(m_ctx); - const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*")); - out = out.replace(rx, QStringLiteral(";\n")); - return out; + QString out = m_template->render(m_ctx); + const QRegularExpression rx(QLatin1String(";\\n([ ]+\\n)*")); + out = out.replace(rx, QStringLiteral(";\n")); + return out; } QString GeneratorGrantleeBase::errorString() const { - return m_template->errorString(); + return m_template->errorString(); } - -bool GeneratorGrantleeBase::generateData(const QString &templateName, - const QString &outDirectory) +bool GeneratorGrantleeBase::generateData(const QString& templateName, const QString& outDirectory) { - QString content; - if (!readFile(templateName, content)) - return false; - if (!setTemplate(templateName, content)) - return false; + QString content; + if (!readFile(templateName, content)) + return false; + if (!setTemplate(templateName, content)) + return false; - content = render(); + content = render(); - QString outFilename; - if (!getFilenameFromData(content, outFilename)) - return false; - + QString outFilename; + if (!getFilenameFromData(content, outFilename)) + return false; - QFile f(outDirectory + QLatin1Char('/') + outFilename); - if (!f.open(QIODevice::WriteOnly)) - { - ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " - << f.errorString() << "(" << f.error() << ")"; - return false; - } - const QByteArray outData = content.toUtf8(); - f.write(outData); - f.close(); - - DEBUG_LOG(m_logger) << "Written data to " << f.fileName(); - return true; -} - -bool GeneratorGrantleeBase::readFile(const QString &filename, QString &data) const -{ - QFile f(filename); - if (!f.open(QIODevice::ReadOnly)) - { - ERROR_LOG(m_logger) << "Error opening file " << filename - << " - error: " << f.errorString(); - return false; - } - data = QString::fromUtf8(f.readAll()); - f.close(); - return true; -} - -bool GeneratorGrantleeBase::getFilenameFromData(const QString &dataToParse, QString &filename) const -{ - - const QString filenameMarker(QStringLiteral("// filename:")); - int idx = dataToParse.indexOf(filenameMarker); - if (idx < 0) - { - ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker - << "' in data!"; - return false; - } - idx += filenameMarker.length() + 1; - int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx); - if (endIdx < 0) - { - ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!"; - return false; - } - filename = dataToParse.mid(idx, endIdx - idx).trimmed(); - - return true; -} - -void GeneratorGrantleeBase::addCustomFunctions(const QVector &customFunctions) -{ - - QVariantList vlCustomDbFunctions; - QVariantList vlCustomDtcFunctions; - vlCustomDbFunctions.reserve(customFunctions.size()); - vlCustomDtcFunctions.reserve(customFunctions.size()); - for (const CustomServiceFunctionInformation &csfi : customFunctions) - { - const QString signature(csfi.returnValue + QLatin1Char(' ') + - csfi.methodName + QLatin1Char('(') + csfi.signature + QLatin1Char(')') + - (csfi.isConst ? QStringLiteral(" const") : QString())); - CustomFunctionWrapper *customFunctionWrapper(new CustomFunctionWrapper(signature, this)); - switch (csfi.type) + QFile f(outDirectory + QLatin1Char('/') + outFilename); + if (!f.open(QIODevice::WriteOnly)) { - case CustomServiceFunctionInformation::Type::Db: - vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper); - break; - case CustomServiceFunctionInformation::Type::Dtc: - vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper); - break; - case CustomServiceFunctionInformation::Type::DbNotify: - - WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): " - << csfi.methodName; - delete customFunctionWrapper; - break; + ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " << f.errorString() << "(" + << f.error() << ")"; + return false; } - DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName; - } - m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions); - m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions); + const QByteArray outData = content.toUtf8(); + f.write(outData); + f.close(); + + DEBUG_LOG(m_logger) << "Written data to " << f.fileName(); + return true; } -void GeneratorGrantleeBase::exportUsedServices(const XmlReader *reader) +bool GeneratorGrantleeBase::readFile(const QString& filename, QString& data) const { - IdlServicesWrapper *idlServicesWrapper(new IdlServicesWrapper(QString(), this)); - const QMap usedServices = reader->usedServices(); - for (auto it = usedServices.begin(); it != usedServices.end(); ++it) - { - - if (!it.value()) - continue; - const QString &svc = it.key(); - const QString fullPath = reader->idlFileForService(svc); - const int idx = fullPath.lastIndexOf(QLatin1Char('.')); + QFile f(filename); + if (!f.open(QIODevice::ReadOnly)) + { + ERROR_LOG(m_logger) << "Error opening file " << filename << " - error: " << f.errorString(); + return false; + } + data = QString::fromUtf8(f.readAll()); + f.close(); + return true; +} + +bool GeneratorGrantleeBase::getFilenameFromData(const QString& dataToParse, QString& filename) const +{ + + const QString filenameMarker(QStringLiteral("// filename:")); + int idx = dataToParse.indexOf(filenameMarker); if (idx < 0) { - ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath; - continue; + ERROR_LOG(m_logger) << "Could not find marker '" << filenameMarker << "' in data!"; + return false; } - const QString idlFile = fullPath.left(idx); - if (idlFile.isEmpty()) + idx += filenameMarker.length() + 1; + int endIdx = dataToParse.indexOf(QLatin1Char('\n'), idx); + if (endIdx < 0) { - WARNING_LOG(m_logger) << "Could not find idl file for service " << svc; - continue; + ERROR_LOG(m_logger) << "Could not find end marker '\\n' in data!"; + return false; } - idlServicesWrapper->addService(svc, idlFile); - DEBUG_LOG(m_logger) << "Added service " << svc; - } - m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper); + filename = dataToParse.mid(idx, endIdx - idx).trimmed(); + + return true; +} + +void GeneratorGrantleeBase::addCustomFunctions(const QVector& customFunctions) +{ + + QVariantList vlCustomDbFunctions; + QVariantList vlCustomDtcFunctions; + vlCustomDbFunctions.reserve(customFunctions.size()); + vlCustomDtcFunctions.reserve(customFunctions.size()); + for (const CustomServiceFunctionInformation& csfi : customFunctions) + { + const QString signature(csfi.returnValue + QLatin1Char(' ') + csfi.methodName + QLatin1Char('(') + + csfi.signature + QLatin1Char(')') + + (csfi.isConst ? QStringLiteral(" const") : QString())); + CustomFunctionWrapper* customFunctionWrapper(new CustomFunctionWrapper(signature, this)); + switch (csfi.type) + { + case CustomServiceFunctionInformation::Type::Db: + vlCustomDbFunctions += QVariant::fromValue(customFunctionWrapper); + break; + case CustomServiceFunctionInformation::Type::Dtc: + vlCustomDtcFunctions += QVariant::fromValue(customFunctionWrapper); + break; + case CustomServiceFunctionInformation::Type::DbNotify: + + WARNING_LOG(m_logger) << "Internal error - Trying to handle DbNotify in addCustomFunctions(): " + << csfi.methodName; + delete customFunctionWrapper; + break; + } + DEBUG_LOG(m_logger) << "Added custom db function " << csfi.methodName; + } + m_ctx->insert(QStringLiteral("custom_dtc_procs"), vlCustomDtcFunctions); + m_ctx->insert(QStringLiteral("custom_db_procs"), vlCustomDbFunctions); +} + +void GeneratorGrantleeBase::exportUsedServices(const XmlReader* reader) +{ + IdlServicesWrapper* idlServicesWrapper(new IdlServicesWrapper(QString(), this)); + const QMap usedServices = reader->usedServices(); + for (auto it = usedServices.begin(); it != usedServices.end(); ++it) + { + + if (!it.value()) + continue; + const QString& svc = it.key(); + const QString fullPath = reader->idlFileForService(svc); + const int idx = fullPath.lastIndexOf(QLatin1Char('.')); + if (idx < 0) + { + ERROR_LOG(m_logger) << "Could not parse file path: " << fullPath; + continue; + } + const QString idlFile = fullPath.left(idx); + if (idlFile.isEmpty()) + { + WARNING_LOG(m_logger) << "Could not find idl file for service " << svc; + continue; + } + idlServicesWrapper->addService(svc, idlFile); + DEBUG_LOG(m_logger) << "Added service " << svc; + } + m_ctx->insert(QStringLiteral("ext_services"), idlServicesWrapper); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.h old mode 100755 new mode 100644 index 8b84b52f0..df86758e9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GeneratorGrantleeBase.h @@ -3,6 +3,7 @@ #pragma once #include "XmlReader.h" + #include #include @@ -17,37 +18,38 @@ class Context; class Engine; class TemplateImpl; using Template = QSharedPointer; -} +} // namespace Grantlee + namespace CodeGen { class StructBuilder; class GeneratorGrantleeBase : public QObject { - Q_OBJECT -public: - virtual ~GeneratorGrantleeBase(); - virtual bool init(const XmlReader *reader, StructBuilder *structBuilder) = 0; - bool setTemplate(const QString &templateName, const QString &tmpl); - QString render() const; - QString errorString() const; - bool generateData(const QString &templateName, - const QString &outDirectory); + Q_OBJECT + public: + virtual ~GeneratorGrantleeBase(); + virtual bool init(const XmlReader* reader, StructBuilder* structBuilder) = 0; + bool setTemplate(const QString& templateName, const QString& tmpl); + QString render() const; + QString errorString() const; + bool generateData(const QString& templateName, const QString& outDirectory); -protected: - NGL::INGLLogger &m_logger; - explicit GeneratorGrantleeBase(const char *loggerName); + protected: + NGL::INGLLogger& m_logger; + explicit GeneratorGrantleeBase(const char* loggerName); - bool initInternal(const XmlReader *reader, StructBuilder *structBuilder); - bool readFile(const QString &filename, QString &data) const; - bool getFilenameFromData(const QString &dataToParse, QString &filename) const; - void addCustomFunctions(const QVector &customFunctions); - void exportUsedServices(const XmlReader *reader); -protected: - NGL::INGLLogger &m_logger; - Grantlee::Engine *m_engine; - Grantlee::Context *m_ctx; - Grantlee::Template m_template; - StructBuilder *m_structBuilder; + bool initInternal(const XmlReader* reader, StructBuilder* structBuilder); + bool readFile(const QString& filename, QString& data) const; + bool getFilenameFromData(const QString& dataToParse, QString& filename) const; + void addCustomFunctions(const QVector& customFunctions); + void exportUsedServices(const XmlReader* reader); + + protected: + NGL::INGLLogger& m_logger; + Grantlee::Engine* m_engine; + Grantlee::Context* m_ctx; + Grantlee::Template m_template; + StructBuilder* m_structBuilder; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.cpp old mode 100755 new mode 100644 index c7f3d5eff..57d0d5aa4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.cpp @@ -1,7 +1,7 @@ - #include "GrantleeWrappers.h" + #include #include @@ -10,241 +10,194 @@ using namespace CodeGen; #ifdef RTI_HEADER_AVAILABLE QString IdlStructWrapper::extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity) { - switch (extensiblity.underlying()) - { - case dds::core::xtypes::ExtensibilityKind_def::FINAL: - return QStringLiteral("FINAL_EXTENSIBILITY"); - case dds::core::xtypes::ExtensibilityKind_def::MUTABLE: - return QStringLiteral("MUTABLE_EXTENSIBILITY"); - case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE: - return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); - } - Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind"); - return QString(); + switch (extensiblity.underlying()) + { + case dds::core::xtypes::ExtensibilityKind_def::FINAL: + return QStringLiteral("FINAL_EXTENSIBILITY"); + case dds::core::xtypes::ExtensibilityKind_def::MUTABLE: + return QStringLiteral("MUTABLE_EXTENSIBILITY"); + case dds::core::xtypes::ExtensibilityKind_def::EXTENSIBLE: + return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); + } + Q_ASSERT_X(false, "IdlStructWrapper::extensibility2String", "Unknown extensiblity kind"); + return QString(); } #else QString IdlStructWrapper::extensibility2String(int /*extensiblity*/) { - // RTI not available - return placeholder - return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); + // RTI not available - return placeholder + return QStringLiteral("EXTENSIBLE_EXTENSIBILITY"); } #endif QString DataTopicWrapper::typeFq() const { - const QString &t = type(); - const QString &s = serviceName(); - if (s.isEmpty()) - return t; - if (t.startsWith(s)) - return t; - return s + QStringLiteral("::") + t; + const QString& t = type(); + const QString& s = serviceName(); + if (s.isEmpty()) + return t; + if (t.startsWith(s)) + return t; + return s + QStringLiteral("::") + t; } QString MemberInformationWrapper::ddsToQVariant() const { - return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())"); + return QStringLiteral("toQVariant(data.") + cppMemberName() + QStringLiteral("())"); } QString MemberInformationWrapper::qVariantToDds() const { - const QString ddsType = isOptional() ? - (QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) : - (cppDdsType()); + const QString ddsType = + isOptional() ? (QStringLiteral("dds::core::optional<") + cppDdsType() + QLatin1Char('>')) : (cppDdsType()); - return QStringLiteral("data.") + cppMemberName() + - QStringLiteral("() = fromQVariant<") + ddsType + QStringLiteral(">(q.value(i++))"); + return QStringLiteral("data.") + cppMemberName() + QStringLiteral("() = fromQVariant<") + ddsType + + QStringLiteral(">(q.value(i++))"); } QString MemberInformationWrapper::ddsToJsonElement() const { - - - - - - + if (cppMemberName().isEmpty()) + return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;"); - - - + const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()"); + if (!isOptional()) + return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() + + QStringLiteral("element.") + memberAccess + cppToJsonPost(); - if (cppMemberName().isEmpty()) - return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;"); - - const QString memberAccess = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()"); - if (!isOptional()) - return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + - cppToJsonPre() + QStringLiteral("element.") + memberAccess + cppToJsonPost(); - - const QString optionalAccess = isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()"); - const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()"); - return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") + - QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + - cppToJsonPre() + QStringLiteral("element.") + getValue + cppToJsonPost(); + const QString optionalAccess = + isCppStruct() ? cppMemberName() + QStringLiteral(".is_set()") : cppMemberName() + QStringLiteral("().is_set()"); + const QString getValue = isCppStruct() ? cppMemberName() : cppMemberName() + QStringLiteral("()"); + return QStringLiteral("if (element.") + optionalAccess + QStringLiteral(") ") + + QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() + + QStringLiteral("element.") + getValue + cppToJsonPost(); } QString MemberInformationWrapper::jsonElementToDds() const { - - - - - - + if (cppMemberName().isEmpty()) + return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + + cppType() + QStringLiteral("\"))") + cppFromJsonPost(); - - - + QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + + QStringLiteral("\"))); ")); + if (isOptional()) + ret += QStringLiteral("if (!val.isNull()) "); - - + if (isCppStruct()) + ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() + + QStringLiteral("val") + cppFromJsonPost(); + else + ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") + cppFromJsonPre2() + + QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")"); - - - - if (cppMemberName().isEmpty()) - return QStringLiteral("element = ") + - cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost(); - - QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); ")); - if (isOptional()) - ret += QStringLiteral("if (!val.isNull()) "); - - if (isCppStruct()) - ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + - cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost(); - else - ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral("(") + - cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost() + QStringLiteral(")"); - - return ret; + return ret; } QString MemberInformationWrapper::dbToJsonElement() const { - - - - + if (cppMemberName().isEmpty()) + return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;"); - - + if (isOptional() || cppType() == QStringLiteral("QDateTime")) + { + QString ret = QStringLiteral("if (") + + ((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) + + QStringLiteral("element.") + cppMemberName() + + ((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ") + : QStringLiteral(".isNull()) ")) + + QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = "); + if (isOptional()) + return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost(); + } - if (cppMemberName().isEmpty()) - return QStringLiteral("obj[QStringLiteral(\"") + cppType() + QStringLiteral("\")] = element;"); - - if (isOptional() || cppType() == QStringLiteral("QDateTime")) - { - QString ret = QStringLiteral("if (") + ((cppType() == QStringLiteral("QDateTime")) ? QString() : QStringLiteral("!")) + - QStringLiteral("element.") + cppMemberName() + - ((cppType() == QStringLiteral("QDateTime")) ? QStringLiteral(".isValid()) ") : QStringLiteral(".isNull()) ")) + - QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = "); - if (isOptional()) - return ret += cppFromQvPre2() + QStringLiteral("element.") + cppMemberName() + cppFromQvPost(); - } - - return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + - cppToJsonPre() + QStringLiteral("element.") + cppMemberName() + cppToJsonPost(); + return QStringLiteral("obj[QStringLiteral(\"") + cppMemberName() + QStringLiteral("\")] = ") + cppToJsonPre() + + QStringLiteral("element.") + cppMemberName() + cppToJsonPost(); } QString MemberInformationWrapper::jsonElementToDb() const { - - - - + if (cppMemberName().isEmpty()) + return QStringLiteral("element = ") + cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + + cppType() + QStringLiteral("\"))") + cppFromJsonPost(); - - + QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + + QStringLiteral("\"))); ")); + if (isOptional()) + ret += QStringLiteral("if (!val.isUndefined()) "); - - + ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + cppFromJsonPre2() + + QStringLiteral("val") + cppFromJsonPost(); - - if (cppMemberName().isEmpty()) - return QStringLiteral("element = ") + - cppFromQvPre2() + QStringLiteral("objElement.value(QStringLiteral(\"") + cppType() + QStringLiteral("\"))") + cppFromJsonPost(); - - QString ret(QStringLiteral("const QJsonValue val(objElement.value(QStringLiteral(\"") + cppMemberName() + QStringLiteral("\"))); ")); - if (isOptional()) - ret += QStringLiteral("if (!val.isUndefined()) "); - - ret += QStringLiteral("element.") + cppMemberName() + QStringLiteral(" = ") + - cppFromJsonPre2() + QStringLiteral("val") + cppFromJsonPost(); - - return ret; + return ret; } QVariantList DbStructWrapper::insertStructures() { - - QStringList tableNames; - QMap> structures; - QMap primaryKeys; - QMap fkComplexTableKeys; - - tableNames.reserve(5); - for (const QVariant &v : std::as_const(m_member)) - { - MemberInformationWrapper *mi = v.value(); - const QString &tableName = mi->info().db.table; - if (mi->info().db.usedForInsert) - { - auto &tnStructure = structures[tableName]; - tnStructure.append(mi); - if (!tableNames.contains(tableName)) - tableNames.push_back(tableName); - } - if (mi->info().fk) - fkComplexTableKeys[mi->info().fk->destination.tableName] = mi; - if (mi->info().db.isPrimaryKey) - { - if (!primaryKeys.contains(tableName)) - primaryKeys[tableName] = mi; - } - if (mi->info().db.isAssignmentForPrimaryTablePk) - fkComplexTableKeys[mi->info().db.table] = mi; - } - - QVariantList vl; - vl.reserve(tableNames.size()); - for (int i = 0; i < tableNames.size(); ++i) - { - const QString &tn = tableNames.at(i); - MemberInformationWrapper *serialMember = fkComplexTableKeys.value(tn); - MemberInformationWrapper *baseId = nullptr; - MemberInformationWrapper *primaryKey = primaryKeys.value(tn); - if (i == 0 && tableNames.size() > 1) - baseId = primaryKeys.value(tn); + QStringList tableNames; + QMap> structures; + QMap primaryKeys; + QMap fkComplexTableKeys; - - - if (tableNames.size() == 1) + tableNames.reserve(5); + for (const QVariant& v : std::as_const(m_member)) { - baseId = nullptr; - - if (!primaryKey) - { - NGL::INGLLogger &logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper"); - WARNING_LOG(logger) << "Table " << tn << " has no primary key!"; - } - else - { - if (primaryKey->dbHasSequence()) - serialMember = primaryKey; - } + MemberInformationWrapper* mi = v.value(); + const QString& tableName = mi->info().db.table; + if (mi->info().db.usedForInsert) + { + auto& tnStructure = structures[tableName]; + tnStructure.append(mi); + if (!tableNames.contains(tableName)) + tableNames.push_back(tableName); + } + if (mi->info().fk) + fkComplexTableKeys[mi->info().fk->destination.tableName] = mi; + if (mi->info().db.isPrimaryKey) + { + if (!primaryKeys.contains(tableName)) + primaryKeys[tableName] = mi; + } + if (mi->info().db.isAssignmentForPrimaryTablePk) + fkComplexTableKeys[mi->info().db.table] = mi; } - const QVector members = structures.value(tn); - TableWrapper *tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this); - vl += QVariant::fromValue(tw); - } + QVariantList vl; + vl.reserve(tableNames.size()); + for (int i = 0; i < tableNames.size(); ++i) + { + const QString& tn = tableNames.at(i); + MemberInformationWrapper* serialMember = fkComplexTableKeys.value(tn); + MemberInformationWrapper* baseId = nullptr; + MemberInformationWrapper* primaryKey = primaryKeys.value(tn); + if (i == 0 && tableNames.size() > 1) + baseId = primaryKeys.value(tn); - return vl; + if (tableNames.size() == 1) + { + baseId = nullptr; + + if (!primaryKey) + { + NGL::INGLLogger& logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("DbStructWrapper"); + WARNING_LOG(logger) << "Table " << tn << " has no primary key!"; + } + else + { + if (primaryKey->dbHasSequence()) + serialMember = primaryKey; + } + } + + const QVector members = structures.value(tn); + TableWrapper* tw = new TableWrapper(tn, members, serialMember, baseId, primaryKey, this); + vl += QVariant::fromValue(tw); + } + + return vl; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.h old mode 100755 new mode 100644 index 50666d242..84cd8f3ce --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/GrantleeWrappers.h @@ -1,13 +1,13 @@ - #pragma once +#include "StructBuilder.h" + #include #include #include #include -#include "StructBuilder.h" #ifdef RTI_HEADER_AVAILABLE #include @@ -17,638 +17,914 @@ namespace CodeGen { class NameWrapper : public QObject { - Q_OBJECT - Q_PROPERTY(QString name READ name) - Q_PROPERTY(QString nameCc READ nameCc) - Q_PROPERTY(QString nameFlc READ nameFlc) -public: - NameWrapper(const QString &name, QObject *parent) - : QObject(parent) - , m_name(name) - {} + Q_OBJECT + Q_PROPERTY(QString name READ name) + Q_PROPERTY(QString nameCc READ nameCc) + Q_PROPERTY(QString nameFlc READ nameFlc) + public: + NameWrapper(const QString& name, QObject* parent) : QObject(parent), m_name(name) {} - QString name() const { return m_name; } - QString nameCc() const { return StructBuilder::camelCaseString(name(), true); } - QString nameFlc() const { return StructBuilder::firstCharLowercase(nameCc()); } -private: - const QString m_name; + QString name() const + { + return m_name; + } + + QString nameCc() const + { + return StructBuilder::camelCaseString(name(), true); + } + + QString nameFlc() const + { + return StructBuilder::firstCharLowercase(nameCc()); + } + + private: + const QString m_name; }; class VariantListWrapper : public NameWrapper { - Q_OBJECT - Q_PROPERTY(QVariantList member READ member) -public: + Q_OBJECT + Q_PROPERTY(QVariantList member READ member) + public: + using NameWrapper::NameWrapper; - using NameWrapper::NameWrapper; - ~VariantListWrapper() - { - for (const QVariant &v : std::as_const(m_member)) + ~VariantListWrapper() { - auto ptr = v.value(); - delete ptr; + for (const QVariant& v : std::as_const(m_member)) + { + auto ptr = v.value(); + delete ptr; + } } - } - QVariantList member() const { return m_member; } -protected: - QVariantList m_member; + QVariantList member() const + { + return m_member; + } + + protected: + QVariantList m_member; }; - class MemberInformationWrapper final : public QObject { - Q_OBJECT - Q_PROPERTY(QString cppMemberName READ cppMemberName) - Q_PROPERTY(QString cppMemberNameCc READ cppMemberNameCc) - Q_PROPERTY(QString cppStructName READ cppStructName) - Q_PROPERTY(QString cppType READ cppType) - Q_PROPERTY(QString cppToQvPre READ cppToQvPre) - Q_PROPERTY(QString cppToQvPost READ cppToQvPost) - Q_PROPERTY(QString cppFromQvPre1 READ cppFromQvPre1) - Q_PROPERTY(QString cppFromQvPre2 READ cppFromQvPre2) - Q_PROPERTY(QString cppFromQvPost READ cppFromQvPost) - Q_PROPERTY(QString cppDefault READ cppDefault) - Q_PROPERTY(QString dbTableName READ dbTableName) - Q_PROPERTY(QString dbColumnName READ dbColumnName) - Q_PROPERTY(QString dbColumnNameView READ dbColumnNameView) - Q_PROPERTY(QString ddsToQVariant READ ddsToQVariant) - Q_PROPERTY(QString qVariantToDds READ qVariantToDds) - Q_PROPERTY(QString ddsToJsonElement READ ddsToJsonElement) - Q_PROPERTY(QString jsonElementToDds READ jsonElementToDds) - Q_PROPERTY(QString dbToJsonElement READ dbToJsonElement) - Q_PROPERTY(QString jsonElementToDb READ jsonElementToDb) - Q_PROPERTY(bool dbHasSequence READ dbHasSequence) - Q_PROPERTY(bool isOptional READ isOptional) - Q_PROPERTY(bool isCppStruct READ isCppStruct) -public: - MemberInformationWrapper(const MemberInformation &mi, QObject *parent) - : QObject(parent) - , m_mi(mi) - {} + Q_OBJECT + Q_PROPERTY(QString cppMemberName READ cppMemberName) + Q_PROPERTY(QString cppMemberNameCc READ cppMemberNameCc) + Q_PROPERTY(QString cppStructName READ cppStructName) + Q_PROPERTY(QString cppType READ cppType) + Q_PROPERTY(QString cppToQvPre READ cppToQvPre) + Q_PROPERTY(QString cppToQvPost READ cppToQvPost) + Q_PROPERTY(QString cppFromQvPre1 READ cppFromQvPre1) + Q_PROPERTY(QString cppFromQvPre2 READ cppFromQvPre2) + Q_PROPERTY(QString cppFromQvPost READ cppFromQvPost) + Q_PROPERTY(QString cppDefault READ cppDefault) + Q_PROPERTY(QString dbTableName READ dbTableName) + Q_PROPERTY(QString dbColumnName READ dbColumnName) + Q_PROPERTY(QString dbColumnNameView READ dbColumnNameView) + Q_PROPERTY(QString ddsToQVariant READ ddsToQVariant) + Q_PROPERTY(QString qVariantToDds READ qVariantToDds) + Q_PROPERTY(QString ddsToJsonElement READ ddsToJsonElement) + Q_PROPERTY(QString jsonElementToDds READ jsonElementToDds) + Q_PROPERTY(QString dbToJsonElement READ dbToJsonElement) + Q_PROPERTY(QString jsonElementToDb READ jsonElementToDb) + Q_PROPERTY(bool dbHasSequence READ dbHasSequence) + Q_PROPERTY(bool isOptional READ isOptional) + Q_PROPERTY(bool isCppStruct READ isCppStruct) + public: + MemberInformationWrapper(const MemberInformation& mi, QObject* parent) : QObject(parent), m_mi(mi) {} - QString cppMemberName() const { return m_mi.cpp.memberName; } - QString cppMemberNameCc() const { return StructBuilder::camelCaseString(m_mi.cpp.memberName, true); } - QString cppStructName() const { return m_mi.cpp.structName; } - QString cppType() const { return m_mi.cpp.type; } - QString cppToQvPre() const { return m_mi.cpp.toVariantPre; } - QString cppToQvPost() const { return m_mi.cpp.toVariantPost; } - QString cppFromQvPre1() const { return m_mi.cpp.fromVariantPre1; } - QString cppFromQvPre2() const { return m_mi.cpp.fromVariantPre2; } - QString cppFromQvPost() const { return m_mi.cpp.fromVariantPost; } - QString cppDefault() const { return m_mi.cpp.defaultValue; } - QString dbTableName() const { return m_mi.db.table; } - QString dbColumnName() const { return m_mi.db.columnName; } - QString dbColumnNameView() const { return m_mi.db.getColumnNameView(); } - QString cppDdsType() const { return m_mi.cpp.ddsType.isEmpty() ? cppType() : m_mi.cpp.ddsType; } - QString ddsToQVariant() const; - QString qVariantToDds() const; - QString ddsToJsonElement() const; - QString jsonElementToDds() const; - QString dbToJsonElement() const; - QString jsonElementToDb() const; - bool dbHasSequence() const { return m_mi.db.hasSequence; } - bool isOptional() const { return m_mi.cpp.isOptional; } - bool isCppStruct() const { return m_mi.cpp.usedForCppStruct; } + QString cppMemberName() const + { + return m_mi.cpp.memberName; + } - - QString cppToJsonPre() const { return m_mi.cpp.toJsonPre.isNull() ? m_mi.cpp.toVariantPre : m_mi.cpp.toJsonPre; } - QString cppToJsonPost() const { return m_mi.cpp.toJsonPost.isNull() ? m_mi.cpp.toVariantPost : m_mi.cpp.toJsonPost; } - QString cppFromJsonPre2() const { return m_mi.cpp.fromJsonPre2.isNull() ? m_mi.cpp.fromVariantPre2: m_mi.cpp.fromJsonPre2; } - QString cppFromJsonPost() const { return m_mi.cpp.fromJsonPost.isNull() ? m_mi.cpp.fromVariantPost : m_mi.cpp.fromJsonPost; } + QString cppMemberNameCc() const + { + return StructBuilder::camelCaseString(m_mi.cpp.memberName, true); + } - MemberInformation info() const - { - return m_mi; - } -private: - const MemberInformation m_mi; + QString cppStructName() const + { + return m_mi.cpp.structName; + } + + QString cppType() const + { + return m_mi.cpp.type; + } + + QString cppToQvPre() const + { + return m_mi.cpp.toVariantPre; + } + + QString cppToQvPost() const + { + return m_mi.cpp.toVariantPost; + } + + QString cppFromQvPre1() const + { + return m_mi.cpp.fromVariantPre1; + } + + QString cppFromQvPre2() const + { + return m_mi.cpp.fromVariantPre2; + } + + QString cppFromQvPost() const + { + return m_mi.cpp.fromVariantPost; + } + + QString cppDefault() const + { + return m_mi.cpp.defaultValue; + } + + QString dbTableName() const + { + return m_mi.db.table; + } + + QString dbColumnName() const + { + return m_mi.db.columnName; + } + + QString dbColumnNameView() const + { + return m_mi.db.getColumnNameView(); + } + + QString cppDdsType() const + { + return m_mi.cpp.ddsType.isEmpty() ? cppType() : m_mi.cpp.ddsType; + } + + QString ddsToQVariant() const; + QString qVariantToDds() const; + QString ddsToJsonElement() const; + QString jsonElementToDds() const; + QString dbToJsonElement() const; + QString jsonElementToDb() const; + + bool dbHasSequence() const + { + return m_mi.db.hasSequence; + } + + bool isOptional() const + { + return m_mi.cpp.isOptional; + } + + bool isCppStruct() const + { + return m_mi.cpp.usedForCppStruct; + } + + QString cppToJsonPre() const + { + return m_mi.cpp.toJsonPre.isNull() ? m_mi.cpp.toVariantPre : m_mi.cpp.toJsonPre; + } + + QString cppToJsonPost() const + { + return m_mi.cpp.toJsonPost.isNull() ? m_mi.cpp.toVariantPost : m_mi.cpp.toJsonPost; + } + + QString cppFromJsonPre2() const + { + return m_mi.cpp.fromJsonPre2.isNull() ? m_mi.cpp.fromVariantPre2 : m_mi.cpp.fromJsonPre2; + } + + QString cppFromJsonPost() const + { + return m_mi.cpp.fromJsonPost.isNull() ? m_mi.cpp.fromVariantPost : m_mi.cpp.fromJsonPost; + } + + MemberInformation info() const + { + return m_mi; + } + + private: + const MemberInformation m_mi; }; class MemberInformationListWrapper : public VariantListWrapper { - Q_OBJECT - Q_PROPERTY(QVariantList cppMember READ cppMember) - Q_PROPERTY(QVariantList jsonMember READ jsonMember) - Q_PROPERTY(QVariantList fkMember READ fkMember) - Q_PROPERTY(QVariantList selectRemoveMember READ selectRemoveMember) - Q_PROPERTY(QVariantList viewMember READ viewMember) - Q_PROPERTY(MemberInformationWrapper *ddsKey READ ddsKey) - Q_PROPERTY(MemberInformationWrapper *primaryKey READ primaryKey) -public: - explicit MemberInformationListWrapper(const QString &name, const QVector &member, QObject *parent) - : VariantListWrapper(name, parent) - { - for (const MemberInformation &mi : member) - m_member += QVariant::fromValue(new MemberInformationWrapper(mi, this)); - } - - QVariantList memberByFilter(const std::function &acceptFilter) const - { - QVariantList vl; - vl.reserve(m_member.size()); - for (const QVariant &v : m_member) + Q_OBJECT + Q_PROPERTY(QVariantList cppMember READ cppMember) + Q_PROPERTY(QVariantList jsonMember READ jsonMember) + Q_PROPERTY(QVariantList fkMember READ fkMember) + Q_PROPERTY(QVariantList selectRemoveMember READ selectRemoveMember) + Q_PROPERTY(QVariantList viewMember READ viewMember) + Q_PROPERTY(MemberInformationWrapper* ddsKey READ ddsKey) + Q_PROPERTY(MemberInformationWrapper* primaryKey READ primaryKey) + public: + explicit MemberInformationListWrapper(const QString& name, const QVector& member, + QObject* parent) + : VariantListWrapper(name, parent) { - MemberInformationWrapper *mi = v.value(); - if (mi && acceptFilter(mi->info())) - vl += v; + for (const MemberInformation& mi : member) + m_member += QVariant::fromValue(new MemberInformationWrapper(mi, this)); } - return vl; - } - QVariantList cppMember() const - { - return memberByFilter([](const MemberInformation &mi) { return mi.cpp.usedForCppStruct; }); - } - QVariantList jsonMember() const - { - return memberByFilter([](const MemberInformation &mi) { return mi.cpp.usedForJson; }); - } - QVariantList fkMember() const - { - return memberByFilter([](const MemberInformation &mi) { return mi.db.isForeignKey; }); - } - QVariantList selectRemoveMember() const - { - return memberByFilter([](const MemberInformation &mi) { return mi.db.generateSelectRemove; }); - } - QVariantList viewMember() const - { - return memberByFilter([](const MemberInformation &mi) { return mi.db.usedForView; }); - } - MemberInformationWrapper *ddsKey() const - { - for (const QVariant &v : m_member) + QVariantList memberByFilter(const std::function& acceptFilter) const { - MemberInformationWrapper *mi = v.value(); - if (mi->info().isDdsKey) - return mi; + QVariantList vl; + vl.reserve(m_member.size()); + for (const QVariant& v : m_member) + { + MemberInformationWrapper* mi = v.value(); + if (mi && acceptFilter(mi->info())) + vl += v; + } + return vl; } - return nullptr; - } - MemberInformationWrapper *primaryKey() const - { - for (const QVariant &v : m_member) + + QVariantList cppMember() const { - MemberInformationWrapper *mi = v.value(); - if (mi->info().db.isPrimaryKey) - return mi; + return memberByFilter([](const MemberInformation& mi) { return mi.cpp.usedForCppStruct; }); + } + + QVariantList jsonMember() const + { + return memberByFilter([](const MemberInformation& mi) { return mi.cpp.usedForJson; }); + } + + QVariantList fkMember() const + { + return memberByFilter([](const MemberInformation& mi) { return mi.db.isForeignKey; }); + } + + QVariantList selectRemoveMember() const + { + return memberByFilter([](const MemberInformation& mi) { return mi.db.generateSelectRemove; }); + } + + QVariantList viewMember() const + { + return memberByFilter([](const MemberInformation& mi) { return mi.db.usedForView; }); + } + + MemberInformationWrapper* ddsKey() const + { + for (const QVariant& v : m_member) + { + MemberInformationWrapper* mi = v.value(); + if (mi->info().isDdsKey) + return mi; + } + return nullptr; + } + + MemberInformationWrapper* primaryKey() const + { + for (const QVariant& v : m_member) + { + MemberInformationWrapper* mi = v.value(); + if (mi->info().db.isPrimaryKey) + return mi; + } + return nullptr; } - return nullptr; - } }; - class TableWrapper final : public NameWrapper { - Q_OBJECT - Q_PROPERTY(QVector member READ member) - - Q_PROPERTY(MemberInformationWrapper *serialMember READ serialMember) - - - Q_PROPERTY(MemberInformationWrapper *baseId READ baseId) - - Q_PROPERTY(MemberInformationWrapper *primaryKey READ primaryKey) -public: - - explicit TableWrapper(const QString &name, - const QVector &member, - MemberInformationWrapper *serialMember, - MemberInformationWrapper *baseId, - MemberInformationWrapper *primaryKey, - QObject *parent) - : NameWrapper(name, parent) - , m_member(member) - , m_serialMember(serialMember) - , m_baseId(baseId) - , m_primaryKey(primaryKey) - {} + Q_OBJECT + Q_PROPERTY(QVector member READ member) - QVector member() const { return m_member; } - MemberInformationWrapper *serialMember() const { return m_serialMember; } - MemberInformationWrapper *baseId() const { return m_baseId; } - MemberInformationWrapper *primaryKey() const { return m_primaryKey; } + Q_PROPERTY(MemberInformationWrapper* serialMember READ serialMember) -private: - QVector m_member; - MemberInformationWrapper *m_serialMember; - MemberInformationWrapper *m_baseId; - MemberInformationWrapper *m_primaryKey; + Q_PROPERTY(MemberInformationWrapper* baseId READ baseId) + + Q_PROPERTY(MemberInformationWrapper* primaryKey READ primaryKey) + public: + explicit TableWrapper(const QString& name, const QVector& member, + MemberInformationWrapper* serialMember, MemberInformationWrapper* baseId, + MemberInformationWrapper* primaryKey, QObject* parent) + : NameWrapper(name, parent), m_member(member), m_serialMember(serialMember), m_baseId(baseId), + m_primaryKey(primaryKey) + { + } + + QVector member() const + { + return m_member; + } + + MemberInformationWrapper* serialMember() const + { + return m_serialMember; + } + + MemberInformationWrapper* baseId() const + { + return m_baseId; + } + + MemberInformationWrapper* primaryKey() const + { + return m_primaryKey; + } + + private: + QVector m_member; + MemberInformationWrapper* m_serialMember; + MemberInformationWrapper* m_baseId; + MemberInformationWrapper* m_primaryKey; }; class DbStructWrapper final : public MemberInformationListWrapper { - Q_OBJECT - Q_PROPERTY(QVariantList insertStructures READ insertStructures) - Q_PROPERTY(QString viewTableName READ viewTableName) - Q_PROPERTY(bool deleteWithoutPkAllowed READ deleteWithoutPkAllowed) - Q_PROPERTY(MemberInformationWrapper *primaryKey READ primaryKey) - Q_PROPERTY(QVariantList dbNotifications READ dbNotifications) + Q_OBJECT + Q_PROPERTY(QVariantList insertStructures READ insertStructures) + Q_PROPERTY(QString viewTableName READ viewTableName) + Q_PROPERTY(bool deleteWithoutPkAllowed READ deleteWithoutPkAllowed) + Q_PROPERTY(MemberInformationWrapper* primaryKey READ primaryKey) + Q_PROPERTY(QVariantList dbNotifications READ dbNotifications) -public: - explicit DbStructWrapper(const CompleteStructInformation &csi, QObject *parent) - : MemberInformationListWrapper(csi.structName, csi.member, parent) - , m_csi(csi) - { - m_dbNotifications.reserve(m_csi.dbNotifications.size()); - for (const auto ¬ification : std::as_const(m_csi.dbNotifications)) - m_dbNotifications += QVariant(notification.methodName); - } - - MemberInformationWrapper *primaryKey() const - { - for (const QVariant &v : m_member) + public: + explicit DbStructWrapper(const CompleteStructInformation& csi, QObject* parent) + : MemberInformationListWrapper(csi.structName, csi.member, parent), m_csi(csi) { - MemberInformationWrapper *mi = v.value(); - if (mi->info().db.isPrimaryKey && mi->info().db.table == primaryTableName()) - return mi; + m_dbNotifications.reserve(m_csi.dbNotifications.size()); + for (const auto& notification : std::as_const(m_csi.dbNotifications)) + m_dbNotifications += QVariant(notification.methodName); } - return nullptr; - } - QVariantList insertStructures(); - bool deleteWithoutPkAllowed() const { return m_csi.tables.size() == 1; } - QVariantList dbNotifications() const { return m_dbNotifications; } - QString primaryTableName() const { return m_csi.primaryTable->name; } - QString viewTableName() const { return (m_csi.tables.size() == 1) ? primaryTableName() : m_csi.viewName; } -private: - const CompleteStructInformation m_csi; - QVariantList m_dbNotifications; + MemberInformationWrapper* primaryKey() const + { + for (const QVariant& v : m_member) + { + MemberInformationWrapper* mi = v.value(); + if (mi->info().db.isPrimaryKey && mi->info().db.table == primaryTableName()) + return mi; + } + return nullptr; + } + + QVariantList insertStructures(); + + bool deleteWithoutPkAllowed() const + { + return m_csi.tables.size() == 1; + } + + QVariantList dbNotifications() const + { + return m_dbNotifications; + } + + QString primaryTableName() const + { + return m_csi.primaryTable->name; + } + + QString viewTableName() const + { + return (m_csi.tables.size() == 1) ? primaryTableName() : m_csi.viewName; + } + + private: + const CompleteStructInformation m_csi; + QVariantList m_dbNotifications; }; class CustomFunctionWrapper final : public QObject { - Q_OBJECT - Q_PROPERTY(QString signature READ signature) -public: - explicit CustomFunctionWrapper(const QString &signature, QObject *parent) - : QObject(parent) - , m_signature(signature) - {} - QString signature() const { return m_signature; } -private: - const QString m_signature; -}; + Q_OBJECT + Q_PROPERTY(QString signature READ signature) + public: + explicit CustomFunctionWrapper(const QString& signature, QObject* parent) : QObject(parent), m_signature(signature) + { + } + QString signature() const + { + return m_signature; + } + + private: + const QString m_signature; +}; class IdlEnumKeyValueWrapper final : public QObject { - Q_OBJECT - Q_PROPERTY(QString key READ key) - Q_PROPERTY(int value READ value) -public: - explicit IdlEnumKeyValueWrapper(const EnumKeyValuePair &ekvp, QObject *parent) - : QObject(parent) - , m_ekvp(ekvp) - {} + Q_OBJECT + Q_PROPERTY(QString key READ key) + Q_PROPERTY(int value READ value) + public: + explicit IdlEnumKeyValueWrapper(const EnumKeyValuePair& ekvp, QObject* parent) : QObject(parent), m_ekvp(ekvp) {} - QString key() const { return m_ekvp.key; } - int value() const { return m_ekvp.value; } + QString key() const + { + return m_ekvp.key; + } -private: - const EnumKeyValuePair m_ekvp; + int value() const + { + return m_ekvp.value; + } + + private: + const EnumKeyValuePair m_ekvp; }; class IdlDataWrapper final : public NameWrapper { - Q_OBJECT - Q_PROPERTY(QString type READ type) - Q_PROPERTY(QString comment READ comment) - Q_PROPERTY(QString isKey READ isKey) - Q_PROPERTY(QString isOptional READ isOptional) - Q_PROPERTY(QString cppType READ cppType) - Q_PROPERTY(QString cppTypeCr READ cppTypeCr) - Q_PROPERTY(QString nameGetter READ nameGetter) -public: - IdlDataWrapper(const IdlData &data, - QObject *parent) - : NameWrapper(data.name, parent) - , m_data(data) - {} + Q_OBJECT + Q_PROPERTY(QString type READ type) + Q_PROPERTY(QString comment READ comment) + Q_PROPERTY(QString isKey READ isKey) + Q_PROPERTY(QString isOptional READ isOptional) + Q_PROPERTY(QString cppType READ cppType) + Q_PROPERTY(QString cppTypeCr READ cppTypeCr) + Q_PROPERTY(QString nameGetter READ nameGetter) + public: + IdlDataWrapper(const IdlData& data, QObject* parent) : NameWrapper(data.name, parent), m_data(data) {} - QString type() const { return m_data.dataTypeInfo->idlType(); } - QString comment() const { return m_data.comment; } - QString isKey() const { return m_data.isKey ? QStringLiteral(" \t //@key") : QString(); } - QString isOptional() const { return m_data.isOptional ? QStringLiteral(" \t //@Optional") : QString(); } - QString cppType() const { return m_data.dataTypeInfo->cppType(); } - QString cppTypeCr() const { return m_data.dataTypeInfo->cppTypeConstRef(); } - QString nameGetter() const { return m_data.name + (m_data.isOptional ? QStringLiteral("().get") : QString()); } -private: - const IdlData m_data; + QString type() const + { + return m_data.dataTypeInfo->idlType(); + } + + QString comment() const + { + return m_data.comment; + } + + QString isKey() const + { + return m_data.isKey ? QStringLiteral(" \t //@key") : QString(); + } + + QString isOptional() const + { + return m_data.isOptional ? QStringLiteral(" \t //@Optional") : QString(); + } + + QString cppType() const + { + return m_data.dataTypeInfo->cppType(); + } + + QString cppTypeCr() const + { + return m_data.dataTypeInfo->cppTypeConstRef(); + } + + QString nameGetter() const + { + return m_data.name + (m_data.isOptional ? QStringLiteral("().get") : QString()); + } + + private: + const IdlData m_data; }; class IdlEnumWrapper final : public VariantListWrapper { - Q_OBJECT -public: - explicit IdlEnumWrapper(const EnumInformation &ei, QObject *parent) - : VariantListWrapper(ei.enumName, parent) - { - m_member.reserve(ei.values.size()); - for (const auto &val : ei.values) - m_member += QVariant::fromValue(new IdlEnumKeyValueWrapper(val, this)); - } + Q_OBJECT + public: + explicit IdlEnumWrapper(const EnumInformation& ei, QObject* parent) : VariantListWrapper(ei.enumName, parent) + { + m_member.reserve(ei.values.size()); + for (const auto& val : ei.values) + m_member += QVariant::fromValue(new IdlEnumKeyValueWrapper(val, this)); + } }; class IdlStructWrapper final : public VariantListWrapper { - Q_OBJECT - Q_PROPERTY(QString comment READ comment) - Q_PROPERTY(QString baseValueType READ baseValueType) - Q_PROPERTY(QString extensibility READ extensibility) -public: - explicit IdlStructWrapper(const CompleteTopicTypeInformation &ctti, QObject *parent) - : VariantListWrapper(ctti.name, parent) - , m_ctti(ctti) - { - m_member.reserve(m_ctti.members.size()); - for (const auto &val : std::as_const(m_ctti.members)) - m_member += QVariant::fromValue(new IdlDataWrapper(val, this)); - } + Q_OBJECT + Q_PROPERTY(QString comment READ comment) + Q_PROPERTY(QString baseValueType READ baseValueType) + Q_PROPERTY(QString extensibility READ extensibility) + public: + explicit IdlStructWrapper(const CompleteTopicTypeInformation& ctti, QObject* parent) + : VariantListWrapper(ctti.name, parent), m_ctti(ctti) + { + m_member.reserve(m_ctti.members.size()); + for (const auto& val : std::as_const(m_ctti.members)) + m_member += QVariant::fromValue(new IdlDataWrapper(val, this)); + } - QString comment() const { return m_ctti.comment; } - QString baseValueType() const { return m_ctti.baseValueType; } - QString extensibility() const { return extensibility2String(m_ctti.extensibility); } + QString comment() const + { + return m_ctti.comment; + } -private: - const CompleteTopicTypeInformation m_ctti; + QString baseValueType() const + { + return m_ctti.baseValueType; + } + + QString extensibility() const + { + return extensibility2String(m_ctti.extensibility); + } + + private: + const CompleteTopicTypeInformation m_ctti; #ifdef RTI_HEADER_AVAILABLE - static QString extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity); + static QString extensibility2String(dds::core::xtypes::ExtensibilityKind extensiblity); #else - static QString extensibility2String(int extensiblity); + static QString extensibility2String(int extensiblity); #endif }; class IdlServiceWrapper final : public QObject { - Q_OBJECT - Q_PROPERTY(QString svcName READ svcName) - Q_PROPERTY(QString baseFilePath READ baseFilePath) -public: - IdlServiceWrapper(const QString &svcName, const QString &baseFilePath) - : m_svcName(svcName) - , m_baseFilePath(baseFilePath) - {} - QString svcName() const { return m_svcName; } - QString baseFilePath() const { return m_baseFilePath; } -private: - const QString m_svcName; - const QString m_baseFilePath; + Q_OBJECT + Q_PROPERTY(QString svcName READ svcName) + Q_PROPERTY(QString baseFilePath READ baseFilePath) + public: + IdlServiceWrapper(const QString& svcName, const QString& baseFilePath) + : m_svcName(svcName), m_baseFilePath(baseFilePath) + { + } + + QString svcName() const + { + return m_svcName; + } + + QString baseFilePath() const + { + return m_baseFilePath; + } + + private: + const QString m_svcName; + const QString m_baseFilePath; }; class FunctionTopicWrapper final : public NameWrapper { - Q_OBJECT - Q_PROPERTY(QString onReply READ onReply) - Q_PROPERTY(QString onRequest READ onRequest) - Q_PROPERTY(QString onError READ onError) - Q_PROPERTY(bool isCoreFt READ isCoreFt) - Q_PROPERTY(bool routeInReplay READ routeInReplay) + Q_OBJECT + Q_PROPERTY(QString onReply READ onReply) + Q_PROPERTY(QString onRequest READ onRequest) + Q_PROPERTY(QString onError READ onError) + Q_PROPERTY(bool isCoreFt READ isCoreFt) + Q_PROPERTY(bool routeInReplay READ routeInReplay) - Q_PROPERTY(QString reply READ reply) - Q_PROPERTY(QString replyFlc READ replyFlc) - Q_PROPERTY(QString replyHandler READ replyHandler) - Q_PROPERTY(QString replyHandlerFlc READ replyHandlerFlc) - Q_PROPERTY(QString replyType READ replyType) - Q_PROPERTY(QString replyTypeFro READ replyTypeFro) - Q_PROPERTY(QVariantList replyParams READ replyParams) - Q_PROPERTY(QString replyHandlerHash READ replyHandlerHash WRITE setReplyHandlerHash) + Q_PROPERTY(QString reply READ reply) + Q_PROPERTY(QString replyFlc READ replyFlc) + Q_PROPERTY(QString replyHandler READ replyHandler) + Q_PROPERTY(QString replyHandlerFlc READ replyHandlerFlc) + Q_PROPERTY(QString replyType READ replyType) + Q_PROPERTY(QString replyTypeFro READ replyTypeFro) + Q_PROPERTY(QVariantList replyParams READ replyParams) + Q_PROPERTY(QString replyHandlerHash READ replyHandlerHash WRITE setReplyHandlerHash) - Q_PROPERTY(QString request READ request) - Q_PROPERTY(QString requestFlc READ requestFlc) - Q_PROPERTY(QString requestHandler READ requestHandler) - Q_PROPERTY(QString requestHandlerFlc READ requestHandlerFlc) - Q_PROPERTY(QString requestType READ requestType) - Q_PROPERTY(QVariantList requestParams READ requestParams) + Q_PROPERTY(QString request READ request) + Q_PROPERTY(QString requestFlc READ requestFlc) + Q_PROPERTY(QString requestHandler READ requestHandler) + Q_PROPERTY(QString requestHandlerFlc READ requestHandlerFlc) + Q_PROPERTY(QString requestType READ requestType) + Q_PROPERTY(QVariantList requestParams READ requestParams) -public: - FunctionTopicWrapper(const FunctionTopic &ft, - const CompleteTopicTypeInformation &siRequest, - const CompleteTopicTypeInformation &siReply, - QObject *parent) - : NameWrapper(ft.name, parent) - , m_ft(ft) - , m_request(siRequest) - , m_reply(siReply) - {} - QString onReply() const { return QLatin1String("on") + m_ft.replyTopicName; } - QString onRequest() const { return QLatin1String("on") + m_ft.requestTopicName; } - QString onError() const { return QLatin1String("on") + m_ft.name + QLatin1String("Error"); } - bool isCoreFt() const { return (m_ft.replyTopicType == QStringLiteral("Core::FunctionReply") || m_ft.replyTopicType == QStringLiteral("FunctionReply")); } - bool routeInReplay() const { return m_ft.routeInReplay; } + public: + FunctionTopicWrapper(const FunctionTopic& ft, const CompleteTopicTypeInformation& siRequest, + const CompleteTopicTypeInformation& siReply, QObject* parent) + : NameWrapper(ft.name, parent), m_ft(ft), m_request(siRequest), m_reply(siReply) + { + } - QString reply() const { return m_ft.replyTopicName; } - QString replyFlc() const { return StructBuilder::firstCharLowercase(reply()); } - QString replyHandler() const { return m_ft.replyTopicName + QLatin1String("Handler"); } - QString replyHandlerFlc() const { return StructBuilder::firstCharLowercase(replyHandler()); } - QString replyType() const { return m_reply.name; } - QString replyTypeFro() const { return isCoreFt() ? QStringLiteral("Core::FunctionReplyObject") : m_reply.name; } + QString onReply() const + { + return QLatin1String("on") + m_ft.replyTopicName; + } - QString request() const { return m_ft.requestTopicName; } - QString requestFlc() const { return StructBuilder::firstCharLowercase(request()); } - QString requestHandler() const { return m_ft.requestTopicName + QLatin1String("Handler"); } - QString requestHandlerFlc() const { return StructBuilder::firstCharLowercase(requestHandler()); } - QString requestType() const { return m_request.name; } + QString onRequest() const + { + return QLatin1String("on") + m_ft.requestTopicName; + } - void addRequestParams(const QVector ¶ms) - { - for (const auto ¶m : params) - m_requestParams.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); - } - QVariantList requestParams() const - { - return m_requestParams; - } - void addReplyParams(const QVector ¶ms) - { - for (const auto ¶m : params) - m_replyParams.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); - } - QVariantList replyParams() const - { - return m_replyParams; - } + QString onError() const + { + return QLatin1String("on") + m_ft.name + QLatin1String("Error"); + } - QString replyHandlerHash() const - { - return m_replyHandlerHash; - } - void setReplyHandlerHash(const QString &hash) - { - m_replyHandlerHash = hash; - } + bool isCoreFt() const + { + return (m_ft.replyTopicType == QStringLiteral("Core::FunctionReply") || + m_ft.replyTopicType == QStringLiteral("FunctionReply")); + } -private: - const FunctionTopic m_ft; - const CompleteTopicTypeInformation m_request; - const CompleteTopicTypeInformation m_reply; - QVariantList m_requestParams; - QVariantList m_replyParams; - QString m_replyHandlerHash; + bool routeInReplay() const + { + return m_ft.routeInReplay; + } + + QString reply() const + { + return m_ft.replyTopicName; + } + + QString replyFlc() const + { + return StructBuilder::firstCharLowercase(reply()); + } + + QString replyHandler() const + { + return m_ft.replyTopicName + QLatin1String("Handler"); + } + + QString replyHandlerFlc() const + { + return StructBuilder::firstCharLowercase(replyHandler()); + } + + QString replyType() const + { + return m_reply.name; + } + + QString replyTypeFro() const + { + return isCoreFt() ? QStringLiteral("Core::FunctionReplyObject") : m_reply.name; + } + + QString request() const + { + return m_ft.requestTopicName; + } + + QString requestFlc() const + { + return StructBuilder::firstCharLowercase(request()); + } + + QString requestHandler() const + { + return m_ft.requestTopicName + QLatin1String("Handler"); + } + + QString requestHandlerFlc() const + { + return StructBuilder::firstCharLowercase(requestHandler()); + } + + QString requestType() const + { + return m_request.name; + } + + void addRequestParams(const QVector& params) + { + for (const auto& param : params) + m_requestParams.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); + } + + QVariantList requestParams() const + { + return m_requestParams; + } + + void addReplyParams(const QVector& params) + { + for (const auto& param : params) + m_replyParams.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); + } + + QVariantList replyParams() const + { + return m_replyParams; + } + + QString replyHandlerHash() const + { + return m_replyHandlerHash; + } + + void setReplyHandlerHash(const QString& hash) + { + m_replyHandlerHash = hash; + } + + private: + const FunctionTopic m_ft; + const CompleteTopicTypeInformation m_request; + const CompleteTopicTypeInformation m_reply; + QVariantList m_requestParams; + QVariantList m_replyParams; + QString m_replyHandlerHash; }; class FunctionTopicsWrapper final : public VariantListWrapper { - Q_OBJECT -public: - Q_PROPERTY(QVariantList topicsToRouteInReplay READ topicsToRouteInReplay) + Q_OBJECT + public: + Q_PROPERTY(QVariantList topicsToRouteInReplay READ topicsToRouteInReplay) - using VariantListWrapper::VariantListWrapper; + using VariantListWrapper::VariantListWrapper; - FunctionTopicWrapper *addFunctionTopic(const FunctionTopic &ft, - const CompleteTopicTypeInformation &siRequest, - const CompleteTopicTypeInformation &siReply) - { - FunctionTopicWrapper *ret = new FunctionTopicWrapper(ft, siRequest, siReply, this); - m_member += QVariant::fromValue(ret); - return ret; - } - - - QVariantList topicsToRouteInReplay() const - { - QVariantList vl; - vl.reserve(m_member.size()); - for (const QVariant &v : m_member) + FunctionTopicWrapper* addFunctionTopic(const FunctionTopic& ft, const CompleteTopicTypeInformation& siRequest, + const CompleteTopicTypeInformation& siReply) { - FunctionTopicWrapper *ft = v.value(); - if (ft->routeInReplay()) - vl += v; + FunctionTopicWrapper* ret = new FunctionTopicWrapper(ft, siRequest, siReply, this); + m_member += QVariant::fromValue(ret); + return ret; + } + + QVariantList topicsToRouteInReplay() const + { + QVariantList vl; + vl.reserve(m_member.size()); + for (const QVariant& v : m_member) + { + FunctionTopicWrapper* ft = v.value(); + if (ft->routeInReplay()) + vl += v; + } + return vl; } - return vl; - } }; class DataTopicWrapper final : public NameWrapper { - Q_OBJECT - Q_PROPERTY(QString serviceName READ serviceName) - Q_PROPERTY(QString type READ type) - Q_PROPERTY(QString typeFq READ typeFq) - Q_PROPERTY(QVariant key READ key) - Q_PROPERTY(bool dtcImpl READ dtcImpl) - Q_PROPERTY(bool dtsImpl READ dtsImpl) - Q_PROPERTY(bool recordTopic READ recordTopic) - Q_PROPERTY(QVariant recTable READ recTable) - Q_PROPERTY(QVariantList trColumns READ trColumns) - Q_PROPERTY(bool hasTrColumns READ hasTrColumns) - Q_PROPERTY(bool routeToClient READ routeToClient) - Q_PROPERTY(bool routeToServer READ routeToServer) - Q_PROPERTY(bool routeInReplay READ routeInReplay) - Q_PROPERTY(bool autosubscribe READ isAutoSubscribe) + Q_OBJECT + Q_PROPERTY(QString serviceName READ serviceName) + Q_PROPERTY(QString type READ type) + Q_PROPERTY(QString typeFq READ typeFq) + Q_PROPERTY(QVariant key READ key) + Q_PROPERTY(bool dtcImpl READ dtcImpl) + Q_PROPERTY(bool dtsImpl READ dtsImpl) + Q_PROPERTY(bool recordTopic READ recordTopic) + Q_PROPERTY(QVariant recTable READ recTable) + Q_PROPERTY(QVariantList trColumns READ trColumns) + Q_PROPERTY(bool hasTrColumns READ hasTrColumns) + Q_PROPERTY(bool routeToClient READ routeToClient) + Q_PROPERTY(bool routeToServer READ routeToServer) + Q_PROPERTY(bool routeInReplay READ routeInReplay) + Q_PROPERTY(bool autosubscribe READ isAutoSubscribe) -public: - DataTopicWrapper(const CompleteTopicTypeInformation &ctti, QObject *parent) - : NameWrapper(ctti.name, parent) - , m_ctti(ctti) - , m_keyData(nullptr) - , m_recordData(nullptr) - {} + public: + DataTopicWrapper(const CompleteTopicTypeInformation& ctti, QObject* parent) + : NameWrapper(ctti.name, parent), m_ctti(ctti), m_keyData(nullptr), m_recordData(nullptr) + { + } - void setKeyColumnData(const IdlData &data) - { - delete m_keyData; - m_keyData = new IdlDataWrapper(data, this); - } + void setKeyColumnData(const IdlData& data) + { + delete m_keyData; + m_keyData = new IdlDataWrapper(data, this); + } - void setTrColumns(const QVector ¶ms) - { - for (const auto ¶m : params) - m_trColumns.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); - } + void setTrColumns(const QVector& params) + { + for (const auto& param : params) + m_trColumns.push_back(QVariant::fromValue(new IdlDataWrapper(param, this))); + } - QVariantList trColumns() const - { - return m_trColumns; - } + QVariantList trColumns() const + { + return m_trColumns; + } - bool hasTrColumns() const - { - return !m_trColumns.empty(); - } + bool hasTrColumns() const + { + return !m_trColumns.empty(); + } - void setRecordTableInformation(const CompleteTableInformation &cti) - { - delete m_recordData; - m_recordData = new MemberInformationListWrapper(cti.name, cti.columns, this); - m_ctti.recordTopic = true; - } + void setRecordTableInformation(const CompleteTableInformation& cti) + { + delete m_recordData; + m_recordData = new MemberInformationListWrapper(cti.name, cti.columns, this); + m_ctti.recordTopic = true; + } - QString serviceName() const { return m_ctti.serviceName; } - QString type() const { return m_ctti.name; } - QString typeFq() const; - QVariant key() const { return m_keyData ? QVariant::fromValue(m_keyData) : QVariant(); } - bool dtsImpl() const { return m_ctti.dtsAutogen; } - bool dtcImpl() const { return m_ctti.dtcAutogen; } - bool recordTopic() const { return m_ctti.recordTopic && m_recordData; } - bool routeToClient() const { return m_ctti.routeToClient; } - bool routeToServer() const { return m_ctti.routeToServer; } - bool routeInReplay() const { return m_ctti.routeInReplay; } - bool isAutoSubscribe() const { return m_ctti.autosubscribe; } - QVariant recTable() const { return recordTopic() ? QVariant::fromValue(m_recordData) : QVariant(); } -private: - CompleteTopicTypeInformation m_ctti; - IdlDataWrapper *m_keyData; - MemberInformationListWrapper *m_recordData; - QVariantList m_trColumns; + QString serviceName() const + { + return m_ctti.serviceName; + } + + QString type() const + { + return m_ctti.name; + } + + QString typeFq() const; + + QVariant key() const + { + return m_keyData ? QVariant::fromValue(m_keyData) : QVariant(); + } + + bool dtsImpl() const + { + return m_ctti.dtsAutogen; + } + + bool dtcImpl() const + { + return m_ctti.dtcAutogen; + } + + bool recordTopic() const + { + return m_ctti.recordTopic && m_recordData; + } + + bool routeToClient() const + { + return m_ctti.routeToClient; + } + + bool routeToServer() const + { + return m_ctti.routeToServer; + } + + bool routeInReplay() const + { + return m_ctti.routeInReplay; + } + + bool isAutoSubscribe() const + { + return m_ctti.autosubscribe; + } + + QVariant recTable() const + { + return recordTopic() ? QVariant::fromValue(m_recordData) : QVariant(); + } + + private: + CompleteTopicTypeInformation m_ctti; + IdlDataWrapper* m_keyData; + MemberInformationListWrapper* m_recordData; + QVariantList m_trColumns; }; class DataTopicsWrapper final : public VariantListWrapper { - Q_OBJECT -public: - Q_PROPERTY(QVariantList topicsToRouteInReplay READ topicsToRouteInReplay) - Q_PROPERTY(QVariantList topicsToRouteToClient READ topicsToRouteToClient) - Q_PROPERTY(QVariantList topicsToRouteToServer READ topicsToRouteToServer) + Q_OBJECT + public: + Q_PROPERTY(QVariantList topicsToRouteInReplay READ topicsToRouteInReplay) + Q_PROPERTY(QVariantList topicsToRouteToClient READ topicsToRouteToClient) + Q_PROPERTY(QVariantList topicsToRouteToServer READ topicsToRouteToServer) - using VariantListWrapper::VariantListWrapper; + using VariantListWrapper::VariantListWrapper; - DataTopicWrapper *addDataTopic(const CompleteTopicTypeInformation &ctti) - { - DataTopicWrapper *ret = new DataTopicWrapper(ctti, this); - m_member += QVariant::fromValue(ret); - return ret; - } - - - QVariantList memberByFilter(const std::function &acceptFilter) const - { - QVariantList vl; - vl.reserve(m_member.size()); - for (const QVariant &v : m_member) + DataTopicWrapper* addDataTopic(const CompleteTopicTypeInformation& ctti) { - DataTopicWrapper *dtw = v.value(); - if (dtw && acceptFilter(dtw)) - vl += v; + DataTopicWrapper* ret = new DataTopicWrapper(ctti, this); + m_member += QVariant::fromValue(ret); + return ret; } - return vl; - } - QVariantList topicsToRouteInReplay() const - { - return memberByFilter([](const DataTopicWrapper *dtw) { return dtw->routeInReplay(); }); - } - QVariantList topicsToRouteToClient() const - { - return memberByFilter([](const DataTopicWrapper *dtw) { return dtw->routeToClient(); }); - } - QVariantList topicsToRouteToServer() const - { - return memberByFilter([](const DataTopicWrapper *dtw) { return dtw->routeToServer(); }); - } + QVariantList memberByFilter(const std::function& acceptFilter) const + { + QVariantList vl; + vl.reserve(m_member.size()); + for (const QVariant& v : m_member) + { + DataTopicWrapper* dtw = v.value(); + if (dtw && acceptFilter(dtw)) + vl += v; + } + return vl; + } + + QVariantList topicsToRouteInReplay() const + { + return memberByFilter([](const DataTopicWrapper* dtw) { return dtw->routeInReplay(); }); + } + + QVariantList topicsToRouteToClient() const + { + return memberByFilter([](const DataTopicWrapper* dtw) { return dtw->routeToClient(); }); + } + + QVariantList topicsToRouteToServer() const + { + return memberByFilter([](const DataTopicWrapper* dtw) { return dtw->routeToServer(); }); + } }; class IdlServicesWrapper final : public VariantListWrapper { - Q_OBJECT -public: - using VariantListWrapper::VariantListWrapper; + Q_OBJECT + public: + using VariantListWrapper::VariantListWrapper; - void addService(const QString &svcName, const QString &baseFilePath) - { - m_member += QVariant::fromValue(new IdlServiceWrapper(svcName, baseFilePath)); - } + void addService(const QString& svcName, const QString& baseFilePath) + { + m_member += QVariant::fromValue(new IdlServiceWrapper(svcName, baseFilePath)); + } }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.cpp old mode 100755 new mode 100644 index 08aa8d696..e065572e3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.cpp @@ -1,940 +1,890 @@ - #include "SqlGenerator.h" + #include "StructBuilder.h" #include "XmlReader.h" +#include +#include #include #include -#include - -#include using namespace CodeGen; - static QString getExerciseSchemaName(int exerciseId) { - return QStringLiteral("ex_") + QString::number(exerciseId); + return QStringLiteral("ex_") + QString::number(exerciseId); } -SqlGenerator::SqlGenerator(XmlReader *xmlReader, StructBuilder *structBuilder) : m_xmlReader(xmlReader) - , m_structBuilder(structBuilder) - , m_createdByXmlFile(false) - , m_isValid(true) - , m_exerciseId(0), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} - -SqlGenerator::SqlGenerator(const QString &xmlFile) - : m_xmlReader(new XmlReader) - , m_structBuilder(new StructBuilder(m_xmlReader)) - , m_createdByXmlFile(true) - , m_isValid(false) - , m_exerciseId(0) +SqlGenerator::SqlGenerator(XmlReader* xmlReader, StructBuilder* structBuilder) + : m_xmlReader(xmlReader), m_structBuilder(structBuilder), m_createdByXmlFile(false), m_isValid(true), + m_exerciseId(0), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_isValid = m_xmlReader->readServiceFile(xmlFile, QString()) && m_structBuilder->buildStructures(); +} + +SqlGenerator::SqlGenerator(const QString& xmlFile) + : m_xmlReader(new XmlReader), m_structBuilder(new StructBuilder(m_xmlReader)), m_createdByXmlFile(true), + m_isValid(false), m_exerciseId(0) +{ + m_isValid = m_xmlReader->readServiceFile(xmlFile, QString()) && m_structBuilder->buildStructures(); } SqlGenerator::~SqlGenerator() { - if (m_createdByXmlFile) - { - delete m_xmlReader; - delete m_structBuilder; - } + if (m_createdByXmlFile) + { + delete m_xmlReader; + delete m_structBuilder; + } } - bool SqlGenerator::generateData(int exerciseId) { - DEBUG_LOG(m_logger) << "Generating SQL data for service " << getServiceAbbr() << " in exercise " << exerciseId << ", this: " << this; + DEBUG_LOG(m_logger) << "Generating SQL data for service " << getServiceAbbr() << " in exercise " << exerciseId + << ", this: " << this; - m_exerciseId = exerciseId; - m_sqlGlobal = SqlStatements(); - m_sqlExercise = SqlStatements(); - m_sqlItemsGlobal = SqlItems(); - m_sqlItemsExercise = SqlItems(); - m_referencedSevices.clear(); + m_exerciseId = exerciseId; + m_sqlGlobal = SqlStatements(); + m_sqlExercise = SqlStatements(); + m_sqlItemsGlobal = SqlItems(); + m_sqlItemsExercise = SqlItems(); + m_referencedSevices.clear(); - if (!handleTables()) - return false; + if (!handleTables()) + return false; - if (!handleViews()) - return false; + if (!handleViews()) + return false; - if (!handleEnumerations()) - return false; + if (!handleEnumerations()) + return false; - return true; + return true; } -bool SqlGenerator::createStatementsForTable(const QString &tableName, const QString &tableNameOut) +bool SqlGenerator::createStatementsForTable(const QString& tableName, const QString& tableNameOut) { - const QMap tables = m_structBuilder->getDbTables(); - for (const CompleteTableInformation &cti : tables) - { - if (cti.name != tableName) - continue; - CompleteTableInformation ctiOut = cti; - ctiOut.name = tableNameOut; - return handleTable(ctiOut); - } - return false; + const QMap tables = m_structBuilder->getDbTables(); + for (const CompleteTableInformation& cti : tables) + { + if (cti.name != tableName) + continue; + CompleteTableInformation ctiOut = cti; + ctiOut.name = tableNameOut; + return handleTable(ctiOut); + } + return false; } bool SqlGenerator::handleTables() { - const QMap tables = m_structBuilder->getDbTables(); - for (const CompleteTableInformation &cti : tables) - { - if (!handleTable(cti)) - return false; - } + const QMap tables = m_structBuilder->getDbTables(); + for (const CompleteTableInformation& cti : tables) + { + if (!handleTable(cti)) + return false; + } - const QMap recTables = m_structBuilder->getRecordingTopicTables(); - MemberInformation miColumnIsValid; - miColumnIsValid.db.columnName = QStringLiteral("dds_is_alive"); - miColumnIsValid.db.datatype = QStringLiteral("boolean"); - miColumnIsValid.db.defaultValue = QStringLiteral("true"); - MemberInformation miInsertionTime; - miInsertionTime.cpp.type = QStringLiteral("timestamp"); - miInsertionTime.db.columnName = QStringLiteral("insert_time"); - miInsertionTime.db.defaultValue = QStringLiteral("now()"); - miInsertionTime.db.usedForInsert = false; - m_structBuilder->fixupQVariantConversions(miInsertionTime); - ConstraintInformation ci; - ci.name = QStringLiteral("IDX_sample_time"); - ci.affectedColumns = QStringList({QStringLiteral("sample_time")}); - ci.type = ConstraintInformation::Type::index; - for (const CompleteTableInformation &cti : recTables) - { - CompleteTableInformation ctiTmp(cti); - ctiTmp.columns.push_back(miColumnIsValid); - ctiTmp.columns.push_back(miInsertionTime); - ctiTmp.constraints.push_back(ci); - if (!handleTable(ctiTmp)) - return false; - } - return true; + const QMap recTables = m_structBuilder->getRecordingTopicTables(); + MemberInformation miColumnIsValid; + miColumnIsValid.db.columnName = QStringLiteral("dds_is_alive"); + miColumnIsValid.db.datatype = QStringLiteral("boolean"); + miColumnIsValid.db.defaultValue = QStringLiteral("true"); + MemberInformation miInsertionTime; + miInsertionTime.cpp.type = QStringLiteral("timestamp"); + miInsertionTime.db.columnName = QStringLiteral("insert_time"); + miInsertionTime.db.defaultValue = QStringLiteral("now()"); + miInsertionTime.db.usedForInsert = false; + m_structBuilder->fixupQVariantConversions(miInsertionTime); + ConstraintInformation ci; + ci.name = QStringLiteral("IDX_sample_time"); + ci.affectedColumns = QStringList({QStringLiteral("sample_time")}); + ci.type = ConstraintInformation::Type::index; + for (const CompleteTableInformation& cti : recTables) + { + CompleteTableInformation ctiTmp(cti); + ctiTmp.columns.push_back(miColumnIsValid); + ctiTmp.columns.push_back(miInsertionTime); + ctiTmp.constraints.push_back(ci); + if (!handleTable(ctiTmp)) + return false; + } + return true; } bool SqlGenerator::handleViews() { - const QMap views = m_structBuilder->getDbViews(); - for (const ViewInformation &vi : views) - { - if (!handleView(vi)) - return false; - } - - return true; -} - -bool SqlGenerator::handleView(const ViewInformation &vi) -{ - DEBUG_LOG(m_logger) << "Handle view " << vi.name; - - const QString parent = vi.baseTable; - - DEBUG_LOG(m_logger) << "Parent = " << parent; - - if (!parent.isEmpty()) - { - const CompleteStructInformation csi = m_structBuilder->structInformationByTableName(parent); - const QString createViewStmt(QStringLiteral("CREATE OR REPLACE VIEW %1 AS SELECT %2\nFROM %3\nWHERE %4;\n")); - const QString dropViewStmt(QStringLiteral("DROP VIEW IF EXISTS %1;")); - - DEBUG_LOG(m_logger) << "csi.primaryTable = " << csi.primaryTable.data()->name; - - if (!csi.primaryTable.isNull()) + const QMap views = m_structBuilder->getDbViews(); + for (const ViewInformation& vi : views) { - QStringList fromTables; - fromTables += vi.baseSchema+QLatin1Char('.')+vi.baseTable; - - QStringList whereConditions; - if (vi.filter.contains(QLatin1String("exercise_id"))) - whereConditions += QLatin1String("exercise_id=")+QString::number(m_exerciseId); - - QStringList fqColumnNames; - - - for (const MemberInformation &mi : csi.member) - { - if (mi.db.usedForView) - fqColumnNames += mi.db.table + QLatin1Char('.') + mi.db.columnName + QLatin1String(" AS ") + mi.db.getColumnNameView(); - } - - DEBUG_LOG(m_logger) << "fqColumnNames = " << fqColumnNames.join(QStringLiteral(", ")); - - - if (!whereConditions.isEmpty()) - addToCreateViews(createViewStmt.arg(csi.viewName, - fqColumnNames.join(QStringLiteral(", ")), - fromTables.join(QStringLiteral(", ")), - whereConditions.join(QStringLiteral(" AND\n"))), - vi.exerciseDependency); - addToDropViews(dropViewStmt.arg(csi.viewName), vi.exerciseDependency); + if (!handleView(vi)) + return false; } - } - return true; - -} - -bool SqlGenerator::handleTable(const CompleteTableInformation &cti) -{ - DEBUG_LOG(m_logger) << "Handle table " << cti.name; - - if (cti.columns.isEmpty()) - { - WARNING_LOG(m_logger) << "Table " << cti.name - << " has no DatabaseServiceStruct - not generating anything for this!"; return true; - } +} - const QString dropTableStmt(QStringLiteral("DROP TABLE IF EXISTS %1 CASCADE;")); - const QString createTableStmt(QStringLiteral("CREATE TABLE IF NOT EXISTS %1 (%2\n);")); - const QString commentTableStmt(QStringLiteral("COMMENT ON TABLE %1 IS '%2';")); +bool SqlGenerator::handleView(const ViewInformation& vi) +{ + DEBUG_LOG(m_logger) << "Handle view " << vi.name; - QStringList tableComments; - addToDropTables(dropTableStmt.arg(cti.name), cti.exerciseDependency); + const QString parent = vi.baseTable; - if ((cti.exerciseDependency & Global) == Global) - { - addToCreateTables(createTableStmt.arg(cti.name, - getTableColumnCreateStatements(cti.name, - cti.columns, - &tableComments, - Global)), - Global); - } - if ((cti.exerciseDependency & Exercise) == Exercise) - { - addToCreateTables(createTableStmt.arg(cti.name, - getTableColumnCreateStatements(cti.name, - cti.columns, - &tableComments, - Exercise)), - Exercise); - } - addToTables(cti.name, cti.exerciseDependency); + DEBUG_LOG(m_logger) << "Parent = " << parent; - if (!cti.comment.isEmpty()) - addToCreateTables(commentTableStmt.arg(cti.name, fixupComment(cti.comment)), cti.exerciseDependency); - addToCreateTables(tableComments, cti.exerciseDependency); - - const QString parent = m_xmlReader->getStruct2BaseClassRelations().value(cti.name); - const CompleteStructInformation csi = m_structBuilder->structInformationByTableName(cti.name); - if (!parent.isEmpty()) - { - const QString createViewStmt(QStringLiteral("CREATE OR REPLACE VIEW %1 AS SELECT %2\nFROM %3\nWHERE %4;\n")); - const QString dropViewStmt(QStringLiteral("DROP VIEW IF EXISTS %1;")); - if (!csi.primaryTable.isNull()) + if (!parent.isEmpty()) { - QStringList fqColumnNames; - QStringList fromTables; - QStringList whereConditions; - fromTables += cti.name; + const CompleteStructInformation csi = m_structBuilder->structInformationByTableName(parent); + const QString createViewStmt(QStringLiteral("CREATE OR REPLACE VIEW %1 AS SELECT %2\nFROM %3\nWHERE %4;\n")); + const QString dropViewStmt(QStringLiteral("DROP VIEW IF EXISTS %1;")); - - for (const MemberInformation &mi : csi.member) - { - if (mi.db.usedForView) - fqColumnNames += mi.db.table + QLatin1Char('.') + mi.db.columnName + QLatin1String(" AS ") + mi.db.getColumnNameView(); - if (mi.cpp.isReadOnly && mi.db.isForeignKey) + DEBUG_LOG(m_logger) << "csi.primaryTable = " << csi.primaryTable.data()->name; + + if (!csi.primaryTable.isNull()) { - - - - for (const QSharedPointer &tiPtr : csi.tables) - { - if (tiPtr->name == mi.db.table) + QStringList fromTables; + fromTables += vi.baseSchema + QLatin1Char('.') + vi.baseTable; + + QStringList whereConditions; + if (vi.filter.contains(QLatin1String("exercise_id"))) + whereConditions += QLatin1String("exercise_id=") + QString::number(m_exerciseId); + + QStringList fqColumnNames; + + for (const MemberInformation& mi : csi.member) { - const QSharedPointer fki = tiPtr->fkInformationForColumn(mi.db.table, mi.db.columnName); - if (!fki.isNull()) - { - - if (!fromTables.contains(fki->destination.tableName)) - { - whereConditions += fki->destination.tableName + QLatin1Char('.') + fki->destination.columnName + - QLatin1String(" = ") + - fki->source.tableName + QLatin1Char('.') + fki->source.columnName; - fromTables += fki->destination.tableName; - } - } - break; + if (mi.db.usedForView) + fqColumnNames += mi.db.table + QLatin1Char('.') + mi.db.columnName + QLatin1String(" AS ") + + mi.db.getColumnNameView(); } - } + + DEBUG_LOG(m_logger) << "fqColumnNames = " << fqColumnNames.join(QStringLiteral(", ")); + + if (!whereConditions.isEmpty()) + addToCreateViews(createViewStmt.arg(csi.viewName, fqColumnNames.join(QStringLiteral(", ")), + fromTables.join(QStringLiteral(", ")), + whereConditions.join(QStringLiteral(" AND\n"))), + vi.exerciseDependency); + addToDropViews(dropViewStmt.arg(csi.viewName), vi.exerciseDependency); } - } - if (!whereConditions.isEmpty()) - { - addToCreateViews(createViewStmt.arg(csi.viewName, - fqColumnNames.join(QStringLiteral(", ")), - fromTables.join(QStringLiteral(", ")), - whereConditions.join(QStringLiteral(" AND\n"))), - cti.exerciseDependency); - } - addToDropViews(dropViewStmt.arg(csi.viewName), cti.exerciseDependency); } - } - if (!generateDbNotifications(cti.name, csi.dbNotifications, cti.exerciseDependency)) - return false; - - generateForeignKeys(cti.foreignKeys, cti.exerciseDependency); - - generateConstraints(cti.name, cti.constraints, cti.exerciseDependency); - - return true; + return true; } - -QString SqlGenerator::getTableColumnCreateStatements(const QString &tableName, - const QVector &columns, - QStringList *tableComments, - ExerciseDependency ed) +bool SqlGenerator::handleTable(const CompleteTableInformation& cti) { - Q_ASSERT(ed == Global || ed == Exercise); + DEBUG_LOG(m_logger) << "Handle table " << cti.name; - const QString commentColumnStmt(QStringLiteral("COMMENT ON COLUMN %1 IS '%2';")); - - - int maxLength = 1; - for (const MemberInformation &mi : columns) - maxLength = std::max(maxLength, static_cast(mi.db.columnName.length())); - maxLength += 1; - - QStringList retCols; - retCols.reserve(columns.size() + 1); - retCols += QString(); - for (int i = 0; i < columns.size(); ++i) - { - const MemberInformation &mi = columns.at(i); - const FullQualifiedColumnInformation &ci = mi.db; - const QString spaces(maxLength - ci.columnName.length(), QLatin1Char(' ')); - QString column = ci.columnName + spaces + ci.datatype; - if (ci.hasSequence) + if (cti.columns.isEmpty()) { - - const QString seqDescr = generateSequence(tableName, ci, ed); - QString schema; - if (ed == Global) - schema = m_xmlReader->getServiceAbbr(); - else - schema = getExerciseSchemaName(m_exerciseId); - - column += QLatin1String(" DEFAULT nextval(( '") + - schema + QLatin1Char('.') + seqDescr + - QLatin1String("'::text)::regclass)"); + WARNING_LOG(m_logger) << "Table " << cti.name + << " has no DatabaseServiceStruct - not generating anything for this!"; + return true; } - if (!ci.canBeNull) - column += QLatin1String(" NOT NULL"); - if (!ci.hasSequence && !ci.defaultValue.isEmpty()) - column += QLatin1String(" DEFAULT ") + ci.defaultValue; - if (i < columns.size() - 1) - column += QLatin1Char(','); - if (!ci.comment.isEmpty()) + + const QString dropTableStmt(QStringLiteral("DROP TABLE IF EXISTS %1 CASCADE;")); + const QString createTableStmt(QStringLiteral("CREATE TABLE IF NOT EXISTS %1 (%2\n);")); + const QString commentTableStmt(QStringLiteral("COMMENT ON TABLE %1 IS '%2';")); + + QStringList tableComments; + addToDropTables(dropTableStmt.arg(cti.name), cti.exerciseDependency); + + if ((cti.exerciseDependency & Global) == Global) { - const QString comment(fixupComment(ci.comment)); - const QString fqn = ci.table + QLatin1Char('.') + ci.columnName; - *tableComments += commentColumnStmt.arg(fqn, comment); - column += QLatin1String(" -- ") + comment; + addToCreateTables(createTableStmt.arg( + cti.name, getTableColumnCreateStatements(cti.name, cti.columns, &tableComments, Global)), + Global); + } + if ((cti.exerciseDependency & Exercise) == Exercise) + { + addToCreateTables(createTableStmt.arg(cti.name, getTableColumnCreateStatements(cti.name, cti.columns, + &tableComments, Exercise)), + Exercise); + } + addToTables(cti.name, cti.exerciseDependency); + + if (!cti.comment.isEmpty()) + addToCreateTables(commentTableStmt.arg(cti.name, fixupComment(cti.comment)), cti.exerciseDependency); + addToCreateTables(tableComments, cti.exerciseDependency); + + const QString parent = m_xmlReader->getStruct2BaseClassRelations().value(cti.name); + const CompleteStructInformation csi = m_structBuilder->structInformationByTableName(cti.name); + if (!parent.isEmpty()) + { + const QString createViewStmt(QStringLiteral("CREATE OR REPLACE VIEW %1 AS SELECT %2\nFROM %3\nWHERE %4;\n")); + const QString dropViewStmt(QStringLiteral("DROP VIEW IF EXISTS %1;")); + if (!csi.primaryTable.isNull()) + { + QStringList fqColumnNames; + QStringList fromTables; + QStringList whereConditions; + fromTables += cti.name; + + for (const MemberInformation& mi : csi.member) + { + if (mi.db.usedForView) + fqColumnNames += mi.db.table + QLatin1Char('.') + mi.db.columnName + QLatin1String(" AS ") + + mi.db.getColumnNameView(); + if (mi.cpp.isReadOnly && mi.db.isForeignKey) + { + + for (const QSharedPointer& tiPtr : csi.tables) + { + if (tiPtr->name == mi.db.table) + { + const QSharedPointer fki = + tiPtr->fkInformationForColumn(mi.db.table, mi.db.columnName); + if (!fki.isNull()) + { + + if (!fromTables.contains(fki->destination.tableName)) + { + whereConditions += fki->destination.tableName + QLatin1Char('.') + + fki->destination.columnName + QLatin1String(" = ") + + fki->source.tableName + QLatin1Char('.') + + fki->source.columnName; + fromTables += fki->destination.tableName; + } + } + break; + } + } + } + } + if (!whereConditions.isEmpty()) + { + addToCreateViews(createViewStmt.arg(csi.viewName, fqColumnNames.join(QStringLiteral(", ")), + fromTables.join(QStringLiteral(", ")), + whereConditions.join(QStringLiteral(" AND\n"))), + cti.exerciseDependency); + } + addToDropViews(dropViewStmt.arg(csi.viewName), cti.exerciseDependency); + } } - retCols += column; + if (!generateDbNotifications(cti.name, csi.dbNotifications, cti.exerciseDependency)) + return false; - if (ci.isPrimaryKey) - generatePrimaryKey(tableName, ci, ed); - } - return retCols.join(QStringLiteral("\n ")); + generateForeignKeys(cti.foreignKeys, cti.exerciseDependency); + + generateConstraints(cti.name, cti.constraints, cti.exerciseDependency); + + return true; } -QString SqlGenerator::generateSequence(const QString &tableName, - const FullQualifiedColumnInformation &ci, +QString SqlGenerator::getTableColumnCreateStatements(const QString& tableName, + const QVector& columns, + QStringList* tableComments, ExerciseDependency ed) +{ + Q_ASSERT(ed == Global || ed == Exercise); + + const QString commentColumnStmt(QStringLiteral("COMMENT ON COLUMN %1 IS '%2';")); + + int maxLength = 1; + for (const MemberInformation& mi : columns) + maxLength = std::max(maxLength, static_cast(mi.db.columnName.length())); + maxLength += 1; + + QStringList retCols; + retCols.reserve(columns.size() + 1); + retCols += QString(); + for (int i = 0; i < columns.size(); ++i) + { + const MemberInformation& mi = columns.at(i); + const FullQualifiedColumnInformation& ci = mi.db; + const QString spaces(maxLength - ci.columnName.length(), QLatin1Char(' ')); + QString column = ci.columnName + spaces + ci.datatype; + if (ci.hasSequence) + { + + const QString seqDescr = generateSequence(tableName, ci, ed); + QString schema; + if (ed == Global) + schema = m_xmlReader->getServiceAbbr(); + else + schema = getExerciseSchemaName(m_exerciseId); + + column += QLatin1String(" DEFAULT nextval(( '") + schema + QLatin1Char('.') + seqDescr + + QLatin1String("'::text)::regclass)"); + } + if (!ci.canBeNull) + column += QLatin1String(" NOT NULL"); + if (!ci.hasSequence && !ci.defaultValue.isEmpty()) + column += QLatin1String(" DEFAULT ") + ci.defaultValue; + if (i < columns.size() - 1) + column += QLatin1Char(','); + if (!ci.comment.isEmpty()) + { + const QString comment(fixupComment(ci.comment)); + const QString fqn = ci.table + QLatin1Char('.') + ci.columnName; + *tableComments += commentColumnStmt.arg(fqn, comment); + column += QLatin1String(" -- ") + comment; + } + + retCols += column; + + if (ci.isPrimaryKey) + generatePrimaryKey(tableName, ci, ed); + } + return retCols.join(QStringLiteral("\n ")); +} + +QString SqlGenerator::generateSequence(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed) { - const QString sequenceName = tableName + QLatin1Char('_') + ci.columnName + QLatin1String("_seq"); + const QString sequenceName = tableName + QLatin1Char('_') + ci.columnName + QLatin1String("_seq"); - - - const QString createSequenceStmt(QLatin1String("CREATE SEQUENCE IF NOT EXISTS %1 INCREMENT %2 START %3 MINVALUE %4;")); + const QString createSequenceStmt( + QLatin1String("CREATE SEQUENCE IF NOT EXISTS %1 INCREMENT %2 START %3 MINVALUE %4;")); - const int minValue = ci.sequenceStart < 1 ? ci.sequenceStart : 1; + const int minValue = ci.sequenceStart < 1 ? ci.sequenceStart : 1; - addToCreateSequences(createSequenceStmt.arg(sequenceName).arg(ci.sequenceIncrement).arg(ci.sequenceStart).arg(minValue), ed); - addToSequences(sequenceName, ed); + addToCreateSequences( + createSequenceStmt.arg(sequenceName).arg(ci.sequenceIncrement).arg(ci.sequenceStart).arg(minValue), ed); + addToSequences(sequenceName, ed); - return sequenceName; + return sequenceName; } -void SqlGenerator::generatePrimaryKey(const QString &tableName, - const FullQualifiedColumnInformation &ci, +void SqlGenerator::generatePrimaryKey(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed) { - QString pkName = QLatin1String("PK_") + tableName + QLatin1Char('_') + ci.columnName; - - if (pkName.size() > 63) pkName.resize(63); + QString pkName = QLatin1String("PK_") + tableName + QLatin1Char('_') + ci.columnName; - addToPks(pkName, ed); + if (pkName.size() > 63) + pkName.resize(63); - - - const QString pkConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 ADD CONSTRAINT %2 PRIMARY KEY (%3);")); - addToCreatePks(pkConstraint.arg(tableName, pkName, ci.columnName), ed); + addToPks(pkName, ed); - const QString pkDropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); - addToDropConstraints(pkDropConstraint.arg(tableName, pkName), ed); + const QString pkConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 ADD CONSTRAINT %2 PRIMARY KEY (%3);")); + addToCreatePks(pkConstraint.arg(tableName, pkName, ci.columnName), ed); + + const QString pkDropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); + addToDropConstraints(pkDropConstraint.arg(tableName, pkName), ed); } -void SqlGenerator::generateForeignKeys(const QVector > &foreignKeys, +void SqlGenerator::generateForeignKeys(const QVector>& foreignKeys, ExerciseDependency ed) { - for (const QSharedPointer &fk : foreignKeys) - generateForeignKey(fk, ed); + for (const QSharedPointer& fk : foreignKeys) + generateForeignKey(fk, ed); } -void SqlGenerator::generateForeignKey(const QSharedPointer &foreignKey, - ExerciseDependency ed) +void SqlGenerator::generateForeignKey(const QSharedPointer& foreignKey, ExerciseDependency ed) { - QString fkName = QLatin1String("FK_") + foreignKey->source.tableName + - QLatin1Char('_') + foreignKey->source.columnName + - QLatin1Char('_') + foreignKey->destination.tableName + - QLatin1Char('_') + foreignKey->destination.columnName; + QString fkName = QLatin1String("FK_") + foreignKey->source.tableName + QLatin1Char('_') + + foreignKey->source.columnName + QLatin1Char('_') + foreignKey->destination.tableName + + QLatin1Char('_') + foreignKey->destination.columnName; - - - if (fkName.size() > 63) fkName = foreignKey->name; + if (fkName.size() > 63) + fkName = foreignKey->name; - addToFks(fkName, ed); + addToFks(fkName, ed); - QString fkConstraint(QStringLiteral("ALTER TABLE %1 ADD CONSTRAINT %2 FOREIGN KEY (%3) REFERENCES %4 (%5)")); - switch (foreignKey->deleteAction) - { - case ForeignKeyInformation::OnDeleteAction::NoAction: - fkConstraint += QStringLiteral(" ON DELETE NO ACTION"); - break; - case ForeignKeyInformation::OnDeleteAction::Cascade: - fkConstraint += QStringLiteral(" ON DELETE CASCADE ON UPDATE CASCADE"); - break; - case ForeignKeyInformation::OnDeleteAction::Restrict: - fkConstraint += QStringLiteral(" ON DELETE RESTRICT"); - break; - case ForeignKeyInformation::OnDeleteAction::SetNull: - fkConstraint += QStringLiteral(" ON DELETE SET NULL"); - break; - case ForeignKeyInformation::OnDeleteAction::SetDefault: - fkConstraint += QStringLiteral(" ON DELETE SET DEFAULT"); - break; - } + QString fkConstraint(QStringLiteral("ALTER TABLE %1 ADD CONSTRAINT %2 FOREIGN KEY (%3) REFERENCES %4 (%5)")); + switch (foreignKey->deleteAction) + { + case ForeignKeyInformation::OnDeleteAction::NoAction: + fkConstraint += QStringLiteral(" ON DELETE NO ACTION"); + break; + case ForeignKeyInformation::OnDeleteAction::Cascade: + fkConstraint += QStringLiteral(" ON DELETE CASCADE ON UPDATE CASCADE"); + break; + case ForeignKeyInformation::OnDeleteAction::Restrict: + fkConstraint += QStringLiteral(" ON DELETE RESTRICT"); + break; + case ForeignKeyInformation::OnDeleteAction::SetNull: + fkConstraint += QStringLiteral(" ON DELETE SET NULL"); + break; + case ForeignKeyInformation::OnDeleteAction::SetDefault: + fkConstraint += QStringLiteral(" ON DELETE SET DEFAULT"); + break; + } - fkConstraint += QLatin1Char(';'); + fkConstraint += QLatin1Char(';'); - - - QString destination; - if (!foreignKey->destination.schema.isEmpty()) - { - const QString &extSchema = foreignKey->destination.schema; - destination = extSchema + QLatin1Char('.') + foreignKey->destination.tableName; - } - else - destination = foreignKey->destination.tableName; + QString destination; + if (!foreignKey->destination.schema.isEmpty()) + { + const QString& extSchema = foreignKey->destination.schema; + destination = extSchema + QLatin1Char('.') + foreignKey->destination.tableName; + } + else + destination = foreignKey->destination.tableName; - const QString &extSvcAbbr = foreignKey->destination.serviceAbbr; - - if (!extSvcAbbr.isEmpty() && !m_referencedSevices.contains(extSvcAbbr)) - m_referencedSevices += extSvcAbbr; + const QString& extSvcAbbr = foreignKey->destination.serviceAbbr; - addToCreateFks(fkConstraint.arg(foreignKey->source.tableName, fkName, foreignKey->source.columnName, - destination, foreignKey->destination.columnName), ed); + if (!extSvcAbbr.isEmpty() && !m_referencedSevices.contains(extSvcAbbr)) + m_referencedSevices += extSvcAbbr; - const QString fkDropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); - addToDropConstraints(fkDropConstraint.arg(foreignKey->source.tableName, fkName), ed); + addToCreateFks(fkConstraint.arg(foreignKey->source.tableName, fkName, foreignKey->source.columnName, destination, + foreignKey->destination.columnName), + ed); + const QString fkDropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); + addToDropConstraints(fkDropConstraint.arg(foreignKey->source.tableName, fkName), ed); } - -void SqlGenerator::generateConstraints(const QString &tableName, - const QVector &constraints, +void SqlGenerator::generateConstraints(const QString& tableName, const QVector& constraints, ExerciseDependency ed) { - for (const ConstraintInformation &constraint : constraints) - generateConstraint(tableName, constraint, ed); + for (const ConstraintInformation& constraint : constraints) + generateConstraint(tableName, constraint, ed); } -void SqlGenerator::generateConstraint(const QString &tableName, - const ConstraintInformation &constraint, +void SqlGenerator::generateConstraint(const QString& tableName, const ConstraintInformation& constraint, ExerciseDependency ed) { - const QString dropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); - switch (constraint.type) - { - case ConstraintInformation::Type::index: - { - QString constraintName = QLatin1String("IDX_") + tableName + QLatin1Char('_') + - constraint.affectedColumns.join(QStringLiteral("_")); - - if (constraintName.size() > 63) constraintName.resize(63); + const QString dropConstraint(QStringLiteral("ALTER TABLE IF EXISTS %1 DROP CONSTRAINT IF EXISTS %2 CASCADE;")); + switch (constraint.type) + { + case ConstraintInformation::Type::index: { + QString constraintName = QLatin1String("IDX_") + tableName + QLatin1Char('_') + + constraint.affectedColumns.join(QStringLiteral("_")); - const QString index(QStringLiteral("CREATE INDEX %1 ON %2 (%3);")); + if (constraintName.size() > 63) + constraintName.resize(63); - addToCreateConstraints(index.arg(constraintName, tableName, constraint.affectedColumns.join(QStringLiteral(", "))), ed); - addToConstraints(constraintName, ed); + const QString index(QStringLiteral("CREATE INDEX %1 ON %2 (%3);")); - addToDropConstraints(dropConstraint.arg(tableName, constraintName), ed); + addToCreateConstraints( + index.arg(constraintName, tableName, constraint.affectedColumns.join(QStringLiteral(", "))), ed); + addToConstraints(constraintName, ed); - break; - } - case ConstraintInformation::Type::unique: - { - QString constraintName = QLatin1String("UQ_") + tableName + QLatin1Char('_') + - constraint.affectedColumns.join(QStringLiteral("_")); - - if (constraintName.size() > 63) constraintName.resize(63); - const QString unique(QStringLiteral("ALTER TABLE %1 ADD CONSTRAINT %2 UNIQUE (%3);")); + addToDropConstraints(dropConstraint.arg(tableName, constraintName), ed); - addToCreateConstraints(unique.arg(tableName, constraintName, constraint.affectedColumns.join(QStringLiteral(", "))), ed); - addToConstraints(constraintName, ed); + break; + } + case ConstraintInformation::Type::unique: { + QString constraintName = QLatin1String("UQ_") + tableName + QLatin1Char('_') + + constraint.affectedColumns.join(QStringLiteral("_")); - addToDropConstraints(dropConstraint.arg(tableName, constraintName), ed); + if (constraintName.size() > 63) + constraintName.resize(63); + const QString unique(QStringLiteral("ALTER TABLE %1 ADD CONSTRAINT %2 UNIQUE (%3);")); - break; - } - case ConstraintInformation::Type::unknown: - break; - } + addToCreateConstraints( + unique.arg(tableName, constraintName, constraint.affectedColumns.join(QStringLiteral(", "))), ed); + addToConstraints(constraintName, ed); + + addToDropConstraints(dropConstraint.arg(tableName, constraintName), ed); + + break; + } + case ConstraintInformation::Type::unknown: + break; + } } bool SqlGenerator::handleEnumerations() { - const QVector enumerations = m_xmlReader->getEnumerations(); - for (const EnumInformation &ei : enumerations) - { - if (!handleEnumeration(ei)) - return false; - } - return true; + const QVector enumerations = m_xmlReader->getEnumerations(); + for (const EnumInformation& ei : enumerations) + { + if (!handleEnumeration(ei)) + return false; + } + return true; } -bool SqlGenerator::handleEnumeration(const EnumInformation &ei) +bool SqlGenerator::handleEnumeration(const EnumInformation& ei) { - const QStringList sql = handleEnumeration(ei, QString()); - if (m_sqlItemsGlobal.tables.contains(ei.tableName)) - m_sqlGlobal.enumerationValues += sql; - if (m_sqlItemsExercise.tables.contains(ei.tableName)) - m_sqlExercise.enumerationValues += sql; + const QStringList sql = handleEnumeration(ei, QString()); + if (m_sqlItemsGlobal.tables.contains(ei.tableName)) + m_sqlGlobal.enumerationValues += sql; + if (m_sqlItemsExercise.tables.contains(ei.tableName)) + m_sqlExercise.enumerationValues += sql; - return true; + return true; } -QStringList SqlGenerator::handleEnumeration(const EnumInformation &ei, const QString &dbSchema) const +QStringList SqlGenerator::handleEnumeration(const EnumInformation& ei, const QString& dbSchema) const { - DEBUG_LOG(m_logger) << "Handle enumeration " << ei.enumName; + DEBUG_LOG(m_logger) << "Handle enumeration " << ei.enumName; - if (ei.tableName.isEmpty()) - { - INFO_LOG(m_logger) << "No table for enumeration " << ei.enumName << " - not creating inserts for this enum"; - return QStringList(); - } + if (ei.tableName.isEmpty()) + { + INFO_LOG(m_logger) << "No table for enumeration " << ei.enumName << " - not creating inserts for this enum"; + return QStringList(); + } - const QString insertEnum(QStringLiteral("INSERT INTO %1 (%2) VALUES (%3);")); - const QString columnNames(QStringLiteral("id, name")); - const QString tablename = dbSchema.isEmpty() ? ei.tableName : dbSchema + QLatin1Char('.') + ei.tableName; + const QString insertEnum(QStringLiteral("INSERT INTO %1 (%2) VALUES (%3);")); + const QString columnNames(QStringLiteral("id, name")); + const QString tablename = dbSchema.isEmpty() ? ei.tableName : dbSchema + QLatin1Char('.') + ei.tableName; - - QStringList enumerationValues; - for (const EnumKeyValuePair &evp : ei.values) - { - const QString values(QString::number(evp.value) + QLatin1String(", '") + - fixupComment(evp.key) + QLatin1Char('\'')); - enumerationValues += insertEnum.arg(tablename, columnNames, values); - } + QStringList enumerationValues; + for (const EnumKeyValuePair& evp : ei.values) + { + const QString values(QString::number(evp.value) + QLatin1String(", '") + fixupComment(evp.key) + + QLatin1Char('\'')); + enumerationValues += insertEnum.arg(tablename, columnNames, values); + } - return enumerationValues; + return enumerationValues; } -bool SqlGenerator::generateDbNotifications(const QString &tableName, - const QVector ¬ifications, +bool SqlGenerator::generateDbNotifications(const QString& tableName, + const QVector& notifications, ExerciseDependency ed) { - for (const DbNotifcationInformation ¬ification : notifications) - { - if (notification.paramNames.isEmpty() || - notification.paramNames.size() > 1) + for (const DbNotifcationInformation& notification : notifications) { - ERROR_LOG(m_logger) << "Can not handle more than one parameter"; - continue; + if (notification.paramNames.isEmpty() || notification.paramNames.size() > 1) + { + ERROR_LOG(m_logger) << "Can not handle more than one parameter"; + continue; + } + generateDbNotification(notification, ed); + if (!generateDbNotificationTrigger(tableName, notification, ed)) + return false; } - generateDbNotification(notification, ed); - if (!generateDbNotificationTrigger(tableName, notification, ed)) - return false; - } - return true; + return true; } -void SqlGenerator::generateDbNotification(const DbNotifcationInformation ¬ification, - ExerciseDependency ed) +void SqlGenerator::generateDbNotification(const DbNotifcationInformation& notification, ExerciseDependency ed) { - const QString func(QStringLiteral("CREATE OR REPLACE FUNCTION public.%1()\n" - "RETURNS TRIGGER AS $$\n" - "DECLARE\n" - " toNotify RECORD;\n" - " toReturn RECORD;\n" - "BEGIN\n" - " IF (TG_OP = 'INSERT') THEN\n" - " toNotify = NEW;\n" - " toReturn = NEW;\n" - " ELSIF (TG_OP = 'UPDATE') THEN\n" - " toNotify = OLD;\n" - " toReturn = NEW;\n" - " ELSIF (TG_OP = 'DELETE') THEN\n" - " toNotify = OLD;\n" - " toReturn = OLD;\n" - " END IF;\n" - " \n" - " PERFORM pg_notify('%2', CAST(toNotify.%3 AS text));\n" - " RETURN toReturn;\n" - "END;\n" - "$$ LANGUAGE plpgsql;")); + const QString func(QStringLiteral("CREATE OR REPLACE FUNCTION public.%1()\n" + "RETURNS TRIGGER AS $$\n" + "DECLARE\n" + " toNotify RECORD;\n" + " toReturn RECORD;\n" + "BEGIN\n" + " IF (TG_OP = 'INSERT') THEN\n" + " toNotify = NEW;\n" + " toReturn = NEW;\n" + " ELSIF (TG_OP = 'UPDATE') THEN\n" + " toNotify = OLD;\n" + " toReturn = NEW;\n" + " ELSIF (TG_OP = 'DELETE') THEN\n" + " toNotify = OLD;\n" + " toReturn = OLD;\n" + " END IF;\n" + " \n" + " PERFORM pg_notify('%2', CAST(toNotify.%3 AS text));\n" + " RETURN toReturn;\n" + "END;\n" + "$$ LANGUAGE plpgsql;")); - const QString triggerFuncName(getNotificationFunctionName(notification)); - addToDbFunctions(func.arg(triggerFuncName, notification.methodName, notification.paramNames.first()), ed); + const QString triggerFuncName(getNotificationFunctionName(notification)); + addToDbFunctions(func.arg(triggerFuncName, notification.methodName, notification.paramNames.first()), ed); } -bool SqlGenerator::generateDbNotificationTrigger(const QString &tableName, - const DbNotifcationInformation ¬ification, +bool SqlGenerator::generateDbNotificationTrigger(const QString& tableName, const DbNotifcationInformation& notification, ExerciseDependency ed) { - - const QString drop(QStringLiteral("DROP TRIGGER IF EXISTS %1 ON %2;")); - const QString func(QStringLiteral("CREATE TRIGGER %1\n") + - QStringLiteral("%2 ON %3 FOR EACH ROW EXECUTE PROCEDURE public.%4();")); - for (DbNotifcationInformation::NotificationType notifyType : notification.notificationType) - { - QString when; - QString triggerNameShortcut; - switch (notifyType) + const QString drop(QStringLiteral("DROP TRIGGER IF EXISTS %1 ON %2;")); + const QString func(QStringLiteral("CREATE TRIGGER %1\n") + + QStringLiteral("%2 ON %3 FOR EACH ROW EXECUTE PROCEDURE public.%4();")); + + for (DbNotifcationInformation::NotificationType notifyType : notification.notificationType) { - case DbNotifcationInformation::NotificationType::BeforeInsert: - when = QStringLiteral("BEFORE INSERT"); - triggerNameShortcut = QStringLiteral("bi"); - break; - case DbNotifcationInformation::NotificationType::AfterInsert: - when = QStringLiteral("AFTER INSERT"); - triggerNameShortcut = QStringLiteral("ai"); - break; - case DbNotifcationInformation::NotificationType::BeforeUpdate: - when = QStringLiteral("BEFORE UPDATE"); - triggerNameShortcut = QStringLiteral("bu"); - break; - case DbNotifcationInformation::NotificationType::AfterUpdate: - when = QStringLiteral("AFTER UPDATE"); - triggerNameShortcut = QStringLiteral("au"); - break; - case DbNotifcationInformation::NotificationType::BeforeDelete: - when = QStringLiteral("BEFORE DELETE"); - triggerNameShortcut = QStringLiteral("bd"); - break; - case DbNotifcationInformation::NotificationType::AfterDelete: - when = QStringLiteral("AFTER DELETE"); - triggerNameShortcut = QStringLiteral("ad"); - break; + QString when; + QString triggerNameShortcut; + switch (notifyType) + { + case DbNotifcationInformation::NotificationType::BeforeInsert: + when = QStringLiteral("BEFORE INSERT"); + triggerNameShortcut = QStringLiteral("bi"); + break; + case DbNotifcationInformation::NotificationType::AfterInsert: + when = QStringLiteral("AFTER INSERT"); + triggerNameShortcut = QStringLiteral("ai"); + break; + case DbNotifcationInformation::NotificationType::BeforeUpdate: + when = QStringLiteral("BEFORE UPDATE"); + triggerNameShortcut = QStringLiteral("bu"); + break; + case DbNotifcationInformation::NotificationType::AfterUpdate: + when = QStringLiteral("AFTER UPDATE"); + triggerNameShortcut = QStringLiteral("au"); + break; + case DbNotifcationInformation::NotificationType::BeforeDelete: + when = QStringLiteral("BEFORE DELETE"); + triggerNameShortcut = QStringLiteral("bd"); + break; + case DbNotifcationInformation::NotificationType::AfterDelete: + when = QStringLiteral("AFTER DELETE"); + triggerNameShortcut = QStringLiteral("ad"); + break; + } + const QString triggerName(QLatin1String("trg_") + triggerNameShortcut + QLatin1Char('_') + + notification.methodName); + const QString triggerFuncName(getNotificationFunctionName(notification)); + addToDbFunctionTrigger(drop.arg(triggerName, tableName), ed); + addToDbFunctionTrigger(func.arg(triggerName, when, tableName, triggerFuncName), ed); } - const QString triggerName(QLatin1String("trg_") + triggerNameShortcut + QLatin1Char('_') + notification.methodName); - const QString triggerFuncName(getNotificationFunctionName(notification)); - addToDbFunctionTrigger(drop.arg(triggerName, tableName), ed); - addToDbFunctionTrigger(func.arg(triggerName, when, tableName, triggerFuncName), ed); - } - return true; + return true; } -QString SqlGenerator::getNotificationFunctionName(const DbNotifcationInformation ¬ification) const +QString SqlGenerator::getNotificationFunctionName(const DbNotifcationInformation& notification) const { - return getServiceAbbr() + QLatin1Char('_') + notification.methodName; + return getServiceAbbr() + QLatin1Char('_') + notification.methodName; } - -QString SqlGenerator::fixupComment(const QString &comment) +QString SqlGenerator::fixupComment(const QString& comment) { - - QString ret = comment; - ret = ret.remove(QLatin1Char('\'')); - ret = ret.replace(QLatin1Char(';'), QLatin1Char(',')); - return ret; + + QString ret = comment; + ret = ret.remove(QLatin1Char('\'')); + ret = ret.replace(QLatin1Char(';'), QLatin1Char(',')); + return ret; } -QStringList SqlGenerator::getDbSettings(const QString &dbSchema) const +QStringList SqlGenerator::getDbSettings(const QString& dbSchema) const { - QStringList data; + QStringList data; - - QString dbUser(QStringLiteral("ets_")); - if (m_exerciseId > 0) - dbUser += QStringLiteral("ex_00"); - else - dbUser += m_xmlReader->getServiceAbbr().toLower(); + QString dbUser(QStringLiteral("ets_")); + if (m_exerciseId > 0) + dbUser += QStringLiteral("ex_00"); + else + dbUser += m_xmlReader->getServiceAbbr().toLower(); - - data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + - QLatin1String(" GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON TABLES TO ") + dbUser + QLatin1Char(';')); + data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + + QLatin1String(" GRANT SELECT,INSERT,UPDATE,DELETE,TRUNCATE ON TABLES TO ") + dbUser + + QLatin1Char(';')); - - data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + - QLatin1String(" GRANT SELECT, REFERENCES ON TABLES TO ets_ro;")); + data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + + QLatin1String(" GRANT SELECT, REFERENCES ON TABLES TO ets_ro;")); - data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + - QLatin1String(" GRANT EXECUTE ON FUNCTIONS TO ") + dbUser + QLatin1Char(';')); + data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + + QLatin1String(" GRANT EXECUTE ON FUNCTIONS TO ") + dbUser + QLatin1Char(';')); - data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + - QLatin1String(" GRANT ALL ON SEQUENCES TO ") + dbUser + QLatin1Char(';')); + data.append(QLatin1String("ALTER DEFAULT PRIVILEGES IN SCHEMA ") + dbSchema + QLatin1Char('\n') + + QLatin1String(" GRANT ALL ON SEQUENCES TO ") + dbUser + QLatin1Char(';')); - - data.append(QLatin1String("SET SEARCH_PATH TO ") + dbSchema + QLatin1String(", PUBLIC;")); + data.append(QLatin1String("SET SEARCH_PATH TO ") + dbSchema + QLatin1String(", PUBLIC;")); - QStringList deps; - deps.reserve(m_referencedSevices.size()); - for(const QString &svc : m_referencedSevices) - deps += QStringLiteral("-- DEPENDS: ") + svc; + QStringList deps; + deps.reserve(m_referencedSevices.size()); + for (const QString& svc : m_referencedSevices) + deps += QStringLiteral("-- DEPENDS: ") + svc; - return deps + data; + return deps + data; } -QStringList SqlGenerator::getAllSqlStmts(const QString &dbSchema, ExerciseDependency ed) const +QStringList SqlGenerator::getAllSqlStmts(const QString& dbSchema, ExerciseDependency ed) const { - DEBUG_LOG(m_logger) << "Creating statements for service " << getServiceAbbr() << " in exercise " << m_exerciseId << ", this: " << this; + DEBUG_LOG(m_logger) << "Creating statements for service " << getServiceAbbr() << " in exercise " << m_exerciseId + << ", this: " << this; - QStringList data; + QStringList data; + + const SqlStatements& sql = getStatements(ed); + if (sql.isEmpty()) + return data; + + if (!dbSchema.isEmpty()) + data << getDbSettings(dbSchema); + + data.append(QStringLiteral("\n-- Drop tables/views/sequences/constraints")); + data.append(sql.dropViews); + data.append(sql.dropConstraints); + data.append(sql.dropTables); + data.append(sql.dropSequences); + + data.append(QStringLiteral("\n-- Create tables")); + data.append(sql.createTables); + + data.append(QStringLiteral("\n-- Create sequence(s)")); + data.append(sql.createSequences); + + data.append(QStringLiteral("\n-- Create primary keys")); + data.append(sql.createPrimaryKeys); + + data.append(QStringLiteral("\n-- Create foreign keys")); + data.append(sql.createForeignKeys); + + data.append(QStringLiteral("\n-- Create views")); + data.append(sql.createViews); + + data.append( + QStringLiteral("\n-- --------------------------------------------------------------------------------")); + data.append(QStringLiteral("\n-- Inserts for static data i.e. enums\n")); + data.append(sql.enumerationValues); + + data.append( + QStringLiteral("\n-- --------------------------------------------------------------------------------")); + data.append(QStringLiteral("\n-- Notify functions for callbacks (signals in db interface)\n")); + data.append(sql.dbFunctions); + + data.append( + QStringLiteral("\n-- --------------------------------------------------------------------------------")); + data.append(QStringLiteral("\n-- Notify function trigger for callbacks (signals in db interface)\n")); + data.append(sql.dbFunctionTrigger); + + data.append( + QStringLiteral("\n-- --------------------------------------------------------------------------------")); + data.append(QStringLiteral("\n-- Indexes \n")); + data.append(sql.createConstraints); - const SqlStatements &sql = getStatements(ed); - if (sql.isEmpty()) return data; - - if (!dbSchema.isEmpty()) - data << getDbSettings(dbSchema); - - - data.append(QStringLiteral("\n-- Drop tables/views/sequences/constraints")); - data.append(sql.dropViews); - data.append(sql.dropConstraints); - data.append(sql.dropTables); - data.append(sql.dropSequences); - - - data.append(QStringLiteral("\n-- Create tables")); - data.append(sql.createTables); - - - data.append(QStringLiteral("\n-- Create sequence(s)")); - data.append(sql.createSequences); - - - data.append(QStringLiteral("\n-- Create primary keys")); - data.append(sql.createPrimaryKeys); - - - data.append(QStringLiteral("\n-- Create foreign keys")); - data.append(sql.createForeignKeys); - - - data.append(QStringLiteral("\n-- Create views")); - data.append(sql.createViews); - - - data.append(QStringLiteral("\n-- --------------------------------------------------------------------------------")); - data.append(QStringLiteral("\n-- Inserts for static data i.e. enums\n")); - data.append(sql.enumerationValues); - - - data.append(QStringLiteral("\n-- --------------------------------------------------------------------------------")); - data.append(QStringLiteral("\n-- Notify functions for callbacks (signals in db interface)\n")); - data.append(sql.dbFunctions); - - - data.append(QStringLiteral("\n-- --------------------------------------------------------------------------------")); - data.append(QStringLiteral("\n-- Notify function trigger for callbacks (signals in db interface)\n")); - data.append(sql.dbFunctionTrigger); - - - data.append(QStringLiteral("\n-- --------------------------------------------------------------------------------")); - data.append(QStringLiteral("\n-- Indexes \n")); - data.append(sql.createConstraints); - - return data; } -QStringList SqlGenerator::getEnumerationInsertValues(const QString &table, const QString &dbSchema) const +QStringList SqlGenerator::getEnumerationInsertValues(const QString& table, const QString& dbSchema) const { - const QVector enumerations = m_xmlReader->getEnumerations(); + const QVector enumerations = m_xmlReader->getEnumerations(); - for (const EnumInformation &ei : enumerations) - { - if (ei.tableName == table) - return handleEnumeration(ei, dbSchema); - } - return QStringList(); + for (const EnumInformation& ei : enumerations) + { + if (ei.tableName == table) + return handleEnumeration(ei, dbSchema); + } + return QStringList(); } -bool SqlGenerator::writeSqlToFile(const QString &dbSchema, const QString &sqlFile, ExerciseDependency ed) const +bool SqlGenerator::writeSqlToFile(const QString& dbSchema, const QString& sqlFile, ExerciseDependency ed) const { - return writeFile(sqlFile, getAllSqlStmts(dbSchema, ed).join(QLatin1Char('\n'))); + return writeFile(sqlFile, getAllSqlStmts(dbSchema, ed).join(QLatin1Char('\n'))); } -bool SqlGenerator::writeSql(const QString &filePath, ExerciseDependency ed) +bool SqlGenerator::writeSql(const QString& filePath, ExerciseDependency ed) { - Q_ASSERT(ed == Global || ed == Exercise); + Q_ASSERT(ed == Global || ed == Exercise); - - QString sqlFile = filePath + getServiceAbbr(); - if (ed == ExerciseDependency::Exercise) - sqlFile += QLatin1Char('_') + getExerciseSchemaName(m_exerciseId); - sqlFile += QLatin1String(".sql"); + QString sqlFile = filePath + getServiceAbbr(); + if (ed == ExerciseDependency::Exercise) + sqlFile += QLatin1Char('_') + getExerciseSchemaName(m_exerciseId); + sqlFile += QLatin1String(".sql"); - const SqlStatements &sql = getStatements(ed); - if (sql.isEmpty()) - { - DEBUG_LOG(m_logger) << "Sql file is emtpy: " << sqlFile; - return writeFile(sqlFile, QString()); - } + const SqlStatements& sql = getStatements(ed); + if (sql.isEmpty()) + { + DEBUG_LOG(m_logger) << "Sql file is emtpy: " << sqlFile; + return writeFile(sqlFile, QString()); + } - + const QString dbSchema = + (ed == ExerciseDependency::Exercise ? getExerciseSchemaName(m_exerciseId) : getServiceAbbr()); - const QString dbSchema = (ed == ExerciseDependency::Exercise ? - getExerciseSchemaName(m_exerciseId) : - getServiceAbbr()); - - INFO_LOG(m_logger) << "Creating sql-stmt for schema (" << dbSchema << ")"; - return writeSqlToFile(dbSchema, sqlFile, ed); + INFO_LOG(m_logger) << "Creating sql-stmt for schema (" << dbSchema << ")"; + return writeSqlToFile(dbSchema, sqlFile, ed); } - -template -static void addInternal(QStringList &global, - QStringList &exercise, - const T &stmt, - ExerciseDependency ed) +template +static void addInternal(QStringList& global, QStringList& exercise, const T& stmt, ExerciseDependency ed) { - switch (ed) - { - case ExerciseDependency::Global: - global += stmt; - break; - case ExerciseDependency::Exercise: - exercise += stmt; - break; - case ExerciseDependency::GlobalAndExercise: - global += stmt; - exercise += stmt; - break; - case ExerciseDependency::Undefined: - break; - } + switch (ed) + { + case ExerciseDependency::Global: + global += stmt; + break; + case ExerciseDependency::Exercise: + exercise += stmt; + break; + case ExerciseDependency::GlobalAndExercise: + global += stmt; + exercise += stmt; + break; + case ExerciseDependency::Undefined: + break; + } } -void SqlGenerator::addToDropSequences(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDropSequences(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dropSequences, m_sqlExercise.dropSequences, stmt, ed); + addInternal(m_sqlGlobal.dropSequences, m_sqlExercise.dropSequences, stmt, ed); } -void SqlGenerator::addToDropTables(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDropTables(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dropTables, m_sqlExercise.dropTables, stmt, ed); + addInternal(m_sqlGlobal.dropTables, m_sqlExercise.dropTables, stmt, ed); } -void SqlGenerator::addToDropViews(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDropViews(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dropViews, m_sqlExercise.dropViews, stmt, ed); + addInternal(m_sqlGlobal.dropViews, m_sqlExercise.dropViews, stmt, ed); } -void SqlGenerator::addToCreateConstraints(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreateConstraints(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createConstraints, m_sqlExercise.createConstraints, stmt, ed); + addInternal(m_sqlGlobal.createConstraints, m_sqlExercise.createConstraints, stmt, ed); } -void SqlGenerator::addToDropConstraints(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDropConstraints(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dropConstraints, m_sqlExercise.dropConstraints, stmt, ed); + addInternal(m_sqlGlobal.dropConstraints, m_sqlExercise.dropConstraints, stmt, ed); } -void SqlGenerator::addToCreateFks(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreateFks(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createForeignKeys, m_sqlExercise.createForeignKeys, stmt, ed); + addInternal(m_sqlGlobal.createForeignKeys, m_sqlExercise.createForeignKeys, stmt, ed); } -void SqlGenerator::addToCreatePks(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreatePks(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createPrimaryKeys, m_sqlExercise.createPrimaryKeys, stmt, ed); + addInternal(m_sqlGlobal.createPrimaryKeys, m_sqlExercise.createPrimaryKeys, stmt, ed); } -void SqlGenerator::addToCreateSequences(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreateSequences(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createSequences, m_sqlExercise.createSequences, stmt, ed); + addInternal(m_sqlGlobal.createSequences, m_sqlExercise.createSequences, stmt, ed); } -void SqlGenerator::addToCreateTables(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreateTables(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createTables, m_sqlExercise.createTables, stmt, ed); + addInternal(m_sqlGlobal.createTables, m_sqlExercise.createTables, stmt, ed); } -void SqlGenerator::addToCreateTables(const QStringList &stmts, ExerciseDependency ed) +void SqlGenerator::addToCreateTables(const QStringList& stmts, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createTables, m_sqlExercise.createTables, stmts, ed); + addInternal(m_sqlGlobal.createTables, m_sqlExercise.createTables, stmts, ed); } -void SqlGenerator::addToCreateViews(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToCreateViews(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.createViews, m_sqlExercise.createViews, stmt, ed); + addInternal(m_sqlGlobal.createViews, m_sqlExercise.createViews, stmt, ed); } -void SqlGenerator::addToDbFunctions(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDbFunctions(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dbFunctions, m_sqlExercise.dbFunctions, stmt, ed); + addInternal(m_sqlGlobal.dbFunctions, m_sqlExercise.dbFunctions, stmt, ed); } -void SqlGenerator::addToDbFunctionTrigger(const QString &stmt, ExerciseDependency ed) +void SqlGenerator::addToDbFunctionTrigger(const QString& stmt, ExerciseDependency ed) { - addInternal(m_sqlGlobal.dbFunctionTrigger, m_sqlExercise.dbFunctionTrigger, stmt, ed); + addInternal(m_sqlGlobal.dbFunctionTrigger, m_sqlExercise.dbFunctionTrigger, stmt, ed); } -void SqlGenerator::addToConstraints(const QString &name, ExerciseDependency ed) +void SqlGenerator::addToConstraints(const QString& name, ExerciseDependency ed) { - addInternal(m_sqlItemsGlobal.constraints, m_sqlItemsExercise.constraints, name, ed); + addInternal(m_sqlItemsGlobal.constraints, m_sqlItemsExercise.constraints, name, ed); } -void SqlGenerator::addToFks(const QString &name, ExerciseDependency ed) +void SqlGenerator::addToFks(const QString& name, ExerciseDependency ed) { - addInternal(m_sqlItemsGlobal.foreignKeys, m_sqlItemsExercise.foreignKeys, name, ed); + addInternal(m_sqlItemsGlobal.foreignKeys, m_sqlItemsExercise.foreignKeys, name, ed); } -void SqlGenerator::addToPks(const QString &name, ExerciseDependency ed) +void SqlGenerator::addToPks(const QString& name, ExerciseDependency ed) { - addInternal(m_sqlItemsGlobal.primaryKeys, m_sqlItemsExercise.primaryKeys, name, ed); + addInternal(m_sqlItemsGlobal.primaryKeys, m_sqlItemsExercise.primaryKeys, name, ed); } -void SqlGenerator::addToSequences(const QString &name, ExerciseDependency ed) +void SqlGenerator::addToSequences(const QString& name, ExerciseDependency ed) { - addInternal(m_sqlItemsGlobal.sequences, m_sqlItemsExercise.sequences, name, ed); + addInternal(m_sqlItemsGlobal.sequences, m_sqlItemsExercise.sequences, name, ed); } -void SqlGenerator::addToTables(const QString &name, ExerciseDependency ed) +void SqlGenerator::addToTables(const QString& name, ExerciseDependency ed) { - addInternal(m_sqlItemsGlobal.tables, m_sqlItemsExercise.tables, name, ed); + addInternal(m_sqlItemsGlobal.tables, m_sqlItemsExercise.tables, name, ed); } -bool SqlGenerator::writeFile(const QString &fn, const QString &content) const +bool SqlGenerator::writeFile(const QString& fn, const QString& content) const { - QFile f(fn); - if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) - { - ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " - << f.errorString(); - return false; - } - f.write(content.toUtf8()); - if (!content.isEmpty()) - f.write("\n"); - f.close(); - return true; + QFile f(fn); + if (!f.open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + ERROR_LOG(m_logger) << "Error opening file '" << f.fileName() << "' for writing: " << f.errorString(); + return false; + } + f.write(content.toUtf8()); + if (!content.isEmpty()) + f.write("\n"); + f.close(); + return true; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.h old mode 100755 new mode 100644 index 46a441206..37214fd47 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/SqlGenerator.h @@ -2,11 +2,12 @@ #pragma once -#include -#include #include "StructBuilder.h" #include "codegen_base_export.h" +#include +#include + namespace NGL { class INGLLogger; @@ -23,152 +24,175 @@ class XmlReader; class CODEGEN_BASE_EXPORT SqlGenerator final { -public: - struct SqlStatements - { - QStringList dropViews; - QStringList dropTables; - QStringList dropSequences; - QStringList dropConstraints; - - QStringList createTables; - QStringList createSequences; - QStringList createPrimaryKeys; - QStringList createForeignKeys; - QStringList createViews; - QStringList createConstraints; - - QStringList enumerationValues; - QStringList dbFunctions; - QStringList dbFunctionTrigger; - - bool isEmpty() const + public: + struct SqlStatements { - return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty(); + QStringList dropViews; + QStringList dropTables; + QStringList dropSequences; + QStringList dropConstraints; + + QStringList createTables; + QStringList createSequences; + QStringList createPrimaryKeys; + QStringList createForeignKeys; + QStringList createViews; + QStringList createConstraints; + + QStringList enumerationValues; + QStringList dbFunctions; + QStringList dbFunctionTrigger; + + bool isEmpty() const + { + return dropViews.isEmpty() && dropTables.isEmpty() && dropSequences.isEmpty() && dropConstraints.isEmpty(); + } + }; + + struct SqlItems + { + QStringList tables; + QStringList sequences; + QStringList primaryKeys; + QStringList foreignKeys; + QStringList constraints; + }; + + public: + Q_DISABLE_COPY(SqlGenerator) + + explicit SqlGenerator(XmlReader* xmlReader, StructBuilder* structBuilder); + explicit SqlGenerator(const QString& xmlFile); + + ~SqlGenerator(); + + bool isValid() const + { + return m_isValid; } - }; - struct SqlItems - { - QStringList tables; - QStringList sequences; - QStringList primaryKeys; - QStringList foreignKeys; - QStringList constraints; - }; + bool generateData(int exerciseId); -public: - Q_DISABLE_COPY(SqlGenerator) + bool createStatementsForTable(const QString& tableName, const QString& tableNameOut); - explicit SqlGenerator(XmlReader *xmlReader, StructBuilder *structBuilder); - explicit SqlGenerator(const QString &xmlFile); + SqlStatements getStatements(ExerciseDependency ed) const + { + return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal); + } - ~SqlGenerator(); + SqlItems getSqlItems(ExerciseDependency ed) const + { + return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal); + } - bool isValid() const { return m_isValid; } - - bool generateData(int exerciseId); + QStringList getEnumerationInsertValues(const QString& table, const QString& dbSchema) const; - bool createStatementsForTable(const QString &tableName, const QString &tableNameOut); + QStringList getReferencedServices() const + { + return m_referencedSevices; + } - SqlStatements getStatements(ExerciseDependency ed) const - { - return (ed == ExerciseDependency::Exercise ? m_sqlExercise : m_sqlGlobal); - } + QStringList getDbSettings(const QString& dbSchema) const; - SqlItems getSqlItems(ExerciseDependency ed) const - { - return (ed == ExerciseDependency::Exercise ? m_sqlItemsExercise : m_sqlItemsGlobal); - } + bool writeSql(const QString& filePath, ExerciseDependency ed); - QStringList getEnumerationInsertValues(const QString &table, const QString &dbSchema) const; - QStringList getReferencedServices() const - { - return m_referencedSevices; - } + bool writeSqlToFile(const QString& dbSchema, const QString& sqlFile, ExerciseDependency ed) const; - QStringList getDbSettings(const QString &dbSchema) const; + QString getServiceAbbr() const + { + return m_xmlReader->getServiceAbbr(); + } - - bool writeSql(const QString &filePath, ExerciseDependency ed); + bool isServiceExerciseIndependent() const + { + return m_xmlReader->isServiceExerciseIndependent(); + } - bool writeSqlToFile(const QString &dbSchema, const QString &sqlFile, ExerciseDependency ed) const; + bool isServiceGlobal() const + { + return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global || + m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise); + } - - QString getServiceAbbr() const { return m_xmlReader->getServiceAbbr(); } - bool isServiceExerciseIndependent() const { return m_xmlReader->isServiceExerciseIndependent(); } - bool isServiceGlobal() const { return (m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::Global || m_xmlReader->defaultExerciseDependency() == CodeGen::ExerciseDependency::GlobalAndExercise); } - CodeGen::ExerciseDependency getExerciseDependency() const { return m_xmlReader->defaultExerciseDependency();} - QStringList getGroupNames() const { return m_xmlReader->getGroupNames(); } + CodeGen::ExerciseDependency getExerciseDependency() const + { + return m_xmlReader->defaultExerciseDependency(); + } - QStringList getAllSqlStmts(const QString &dbSchema, ExerciseDependency ed) const; + QStringList getGroupNames() const + { + return m_xmlReader->getGroupNames(); + } + QStringList getAllSqlStmts(const QString& dbSchema, ExerciseDependency ed) const; -protected: + protected: + NGL::INGLLogger& m_logger; - NGL::INGLLogger &m_logger; -private: - bool handleTables(); - bool handleViews(); - bool handleTable(const CompleteTableInformation &cti); - bool handleView(const ViewInformation &vi); - QString getTableColumnCreateStatements(const QString &tableName, - const QVector &columns, - QStringList *tableComments, ExerciseDependency ed); - QString generateSequence(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed); - void generatePrimaryKey(const QString &tableName, const FullQualifiedColumnInformation &ci, ExerciseDependency ed); - void generateForeignKeys(const QVector > &foreignKeys, ExerciseDependency ed); - void generateForeignKey(const QSharedPointer &foreignKey, ExerciseDependency ed); - void generateConstraints(const QString &tableName, const QVector &constraints, ExerciseDependency ed); - void generateConstraint(const QString &tableName, const ConstraintInformation &constraint, ExerciseDependency ed); - bool handleEnumerations(); - bool handleEnumeration(const EnumInformation &ei); - QStringList handleEnumeration(const EnumInformation &ei, const QString &dbSchema) const; - bool generateDbNotifications(const QString &tableName, const QVector ¬ifications, ExerciseDependency ed); - void generateDbNotification(const DbNotifcationInformation ¬ification, ExerciseDependency ed); - bool generateDbNotificationTrigger(const QString &tableName, const DbNotifcationInformation ¬ification, ExerciseDependency ed); - QString getNotificationFunctionName(const DbNotifcationInformation ¬ification) const; - static QString fixupComment(const QString &comment); + private: + bool handleTables(); + bool handleViews(); + bool handleTable(const CompleteTableInformation& cti); + bool handleView(const ViewInformation& vi); + QString getTableColumnCreateStatements(const QString& tableName, const QVector& columns, + QStringList* tableComments, ExerciseDependency ed); + QString generateSequence(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed); + void generatePrimaryKey(const QString& tableName, const FullQualifiedColumnInformation& ci, ExerciseDependency ed); + void generateForeignKeys(const QVector>& foreignKeys, ExerciseDependency ed); + void generateForeignKey(const QSharedPointer& foreignKey, ExerciseDependency ed); + void generateConstraints(const QString& tableName, const QVector& constraints, + ExerciseDependency ed); + void generateConstraint(const QString& tableName, const ConstraintInformation& constraint, ExerciseDependency ed); + bool handleEnumerations(); + bool handleEnumeration(const EnumInformation& ei); + QStringList handleEnumeration(const EnumInformation& ei, const QString& dbSchema) const; + bool generateDbNotifications(const QString& tableName, const QVector& notifications, + ExerciseDependency ed); + void generateDbNotification(const DbNotifcationInformation& notification, ExerciseDependency ed); + bool generateDbNotificationTrigger(const QString& tableName, const DbNotifcationInformation& notification, + ExerciseDependency ed); + QString getNotificationFunctionName(const DbNotifcationInformation& notification) const; + static QString fixupComment(const QString& comment); -private: - XmlReader *m_xmlReader; - StructBuilder *m_structBuilder; - bool m_createdByXmlFile; + private: + XmlReader* m_xmlReader; + StructBuilder* m_structBuilder; + bool m_createdByXmlFile; - void addToDropSequences(const QString &stmt, ExerciseDependency ed); - void addToDropTables(const QString &stmt, ExerciseDependency ed); - void addToDropViews(const QString &stmt, ExerciseDependency ed); - void addToDropConstraints(const QString &stmt, ExerciseDependency ed); + void addToDropSequences(const QString& stmt, ExerciseDependency ed); + void addToDropTables(const QString& stmt, ExerciseDependency ed); + void addToDropViews(const QString& stmt, ExerciseDependency ed); + void addToDropConstraints(const QString& stmt, ExerciseDependency ed); - void addToCreateConstraints(const QString &stmt, ExerciseDependency ed); - void addToCreateFks(const QString &stmt, ExerciseDependency ed); - void addToCreatePks(const QString &stmt, ExerciseDependency ed); - void addToCreateSequences(const QString &stmt, ExerciseDependency ed); - void addToCreateTables(const QString &stmt, ExerciseDependency ed); - void addToCreateTables(const QStringList &stmts, ExerciseDependency ed); - void addToCreateViews(const QString &stmt, ExerciseDependency ed); + void addToCreateConstraints(const QString& stmt, ExerciseDependency ed); + void addToCreateFks(const QString& stmt, ExerciseDependency ed); + void addToCreatePks(const QString& stmt, ExerciseDependency ed); + void addToCreateSequences(const QString& stmt, ExerciseDependency ed); + void addToCreateTables(const QString& stmt, ExerciseDependency ed); + void addToCreateTables(const QStringList& stmts, ExerciseDependency ed); + void addToCreateViews(const QString& stmt, ExerciseDependency ed); - void addToDbFunctions(const QString &stmt, ExerciseDependency ed); - void addToDbFunctionTrigger(const QString &stmt, ExerciseDependency ed); + void addToDbFunctions(const QString& stmt, ExerciseDependency ed); + void addToDbFunctionTrigger(const QString& stmt, ExerciseDependency ed); - void addToConstraints(const QString &name, ExerciseDependency ed); - void addToFks(const QString &name, ExerciseDependency ed); - void addToPks(const QString &name, ExerciseDependency ed); - void addToSequences(const QString &name, ExerciseDependency ed); - void addToTables(const QString &name, ExerciseDependency ed); + void addToConstraints(const QString& name, ExerciseDependency ed); + void addToFks(const QString& name, ExerciseDependency ed); + void addToPks(const QString& name, ExerciseDependency ed); + void addToSequences(const QString& name, ExerciseDependency ed); + void addToTables(const QString& name, ExerciseDependency ed); - bool writeFile(const QString &fn, const QString &content) const; + bool writeFile(const QString& fn, const QString& content) const; - SqlStatements m_sqlGlobal; - SqlStatements m_sqlExercise; + SqlStatements m_sqlGlobal; + SqlStatements m_sqlExercise; - SqlItems m_sqlItemsGlobal; - SqlItems m_sqlItemsExercise; + SqlItems m_sqlItemsGlobal; + SqlItems m_sqlItemsExercise; - QStringList m_referencedSevices; + QStringList m_referencedSevices; - bool m_isValid; - int m_exerciseId; + bool m_isValid; + int m_exerciseId; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.cpp old mode 100755 new mode 100644 index d41c638e1..6f3c0fdde --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.cpp @@ -1,1430 +1,1360 @@ - #include "StructBuilder.h" +#include #include #include -#include - using namespace CodeGen; - - - class DataTypeInfoIdl : public DataTypeInfo { -protected: - DataTypeInfoIdl(const QString &name, const QString &idlType, bool isPod) - : DataTypeInfo(name, isPod) - , m_idlType(idlType) - {} -public: - QString idlType() const override final { return m_idlType; } -private: - const QString m_idlType; + protected: + DataTypeInfoIdl(const QString& name, const QString& idlType, bool isPod) + : DataTypeInfo(name, isPod), m_idlType(idlType) + { + } + + public: + QString idlType() const override final + { + return m_idlType; + } + + private: + const QString m_idlType; }; class DataTypeInfoSimple : public DataTypeInfoIdl { -public: - DataTypeInfoSimple(const QString &name, - const QString &idlType, - const QString &ddsType, - const QString &sqlType, - const QString &cppType, - bool isPod) - : DataTypeInfoIdl(name, idlType, isPod) - , m_ddsType(ddsType) - , m_sqlType(sqlType) - , m_cppType(cppType) - {} - QString ddsType() const override final { return m_ddsType; } - QString sqlType() const override final { return m_sqlType; } - QString cppType() const override final { return m_cppType; } -protected: - QString m_ddsType; - QString m_sqlType; - QString m_cppType; + public: + DataTypeInfoSimple(const QString& name, const QString& idlType, const QString& ddsType, const QString& sqlType, + const QString& cppType, bool isPod) + : DataTypeInfoIdl(name, idlType, isPod), m_ddsType(ddsType), m_sqlType(sqlType), m_cppType(cppType) + { + } + + QString ddsType() const override final + { + return m_ddsType; + } + + QString sqlType() const override final + { + return m_sqlType; + } + + QString cppType() const override final + { + return m_cppType; + } + + protected: + QString m_ddsType; + QString m_sqlType; + QString m_cppType; }; class DataTypeInfoStructure final : public DataTypeInfoSimple { -public: - DataTypeInfoStructure(const QString &name, const QString &idlType, StructBuilder *structBuilder) - : DataTypeInfoSimple(name, idlType, QString(), idlType, idlType, false) - { - const CompleteTopicTypeInformation ctti = structBuilder->topicTypeInformationByStructType(idlType); - Q_ASSERT(ctti.isValid()); - - m_member.reserve(ctti.members.size()); - for (const IdlData &idlData : ctti.members) - m_member += DataTypeInfo::fromIdlDataType(idlData.name, idlData.type, structBuilder); - m_serviceName = ctti.serviceName; - if (ctti.name.startsWith(m_serviceName + QStringLiteral("::"))) - m_ddsType = ctti.name; - else - m_ddsType = m_serviceName + QStringLiteral("::") + ctti.name; - } - bool isStructure() const override final { return true; } - virtual QVector> member() const override final { return m_member; } -private: - QVector> m_member; - QString m_serviceName; + public: + DataTypeInfoStructure(const QString& name, const QString& idlType, StructBuilder* structBuilder) + : DataTypeInfoSimple(name, idlType, QString(), idlType, idlType, false) + { + const CompleteTopicTypeInformation ctti = structBuilder->topicTypeInformationByStructType(idlType); + Q_ASSERT(ctti.isValid()); + + m_member.reserve(ctti.members.size()); + for (const IdlData& idlData : ctti.members) + m_member += DataTypeInfo::fromIdlDataType(idlData.name, idlData.type, structBuilder); + m_serviceName = ctti.serviceName; + if (ctti.name.startsWith(m_serviceName + QStringLiteral("::"))) + m_ddsType = ctti.name; + else + m_ddsType = m_serviceName + QStringLiteral("::") + ctti.name; + } + + bool isStructure() const override final + { + return true; + } + + virtual QVector> member() const override final + { + return m_member; + } + + private: + QVector> m_member; + QString m_serviceName; }; class DataTypeInfoSequence final : public DataTypeInfoIdl { -public: - DataTypeInfoSequence(const QString &name, const QString &idlType, StructBuilder *structBuilder, const QString &svcName) - : DataTypeInfoIdl(name, idlType, false) - { - - const int start = idlType.indexOf(QLatin1Char('<')); - const int end = idlType.lastIndexOf(QLatin1Char('>')); - Q_ASSERT(start >= 0 && end >= 0 && end > start); - const QString inner = idlType.mid(start + 1, end - start - 1); - m_innerDataType = DataTypeInfo::fromIdlDataType(QStringLiteral("inner"), inner, structBuilder, svcName); - Q_ASSERT(m_innerDataType); - } + public: + DataTypeInfoSequence(const QString& name, const QString& idlType, StructBuilder* structBuilder, + const QString& svcName) + : DataTypeInfoIdl(name, idlType, false) + { - QString ddsType() const override final - { - return QLatin1String("std::vector<") + m_innerDataType->ddsType() + QLatin1Char('>'); - } - QString sqlType() const override final - { - return QStringLiteral("jsonb"); - } - QString cppType() const override final - { - return QLatin1String("std::vector<") + m_innerDataType->cppType() + QLatin1Char('>'); - } - QString cppTypeConstRef() const override final - { - return QLatin1String("const std::vector<") + m_innerDataType->cppType() + QLatin1String("> &"); - } - virtual bool isSequence() const override final { return true; } - QSharedPointer innerDataType() const override final { return m_innerDataType; } -private: - QSharedPointer m_innerDataType; + const int start = idlType.indexOf(QLatin1Char('<')); + const int end = idlType.lastIndexOf(QLatin1Char('>')); + Q_ASSERT(start >= 0 && end >= 0 && end > start); + const QString inner = idlType.mid(start + 1, end - start - 1); + m_innerDataType = DataTypeInfo::fromIdlDataType(QStringLiteral("inner"), inner, structBuilder, svcName); + Q_ASSERT(m_innerDataType); + } + + QString ddsType() const override final + { + return QLatin1String("std::vector<") + m_innerDataType->ddsType() + QLatin1Char('>'); + } + + QString sqlType() const override final + { + return QStringLiteral("jsonb"); + } + + QString cppType() const override final + { + return QLatin1String("std::vector<") + m_innerDataType->cppType() + QLatin1Char('>'); + } + + QString cppTypeConstRef() const override final + { + return QLatin1String("const std::vector<") + m_innerDataType->cppType() + QLatin1String("> &"); + } + + virtual bool isSequence() const override final + { + return true; + } + + QSharedPointer innerDataType() const override final + { + return m_innerDataType; + } + + private: + QSharedPointer m_innerDataType; }; -QSharedPointer DataTypeInfo::fromIdlDataType(const QString &name, - const QString &idlType, - StructBuilder *structBuilder, - const QString &svcName) +QSharedPointer DataTypeInfo::fromIdlDataType(const QString& name, const QString& idlType, + StructBuilder* structBuilder, const QString& svcName) { - const QString fullIdlType = (svcName.isEmpty() || idlType.contains(QLatin1String("::"))) - ? idlType : svcName + QLatin1String("::") + idlType; + const QString fullIdlType = (svcName.isEmpty() || idlType.contains(QLatin1String("::"))) + ? idlType + : svcName + QLatin1String("::") + idlType; - if (idlType == QLatin1String("sequence")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("std::vector"), - QStringLiteral("bytea"), - QStringLiteral("QByteArray"), - false)); - if (idlType == QLatin1String("boolean")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("bool"), - QStringLiteral("boolean"), - QStringLiteral("bool"), - true)); - if (idlType == QLatin1String("char")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("char"), - QStringLiteral("char"), - QStringLiteral("char"), - true)); - if (idlType == QLatin1String("double")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("double"), - QStringLiteral("double precision"), - QStringLiteral("double"), - true)); - if (idlType == QLatin1String("long")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("int32_t"), - QStringLiteral("integer"), - QStringLiteral("qint32"), - true)); - if (idlType == QLatin1String("long long")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("rti::core::int64"), - QStringLiteral("bigint"), - QStringLiteral("qint64"), - true)); - if (idlType == QLatin1String("short")) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("int16_t"), - QStringLiteral("smallint"), - QStringLiteral("qint16"), - true)); - if (idlType.startsWith(QLatin1String("string"))) - return QSharedPointer(new DataTypeInfoSimple(name, - idlType, - QStringLiteral("std::string"), - QStringLiteral("text"), - QStringLiteral("std::string"), - false)); - if (idlType.startsWith(QLatin1String("sequence"))) - return QSharedPointer(new DataTypeInfoSequence(name, idlType, structBuilder, svcName)); + if (idlType == QLatin1String("sequence")) + return QSharedPointer( + new DataTypeInfoSimple(name, idlType, QStringLiteral("std::vector"), QStringLiteral("bytea"), + QStringLiteral("QByteArray"), false)); + if (idlType == QLatin1String("boolean")) + return QSharedPointer(new DataTypeInfoSimple( + name, idlType, QStringLiteral("bool"), QStringLiteral("boolean"), QStringLiteral("bool"), true)); + if (idlType == QLatin1String("char")) + return QSharedPointer(new DataTypeInfoSimple( + name, idlType, QStringLiteral("char"), QStringLiteral("char"), QStringLiteral("char"), true)); + if (idlType == QLatin1String("double")) + return QSharedPointer(new DataTypeInfoSimple(name, idlType, QStringLiteral("double"), + QStringLiteral("double precision"), + QStringLiteral("double"), true)); + if (idlType == QLatin1String("long")) + return QSharedPointer(new DataTypeInfoSimple( + name, idlType, QStringLiteral("int32_t"), QStringLiteral("integer"), QStringLiteral("qint32"), true)); + if (idlType == QLatin1String("long long")) + return QSharedPointer(new DataTypeInfoSimple(name, idlType, QStringLiteral("rti::core::int64"), + QStringLiteral("bigint"), QStringLiteral("qint64"), + true)); + if (idlType == QLatin1String("short")) + return QSharedPointer(new DataTypeInfoSimple( + name, idlType, QStringLiteral("int16_t"), QStringLiteral("smallint"), QStringLiteral("qint16"), true)); + if (idlType.startsWith(QLatin1String("string"))) + return QSharedPointer(new DataTypeInfoSimple(name, idlType, QStringLiteral("std::string"), + QStringLiteral("text"), + QStringLiteral("std::string"), false)); + if (idlType.startsWith(QLatin1String("sequence"))) + return QSharedPointer(new DataTypeInfoSequence(name, idlType, structBuilder, svcName)); - - const EnumInformation ei = structBuilder->enumInformationByType(fullIdlType, true, false); - if (ei.isValid()) - return QSharedPointer(new DataTypeInfoSimple(name, idlType, ei.enumName, QStringLiteral("integer"), ei.enumName, true)); + const EnumInformation ei = structBuilder->enumInformationByType(fullIdlType, true, false); + if (ei.isValid()) + return QSharedPointer( + new DataTypeInfoSimple(name, idlType, ei.enumName, QStringLiteral("integer"), ei.enumName, true)); - - const CompleteTopicTypeInformation ctti = structBuilder->topicTypeInformationByStructType(fullIdlType, true); - if (ctti.isValid()) - return QSharedPointer(new DataTypeInfoStructure(name, idlType, structBuilder)); + const CompleteTopicTypeInformation ctti = structBuilder->topicTypeInformationByStructType(fullIdlType, true); + if (ctti.isValid()) + return QSharedPointer(new DataTypeInfoStructure(name, idlType, structBuilder)); - - return QSharedPointer(new DataTypeInfoSimple(name, idlType, idlType, QStringLiteral("integer"), idlType, true)); + return QSharedPointer( + new DataTypeInfoSimple(name, idlType, idlType, QStringLiteral("integer"), idlType, true)); } - - - - -StructBuilder::StructBuilder(XmlReader *xmlReader) - : m_needPoint3d(false) - , m_needPgArrayInclude(false) - , m_xmlReader(xmlReader) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CodeGen.StructBuilder")) - , m_loggerCSV(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("fileCSV")) -{} +StructBuilder::StructBuilder(XmlReader* xmlReader) + : m_needPoint3d(false), m_needPgArrayInclude(false), m_xmlReader(xmlReader), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("CodeGen.StructBuilder")), + m_loggerCSV(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("fileCSV")) +{ +} bool StructBuilder::buildStructures() { - m_structInfos.clear(); - m_topicTypeInfos.clear(); - m_enumInfos.clear(); - m_sqlTableInformations.clear(); - m_sqlTableInformationsAlreadyAvailable.clear(); - m_sqlViewInformations.clear(); - m_externalTopicTypes.clear(); - m_serializeFromToJsonTopics.clear(); - m_jsonStructureInformation.clear(); + m_structInfos.clear(); + m_topicTypeInfos.clear(); + m_enumInfos.clear(); + m_sqlTableInformations.clear(); + m_sqlTableInformationsAlreadyAvailable.clear(); + m_sqlViewInformations.clear(); + m_externalTopicTypes.clear(); + m_serializeFromToJsonTopics.clear(); + m_jsonStructureInformation.clear(); - m_needPoint3d = false; - m_needPgArrayInclude = false; + m_needPoint3d = false; + m_needPgArrayInclude = false; - - const QMap > tables = m_xmlReader->getTables(); - for (const QSharedPointer &ti : tables) - { - CompleteTableInformation cti(*ti); - if (cti.exerciseDependency == ExerciseDependency::Undefined) - cti.exerciseDependency = m_xmlReader->defaultExerciseDependency(); - - m_sqlTableInformations[ti->name] = cti; - } - - const QMap > views = m_xmlReader->getViews(); - for (const QSharedPointer &vi : views) - { - ViewInformation cti(*vi); - if (cti.exerciseDependency == ExerciseDependency::Undefined) - cti.exerciseDependency = m_xmlReader->defaultExerciseDependency(); - - m_sqlViewInformations[vi->name] = cti; - } - - - const QVector enumData = m_xmlReader->getEnumerations(); - for (const EnumInformation &ei : enumData) - { - if (!handleEnum(ei)) - return false; - } - - const QVector structsToGenerate = m_xmlReader->getStructToGenerate(); - for (const ServiceStructInformation &ssi : structsToGenerate) - { - if (!handleTable(ssi)) - return false; - } - - const QVector idlStructsToGenerate = m_xmlReader->getIdlStructToGenerate(); - for (const TopicTypeInformation &tti : idlStructsToGenerate) - { - DEBUG_LOG(m_loggerCSV) << tti.name; - if (!handleIdlStructInfo(tti, m_topicTypeInfos)) - return false; - } - const QVector idlExternalTopicTypes = m_xmlReader->getExternalTopicTypes(); - for (const TopicTypeInformation &tti : idlExternalTopicTypes) - { - const ServiceTypeStruct sts = extractServiceAndTypeFromTypename(tti.name); - if (!sts.isExternalType()) + const QMap> tables = m_xmlReader->getTables(); + for (const QSharedPointer& ti : tables) { - ERROR_LOG(m_logger) << "Invalid external topic type name: '" << tti.name << "'"; - return false; + CompleteTableInformation cti(*ti); + if (cti.exerciseDependency == ExerciseDependency::Undefined) + cti.exerciseDependency = m_xmlReader->defaultExerciseDependency(); + + m_sqlTableInformations[ti->name] = cti; } - if (!handleIdlStructInfo(tti, m_externalTopicTypes, sts.service)) - return false; - } - return true; -} - -bool StructBuilder::handleEnum(const EnumInformation &ei) -{ - m_enumInfos.push_back(ei); - - - if (ei.tableName.isEmpty()) - return true; - - QSharedPointer ti = m_xmlReader->getTable(ei.tableName); - if (ti.isNull()) - { - WARNING_LOG(m_logger) << "Could not find table information for enum: " - << ei.enumName << ", table: " << ei.tableName; - return false; - } - - CompleteTableInformation cti = m_sqlTableInformations[ei.tableName]; - for (const ColumnInformation &ci : std::as_const(ti->plainColumns)) - { - MemberInformation mi; - mi.db = FullQualifiedColumnInformation(ci, ei.tableName); - cti.columns.push_back(std::move(mi)); - } - m_sqlTableInformations[ei.tableName] = cti; - - return true; -} - -CompleteStructInformation StructBuilder::structInformationByTableName(const QString &tableName) const -{ - for (const CompleteStructInformation &csi : m_structInfos) - { - if (csi.primaryTable->name == tableName) - return csi; - } - return CompleteStructInformation(); -} - -EnumInformation StructBuilder::enumInformationByType(const QString &type, bool checkExternals, bool verbose) -{ - if (type.isEmpty()) - return EnumInformation(); - const ServiceTypeStruct extInfo = extractServiceAndTypeFromTypename(type); - if (extInfo.isExternalType()) - { - if (!checkExternals) + const QMap> views = m_xmlReader->getViews(); + for (const QSharedPointer& vi : views) { - ERROR_LOG(m_logger) << "Could not find enumeration '" << type << "'"; - return EnumInformation(); + ViewInformation cti(*vi); + if (cti.exerciseDependency == ExerciseDependency::Undefined) + cti.exerciseDependency = m_xmlReader->defaultExerciseDependency(); + + m_sqlViewInformations[vi->name] = cti; } - if (extInfo.type.isEmpty()) + + const QVector enumData = m_xmlReader->getEnumerations(); + for (const EnumInformation& ei : enumData) { - WARNING_LOG(m_logger) << "Could not parse external enumeration '" << type << "'"; - return EnumInformation(); + if (!handleEnum(ei)) + return false; } - return m_xmlReader->getExternalEnumeration(extInfo.service, extInfo.type, verbose); - } - for (const EnumInformation &ei : std::as_const(m_enumInfos)) - { - if (ei.enumName == type) - return ei; - } - if (verbose) - ERROR_LOG(m_logger) << "Could not find enumeration '" << type << "'"; - return EnumInformation(); -} - -CompleteTopicTypeInformation StructBuilder::topicTypeInformationByStructType(const QString &type, bool checkExternals) -{ - DEBUG_LOG(m_logger) << "topicTypeInformationByStructType(" << type << ")"; - if (type.isEmpty()) - return CompleteTopicTypeInformation(); - - const ServiceTypeStruct extInfo = extractServiceAndTypeFromTypename(type); - if (extInfo.isExternalType()) - { - if (!checkExternals) - return CompleteTopicTypeInformation(); - - return externalTopicTypeByStructType(extInfo); - } - for (const CompleteTopicTypeInformation &csi : std::as_const(m_topicTypeInfos)) - { - if (csi.name == type) - return csi; - } - - DEBUG_LOG(m_logger) << "Type '" << type << "' not found in idlStructs - maybe not yet exported or an enum"; - const QVector idlStructsToGenerate = m_xmlReader->getIdlStructToGenerate(); - for (const TopicTypeInformation &tti : idlStructsToGenerate) - { - if (tti.name == type) + const QVector structsToGenerate = m_xmlReader->getStructToGenerate(); + for (const ServiceStructInformation& ssi : structsToGenerate) { - DEBUG_LOG(m_logger) << "Found not yet exported type " << type; - if (!handleIdlStructInfo(tti, m_topicTypeInfos)) - return CompleteTopicTypeInformation(); - return topicTypeInformationByStructType(type); + if (!handleTable(ssi)) + return false; } - } - ERROR_LOG(m_logger) << "Could not find type '" << type << "' in idlStructs"; - return CompleteTopicTypeInformation(); -} -CompleteTopicTypeInformation StructBuilder::externalTopicTypeByStructType(const ServiceTypeStruct &sts) -{ - const QString typeToSearch = sts.fqType(); - DEBUG_LOG(m_logger) << "externalTopicTypeByStructType " << typeToSearch; - for (const CompleteTopicTypeInformation &ctti : std::as_const(m_externalTopicTypes)) - { - if (ctti.name == typeToSearch) - return ctti; - } - if (!loadExternalTopicType(sts)) - return CompleteTopicTypeInformation(); - return externalTopicTypeByStructType(sts); -} - -bool StructBuilder::loadExternalTopicType(const ServiceTypeStruct &sts) -{ - DEBUG_LOG(m_logger) << "loadExternalTopicType(" << sts.fqType() << ")"; - - - const TopicTypeInformation tti = m_xmlReader->loadExternalTopicType(sts.service, sts.type); - if (!tti.isValid()) - { - DEBUG_LOG(m_logger) << "Could not find external topic '" << sts.fqType() << "'"; - return false; - } - - if (!handleIdlStructInfo(tti, m_externalTopicTypes, sts.service)) - return false; - return true; -} - - -bool StructBuilder::getColumnsFromTable(const QString &tableName, - QVector &columns, - QVector &tableNames) const -{ - if (tableName.isEmpty()) - return true; - - const QString parentTable = m_xmlReader->getStruct2BaseClassRelations().value(tableName); - if (!getColumnsFromTable(parentTable, columns, tableNames)) - return false; - tableNames += tableName; - const QSharedPointer ti = m_xmlReader->getTable(tableName); - QVector constraints; - constraints.reserve(ti->constraints.size()); - for (const ConstraintInformation &ci : std::as_const(ti->constraints)) - { - if (ci.affectedColumns.size() != 1) - continue; - if (ci.type != ConstraintInformation::Type::index) - continue; - constraints += ci; - } - - columns.reserve(columns.size() + ti->plainColumns.size()); - for (const auto &plainColum : std::as_const(ti->plainColumns)) - { - ColumnInformationEx cie(ColumnInformationEx(plainColum, ti)); - for (int j = 0; j < constraints.size(); ++j) + const QVector idlStructsToGenerate = m_xmlReader->getIdlStructToGenerate(); + for (const TopicTypeInformation& tti : idlStructsToGenerate) { - const ConstraintInformation &ci = constraints.at(j); - if (ci.affectedColumns.first() == cie.columnName) - { - cie.generateSelectRemove = true; - constraints.remove(j); - break; - } + DEBUG_LOG(m_loggerCSV) << tti.name; + if (!handleIdlStructInfo(tti, m_topicTypeInfos)) + return false; } - columns += cie; - } - return true; -} - -bool StructBuilder::handleTable(const ServiceStructInformation &ssi) -{ - DEBUG_LOG(m_loggerCSV) << "StructInfo name: #" << ssi.name; - - CompleteStructInformation csi; - csi.structName = ssi.name; - csi.primaryTable = m_xmlReader->getTable(ssi.primaryTable); - csi.viewName = csi.primaryTable->name + QLatin1String("_view"); - csi.hasStaticContent = ssi.hasStaticContent; - csi.dbNotifications = ssi.dbNotifications; - - DEBUG_LOG(m_loggerCSV) << "primaryTable: " << csi.primaryTable.data(); - DEBUG_LOG(m_loggerCSV) << "hasStaticContent: " << csi.hasStaticContent; - - - QVector columns; - QVector tableNames; - if (!getColumnsFromTable(ssi.primaryTable, columns, tableNames)) - { - WARNING_LOG(m_logger) << "Could not retrieve columns from table " - << ssi.primaryTable; - return false; - } - DEBUG_LOG(m_logger) << "Got " << columns.size() << " columns for table " - << ssi.primaryTable; - - QSet sqlTables; - - - csi.member.reserve(columns.size() + 1); - MemberInformation miPkFirstTable, miPkLastTable; - for (const ColumnInformationEx &ci : std::as_const(columns)) - { - DEBUG_LOG(m_logger) << "handling column " << ci.columnName; - - const QSharedPointer ti = ci.table; - if (ti.isNull()) + const QVector idlExternalTopicTypes = m_xmlReader->getExternalTopicTypes(); + for (const TopicTypeInformation& tti : idlExternalTopicTypes) { - WARNING_LOG(m_logger) << "Could not find table for column " << ci.columnName - << " primary table is " << ssi.primaryTable.data(); - return false; - } - csi.tables += ti; - sqlTables += ti->name; - - MemberInformation memberInfo; - memberInfo.ea.column = ci.columnName; - memberInfo.ea.table = ti->name; - memberInfo.ea.type = ci.datatype; - - memberInfo.db = FullQualifiedColumnInformation(ci, memberInfo.ea.table); - - if (ci.hasSequence) - { - memberInfo.db.usedForInsert = !ci.isPrimaryKey; - memberInfo.db.hasSequence = true; - } - else - memberInfo.db.usedForInsert = true; - - memberInfo.db.usedForView = !ci.isPrimaryKey; - - memberInfo.cpp.structName = ssi.name; - memberInfo.cpp.memberName = camelCaseString(ci.columnName); - memberInfo.cpp.type = ci.datatype; - memberInfo.cpp.usedForCppStruct = !ci.isPrimaryKey; - - if (ci.isForeignKey) - { - const QSharedPointer fki = ti->fkInformationForColumn(ti->name, ci.columnName); - if (!fki.isNull()) - { - - for(const auto &tbl : std::as_const(csi.tables)) + const ServiceTypeStruct sts = extractServiceAndTypeFromTypename(tti.name); + if (!sts.isExternalType()) { - if (tbl->name == fki->destination.tableName) - { - memberInfo.cpp.isReadOnly = true; - memberInfo.fk = fki; - memberInfo.cpp.memberName = QLatin1String("priv_") + memberInfo.cpp.memberName; - break; - } - } - - if (memberInfo.fk.isNull()) - { - - if (fki->destination.service.isEmpty()) - { - - for (const EnumInformation &ei : std::as_const(m_enumInfos)) - { - if (ei.tableName == fki->destination.tableName) - { - memberInfo.enumeration = QSharedPointer(new EnumInformation(ei)); - break; - } - } - } - else - { - - QString enumType = fki->destination.service + QStringLiteral("::") + - camelCaseString(fki->destination.tableName, true); - - EnumInformation ei = enumInformationByType(enumType, true, false); - DEBUG_LOG(m_logger) << "Checking if " << enumType << " is an enum: " << ei.isValid(); - if (!ei.isValid() && fki->destination.tableName.contains(QLatin1Char('_'))) - { - - enumType = fki->destination.service + QStringLiteral("::") + - camelCaseString(fki->destination.tableName.section(QLatin1Char('_'), 1), true); - ei = enumInformationByType(enumType, true, false); - DEBUG_LOG(m_logger) << "Checking if " << enumType << " is an enum: " << ei.isValid(); - } - if (ei.isValid() && - ei.tableName == fki->destination.tableName) - memberInfo.enumeration = QSharedPointer(new EnumInformation(ei)); - } - } - } - } - MemberInformation memberInfoJson = memberInfo; - memberInfoJson.cpp.usedForJson = true; - memberInfoJson.cpp.usedForCppStruct = false; - memberInfoJson.db.isForeignKey = false; - memberInfoJson.db.generateSelectRemove = false; - memberInfoJson.db.usedForView = false; - memberInfoJson.db.usedForInsert = false; - - if (ci.isOptional) - { - memberInfo.cpp.isOptional = true; - memberInfoJson.cpp.isOptional = true; - memberInfo.ea.type = QStringLiteral("QVariant"); - memberInfo.cpp.type = memberInfo.ea.type; - } - - if (!fixupCustomDbDatatypes(memberInfo, csi.member) || - !fixupQVariantConversions(memberInfo)) - return false; - - if (!fixupCustomDbDatatypes(memberInfoJson, csi.member) || - !fixupQVariantConversions(memberInfoJson)) - return false; - - if (ci.isPrimaryKey && tableNames.first() == ti->name) - { - - miPkFirstTable = memberInfo; - } - if (ci.isPrimaryKey && tableNames.last() == ti->name) - { - - miPkLastTable = memberInfo; - } - - csi.member.push_back(memberInfo); - csi.member.push_back(memberInfoJson); - - addToSqlTableInformation(memberInfo); - - DEBUG_LOG(m_loggerCSV) << memberInfo.toString(); - } - - if (!miPkFirstTable.isEmpty()) - { - miPkFirstTable.db.usedForInsert = false; - miPkFirstTable.db.usedForView = true; - miPkFirstTable.cpp.usedForCppStruct = true; - csi.member.push_front(miPkFirstTable); - } - - if (tableNames.size() > 1 && !miPkLastTable.isEmpty()) - { - - - miPkLastTable.db.usedForInsert = false; - miPkLastTable.db.usedForView = true; - miPkLastTable.cpp.usedForCppStruct = true; - miPkLastTable.db.isAssignmentForPrimaryTablePk = true; - miPkLastTable.db.columnNameView = - miPkLastTable.db.table + QLatin1Char('_') + miPkLastTable.db.columnName; - - QString name = miPkLastTable.db.table; - if (name.startsWith(m_xmlReader->getServiceAbbr().toLower())) - name = name.mid(m_xmlReader->getServiceAbbr().size() + 1); - miPkLastTable.cpp.memberName = camelCaseString(QLatin1String("priv_") + name + QLatin1String("_id")); - csi.member.push_back(miPkLastTable); - } - - - m_structInfos.push_back(csi); - - m_sqlTableInformationsAlreadyAvailable += sqlTables; - return true; -} - -bool StructBuilder::handleIdlStructInfo(const TopicTypeInformation &tti, - QVector &destination, - const QString &svcName) -{ - - for (const CompleteTopicTypeInformation &c : std::as_const(destination)) - { - if (c.name == tti.name) - return true; - } - - CompleteTopicTypeInformation ctti(tti); - ctti.members.reserve(tti.columns.size()); - - - for (const auto &ci : tti.columns) - { - IdlData idlData(ci); - idlData.dataTypeInfo = DataTypeInfo::fromIdlDataType(idlData.name, idlData.type, this, svcName); - ctti.members.push_back(idlData); - - - if (idlData.isKey && idlData.isOptional) - { - ERROR_LOG(m_logger) << "Column option isKey & isOptional are mutually exclusive!"; - ERROR_LOG(m_logger) << "Change column '" << tti.name << "." - << idlData.name << "'' to have either key or optional parameter "; - return false; - } - } - - - if (!svcName.isEmpty() && - !ctti.baseValueType.isEmpty() && - !ctti.baseValueType.contains(QLatin1String("::"))) - ctti.baseValueType = svcName + QStringLiteral("::") + ctti.baseValueType; - - ctti.serviceName = svcName.isEmpty() ? m_xmlReader->getServiceNamespace() : svcName; - - destination.push_back(ctti); - - return true; -} - -bool StructBuilder::fixupCustomDbDatatypes(MemberInformation &memberInfo, QVector &members) -{ - if (!fixupDatatypePoint2d(memberInfo, members)) - return false; - if (!fixupDatatypePoint3d(memberInfo, members)) - return false; - if (!fixupDatatypeIntegerArray(memberInfo)) - return false; - return true; -} - -bool StructBuilder::fixupDatatypePoint2d(MemberInformation &memberInfo, - QVector &members) -{ - if (memberInfo.ea.type.toLower() != QLatin1String("point_2d")) - return true; - - MemberInformation mi = memberInfo; - mi.db.datatype = QStringLiteral("double precision"); - mi.cpp.type = QStringLiteral("QPointF"); - mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); - - - MemberInformation miX = mi; - MemberInformation miY = mi; - - miX.db.columnName = memberInfo.db.columnName + QLatin1String("_x"); - miY.db.columnName = memberInfo.db.columnName + QLatin1String("_y"); - - miY.cpp.usedForCppStruct = false; - miY.cpp.usedForJson = false; - - miX.cpp.toVariantPost = QStringLiteral(".x()"); - miY.cpp.toVariantPost = QStringLiteral(".y()"); - - miX.cpp.fromVariantPre1 = QStringLiteral(".rx()"); - miY.cpp.fromVariantPre1 = QStringLiteral(".ry()"); - - miX.cpp.memberName = camelCaseString(miX.cpp.memberName); - - - miX.cpp.toJsonPre = QStringLiteral("toJson("); - miX.cpp.toJsonPost = QStringLiteral(")"); - miX.cpp.fromJsonPre2 = QStringLiteral("fromJson("); - miX.cpp.fromJsonPost = QStringLiteral(")"); - - members.push_back(miX); - - if (memberInfo.cpp.usedForCppStruct) - addToSqlTableInformation(miX); - - DEBUG_LOG(m_loggerCSV) << miX.toString(); - - memberInfo = miY; - - return true; -} - -bool StructBuilder::fixupDatatypePoint3d(MemberInformation &memberInfo, - QVector &members) -{ - if (memberInfo.ea.type.toLower() != QLatin1String("point_3d")) - return true; - - MemberInformation mi = memberInfo; - mi.db.datatype = QStringLiteral("double precision"); - mi.cpp.type = QStringLiteral("LtsUtils::QPoint3D"); - mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); - - - MemberInformation miX = mi; - MemberInformation miY = mi; - MemberInformation miZ = mi; - - miX.db.columnName = memberInfo.db.columnName + QLatin1String("_x"); - miY.db.columnName = memberInfo.db.columnName + QLatin1String("_y"); - miZ.db.columnName = memberInfo.db.columnName + QLatin1String("_z"); - - miY.cpp.usedForCppStruct = false; - miZ.cpp.usedForCppStruct = false; - miY.cpp.usedForJson = false; - miZ.cpp.usedForJson = false; - - miX.cpp.toVariantPost = QStringLiteral(".x()"); - miY.cpp.toVariantPost = QStringLiteral(".y()"); - miZ.cpp.toVariantPost = QStringLiteral(".z()"); - - miX.cpp.fromVariantPre1 = QStringLiteral(".rx()"); - miY.cpp.fromVariantPre1 = QStringLiteral(".ry()"); - miZ.cpp.fromVariantPre1 = QStringLiteral(".rz()"); - - miX.cpp.memberName = camelCaseString(miX.cpp.memberName); - - - miX.cpp.toJsonPre = QStringLiteral("toJson("); - miX.cpp.toJsonPost = QStringLiteral(")"); - miX.cpp.fromJsonPre2 = QStringLiteral("fromJson("); - miX.cpp.fromJsonPost = QStringLiteral(")"); - - members.push_back(miX); - members.push_back(miY); - - if (memberInfo.cpp.usedForCppStruct) - { - addToSqlTableInformation(miX); - addToSqlTableInformation(miY); - } - DEBUG_LOG(m_loggerCSV) << miX.toString(); - - memberInfo = miZ; - - m_needPoint3d = true; - - return true; -} - -bool StructBuilder::fixupDatatypeIntegerArray(MemberInformation &memberInfo) -{ - - if (memberInfo.ea.type.toLower() == QLatin1String("integer[]")) - { - memberInfo.db.datatype = memberInfo.ea.type.toLower(); - memberInfo.cpp.type = QStringLiteral("LtsUtils::IntArray"); - memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::IntArray::fromPgString("); - memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); - memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); - - m_needPgArrayInclude = true; - } - else if (memberInfo.ea.type.toLower() == QLatin1String("bigint[]")) - { - memberInfo.db.datatype = memberInfo.ea.type.toLower(); - memberInfo.cpp.type = QStringLiteral("LtsUtils::BigintArray"); - memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::BigintArray::fromPgString("); - memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); - memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); - - m_needPgArrayInclude = true; - } - else if (memberInfo.cpp.type.toLower() == QLatin1String("sequence")) - { - memberInfo.db.datatype = QStringLiteral("integer[]"); - memberInfo.cpp.type = QStringLiteral("std::vector"); - memberInfo.cpp.fromVariantPre2 = QStringLiteral("std::vector(LtsUtils::IntArray::fromPgString("); - memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())())"); - memberInfo.cpp.toVariantPre = QStringLiteral("LtsUtils::IntArray("); - memberInfo.cpp.toVariantPost = QStringLiteral(").toPgString()"); - - m_needPgArrayInclude = true; - } - else if (memberInfo.ea.type.toLower() == QLatin1String("integer[][]")) - { - memberInfo.db.datatype = memberInfo.ea.type.toLower(); - memberInfo.cpp.type = QStringLiteral("LtsUtils::IntArray2D"); - memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::IntArray2D::fromPgString("); - memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); - memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); - - m_needPgArrayInclude = true; - } - else if (memberInfo.ea.type.toLower() == QLatin1String("bigint[][]")) - { - memberInfo.db.datatype = memberInfo.ea.type.toLower(); - memberInfo.cpp.type = QStringLiteral("LtsUtils::BigintArray2D"); - memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::BigintArray2D::fromPgString("); - memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); - memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); - - m_needPgArrayInclude = true; - } - - return true; -} - - -bool StructBuilder::fixupQVariantConversions(MemberInformation &mi) const -{ - - if (!mi.cpp.toVariantPost.isEmpty()) - return true; - mi.cpp.toVariantPre.clear(); - mi.cpp.toVariantPost.clear(); - mi.cpp.fromVariantPre1.clear(); - mi.cpp.fromVariantPre2.clear(); - mi.cpp.fromVariantPost.clear(); - - if (mi.enumeration) - { - QString svcName(mi.enumeration->serviceName); - if (!svcName.isEmpty()) - svcName += QStringLiteral("::"); - mi.cpp.type = svcName + mi.enumeration->enumName; - mi.cpp.fromVariantPre2 = QStringLiteral("static_cast<") + - svcName + mi.enumeration->enumName + - QStringLiteral("_def::type>("); - mi.cpp.fromVariantPost = QStringLiteral(".toInt())"); - mi.cpp.toVariantPre = QStringLiteral("static_cast("); - mi.cpp.toVariantPost = QStringLiteral(".underlying())"); - if (!mi.enumeration->values.isEmpty()) - { - mi.cpp.defaultValue = svcName + mi.enumeration->enumName + QStringLiteral("::") + - mi.enumeration->values.first().key; - } - return true; - } - const QString datatype = mi.cpp.type.toLower(); - if (datatype == QLatin1String("bigint") || - datatype == QLatin1String("qint64") || - datatype == QLatin1String("long long")) - { - mi.cpp.type = QStringLiteral("qint64"); - mi.cpp.fromVariantPost = QStringLiteral(".toLongLong()"); - mi.cpp.fromJsonPost = QStringLiteral(".toDouble()"); - mi.cpp.defaultValue = QLatin1Char('0'); - } - else if (datatype == QLatin1String("boolean") || - datatype == QLatin1String("bool")) - { - mi.cpp.type = QStringLiteral("bool"); - mi.cpp.fromVariantPost = QStringLiteral(".toBool()"); - mi.cpp.defaultValue = QStringLiteral("false"); - } - else if (datatype == QLatin1String("bytea") || - datatype == QLatin1String("QByteArray")) - { - - mi.cpp.type = QStringLiteral("QByteArray"); - mi.cpp.fromVariantPost = QStringLiteral(".toByteArray()"); - mi.cpp.toJsonPre = QStringLiteral("QString::fromLatin1("); - mi.cpp.toJsonPost = QStringLiteral(".toBase64())"); - mi.cpp.fromJsonPre2 = QStringLiteral("QByteArray::fromBase64("); - mi.cpp.fromJsonPost = QStringLiteral(".toString().toLatin1())"); - mi.cpp.defaultValue.clear(); - } - else if (datatype == QLatin1String("sequence")) - { - - mi.cpp.type = QStringLiteral("QByteArray"); - mi.cpp.ddsType = QStringLiteral("std::vector"); - - mi.cpp.toVariantPre = QStringLiteral("octetSequenceToQVariant("); - mi.cpp.toVariantPost = QStringLiteral(")"); - - mi.cpp.fromVariantPre2 = QStringLiteral("qVariantToOctetSequence("); - mi.cpp.fromVariantPost = QStringLiteral(")"); - - mi.cpp.toJsonPre = QStringLiteral("toJson("); - mi.cpp.toJsonPost = QStringLiteral(")"); - mi.cpp.fromJsonPre2 = QStringLiteral("fromJson>("); - mi.cpp.fromJsonPost = QStringLiteral(")"); - - mi.cpp.defaultValue.clear(); - } - else if (datatype == QLatin1String("char")) - { - mi.cpp.type = QStringLiteral("char"); - mi.cpp.fromVariantPost = QStringLiteral(".toChar().toLatin1()"); - mi.cpp.fromJsonPost = QStringLiteral(".toInt()"); - mi.cpp.defaultValue = QStringLiteral("\\0"); - } - else if (datatype == QLatin1String("integer") || - datatype == QLatin1String("qint32") || - datatype == QLatin1String("long")) - { - mi.cpp.type = QStringLiteral("qint32"); - mi.cpp.fromVariantPost = QStringLiteral(".toInt()"); - mi.cpp.defaultValue = QLatin1Char('0'); - } - else if (datatype == QLatin1String("real") || - datatype == QLatin1String("double") || - datatype == QLatin1String("double precision") || - datatype == QLatin1String("float")) - { - mi.cpp.type = QStringLiteral("double"); - mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); - mi.cpp.defaultValue = QStringLiteral("0.0"); - mi.db.datatype = QStringLiteral("double precision"); - } - else if (datatype == QLatin1String("numeric") || - datatype == QLatin1String("decimal")) - { - mi.cpp.type = QStringLiteral("double"); - mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); - mi.cpp.defaultValue = QStringLiteral("0.0"); - mi.db.datatype = QStringLiteral("numeric"); - } - else if (datatype == QLatin1String("smallint") || - datatype == QLatin1String("qint16") || - datatype == QLatin1String("short")) - { - mi.cpp.type = QStringLiteral("qint16"); - mi.cpp.fromVariantPost = QStringLiteral(".toInt()"); - mi.cpp.defaultValue = QLatin1Char('0'); - } - else if (datatype == QLatin1String("text") || - datatype == QLatin1String("QString")) - { - - mi.cpp.type = QStringLiteral("QString"); - mi.cpp.fromVariantPost = QStringLiteral(".toString()"); - mi.cpp.defaultValue = QString(); - } - else if (datatype == QLatin1String("json") || - datatype == QLatin1String("jsonb")) - { - - mi.cpp.type = QStringLiteral("QString"); - mi.cpp.fromVariantPre2 = QStringLiteral("qVariantToJsonString("); - mi.cpp.fromVariantPost = QStringLiteral(")"); - mi.cpp.fromJsonPre2 = QStringLiteral("jsonValueToJsonString("); - mi.cpp.fromJsonPost = QStringLiteral(")"); - mi.cpp.toVariantPre = QStringLiteral("fixupEmptyJsonString("); - mi.cpp.toVariantPost = QStringLiteral(")"); - mi.cpp.defaultValue = QStringLiteral("QLatin1String(\"{}\")"); - } - else if (datatype.startsWith(QLatin1String("string"))) - { - - mi.cpp.type = QStringLiteral("std::string"); - mi.cpp.toVariantPre = QStringLiteral("QString::fromStdString("); - mi.cpp.toVariantPost = QStringLiteral(")"); - - mi.cpp.fromVariantPost = QStringLiteral(".toString().toStdString()"); - - mi.cpp.fromJsonPre2 = QStringLiteral("fromJson("); - mi.cpp.fromJsonPost = QStringLiteral(")"); - } - else if (datatype == QLatin1String("timestamp") || - datatype == QLatin1String("qdatetime")) - { - mi.db.datatype = QStringLiteral("bigint"); - if (mi.db.defaultValue.toLower() == QStringLiteral("now()")) - mi.db.defaultValue = QStringLiteral("(extract(epoch from now()) * 1000)"); - mi.cpp.type = QStringLiteral("QDateTime"); - mi.cpp.fromVariantPre2 = QStringLiteral("NSqlQuery::qVariantToQDateTime("); - mi.cpp.fromVariantPost = QStringLiteral(")"); - mi.cpp.toVariantPre = QStringLiteral("NSqlQuery::qDateTimeToQVariant("); - mi.cpp.toVariantPost = QStringLiteral(")"); - mi.cpp.toJsonPre = QLatin1String(""); - mi.cpp.toJsonPost = QStringLiteral(".toMSecsSinceEpoch()"); - mi.cpp.fromJsonPre2 = QStringLiteral("QDateTime::fromMSecsSinceEpoch("); - mi.cpp.fromJsonPost = QStringLiteral(".toDouble())"); - } - else if (datatype == QLatin1String("qvariant")) - { - - } - else - { - ERROR_LOG(m_logger) << "Unknown cpp datatype: " << mi.cpp.type; - return false; - } - return true; -} - - - - - - -QVector StructBuilder::buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation &ctti, - const QString &tableName, - const QString &columnNamePrefix, - const QString &cppStructure) -{ - QVector ret; - if (!ctti.isValid()) - return ret; - - if (!ctti.baseValueType.isEmpty()) - { - ret += buildDbTableInformationFromIdlData(topicTypeInformationByStructType(ctti.baseValueType), - tableName, - columnNamePrefix, - cppStructure); - } - - for (const IdlData &member : ctti.members) - { - if (member.dataTypeInfo->isStructure() && !member.isOptional) - { - const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(member.type); - if (!cttiChild.isValid()) - { - ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; - continue; - } - QString pre; - if (!columnNamePrefix.isEmpty()) - pre += columnNamePrefix; - pre += member.name + QLatin1Char('_'); - ret += buildDbTableInformationFromIdlData(cttiChild, - tableName, - StructBuilder::camelCaseToUnderline(pre), - cppStructure + member.name + QStringLiteral("().") - ); - continue; - } - - if(member.dataTypeInfo->isSequence() && member.dataTypeInfo->innerDataType()->isStructure()) - { - const CompleteTopicTypeInformation &cttiChild = topicTypeInformationByStructType(member.dataTypeInfo->innerDataType()->idlType()); - if (!cttiChild.isValid()) - { - ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; - continue; - } - buildDbTableInformationFromIdlData(cttiChild, - tableName, - columnNamePrefix, - member.name - ); - - } - - MemberInformation mi; - mi.isDdsKey = member.isKey; - mi.db.table = tableName; - mi.db.columnName = columnNamePrefix + StructBuilder::camelCaseToUnderline(member.name); - mi.db.datatype = member.dataTypeInfo->sqlType(); - mi.db.usedForView = true; - mi.cpp.memberName = cppStructure + member.name; - mi.cpp.type = member.type; - mi.cpp.usedForCppStruct = true; - mi.cpp.isOptional = member.isOptional; - - - const EnumInformation ei = enumInformationByType(member.type, true, false); - if (ei.isValid()) - mi.enumeration = QSharedPointer(new EnumInformation(ei)); - - if ((member.dataTypeInfo->isSequence() && member.dataTypeInfo->innerDataType()->idlType() != QLatin1String("octet")) || - (member.dataTypeInfo->isStructure() && member.isOptional)) - { - - - mi.db.datatype = QStringLiteral("jsonb"); - mi.cpp.toJsonPre = QStringLiteral("toJson("); - mi.cpp.toJsonPost = QStringLiteral(")"); - mi.cpp.type = member.dataTypeInfo->ddsType(); - - - mi.cpp.fromVariantPre2 = QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); - mi.cpp.fromVariantPost = QStringLiteral(")"); - - if (member.dataTypeInfo->isSequence()) - addToSerializeFromToJsonTopics(member.dataTypeInfo->innerDataType()); - else - addToSerializeFromToJsonTopics(DataTypeInfo::fromIdlDataType(mi.cpp.memberName, member.type, this)); - } - else - { - fixupCustomDbDatatypes(mi, ret); - fixupQVariantConversions(mi); - } - ret += mi; - } - return ret; -} - - - - - - -bool StructBuilder::buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation &ctti) -{ - if (!ctti.isValid()) - return false; - if (m_jsonStructureInformation.contains(ctti.name)) - return true; - - if (!ctti.baseValueType.isEmpty()) - { - if (!buildJSonStructureInformationFromIdlData(topicTypeInformationByStructType(ctti.baseValueType))) - return false; - } - - QVector content; - content.reserve(ctti.members.size()); - for (const IdlData &member : ctti.members) - { - MemberInformation mi; - mi.isDdsKey = member.isKey; - mi.db.table = ctti.name; - mi.db.columnName = StructBuilder::camelCaseToUnderline(member.name); - mi.db.datatype = member.dataTypeInfo->sqlType(); - mi.db.usedForView = true; - mi.cpp.memberName = member.name; - mi.cpp.type = member.type; - mi.cpp.usedForCppStruct = true; - mi.cpp.isOptional = member.isOptional; - - if (member.dataTypeInfo->isStructure()) - { - const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(member.type); - if (!cttiChild.isValid()) - { - ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; - continue; - } - if (!buildJSonStructureInformationFromIdlData(cttiChild)) - return false; - - mi.cpp.toJsonPre = QStringLiteral("toJson("); - mi.cpp.toJsonPost = QStringLiteral(")"); - mi.cpp.type = member.dataTypeInfo->ddsType(); - - - mi.cpp.fromVariantPre2 = QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); - mi.cpp.fromVariantPost = QStringLiteral(")"); - } - else if (member.dataTypeInfo->isSequence() && - member.dataTypeInfo->innerDataType()->idlType() != QLatin1String("octet")) - { - auto inner = member.dataTypeInfo->innerDataType(); - if (inner->isStructure()) - { - const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(inner->idlType()); - if (cttiChild.isValid()) - { - if (!buildJSonStructureInformationFromIdlData(cttiChild)) + ERROR_LOG(m_logger) << "Invalid external topic type name: '" << tti.name << "'"; return false; } + if (!handleIdlStructInfo(tti, m_externalTopicTypes, sts.service)) + return false; + } + + return true; +} + +bool StructBuilder::handleEnum(const EnumInformation& ei) +{ + m_enumInfos.push_back(ei); + + if (ei.tableName.isEmpty()) + return true; + + QSharedPointer ti = m_xmlReader->getTable(ei.tableName); + if (ti.isNull()) + { + WARNING_LOG(m_logger) << "Could not find table information for enum: " << ei.enumName + << ", table: " << ei.tableName; + return false; + } + + CompleteTableInformation cti = m_sqlTableInformations[ei.tableName]; + for (const ColumnInformation& ci : std::as_const(ti->plainColumns)) + { + MemberInformation mi; + mi.db = FullQualifiedColumnInformation(ci, ei.tableName); + cti.columns.push_back(std::move(mi)); + } + m_sqlTableInformations[ei.tableName] = cti; + + return true; +} + +CompleteStructInformation StructBuilder::structInformationByTableName(const QString& tableName) const +{ + for (const CompleteStructInformation& csi : m_structInfos) + { + if (csi.primaryTable->name == tableName) + return csi; + } + return CompleteStructInformation(); +} + +EnumInformation StructBuilder::enumInformationByType(const QString& type, bool checkExternals, bool verbose) +{ + if (type.isEmpty()) + return EnumInformation(); + const ServiceTypeStruct extInfo = extractServiceAndTypeFromTypename(type); + if (extInfo.isExternalType()) + { + if (!checkExternals) + { + ERROR_LOG(m_logger) << "Could not find enumeration '" << type << "'"; + return EnumInformation(); + } + if (extInfo.type.isEmpty()) + { + WARNING_LOG(m_logger) << "Could not parse external enumeration '" << type << "'"; + return EnumInformation(); + } + return m_xmlReader->getExternalEnumeration(extInfo.service, extInfo.type, verbose); + } + + for (const EnumInformation& ei : std::as_const(m_enumInfos)) + { + if (ei.enumName == type) + return ei; + } + if (verbose) + ERROR_LOG(m_logger) << "Could not find enumeration '" << type << "'"; + return EnumInformation(); +} + +CompleteTopicTypeInformation StructBuilder::topicTypeInformationByStructType(const QString& type, bool checkExternals) +{ + DEBUG_LOG(m_logger) << "topicTypeInformationByStructType(" << type << ")"; + if (type.isEmpty()) + return CompleteTopicTypeInformation(); + + const ServiceTypeStruct extInfo = extractServiceAndTypeFromTypename(type); + if (extInfo.isExternalType()) + { + if (!checkExternals) + return CompleteTopicTypeInformation(); + + return externalTopicTypeByStructType(extInfo); + } + for (const CompleteTopicTypeInformation& csi : std::as_const(m_topicTypeInfos)) + { + if (csi.name == type) + return csi; + } + + DEBUG_LOG(m_logger) << "Type '" << type << "' not found in idlStructs - maybe not yet exported or an enum"; + const QVector idlStructsToGenerate = m_xmlReader->getIdlStructToGenerate(); + for (const TopicTypeInformation& tti : idlStructsToGenerate) + { + if (tti.name == type) + { + DEBUG_LOG(m_logger) << "Found not yet exported type " << type; + if (!handleIdlStructInfo(tti, m_topicTypeInfos)) + return CompleteTopicTypeInformation(); + return topicTypeInformationByStructType(type); + } + } + ERROR_LOG(m_logger) << "Could not find type '" << type << "' in idlStructs"; + return CompleteTopicTypeInformation(); +} + +CompleteTopicTypeInformation StructBuilder::externalTopicTypeByStructType(const ServiceTypeStruct& sts) +{ + const QString typeToSearch = sts.fqType(); + DEBUG_LOG(m_logger) << "externalTopicTypeByStructType " << typeToSearch; + for (const CompleteTopicTypeInformation& ctti : std::as_const(m_externalTopicTypes)) + { + if (ctti.name == typeToSearch) + return ctti; + } + if (!loadExternalTopicType(sts)) + return CompleteTopicTypeInformation(); + return externalTopicTypeByStructType(sts); +} + +bool StructBuilder::loadExternalTopicType(const ServiceTypeStruct& sts) +{ + DEBUG_LOG(m_logger) << "loadExternalTopicType(" << sts.fqType() << ")"; + + const TopicTypeInformation tti = m_xmlReader->loadExternalTopicType(sts.service, sts.type); + if (!tti.isValid()) + { + DEBUG_LOG(m_logger) << "Could not find external topic '" << sts.fqType() << "'"; + return false; + } + + if (!handleIdlStructInfo(tti, m_externalTopicTypes, sts.service)) + return false; + return true; +} + +bool StructBuilder::getColumnsFromTable(const QString& tableName, QVector& columns, + QVector& tableNames) const +{ + if (tableName.isEmpty()) + return true; + + const QString parentTable = m_xmlReader->getStruct2BaseClassRelations().value(tableName); + if (!getColumnsFromTable(parentTable, columns, tableNames)) + return false; + tableNames += tableName; + const QSharedPointer ti = m_xmlReader->getTable(tableName); + QVector constraints; + constraints.reserve(ti->constraints.size()); + for (const ConstraintInformation& ci : std::as_const(ti->constraints)) + { + if (ci.affectedColumns.size() != 1) + continue; + if (ci.type != ConstraintInformation::Type::index) + continue; + constraints += ci; + } + + columns.reserve(columns.size() + ti->plainColumns.size()); + for (const auto& plainColum : std::as_const(ti->plainColumns)) + { + ColumnInformationEx cie(ColumnInformationEx(plainColum, ti)); + for (int j = 0; j < constraints.size(); ++j) + { + const ConstraintInformation& ci = constraints.at(j); + if (ci.affectedColumns.first() == cie.columnName) + { + cie.generateSelectRemove = true; + constraints.remove(j); + break; + } + } + columns += cie; + } + return true; +} + +bool StructBuilder::handleTable(const ServiceStructInformation& ssi) +{ + DEBUG_LOG(m_loggerCSV) << "StructInfo name: #" << ssi.name; + + CompleteStructInformation csi; + csi.structName = ssi.name; + csi.primaryTable = m_xmlReader->getTable(ssi.primaryTable); + csi.viewName = csi.primaryTable->name + QLatin1String("_view"); + csi.hasStaticContent = ssi.hasStaticContent; + csi.dbNotifications = ssi.dbNotifications; + + DEBUG_LOG(m_loggerCSV) << "primaryTable: " << csi.primaryTable.data(); + DEBUG_LOG(m_loggerCSV) << "hasStaticContent: " << csi.hasStaticContent; + + QVector columns; + QVector tableNames; + if (!getColumnsFromTable(ssi.primaryTable, columns, tableNames)) + { + WARNING_LOG(m_logger) << "Could not retrieve columns from table " << ssi.primaryTable; + return false; + } + DEBUG_LOG(m_logger) << "Got " << columns.size() << " columns for table " << ssi.primaryTable; + + QSet sqlTables; + + csi.member.reserve(columns.size() + 1); + MemberInformation miPkFirstTable, miPkLastTable; + for (const ColumnInformationEx& ci : std::as_const(columns)) + { + DEBUG_LOG(m_logger) << "handling column " << ci.columnName; + + const QSharedPointer ti = ci.table; + if (ti.isNull()) + { + WARNING_LOG(m_logger) << "Could not find table for column " << ci.columnName << " primary table is " + << ssi.primaryTable.data(); + return false; + } + csi.tables += ti; + sqlTables += ti->name; + + MemberInformation memberInfo; + memberInfo.ea.column = ci.columnName; + memberInfo.ea.table = ti->name; + memberInfo.ea.type = ci.datatype; + + memberInfo.db = FullQualifiedColumnInformation(ci, memberInfo.ea.table); + + if (ci.hasSequence) + { + memberInfo.db.usedForInsert = !ci.isPrimaryKey; + memberInfo.db.hasSequence = true; + } else - WARNING_LOG(m_logger) << "Can not find structure '" << member.type << "'"; - } + memberInfo.db.usedForInsert = true; - - - mi.db.datatype = QStringLiteral("jsonb"); - mi.cpp.toJsonPre = QStringLiteral("toJson("); - mi.cpp.toJsonPost = QStringLiteral(")"); - mi.cpp.type = member.dataTypeInfo->ddsType(); + memberInfo.db.usedForView = !ci.isPrimaryKey; - - mi.cpp.fromVariantPre2 = QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); - mi.cpp.fromVariantPost = QStringLiteral(")"); + memberInfo.cpp.structName = ssi.name; + memberInfo.cpp.memberName = camelCaseString(ci.columnName); + memberInfo.cpp.type = ci.datatype; + memberInfo.cpp.usedForCppStruct = !ci.isPrimaryKey; + + if (ci.isForeignKey) + { + const QSharedPointer fki = ti->fkInformationForColumn(ti->name, ci.columnName); + if (!fki.isNull()) + { + + for (const auto& tbl : std::as_const(csi.tables)) + { + if (tbl->name == fki->destination.tableName) + { + memberInfo.cpp.isReadOnly = true; + memberInfo.fk = fki; + memberInfo.cpp.memberName = QLatin1String("priv_") + memberInfo.cpp.memberName; + break; + } + } + + if (memberInfo.fk.isNull()) + { + + if (fki->destination.service.isEmpty()) + { + + for (const EnumInformation& ei : std::as_const(m_enumInfos)) + { + if (ei.tableName == fki->destination.tableName) + { + memberInfo.enumeration = QSharedPointer(new EnumInformation(ei)); + break; + } + } + } + else + { + + QString enumType = fki->destination.service + QStringLiteral("::") + + camelCaseString(fki->destination.tableName, true); + + EnumInformation ei = enumInformationByType(enumType, true, false); + DEBUG_LOG(m_logger) << "Checking if " << enumType << " is an enum: " << ei.isValid(); + if (!ei.isValid() && fki->destination.tableName.contains(QLatin1Char('_'))) + { + + enumType = fki->destination.service + QStringLiteral("::") + + camelCaseString(fki->destination.tableName.section(QLatin1Char('_'), 1), true); + ei = enumInformationByType(enumType, true, false); + DEBUG_LOG(m_logger) << "Checking if " << enumType << " is an enum: " << ei.isValid(); + } + if (ei.isValid() && ei.tableName == fki->destination.tableName) + memberInfo.enumeration = QSharedPointer(new EnumInformation(ei)); + } + } + } + } + MemberInformation memberInfoJson = memberInfo; + memberInfoJson.cpp.usedForJson = true; + memberInfoJson.cpp.usedForCppStruct = false; + memberInfoJson.db.isForeignKey = false; + memberInfoJson.db.generateSelectRemove = false; + memberInfoJson.db.usedForView = false; + memberInfoJson.db.usedForInsert = false; + + if (ci.isOptional) + { + memberInfo.cpp.isOptional = true; + memberInfoJson.cpp.isOptional = true; + memberInfo.ea.type = QStringLiteral("QVariant"); + memberInfo.cpp.type = memberInfo.ea.type; + } + + if (!fixupCustomDbDatatypes(memberInfo, csi.member) || !fixupQVariantConversions(memberInfo)) + return false; + + if (!fixupCustomDbDatatypes(memberInfoJson, csi.member) || !fixupQVariantConversions(memberInfoJson)) + return false; + + if (ci.isPrimaryKey && tableNames.first() == ti->name) + { + + miPkFirstTable = memberInfo; + } + if (ci.isPrimaryKey && tableNames.last() == ti->name) + { + + miPkLastTable = memberInfo; + } + + csi.member.push_back(memberInfo); + csi.member.push_back(memberInfoJson); + + addToSqlTableInformation(memberInfo); + + DEBUG_LOG(m_loggerCSV) << memberInfo.toString(); + } + + if (!miPkFirstTable.isEmpty()) + { + miPkFirstTable.db.usedForInsert = false; + miPkFirstTable.db.usedForView = true; + miPkFirstTable.cpp.usedForCppStruct = true; + csi.member.push_front(miPkFirstTable); + } + + if (tableNames.size() > 1 && !miPkLastTable.isEmpty()) + { + + miPkLastTable.db.usedForInsert = false; + miPkLastTable.db.usedForView = true; + miPkLastTable.cpp.usedForCppStruct = true; + miPkLastTable.db.isAssignmentForPrimaryTablePk = true; + miPkLastTable.db.columnNameView = miPkLastTable.db.table + QLatin1Char('_') + miPkLastTable.db.columnName; + + QString name = miPkLastTable.db.table; + if (name.startsWith(m_xmlReader->getServiceAbbr().toLower())) + name = name.mid(m_xmlReader->getServiceAbbr().size() + 1); + miPkLastTable.cpp.memberName = camelCaseString(QLatin1String("priv_") + name + QLatin1String("_id")); + csi.member.push_back(miPkLastTable); + } + + m_structInfos.push_back(csi); + + m_sqlTableInformationsAlreadyAvailable += sqlTables; + return true; +} + +bool StructBuilder::handleIdlStructInfo(const TopicTypeInformation& tti, + QVector& destination, const QString& svcName) +{ + + for (const CompleteTopicTypeInformation& c : std::as_const(destination)) + { + if (c.name == tti.name) + return true; + } + + CompleteTopicTypeInformation ctti(tti); + ctti.members.reserve(tti.columns.size()); + + for (const auto& ci : tti.columns) + { + IdlData idlData(ci); + idlData.dataTypeInfo = DataTypeInfo::fromIdlDataType(idlData.name, idlData.type, this, svcName); + ctti.members.push_back(idlData); + + if (idlData.isKey && idlData.isOptional) + { + ERROR_LOG(m_logger) << "Column option isKey & isOptional are mutually exclusive!"; + ERROR_LOG(m_logger) << "Change column '" << tti.name << "." << idlData.name + << "'' to have either key or optional parameter "; + return false; + } + } + + if (!svcName.isEmpty() && !ctti.baseValueType.isEmpty() && !ctti.baseValueType.contains(QLatin1String("::"))) + ctti.baseValueType = svcName + QStringLiteral("::") + ctti.baseValueType; + + ctti.serviceName = svcName.isEmpty() ? m_xmlReader->getServiceNamespace() : svcName; + + destination.push_back(ctti); + + return true; +} + +bool StructBuilder::fixupCustomDbDatatypes(MemberInformation& memberInfo, QVector& members) +{ + if (!fixupDatatypePoint2d(memberInfo, members)) + return false; + if (!fixupDatatypePoint3d(memberInfo, members)) + return false; + if (!fixupDatatypeIntegerArray(memberInfo)) + return false; + return true; +} + +bool StructBuilder::fixupDatatypePoint2d(MemberInformation& memberInfo, QVector& members) +{ + if (memberInfo.ea.type.toLower() != QLatin1String("point_2d")) + return true; + + MemberInformation mi = memberInfo; + mi.db.datatype = QStringLiteral("double precision"); + mi.cpp.type = QStringLiteral("QPointF"); + mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); + + MemberInformation miX = mi; + MemberInformation miY = mi; + + miX.db.columnName = memberInfo.db.columnName + QLatin1String("_x"); + miY.db.columnName = memberInfo.db.columnName + QLatin1String("_y"); + + miY.cpp.usedForCppStruct = false; + miY.cpp.usedForJson = false; + + miX.cpp.toVariantPost = QStringLiteral(".x()"); + miY.cpp.toVariantPost = QStringLiteral(".y()"); + + miX.cpp.fromVariantPre1 = QStringLiteral(".rx()"); + miY.cpp.fromVariantPre1 = QStringLiteral(".ry()"); + + miX.cpp.memberName = camelCaseString(miX.cpp.memberName); + + miX.cpp.toJsonPre = QStringLiteral("toJson("); + miX.cpp.toJsonPost = QStringLiteral(")"); + miX.cpp.fromJsonPre2 = QStringLiteral("fromJson("); + miX.cpp.fromJsonPost = QStringLiteral(")"); + + members.push_back(miX); + + if (memberInfo.cpp.usedForCppStruct) + addToSqlTableInformation(miX); + + DEBUG_LOG(m_loggerCSV) << miX.toString(); + + memberInfo = miY; + + return true; +} + +bool StructBuilder::fixupDatatypePoint3d(MemberInformation& memberInfo, QVector& members) +{ + if (memberInfo.ea.type.toLower() != QLatin1String("point_3d")) + return true; + + MemberInformation mi = memberInfo; + mi.db.datatype = QStringLiteral("double precision"); + mi.cpp.type = QStringLiteral("LtsUtils::QPoint3D"); + mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); + + MemberInformation miX = mi; + MemberInformation miY = mi; + MemberInformation miZ = mi; + + miX.db.columnName = memberInfo.db.columnName + QLatin1String("_x"); + miY.db.columnName = memberInfo.db.columnName + QLatin1String("_y"); + miZ.db.columnName = memberInfo.db.columnName + QLatin1String("_z"); + + miY.cpp.usedForCppStruct = false; + miZ.cpp.usedForCppStruct = false; + miY.cpp.usedForJson = false; + miZ.cpp.usedForJson = false; + + miX.cpp.toVariantPost = QStringLiteral(".x()"); + miY.cpp.toVariantPost = QStringLiteral(".y()"); + miZ.cpp.toVariantPost = QStringLiteral(".z()"); + + miX.cpp.fromVariantPre1 = QStringLiteral(".rx()"); + miY.cpp.fromVariantPre1 = QStringLiteral(".ry()"); + miZ.cpp.fromVariantPre1 = QStringLiteral(".rz()"); + + miX.cpp.memberName = camelCaseString(miX.cpp.memberName); + + miX.cpp.toJsonPre = QStringLiteral("toJson("); + miX.cpp.toJsonPost = QStringLiteral(")"); + miX.cpp.fromJsonPre2 = QStringLiteral("fromJson("); + miX.cpp.fromJsonPost = QStringLiteral(")"); + + members.push_back(miX); + members.push_back(miY); + + if (memberInfo.cpp.usedForCppStruct) + { + addToSqlTableInformation(miX); + addToSqlTableInformation(miY); + } + DEBUG_LOG(m_loggerCSV) << miX.toString(); + + memberInfo = miZ; + + m_needPoint3d = true; + + return true; +} + +bool StructBuilder::fixupDatatypeIntegerArray(MemberInformation& memberInfo) +{ + + if (memberInfo.ea.type.toLower() == QLatin1String("integer[]")) + { + memberInfo.db.datatype = memberInfo.ea.type.toLower(); + memberInfo.cpp.type = QStringLiteral("LtsUtils::IntArray"); + memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::IntArray::fromPgString("); + memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); + memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); + + m_needPgArrayInclude = true; + } + else if (memberInfo.ea.type.toLower() == QLatin1String("bigint[]")) + { + memberInfo.db.datatype = memberInfo.ea.type.toLower(); + memberInfo.cpp.type = QStringLiteral("LtsUtils::BigintArray"); + memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::BigintArray::fromPgString("); + memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); + memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); + + m_needPgArrayInclude = true; + } + else if (memberInfo.cpp.type.toLower() == QLatin1String("sequence")) + { + memberInfo.db.datatype = QStringLiteral("integer[]"); + memberInfo.cpp.type = QStringLiteral("std::vector"); + memberInfo.cpp.fromVariantPre2 = QStringLiteral("std::vector(LtsUtils::IntArray::fromPgString("); + memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())())"); + memberInfo.cpp.toVariantPre = QStringLiteral("LtsUtils::IntArray("); + memberInfo.cpp.toVariantPost = QStringLiteral(").toPgString()"); + + m_needPgArrayInclude = true; + } + else if (memberInfo.ea.type.toLower() == QLatin1String("integer[][]")) + { + memberInfo.db.datatype = memberInfo.ea.type.toLower(); + memberInfo.cpp.type = QStringLiteral("LtsUtils::IntArray2D"); + memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::IntArray2D::fromPgString("); + memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); + memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); + + m_needPgArrayInclude = true; + } + else if (memberInfo.ea.type.toLower() == QLatin1String("bigint[][]")) + { + memberInfo.db.datatype = memberInfo.ea.type.toLower(); + memberInfo.cpp.type = QStringLiteral("LtsUtils::BigintArray2D"); + memberInfo.cpp.fromVariantPre2 = QStringLiteral("LtsUtils::BigintArray2D::fromPgString("); + memberInfo.cpp.fromVariantPost = QStringLiteral(".toString())"); + memberInfo.cpp.toVariantPost = QStringLiteral(".toPgString()"); + + m_needPgArrayInclude = true; + } + + return true; +} + +bool StructBuilder::fixupQVariantConversions(MemberInformation& mi) const +{ + + if (!mi.cpp.toVariantPost.isEmpty()) + return true; + mi.cpp.toVariantPre.clear(); + mi.cpp.toVariantPost.clear(); + mi.cpp.fromVariantPre1.clear(); + mi.cpp.fromVariantPre2.clear(); + mi.cpp.fromVariantPost.clear(); + + if (mi.enumeration) + { + QString svcName(mi.enumeration->serviceName); + if (!svcName.isEmpty()) + svcName += QStringLiteral("::"); + mi.cpp.type = svcName + mi.enumeration->enumName; + mi.cpp.fromVariantPre2 = + QStringLiteral("static_cast<") + svcName + mi.enumeration->enumName + QStringLiteral("_def::type>("); + mi.cpp.fromVariantPost = QStringLiteral(".toInt())"); + mi.cpp.toVariantPre = QStringLiteral("static_cast("); + mi.cpp.toVariantPost = QStringLiteral(".underlying())"); + if (!mi.enumeration->values.isEmpty()) + { + mi.cpp.defaultValue = + svcName + mi.enumeration->enumName + QStringLiteral("::") + mi.enumeration->values.first().key; + } + return true; + } + const QString datatype = mi.cpp.type.toLower(); + if (datatype == QLatin1String("bigint") || datatype == QLatin1String("qint64") || + datatype == QLatin1String("long long")) + { + mi.cpp.type = QStringLiteral("qint64"); + mi.cpp.fromVariantPost = QStringLiteral(".toLongLong()"); + mi.cpp.fromJsonPost = QStringLiteral(".toDouble()"); + mi.cpp.defaultValue = QLatin1Char('0'); + } + else if (datatype == QLatin1String("boolean") || datatype == QLatin1String("bool")) + { + mi.cpp.type = QStringLiteral("bool"); + mi.cpp.fromVariantPost = QStringLiteral(".toBool()"); + mi.cpp.defaultValue = QStringLiteral("false"); + } + else if (datatype == QLatin1String("bytea") || datatype == QLatin1String("QByteArray")) + { + + mi.cpp.type = QStringLiteral("QByteArray"); + mi.cpp.fromVariantPost = QStringLiteral(".toByteArray()"); + mi.cpp.toJsonPre = QStringLiteral("QString::fromLatin1("); + mi.cpp.toJsonPost = QStringLiteral(".toBase64())"); + mi.cpp.fromJsonPre2 = QStringLiteral("QByteArray::fromBase64("); + mi.cpp.fromJsonPost = QStringLiteral(".toString().toLatin1())"); + mi.cpp.defaultValue.clear(); + } + else if (datatype == QLatin1String("sequence")) + { + + mi.cpp.type = QStringLiteral("QByteArray"); + mi.cpp.ddsType = QStringLiteral("std::vector"); + + mi.cpp.toVariantPre = QStringLiteral("octetSequenceToQVariant("); + mi.cpp.toVariantPost = QStringLiteral(")"); + + mi.cpp.fromVariantPre2 = QStringLiteral("qVariantToOctetSequence("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + + mi.cpp.toJsonPre = QStringLiteral("toJson("); + mi.cpp.toJsonPost = QStringLiteral(")"); + mi.cpp.fromJsonPre2 = QStringLiteral("fromJson>("); + mi.cpp.fromJsonPost = QStringLiteral(")"); + + mi.cpp.defaultValue.clear(); + } + else if (datatype == QLatin1String("char")) + { + mi.cpp.type = QStringLiteral("char"); + mi.cpp.fromVariantPost = QStringLiteral(".toChar().toLatin1()"); + mi.cpp.fromJsonPost = QStringLiteral(".toInt()"); + mi.cpp.defaultValue = QStringLiteral("\\0"); + } + else if (datatype == QLatin1String("integer") || datatype == QLatin1String("qint32") || + datatype == QLatin1String("long")) + { + mi.cpp.type = QStringLiteral("qint32"); + mi.cpp.fromVariantPost = QStringLiteral(".toInt()"); + mi.cpp.defaultValue = QLatin1Char('0'); + } + else if (datatype == QLatin1String("real") || datatype == QLatin1String("double") || + datatype == QLatin1String("double precision") || datatype == QLatin1String("float")) + { + mi.cpp.type = QStringLiteral("double"); + mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); + mi.cpp.defaultValue = QStringLiteral("0.0"); + mi.db.datatype = QStringLiteral("double precision"); + } + else if (datatype == QLatin1String("numeric") || datatype == QLatin1String("decimal")) + { + mi.cpp.type = QStringLiteral("double"); + mi.cpp.fromVariantPost = QStringLiteral(".toDouble()"); + mi.cpp.defaultValue = QStringLiteral("0.0"); + mi.db.datatype = QStringLiteral("numeric"); + } + else if (datatype == QLatin1String("smallint") || datatype == QLatin1String("qint16") || + datatype == QLatin1String("short")) + { + mi.cpp.type = QStringLiteral("qint16"); + mi.cpp.fromVariantPost = QStringLiteral(".toInt()"); + mi.cpp.defaultValue = QLatin1Char('0'); + } + else if (datatype == QLatin1String("text") || datatype == QLatin1String("QString")) + { + + mi.cpp.type = QStringLiteral("QString"); + mi.cpp.fromVariantPost = QStringLiteral(".toString()"); + mi.cpp.defaultValue = QString(); + } + else if (datatype == QLatin1String("json") || datatype == QLatin1String("jsonb")) + { + + mi.cpp.type = QStringLiteral("QString"); + mi.cpp.fromVariantPre2 = QStringLiteral("qVariantToJsonString("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + mi.cpp.fromJsonPre2 = QStringLiteral("jsonValueToJsonString("); + mi.cpp.fromJsonPost = QStringLiteral(")"); + mi.cpp.toVariantPre = QStringLiteral("fixupEmptyJsonString("); + mi.cpp.toVariantPost = QStringLiteral(")"); + mi.cpp.defaultValue = QStringLiteral("QLatin1String(\"{}\")"); + } + else if (datatype.startsWith(QLatin1String("string"))) + { + + mi.cpp.type = QStringLiteral("std::string"); + mi.cpp.toVariantPre = QStringLiteral("QString::fromStdString("); + mi.cpp.toVariantPost = QStringLiteral(")"); + + mi.cpp.fromVariantPost = QStringLiteral(".toString().toStdString()"); + + mi.cpp.fromJsonPre2 = QStringLiteral("fromJson("); + mi.cpp.fromJsonPost = QStringLiteral(")"); + } + else if (datatype == QLatin1String("timestamp") || datatype == QLatin1String("qdatetime")) + { + mi.db.datatype = QStringLiteral("bigint"); + if (mi.db.defaultValue.toLower() == QStringLiteral("now()")) + mi.db.defaultValue = QStringLiteral("(extract(epoch from now()) * 1000)"); + mi.cpp.type = QStringLiteral("QDateTime"); + mi.cpp.fromVariantPre2 = QStringLiteral("NSqlQuery::qVariantToQDateTime("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + mi.cpp.toVariantPre = QStringLiteral("NSqlQuery::qDateTimeToQVariant("); + mi.cpp.toVariantPost = QStringLiteral(")"); + mi.cpp.toJsonPre = QLatin1String(""); + mi.cpp.toJsonPost = QStringLiteral(".toMSecsSinceEpoch()"); + mi.cpp.fromJsonPre2 = QStringLiteral("QDateTime::fromMSecsSinceEpoch("); + mi.cpp.fromJsonPost = QStringLiteral(".toDouble())"); + } + else if (datatype == QLatin1String("qvariant")) + { } else { - - const EnumInformation ei = enumInformationByType(member.type, true, false); - if (ei.isValid()) - mi.enumeration = QSharedPointer(new EnumInformation(ei)); - - fixupCustomDbDatatypes(mi, content); - fixupQVariantConversions(mi); + ERROR_LOG(m_logger) << "Unknown cpp datatype: " << mi.cpp.type; + return false; } - content += mi; - } - m_jsonStructureInformation[ctti.name] = content; - - return true; + return true; } -CompleteTableInformation StructBuilder::completeTableInformation(const CompleteTopicTypeInformation &ctti) +QVector StructBuilder::buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation& ctti, + const QString& tableName, + const QString& columnNamePrefix, + const QString& cppStructure) { - CompleteTableInformation cti; - cti.structName = ctti.name; - cti.name = QStringLiteral("rec_") + camelCaseToUnderline(ctti.name); - cti.comment = QStringLiteral("recorded data for topic ") + ctti.name; - cti.columns = buildDbTableInformationFromIdlData(ctti, cti.name, QString(), QString()); - buildJSonStructureInformationFromIdlData(ctti); - cti.exerciseDependency = ExerciseDependency::Exercise; - return cti; + QVector ret; + if (!ctti.isValid()) + return ret; + + if (!ctti.baseValueType.isEmpty()) + { + ret += buildDbTableInformationFromIdlData(topicTypeInformationByStructType(ctti.baseValueType), tableName, + columnNamePrefix, cppStructure); + } + + for (const IdlData& member : ctti.members) + { + if (member.dataTypeInfo->isStructure() && !member.isOptional) + { + const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(member.type); + if (!cttiChild.isValid()) + { + ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; + continue; + } + QString pre; + if (!columnNamePrefix.isEmpty()) + pre += columnNamePrefix; + pre += member.name + QLatin1Char('_'); + ret += buildDbTableInformationFromIdlData(cttiChild, tableName, StructBuilder::camelCaseToUnderline(pre), + cppStructure + member.name + QStringLiteral("().")); + continue; + } + + if (member.dataTypeInfo->isSequence() && member.dataTypeInfo->innerDataType()->isStructure()) + { + const CompleteTopicTypeInformation& cttiChild = + topicTypeInformationByStructType(member.dataTypeInfo->innerDataType()->idlType()); + if (!cttiChild.isValid()) + { + ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; + continue; + } + buildDbTableInformationFromIdlData(cttiChild, tableName, columnNamePrefix, member.name); + } + + MemberInformation mi; + mi.isDdsKey = member.isKey; + mi.db.table = tableName; + mi.db.columnName = columnNamePrefix + StructBuilder::camelCaseToUnderline(member.name); + mi.db.datatype = member.dataTypeInfo->sqlType(); + mi.db.usedForView = true; + mi.cpp.memberName = cppStructure + member.name; + mi.cpp.type = member.type; + mi.cpp.usedForCppStruct = true; + mi.cpp.isOptional = member.isOptional; + + const EnumInformation ei = enumInformationByType(member.type, true, false); + if (ei.isValid()) + mi.enumeration = QSharedPointer(new EnumInformation(ei)); + + if ((member.dataTypeInfo->isSequence() && + member.dataTypeInfo->innerDataType()->idlType() != QLatin1String("octet")) || + (member.dataTypeInfo->isStructure() && member.isOptional)) + { + + mi.db.datatype = QStringLiteral("jsonb"); + mi.cpp.toJsonPre = QStringLiteral("toJson("); + mi.cpp.toJsonPost = QStringLiteral(")"); + mi.cpp.type = member.dataTypeInfo->ddsType(); + + mi.cpp.fromVariantPre2 = + QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + + if (member.dataTypeInfo->isSequence()) + addToSerializeFromToJsonTopics(member.dataTypeInfo->innerDataType()); + else + addToSerializeFromToJsonTopics(DataTypeInfo::fromIdlDataType(mi.cpp.memberName, member.type, this)); + } + else + { + fixupCustomDbDatatypes(mi, ret); + fixupQVariantConversions(mi); + } + ret += mi; + } + return ret; +} + +bool StructBuilder::buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation& ctti) +{ + if (!ctti.isValid()) + return false; + if (m_jsonStructureInformation.contains(ctti.name)) + return true; + + if (!ctti.baseValueType.isEmpty()) + { + if (!buildJSonStructureInformationFromIdlData(topicTypeInformationByStructType(ctti.baseValueType))) + return false; + } + + QVector content; + content.reserve(ctti.members.size()); + for (const IdlData& member : ctti.members) + { + MemberInformation mi; + mi.isDdsKey = member.isKey; + mi.db.table = ctti.name; + mi.db.columnName = StructBuilder::camelCaseToUnderline(member.name); + mi.db.datatype = member.dataTypeInfo->sqlType(); + mi.db.usedForView = true; + mi.cpp.memberName = member.name; + mi.cpp.type = member.type; + mi.cpp.usedForCppStruct = true; + mi.cpp.isOptional = member.isOptional; + + if (member.dataTypeInfo->isStructure()) + { + const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(member.type); + if (!cttiChild.isValid()) + { + ERROR_LOG(m_logger) << "Can not find structure '" << member.type << "'"; + continue; + } + if (!buildJSonStructureInformationFromIdlData(cttiChild)) + return false; + + mi.cpp.toJsonPre = QStringLiteral("toJson("); + mi.cpp.toJsonPost = QStringLiteral(")"); + mi.cpp.type = member.dataTypeInfo->ddsType(); + + mi.cpp.fromVariantPre2 = + QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + } + else if (member.dataTypeInfo->isSequence() && + member.dataTypeInfo->innerDataType()->idlType() != QLatin1String("octet")) + { + auto inner = member.dataTypeInfo->innerDataType(); + if (inner->isStructure()) + { + const CompleteTopicTypeInformation cttiChild = topicTypeInformationByStructType(inner->idlType()); + if (cttiChild.isValid()) + { + if (!buildJSonStructureInformationFromIdlData(cttiChild)) + return false; + } + else + WARNING_LOG(m_logger) << "Can not find structure '" << member.type << "'"; + } + + mi.db.datatype = QStringLiteral("jsonb"); + mi.cpp.toJsonPre = QStringLiteral("toJson("); + mi.cpp.toJsonPost = QStringLiteral(")"); + mi.cpp.type = member.dataTypeInfo->ddsType(); + + mi.cpp.fromVariantPre2 = + QStringLiteral("fromJson<") + member.dataTypeInfo->ddsType() + QStringLiteral(">("); + mi.cpp.fromVariantPost = QStringLiteral(")"); + } + else + { + + const EnumInformation ei = enumInformationByType(member.type, true, false); + if (ei.isValid()) + mi.enumeration = QSharedPointer(new EnumInformation(ei)); + + fixupCustomDbDatatypes(mi, content); + fixupQVariantConversions(mi); + } + content += mi; + } + m_jsonStructureInformation[ctti.name] = content; + + return true; +} + +CompleteTableInformation StructBuilder::completeTableInformation(const CompleteTopicTypeInformation& ctti) +{ + CompleteTableInformation cti; + cti.structName = ctti.name; + cti.name = QStringLiteral("rec_") + camelCaseToUnderline(ctti.name); + cti.comment = QStringLiteral("recorded data for topic ") + ctti.name; + cti.columns = buildDbTableInformationFromIdlData(ctti, cti.name, QString(), QString()); + buildJSonStructureInformationFromIdlData(ctti); + cti.exerciseDependency = ExerciseDependency::Exercise; + return cti; } MemberInformation StructBuilder::getRecordPrimaryKey() const { - MemberInformation miPrimaryKey; - miPrimaryKey.db.isPrimaryKey = true; - miPrimaryKey.db.columnName = QStringLiteral("rec_id"); - miPrimaryKey.db.datatype = QStringLiteral("bigint"); - miPrimaryKey.db.hasSequence = true; - miPrimaryKey.db.sequenceStart = 1; - miPrimaryKey.db.sequenceIncrement = 1; - miPrimaryKey.db.usedForView = false; - miPrimaryKey.cpp.type = QStringLiteral("bigint"); - miPrimaryKey.cpp.usedForCppStruct = false; - fixupQVariantConversions(miPrimaryKey); - return miPrimaryKey; + MemberInformation miPrimaryKey; + miPrimaryKey.db.isPrimaryKey = true; + miPrimaryKey.db.columnName = QStringLiteral("rec_id"); + miPrimaryKey.db.datatype = QStringLiteral("bigint"); + miPrimaryKey.db.hasSequence = true; + miPrimaryKey.db.sequenceStart = 1; + miPrimaryKey.db.sequenceIncrement = 1; + miPrimaryKey.db.usedForView = false; + miPrimaryKey.cpp.type = QStringLiteral("bigint"); + miPrimaryKey.cpp.usedForCppStruct = false; + fixupQVariantConversions(miPrimaryKey); + return miPrimaryKey; } -CompleteTableInformation StructBuilder::getRecordingTopicTable(const QString &structName) +CompleteTableInformation StructBuilder::getRecordingTopicTable(const QString& structName) { - const auto vec = structName.contains(QLatin1String("::")) ? m_externalTopicTypes : m_topicTypeInfos; - - for (const CompleteTopicTypeInformation &ctti : std::as_const(vec)) - { - if (structName != ctti.name) - continue; - MemberInformation miPrimaryKey(getRecordPrimaryKey()); - miPrimaryKey.db.table = ctti.name; - return getRecordingTopicTable(ctti, getRecordPrimaryKey()); - } - return CompleteTableInformation(); + const auto vec = structName.contains(QLatin1String("::")) ? m_externalTopicTypes : m_topicTypeInfos; + + for (const CompleteTopicTypeInformation& ctti : std::as_const(vec)) + { + if (structName != ctti.name) + continue; + MemberInformation miPrimaryKey(getRecordPrimaryKey()); + miPrimaryKey.db.table = ctti.name; + return getRecordingTopicTable(ctti, getRecordPrimaryKey()); + } + return CompleteTableInformation(); } -CompleteTableInformation StructBuilder::getRecordingTopicTable(const CompleteTopicTypeInformation &ctti, - const MemberInformation &miPrimaryKey) +CompleteTableInformation StructBuilder::getRecordingTopicTable(const CompleteTopicTypeInformation& ctti, + const MemberInformation& miPrimaryKey) { - CompleteTableInformation cti = completeTableInformation(ctti); - cti.columns.push_back(miPrimaryKey); - return cti; + CompleteTableInformation cti = completeTableInformation(ctti); + cti.columns.push_back(miPrimaryKey); + return cti; } QMap StructBuilder::getRecordingTopicTables() { - - QMap ret; - MemberInformation miPrimaryKey(getRecordPrimaryKey()); - - for (const CompleteTopicTypeInformation &ctti : std::as_const(m_topicTypeInfos)) - { - if (!ctti.recordTopic) - continue; - if (!ctti.isDataObject) + QMap ret; + + MemberInformation miPrimaryKey(getRecordPrimaryKey()); + + for (const CompleteTopicTypeInformation& ctti : std::as_const(m_topicTypeInfos)) { - WARNING_LOG(m_logger) << "Trying to record topic '" << ctti.name - << "' which is not directly published - ignoring!"; - continue; + if (!ctti.recordTopic) + continue; + if (!ctti.isDataObject) + { + WARNING_LOG(m_logger) << "Trying to record topic '" << ctti.name + << "' which is not directly published - ignoring!"; + continue; + } + DEBUG_LOG(m_logger) << "Rec table: " << ctti.name; + miPrimaryKey.db.table = ctti.name; + ret.insert(ctti.name, getRecordingTopicTable(ctti, miPrimaryKey)); } - DEBUG_LOG(m_logger) << "Rec table: " << ctti.name; - miPrimaryKey.db.table = ctti.name; - ret.insert(ctti.name, getRecordingTopicTable(ctti, miPrimaryKey)); - } - return ret; + return ret; } -void StructBuilder::addToSerializeFromToJsonTopics(const QSharedPointer &toAdd) +void StructBuilder::addToSerializeFromToJsonTopics(const QSharedPointer& toAdd) { - typedef QSharedPointer sDTI; - for (const sDTI &dti : std::as_const(m_serializeFromToJsonTopics)) - { - if (dti->cppType() == toAdd->cppType()) - return; - } - m_serializeFromToJsonTopics += toAdd; + typedef QSharedPointer sDTI; + for (const sDTI& dti : std::as_const(m_serializeFromToJsonTopics)) + { + if (dti->cppType() == toAdd->cppType()) + return; + } + m_serializeFromToJsonTopics += toAdd; } QVector> StructBuilder::getSerializeFromToJsonTopics() const { - return m_serializeFromToJsonTopics; + return m_serializeFromToJsonTopics; } -QString StructBuilder::firstCharLowercase(const QString &txt) +QString StructBuilder::firstCharLowercase(const QString& txt) { - QString ret = txt; - if (txt.isEmpty()) + QString ret = txt; + if (txt.isEmpty()) + return ret; + ret[0] = ret[0].toLower(); return ret; - ret[0] = ret[0].toLower(); - return ret; } -QString StructBuilder::camelCaseString(const QString &in, bool bFirstUppercase) +QString StructBuilder::camelCaseString(const QString& in, bool bFirstUppercase) { - Q_DECL_CONSTEXPR const QChar s_underline(QLatin1Char('_')); - QString out; - out.reserve(in.size()); - bool bNextIsUpperCase = bFirstUppercase; - for (const auto c : in) - { - if (c == s_underline) - bNextIsUpperCase = true; - else + Q_DECL_CONSTEXPR const QChar s_underline(QLatin1Char('_')); + QString out; + out.reserve(in.size()); + bool bNextIsUpperCase = bFirstUppercase; + for (const auto c : in) { - out += (bNextIsUpperCase ? c.toUpper() : c); - bNextIsUpperCase = false; + if (c == s_underline) + bNextIsUpperCase = true; + else + { + out += (bNextIsUpperCase ? c.toUpper() : c); + bNextIsUpperCase = false; + } } - } - return out; -} - -QString StructBuilder::camelCaseToUnderline(const QString &in) -{ - QString out; - if (in.isEmpty()) return out; - out.reserve(in.size()); - out += in.at(0).toLower(); - for (int i = 1; i < in.size(); ++i) - { - const QChar c = in.at(i); - if (!c.isLetter() || c.isLower()) - out += c; - else - out += QLatin1Char('_') + c.toLower(); - } - return out; } -StructBuilder::ServiceTypeStruct StructBuilder::extractServiceAndTypeFromTypename(const QString &type) +QString StructBuilder::camelCaseToUnderline(const QString& in) { - const QStringList sl = QString(type).split(QStringLiteral("::")); - QStringView extServiceRef; - QStringView extTypeRef; - if (sl.size() == 1) - extTypeRef = sl.at(0); - else if (sl.size() == 2) - { - extServiceRef = sl.at(0); - extTypeRef = sl.at(1); - } - else - WARNING_LOG(m_logger) << "Error parsing type: " << type; - StructBuilder::ServiceTypeStruct ret; - if (!extServiceRef.isEmpty()) - { - if (extServiceRef.contains(QLatin1Char('<'))) - ret.service = QString(extServiceRef).split(QLatin1Char('<')).at(1); - else - ret.service = QString(extServiceRef); - } - if (!extTypeRef.isEmpty()) - { - if (extTypeRef.contains(QLatin1Char('>'))) - ret.type = QString(extTypeRef).split(QLatin1Char('>')).at(0); - else - ret.type = QString(extTypeRef); - } - return ret; + QString out; + if (in.isEmpty()) + return out; + out.reserve(in.size()); + out += in.at(0).toLower(); + for (int i = 1; i < in.size(); ++i) + { + const QChar c = in.at(i); + if (!c.isLetter() || c.isLower()) + out += c; + else + out += QLatin1Char('_') + c.toLower(); + } + return out; } -void StructBuilder::addToSqlTableInformation(const MemberInformation &mi) +StructBuilder::ServiceTypeStruct StructBuilder::extractServiceAndTypeFromTypename(const QString& type) { - if (!m_sqlTableInformationsAlreadyAvailable.contains(mi.db.table)) - m_sqlTableInformations[mi.db.table].columns.append(mi); + const QStringList sl = QString(type).split(QStringLiteral("::")); + QStringView extServiceRef; + QStringView extTypeRef; + if (sl.size() == 1) + extTypeRef = sl.at(0); + else if (sl.size() == 2) + { + extServiceRef = sl.at(0); + extTypeRef = sl.at(1); + } + else + WARNING_LOG(m_logger) << "Error parsing type: " << type; + StructBuilder::ServiceTypeStruct ret; + if (!extServiceRef.isEmpty()) + { + if (extServiceRef.contains(QLatin1Char('<'))) + ret.service = QString(extServiceRef).split(QLatin1Char('<')).at(1); + else + ret.service = QString(extServiceRef); + } + if (!extTypeRef.isEmpty()) + { + if (extTypeRef.contains(QLatin1Char('>'))) + ret.type = QString(extTypeRef).split(QLatin1Char('>')).at(0); + else + ret.type = QString(extTypeRef); + } + return ret; +} + +void StructBuilder::addToSqlTableInformation(const MemberInformation& mi) +{ + if (!m_sqlTableInformationsAlreadyAvailable.contains(mi.db.table)) + m_sqlTableInformations[mi.db.table].columns.append(mi); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.h old mode 100755 new mode 100644 index a615e5939..77819848d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/StructBuilder.h @@ -2,10 +2,11 @@ #pragma once -#include #include "XmlReader.h" #include "codegen_base_export.h" +#include + namespace NGL { class INGLLogger; @@ -17,325 +18,368 @@ class StructBuilder; struct EaData { - QString table; - QString column; - QString type; + QString table; + QString column; + QString type; - QString toString() const - { - return table + - QLatin1Char(';') + column + - QLatin1Char(';') + type; - } + QString toString() const + { + return table + QLatin1Char(';') + column + QLatin1Char(';') + type; + } }; struct FullQualifiedColumnInformation : public ColumnInformation { - QString table; - bool usedForInsert = false; - bool usedForView = false; - QString columnNameView; + QString table; + bool usedForInsert = false; + bool usedForView = false; + QString columnNameView; - QString getColumnNameView() const { return columnNameView.isEmpty() ? columnName : columnNameView; } + QString getColumnNameView() const + { + return columnNameView.isEmpty() ? columnName : columnNameView; + } - FullQualifiedColumnInformation() = default; - FullQualifiedColumnInformation(const ColumnInformation &ci, const QString &tableName) - : ColumnInformation(ci) - , table(tableName) - {} + FullQualifiedColumnInformation() = default; - QString toString() const - { - return table + - QLatin1Char(';') + columnName + - QLatin1Char(';') + datatype + - - QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + (isForeignKey ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + (usedForInsert ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + (usedForView ? QLatin1String("true") : QLatin1String("false")); - } + FullQualifiedColumnInformation(const ColumnInformation& ci, const QString& tableName) + : ColumnInformation(ci), table(tableName) + { + } + + QString toString() const + { + return table + QLatin1Char(';') + columnName + QLatin1Char(';') + datatype + + + QLatin1Char(';') + (isPrimaryKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + + (isForeignKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + + (usedForInsert ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + + (usedForView ? QLatin1String("true") : QLatin1String("false")); + } }; class DataTypeInfo { -public: - DataTypeInfo(const QString &name, bool isPod) - : m_name(name) - , m_isPod(isPod) - {} - virtual ~DataTypeInfo() = default; - virtual QString name() const { return m_name; } - virtual QString idlType() const = 0; - virtual QString ddsType() const = 0; - virtual QString sqlType() const = 0; - virtual QString cppType() const = 0; - virtual QString cppTypeConstRef() const { return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &"); } - virtual bool isPod() const { return m_isPod; } - virtual bool isSequence() const { return false; } - virtual bool isStructure() const { return false; } - virtual QVector> member() const { return QVector>(); } - virtual QSharedPointer innerDataType() const { return QSharedPointer(); } + public: + DataTypeInfo(const QString& name, bool isPod) : m_name(name), m_isPod(isPod) {} - static QSharedPointer fromIdlDataType(const QString &name, - const QString &idlType, - StructBuilder *structBuilder, - const QString &svcName = QString()); -protected: - const QString m_name; - const bool m_isPod; + virtual ~DataTypeInfo() = default; + + virtual QString name() const + { + return m_name; + } + + virtual QString idlType() const = 0; + virtual QString ddsType() const = 0; + virtual QString sqlType() const = 0; + virtual QString cppType() const = 0; + + virtual QString cppTypeConstRef() const + { + return isPod() ? cppType() : QLatin1String("const ") + cppType() + QLatin1String(" &"); + } + + virtual bool isPod() const + { + return m_isPod; + } + + virtual bool isSequence() const + { + return false; + } + + virtual bool isStructure() const + { + return false; + } + + virtual QVector> member() const + { + return QVector>(); + } + + virtual QSharedPointer innerDataType() const + { + return QSharedPointer(); + } + + static QSharedPointer fromIdlDataType(const QString& name, const QString& idlType, + StructBuilder* structBuilder, + const QString& svcName = QString()); + + protected: + const QString m_name; + const bool m_isPod; }; struct IdlData : public IdlColumnInformation { - QSharedPointer dataTypeInfo; + QSharedPointer dataTypeInfo; - IdlData() = default; - explicit IdlData(const IdlColumnInformation &ci) - : IdlColumnInformation(ci) - {} + IdlData() = default; - QString toString() const - { - return name + - QLatin1Char(';') + type + - - QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + (isOptional ? QLatin1String("true") : QLatin1String("false")); - } + explicit IdlData(const IdlColumnInformation& ci) : IdlColumnInformation(ci) {} + + QString toString() const + { + return name + QLatin1Char(';') + type + + + QLatin1Char(';') + (isKey ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + + (isOptional ? QLatin1String("true") : QLatin1String("false")); + } }; - - struct CppData { - QString structName; - QString memberName; - QString defaultValue; - bool usedForCppStruct = false; - bool usedForJson = false; - bool isReadOnly = false; - bool isOptional = false; - QString type; - QString ddsType; - QString toVariantPre; - QString toVariantPost; - QString fromVariantPre1; - QString fromVariantPre2; - QString fromVariantPost; + QString structName; + QString memberName; + QString defaultValue; + bool usedForCppStruct = false; + bool usedForJson = false; + bool isReadOnly = false; + bool isOptional = false; + QString type; + QString ddsType; + QString toVariantPre; + QString toVariantPost; + QString fromVariantPre1; + QString fromVariantPre2; + QString fromVariantPost; - QString toJsonPre; - QString toJsonPost; - QString fromJsonPre2; - QString fromJsonPost; + QString toJsonPre; + QString toJsonPost; + QString fromJsonPre2; + QString fromJsonPost; - QString toString() const - { - return structName + - QLatin1Char(';') + memberName + - QLatin1Char(';') + (usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + (isReadOnly ? QLatin1String("true") : QLatin1String("false")) + - QLatin1Char(';') + type + - QLatin1Char(';') + toVariantPre + - QLatin1Char(';') + toVariantPost + - QLatin1Char(';') + fromVariantPre1 + - QLatin1Char(';') + fromVariantPre2 + - QLatin1Char(';') + fromVariantPost; - } + QString toString() const + { + return structName + QLatin1Char(';') + memberName + QLatin1Char(';') + + (usedForCppStruct ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + + (isReadOnly ? QLatin1String("true") : QLatin1String("false")) + QLatin1Char(';') + type + + QLatin1Char(';') + toVariantPre + QLatin1Char(';') + toVariantPost + QLatin1Char(';') + fromVariantPre1 + + QLatin1Char(';') + fromVariantPre2 + QLatin1Char(';') + fromVariantPost; + } }; struct MemberInformation { - EaData ea; - FullQualifiedColumnInformation db; - CppData cpp; - bool isDdsKey = false; - QSharedPointer fk; - QSharedPointer enumeration; + EaData ea; + FullQualifiedColumnInformation db; + CppData cpp; + bool isDdsKey = false; + QSharedPointer fk; + QSharedPointer enumeration; - QString toString() const - { - return ea.toString() + QLatin1Char(';') + - db.toString() + QLatin1Char(';') + - cpp.toString(); - } - bool isEmpty() const - { - return ea.column.isEmpty(); - } + QString toString() const + { + return ea.toString() + QLatin1Char(';') + db.toString() + QLatin1Char(';') + cpp.toString(); + } + + bool isEmpty() const + { + return ea.column.isEmpty(); + } }; struct CompleteStructInformation { - QString structName; - QString viewName; - QSet > tables; - QSharedPointer primaryTable; - QVector member; - QVector dbNotifications; - bool hasStaticContent = false; + QString structName; + QString viewName; + QSet> tables; + QSharedPointer primaryTable; + QVector member; + QVector dbNotifications; + bool hasStaticContent = false; - bool isEmpty() const - { - return primaryTable.isNull(); - } + bool isEmpty() const + { + return primaryTable.isNull(); + } }; struct CompleteTopicTypeInformation final : public TopicTypeInformationBase { - QString serviceName; + QString serviceName; - QVector members; + QVector members; - CompleteTopicTypeInformation() = default; - explicit CompleteTopicTypeInformation(const TopicTypeInformationBase &s) - : TopicTypeInformationBase(s) - {} + CompleteTopicTypeInformation() = default; - bool hasBaseValue() const { return !baseValueType.isEmpty(); } - bool isValid() const { return TopicTypeInformationBase::isValid() && !members.isEmpty(); } + explicit CompleteTopicTypeInformation(const TopicTypeInformationBase& s) : TopicTypeInformationBase(s) {} + + bool hasBaseValue() const + { + return !baseValueType.isEmpty(); + } + + bool isValid() const + { + return TopicTypeInformationBase::isValid() && !members.isEmpty(); + } }; - struct CompleteTableInformation : public TableInformation { - QVector columns; - explicit CompleteTableInformation(const TableInformation &o) - : TableInformation(o) - {} - CompleteTableInformation() = default; - bool isEmpty() const { return columns.isEmpty(); } + QVector columns; + + explicit CompleteTableInformation(const TableInformation& o) : TableInformation(o) {} + + CompleteTableInformation() = default; + + bool isEmpty() const + { + return columns.isEmpty(); + } }; class CODEGEN_BASE_EXPORT StructBuilder { - struct ColumnInformationEx : public ColumnInformation - { - QSharedPointer table; + struct ColumnInformationEx : public ColumnInformation + { + QSharedPointer table; - ColumnInformationEx() = default; - ColumnInformationEx(const ColumnInformation &o, - const QSharedPointer &ti) - : ColumnInformation(o) - , table(ti) - {} - }; + ColumnInformationEx() = default; -public: - struct ServiceTypeStruct - { - QString service; - QString type; - bool bIsSequence = false; - bool isExternalType() const { return !service.isEmpty(); } - bool isSequence() const { return bIsSequence; } - QString fqType() const { return service + QStringLiteral("::") + type; } - }; + ColumnInformationEx(const ColumnInformation& o, const QSharedPointer& ti) + : ColumnInformation(o), table(ti) + { + } + }; - explicit StructBuilder(XmlReader *xmlReader); - ~StructBuilder() = default; + public: + struct ServiceTypeStruct + { + QString service; + QString type; + bool bIsSequence = false; - bool buildStructures(); - QVector structInformations() const - { - return m_structInfos; - } - QVector topicTypeInformations() const - { - return m_topicTypeInfos; - } + bool isExternalType() const + { + return !service.isEmpty(); + } - CompleteStructInformation structInformationByTableName(const QString &tableName) const; + bool isSequence() const + { + return bIsSequence; + } - EnumInformation enumInformationByType(const QString &type, bool checkExternals = true, bool verbose = true); + QString fqType() const + { + return service + QStringLiteral("::") + type; + } + }; - CompleteTopicTypeInformation topicTypeInformationByStructType(const QString &type, bool checkExternals = true); - CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct &sts); + explicit StructBuilder(XmlReader* xmlReader); + ~StructBuilder() = default; - QVector enumInformations() const - { - return m_enumInfos; - } + bool buildStructures(); - QMap getDbTables() const - { - return m_sqlTableInformations; - } + QVector structInformations() const + { + return m_structInfos; + } - QMap getDbViews() const - { - return m_sqlViewInformations; - } + QVector topicTypeInformations() const + { + return m_topicTypeInfos; + } - bool needPoint3d() const - { - return m_needPoint3d; - } + CompleteStructInformation structInformationByTableName(const QString& tableName) const; - bool needPgArrayInclude() const - { - return m_needPgArrayInclude; - } + EnumInformation enumInformationByType(const QString& type, bool checkExternals = true, bool verbose = true); - CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation &ctti); - CompleteTableInformation getRecordingTopicTable(const QString &structName); - QMap getRecordingTopicTables(); - QVector > getSerializeFromToJsonTopics() const; - bool fixupQVariantConversions(MemberInformation &mi) const; + CompleteTopicTypeInformation topicTypeInformationByStructType(const QString& type, bool checkExternals = true); + CompleteTopicTypeInformation externalTopicTypeByStructType(const ServiceTypeStruct& sts); - Q_REQUIRED_RESULT static QString firstCharLowercase(const QString &txt); - Q_REQUIRED_RESULT static QString camelCaseString(const QString &in, bool bFirstUppercase = false); - Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString &in); + QVector enumInformations() const + { + return m_enumInfos; + } - bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation &ctti); - QMap> jsonStructureInformation() const { return m_jsonStructureInformation; } + QMap getDbTables() const + { + return m_sqlTableInformations; + } -private: - bool handleEnum(const EnumInformation &ei); - bool handleTable(const ServiceStructInformation &ssi); - bool handleIdlStructInfo(const TopicTypeInformation &tti, - QVector &destination, - const QString &svcName = QString()); - bool loadExternalTopicType(const ServiceTypeStruct &sts); + QMap getDbViews() const + { + return m_sqlViewInformations; + } - bool getColumnsFromTable(const QString &tableName, - QVector &columns, - QVector &tableNames) const; + bool needPoint3d() const + { + return m_needPoint3d; + } - bool fixupCustomDbDatatypes(MemberInformation &memberInfo, QVector &members); - bool fixupDatatypePoint2d(MemberInformation &memberInfo, QVector &members); - bool fixupDatatypePoint3d(MemberInformation &memberInfo, QVector &members); - bool fixupDatatypeIntegerArray(MemberInformation &memberInfo); + bool needPgArrayInclude() const + { + return m_needPgArrayInclude; + } - QVector buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation &ctti, - const QString &tableName, - const QString &columnNamePrefix, - const QString &cppStructure); - void addToSerializeFromToJsonTopics(const QSharedPointer &toAdd); - CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation &ctti, - const MemberInformation &miPrimaryKey); - MemberInformation getRecordPrimaryKey() const; + CompleteTableInformation completeTableInformation(const CompleteTopicTypeInformation& ctti); + CompleteTableInformation getRecordingTopicTable(const QString& structName); + QMap getRecordingTopicTables(); + QVector> getSerializeFromToJsonTopics() const; + bool fixupQVariantConversions(MemberInformation& mi) const; - ServiceTypeStruct extractServiceAndTypeFromTypename(const QString &type); + Q_REQUIRED_RESULT static QString firstCharLowercase(const QString& txt); + Q_REQUIRED_RESULT static QString camelCaseString(const QString& in, bool bFirstUppercase = false); + Q_REQUIRED_RESULT static QString camelCaseToUnderline(const QString& in); - void addToSqlTableInformation(const MemberInformation &mi); -private: - QVector m_structInfos; - QVector m_topicTypeInfos; - mutable QVector m_externalTopicTypes; - QVector m_enumInfos; - QMap m_sqlTableInformations; - QMap m_sqlViewInformations; - QSet m_sqlTableInformationsAlreadyAvailable; - QVector> m_serializeFromToJsonTopics; + bool buildJSonStructureInformationFromIdlData(const CompleteTopicTypeInformation& ctti); - QMap> m_jsonStructureInformation; + QMap> jsonStructureInformation() const + { + return m_jsonStructureInformation; + } - bool m_needPoint3d; - bool m_needPgArrayInclude; + private: + bool handleEnum(const EnumInformation& ei); + bool handleTable(const ServiceStructInformation& ssi); + bool handleIdlStructInfo(const TopicTypeInformation& tti, QVector& destination, + const QString& svcName = QString()); + bool loadExternalTopicType(const ServiceTypeStruct& sts); - XmlReader *m_xmlReader; - NGL::INGLLogger &m_logger; - NGL::INGLLogger &m_loggerCSV; + bool getColumnsFromTable(const QString& tableName, QVector& columns, + QVector& tableNames) const; + + bool fixupCustomDbDatatypes(MemberInformation& memberInfo, QVector& members); + bool fixupDatatypePoint2d(MemberInformation& memberInfo, QVector& members); + bool fixupDatatypePoint3d(MemberInformation& memberInfo, QVector& members); + bool fixupDatatypeIntegerArray(MemberInformation& memberInfo); + + QVector buildDbTableInformationFromIdlData(const CompleteTopicTypeInformation& ctti, + const QString& tableName, + const QString& columnNamePrefix, + const QString& cppStructure); + void addToSerializeFromToJsonTopics(const QSharedPointer& toAdd); + CompleteTableInformation getRecordingTopicTable(const CompleteTopicTypeInformation& ctti, + const MemberInformation& miPrimaryKey); + MemberInformation getRecordPrimaryKey() const; + + ServiceTypeStruct extractServiceAndTypeFromTypename(const QString& type); + + void addToSqlTableInformation(const MemberInformation& mi); + + private: + QVector m_structInfos; + QVector m_topicTypeInfos; + mutable QVector m_externalTopicTypes; + QVector m_enumInfos; + QMap m_sqlTableInformations; + QMap m_sqlViewInformations; + QSet m_sqlTableInformationsAlreadyAvailable; + QVector> m_serializeFromToJsonTopics; + + QMap> m_jsonStructureInformation; + + bool m_needPoint3d; + bool m_needPgArrayInclude; + + XmlReader* m_xmlReader; + NGL::INGLLogger& m_logger; + NGL::INGLLogger& m_loggerCSV; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.cpp old mode 100755 new mode 100644 index 44a8a6af8..8e5ebd070 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.cpp @@ -1,931 +1,895 @@  #include "XmlReader.h" -#include #include - #include -#include #include +#include #include #include +#include using namespace CodeGen; - class XmlReaderException : public std::exception { -public: - explicit XmlReaderException(const QString &msg) noexcept - : m_msg(msg.toUtf8()) - {} + public: + explicit XmlReaderException(const QString& msg) noexcept : m_msg(msg.toUtf8()) {} - ~XmlReaderException() = default; + ~XmlReaderException() = default; - virtual const char *what() const noexcept - { - return m_msg.data(); - } -private: - const QByteArray m_msg; + virtual const char* what() const noexcept + { + return m_msg.data(); + } + + private: + const QByteArray m_msg; }; XmlReader::XmlReader() : m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} -bool XmlReader::readServiceFile(const QString &svcFile, - const QString &idlServiceInfoFile, - const XmlReader *parent) +bool XmlReader::readServiceFile(const QString& svcFile, const QString& idlServiceInfoFile, const XmlReader* parent) { - m_externalXmlInformations.clear(); - m_idlFiles.clear(); - m_xmlFiles.clear(); - m_usedServices.clear(); - m_fullServiceName2Abbreviation.clear(); - - m_svcNamespace.clear(); - m_svcAbbr.clear(); - m_svcProcNames.clear(); - m_customRecordReplay = false; - m_exerciseDependency = ExerciseDependency::Exercise; - m_dbClassTables.clear(); - m_struct2BaseClass.clear(); - m_structsToGenerate.clear(); - m_idlStructsToGenerate.clear(); - m_tables.clear(); - m_views.clear(); - m_enumerations.clear(); - m_functionTopics.clear(); - m_externalTopicTypes.clear(); - m_customFunctions.clear(); - m_prio = 0; - m_svcDevMode = false; + m_externalXmlInformations.clear(); + m_idlFiles.clear(); + m_xmlFiles.clear(); + m_usedServices.clear(); + m_fullServiceName2Abbreviation.clear(); - - if (parent) - { - m_idlFiles = parent->m_idlFiles; - m_xmlFiles = parent->m_xmlFiles; - m_fullServiceName2Abbreviation = parent->m_fullServiceName2Abbreviation; - m_externalXmlInformations = parent->m_externalXmlInformations; - } + m_svcNamespace.clear(); + m_svcAbbr.clear(); + m_svcProcNames.clear(); + m_customRecordReplay = false; + m_exerciseDependency = ExerciseDependency::Exercise; + m_dbClassTables.clear(); + m_struct2BaseClass.clear(); + m_structsToGenerate.clear(); + m_idlStructsToGenerate.clear(); + m_tables.clear(); + m_views.clear(); + m_enumerations.clear(); + m_functionTopics.clear(); + m_externalTopicTypes.clear(); + m_customFunctions.clear(); + m_prio = 0; + m_svcDevMode = false; - - - loadIdlInfofile(idlServiceInfoFile); - - - QFile f(svcFile); - if (!f.exists()) - { - ERROR_LOG(m_logger) << "Service file '" << svcFile << "' not found!"; - return false; - } - if (!f.open(QIODevice::ReadOnly)) - { - m_errorString = QLatin1String("Can not open service file '") + svcFile + - QLatin1String("' for reading: ") + f.errorString(); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - INFO_LOG(m_logger) << "SvcFile: " << svcFile; - - - QString errMsg; - int errLine = 0; - int errColumn = 0; - QDomDocument doc; - if (!doc.setContent(&f, &errMsg, &errLine, &errColumn)) - { - m_errorString = QLatin1String("Error parsing service file '") + svcFile + QLatin1String("': ") + - errMsg + QLatin1String(" at ") + QString::number(errLine) + - QLatin1Char(':') + QString::number(errColumn); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - - - - - - - - QDomElement domRoot = doc.documentElement(); - if (!domRoot.hasAttribute(QStringLiteral("namespace"))) - { - m_errorString = QLatin1String("Xml file '") + svcFile + - QLatin1String("' is not a valid service file: service name/namespace is missing"); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - m_svcNamespace = getAttribute(domRoot, QStringLiteral("namespace")); - m_svcAbbr = getAttribute(domRoot, QStringLiteral("abbreviation")).toLower(); - m_svcProcNames = getAttribute(domRoot, QStringLiteral("procNames")).split(QLatin1Char(',')); - m_customRecordReplay = getAttributeBool(domRoot, QStringLiteral("customRecordReplay"), true, false); - - QString devModeStr = getAttribute(domRoot, QStringLiteral("devMode"), true); - m_svcDevMode = devModeStr == QStringLiteral("1") || - devModeStr == QStringLiteral("true"); - INFO_LOG(m_logger) << "devMode: " << m_svcDevMode; - - const QString groupNamesString = getAttribute(domRoot, QStringLiteral("groups"), true); - if (!groupNamesString.isEmpty()) - { - m_groupNames = groupNamesString.split(QLatin1Char(','), Qt::SkipEmptyParts); - INFO_LOG(m_logger) << "groups: " << groupNamesString; - } - else - m_groupNames.clear(); - - m_exerciseDependency = string2ExerciseDependency(getAttribute(domRoot, QStringLiteral("exerciseDependency"), true)); - - - - if (m_groupNames.contains(QStringLiteral("Core")) || - m_groupNames.contains(QStringLiteral("Master"))) - { - if (m_exerciseDependency != ExerciseDependency::Global && - m_exerciseDependency != ExerciseDependency::GlobalAndExercise) + if (parent) { - WARNING_LOG(m_logger) << "Service " << getServiceNamespace() - << " is not marked as exercise independent but should be started in group Core/Master"; - } - } - - INFO_LOG(m_logger) << "exerciseDependency: " << (int)m_exerciseDependency; - if ( domRoot.hasAttribute(QStringLiteral("prio"))) - { - m_prio = getAttribute(domRoot, QStringLiteral("prio"), 0).toInt(); - } - try - { - parseDBSserviceStructs(domRoot.firstChildElement(QStringLiteral("dbServiceStructs"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing dbServiceStructs: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseDBTables(domRoot.firstChildElement(QStringLiteral("tables"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing dbtables: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseDBViews(domRoot.firstChildElement(QStringLiteral("views"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing dbviews: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseEnumerations(domRoot.firstChildElement(QStringLiteral("enumerations"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing enumerations: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseCustomDtcFunctions(domRoot.firstChildElement(QStringLiteral("customDtcFunctions"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing custom dtc functions: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseTopicTypes(domRoot.firstChildElement(QStringLiteral("topicTypes"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing idl strucs: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - try - { - parseFunctionTopics(domRoot.firstChildElement(QStringLiteral("functionTopics"))); - } - catch (const XmlReaderException &ex) - { - m_errorString = QLatin1String("Error parsing function topics: ") + QLatin1String(ex.what()); - ERROR_LOG(m_logger) << m_errorString; - return false; - } - - return true; -} - -QString XmlReader::getAttribute(const QDomElement &element, - const QString &attributeName, - bool bOptional) -{ - if (!element.hasAttribute(attributeName)) - { - if (bOptional) - return QString(); - throw XmlReaderException(QLatin1String("Element ") + element.tagName() + - QLatin1String(" has no attribute ") + attributeName); - } - return element.attribute(attributeName); -} - -bool XmlReader::getAttributeBool(const QDomElement &element, - const QString &attributeName, - bool bOptional, bool defaultValue) -{ - QString str = getAttribute(element, attributeName, bOptional); - if (str.isEmpty()) - return defaultValue; - bool bOk; - bool ret = (str.toInt(&bOk) != 0); - if (!bOk) - throw XmlReaderException(QLatin1String("Can not parse boolean value: ") + str); - return ret; -} - -int XmlReader::getAttributeInt(const QDomElement &element, - const QString &attributeName, - bool bOptional, int defaultValue) -{ - QString str = getAttribute(element, attributeName, bOptional); - if (str.isEmpty()) - return defaultValue; - bool bOk; - int ret = str.toInt(&bOk); - if (!bOk) - { - - ret = str.toUInt(&bOk,16); - if(!bOk) - throw XmlReaderException(QLatin1String("Can not parse int value: ") + str); - } - return ret; -} - -void XmlReader::parseDBSserviceStructs(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - - QDomElement domDbStruct = rootElement.firstChildElement(QStringLiteral("serviceStruct")); - while (!domDbStruct.isNull()) - { - ServiceStructInformation ssi; - ssi.name = getAttribute(domDbStruct, QStringLiteral("name")); - ssi.primaryTable = getAttribute(domDbStruct, QStringLiteral("table")); - ssi.hasStaticContent = getAttributeBool(domDbStruct, QStringLiteral("static"), true, false); - - QDomElement domFunc = domDbStruct.firstChildElement(QStringLiteral("function")); - while (!domFunc.isNull()) - { - m_customFunctions += parseCustomFunction(domFunc, CustomServiceFunctionInformation::Type::Db); - domFunc = domFunc.nextSiblingElement(domFunc.tagName()); + m_idlFiles = parent->m_idlFiles; + m_xmlFiles = parent->m_xmlFiles; + m_fullServiceName2Abbreviation = parent->m_fullServiceName2Abbreviation; + m_externalXmlInformations = parent->m_externalXmlInformations; } - QDomElement domNotify = domDbStruct.firstChildElement(QStringLiteral("notification")); - while (!domNotify.isNull()) + loadIdlInfofile(idlServiceInfoFile); + + QFile f(svcFile); + if (!f.exists()) { - ssi.dbNotifications.append(parseDbNotification(domNotify)); - domNotify = domNotify.nextSiblingElement(domNotify.tagName()); + ERROR_LOG(m_logger) << "Service file '" << svcFile << "' not found!"; + return false; + } + if (!f.open(QIODevice::ReadOnly)) + { + m_errorString = + QLatin1String("Can not open service file '") + svcFile + QLatin1String("' for reading: ") + f.errorString(); + ERROR_LOG(m_logger) << m_errorString; + return false; } - m_structsToGenerate.push_back(ssi); + INFO_LOG(m_logger) << "SvcFile: " << svcFile; - domDbStruct = domDbStruct.nextSiblingElement(domDbStruct.tagName()); - } - std::sort(m_structsToGenerate.begin(), m_structsToGenerate.end()); - - - domDbStruct = rootElement.firstChildElement(QStringLiteral("table")); - while (!domDbStruct.isNull()) - { - const QString table = getAttribute(domDbStruct, QStringLiteral("name")); - const QString parentTable = getAttribute(domDbStruct, QStringLiteral("base"), true); - m_struct2BaseClass[table] = parentTable; - - domDbStruct = domDbStruct.nextSiblingElement(domDbStruct.tagName()); - } - INFO_LOG(m_logger) << "Read " << m_structsToGenerate.size() << " database service struct(s)"; -} - -void XmlReader::parseDBTables(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - QDomElement domDbTable = rootElement.firstChildElement(QStringLiteral("table")); - while (!domDbTable.isNull()) - { - QSharedPointer ti(new TableInformation); - ti->name = getAttribute(domDbTable, QStringLiteral("name")); - ti->structName = QLatin1String("t_") + ti->name; - ti->comment = getAttribute(domDbTable, QStringLiteral("comment"), true); - ti->exerciseDependency = string2ExerciseDependency(getAttribute(domDbTable, QStringLiteral("exerciseDependency"), true)); - - QDomElement domColumn = domDbTable.firstChildElement(QStringLiteral("column")); - while (!domColumn.isNull()) + QString errMsg; + int errLine = 0; + int errColumn = 0; + QDomDocument doc; + if (!doc.setContent(&f, &errMsg, &errLine, &errColumn)) { - ti->plainColumns.append(parseTableColumn(domColumn, ti->name)); - domColumn = domColumn.nextSiblingElement(domColumn.tagName()); + m_errorString = QLatin1String("Error parsing service file '") + svcFile + QLatin1String("': ") + errMsg + + QLatin1String(" at ") + QString::number(errLine) + QLatin1Char(':') + + QString::number(errColumn); + ERROR_LOG(m_logger) << m_errorString; + return false; } - QDomElement domForeignKey = domDbTable.firstChildElement(QStringLiteral("foreignKey")); - while (!domForeignKey.isNull()) + QDomElement domRoot = doc.documentElement(); + if (!domRoot.hasAttribute(QStringLiteral("namespace"))) { - ti->foreignKeys.append(parseForeignKey(domForeignKey)); - domForeignKey = domForeignKey.nextSiblingElement(domForeignKey.tagName()); + m_errorString = QLatin1String("Xml file '") + svcFile + + QLatin1String("' is not a valid service file: service name/namespace is missing"); + ERROR_LOG(m_logger) << m_errorString; + return false; } - QDomElement domConstraint = domDbTable.firstChildElement(QStringLiteral("constraint")); - while (!domConstraint.isNull()) + m_svcNamespace = getAttribute(domRoot, QStringLiteral("namespace")); + m_svcAbbr = getAttribute(domRoot, QStringLiteral("abbreviation")).toLower(); + m_svcProcNames = getAttribute(domRoot, QStringLiteral("procNames")).split(QLatin1Char(',')); + m_customRecordReplay = getAttributeBool(domRoot, QStringLiteral("customRecordReplay"), true, false); + + QString devModeStr = getAttribute(domRoot, QStringLiteral("devMode"), true); + m_svcDevMode = devModeStr == QStringLiteral("1") || devModeStr == QStringLiteral("true"); + INFO_LOG(m_logger) << "devMode: " << m_svcDevMode; + + const QString groupNamesString = getAttribute(domRoot, QStringLiteral("groups"), true); + if (!groupNamesString.isEmpty()) { - ti->constraints.append(parseConstraint(domConstraint)); - domConstraint = domConstraint.nextSiblingElement(domConstraint.tagName()); - } - - m_tables.insert(ti->name, ti); - - domDbTable = domDbTable.nextSiblingElement(domDbTable.tagName()); - } - - INFO_LOG(m_logger) << "Read " << m_tables.size() << " database table(s)"; -} - -void XmlReader::parseDBViews(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - QDomElement domDbView = rootElement.firstChildElement(QStringLiteral("view")); - while (!domDbView.isNull()) - { - QSharedPointer vi(new ViewInformation); - vi->name = getAttribute(domDbView, QStringLiteral("name")); - vi->structName = QLatin1String("v_") + vi->name; - vi->baseSchema = m_svcAbbr; - vi->baseTable = getAttribute(domDbView, QStringLiteral("base")); - vi->comment = getAttribute(domDbView, QStringLiteral("comment"), true); - vi->filter = getAttribute(domDbView, QStringLiteral("filter")); - vi->exerciseDependency = string2ExerciseDependency(getAttribute(domDbView, QStringLiteral("exerciseDependency"), true)); - - DEBUG_LOG(m_logger) << "Base table = " << vi->baseTable; - - - m_views.insert(vi->name, vi); - - domDbView = domDbView.nextSiblingElement(domDbView.tagName()); - } - - INFO_LOG(m_logger) << "Read " << m_views.size() << " database view(s)"; -} - -void XmlReader::parseEnumerations(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - QDomElement domEnum = rootElement.firstChildElement(QStringLiteral("enumeration")); - while (!domEnum.isNull()) - { - EnumInformation enumeration; - enumeration.serviceName = getServiceNamespace(); - enumeration.enumName = getAttribute(domEnum, QStringLiteral("name")); - enumeration.tableName = getAttribute(domEnum, QStringLiteral("table"), true); - - QDomElement enumVal = domEnum.firstChildElement(QStringLiteral("attribute")); - while (!enumVal.isNull()) - { - EnumKeyValuePair evp; - evp.key = getAttribute(enumVal, QStringLiteral("key")); - evp.value = getAttributeInt(enumVal, QStringLiteral("value")); - enumeration.values.append(evp); - - enumVal = enumVal.nextSiblingElement(enumVal.tagName()); - } - - m_enumerations.push_back(enumeration); - - domEnum = domEnum.nextSiblingElement(domEnum.tagName()); - } - INFO_LOG(m_logger) << "Read " << m_enumerations.size() << " enumeration(s)"; -} - -void XmlReader::parseCustomDtcFunctions(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - QDomElement domElement = rootElement.firstChildElement(QStringLiteral("customDtcFunction")); - while (!domElement.isNull()) - { - - QDomElement domFunc = domElement.firstChildElement(QStringLiteral("function")); - while (!domFunc.isNull()) - { - m_customFunctions += parseCustomFunction(domFunc, CustomServiceFunctionInformation::Type::Dtc); - domFunc = domFunc.nextSiblingElement(domFunc.tagName()); - } - domElement = domElement.nextSiblingElement(domElement.tagName()); - } - INFO_LOG(m_logger) << "Read " << m_enumerations.size() << " customDtcFunction(s)"; -} - - - -void XmlReader::parseTopicTypes(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - - QDomElement domIdlStruct = rootElement.firstChildElement(QStringLiteral("topicType")); - while (!domIdlStruct.isNull()) - { - TopicTypeInformation isi; - isi.name = getAttribute(domIdlStruct, QStringLiteral("name")); - isi.baseValueType = getAttribute(domIdlStruct, QStringLiteral("baseValueType"), true); - - - const QStringList sl = isi.baseValueType.split(QStringLiteral("::")); - if (sl.size() == 2) - loadExternalTopicType(sl.at(0), sl.at(1)); - - const QString tmp = getAttribute(domIdlStruct, QStringLiteral("extensibility"), true); - -#ifdef RTI_HEADER_AVAILABLE - if (tmp.compare(QLatin1String("FINAL"), Qt::CaseInsensitive) == 0) isi.extensibility = dds::core::xtypes::ExtensibilityKind::FINAL; - if (tmp.compare(QLatin1String("MUTABLE"), Qt::CaseInsensitive) == 0) isi.extensibility = dds::core::xtypes::ExtensibilityKind::MUTABLE; - if (tmp.compare(QLatin1String("EXTENSIBLE"), Qt::CaseInsensitive) == 0) isi.extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE; -#else - // RTI not available - skip extensibility parsing - Q_UNUSED(tmp) -#endif - - isi.comment = getAttribute(domIdlStruct, QStringLiteral("comment"), true); - isi.isDataObject = getAttributeBool(domIdlStruct, QStringLiteral("isDataObject"), true, false); - isi.dtsAutogen = getAttributeBool(domIdlStruct, QStringLiteral("autogenDTS"), true, true); - isi.dtcAutogen = getAttributeBool(domIdlStruct, QStringLiteral("autogenDTC"), true, true); - isi.recordTopic = getAttributeBool(domIdlStruct, QStringLiteral("recordTopic"), true, false); - isi.routeToClient = getAttributeBool(domIdlStruct, QStringLiteral("routeToClient"), true, true); - isi.routeToServer = getAttributeBool(domIdlStruct, QStringLiteral("routeToServer"), true, false); - isi.routeInReplay = getAttributeBool(domIdlStruct, QStringLiteral("routeInReplay"), true, false); - isi.autosubscribe = getAttributeBool(domIdlStruct, QStringLiteral("autosubscribe"), true, true); - - QDomElement domColumn = domIdlStruct.firstChildElement(QStringLiteral("column")); - while (!domColumn.isNull()) - { - isi.columns.append(parseIdlStructColumn(domColumn)); - domColumn = domColumn.nextSiblingElement(domColumn.tagName()); - } - - - m_idlStructsToGenerate.insert(isi.name, isi); - - domIdlStruct = domIdlStruct.nextSiblingElement(domIdlStruct.tagName()); - } - - - INFO_LOG(m_logger) << "Read " << m_idlStructsToGenerate.size() << " idl struct(s)"; -} - -void XmlReader::parseFunctionTopics(const QDomElement &rootElement) -{ - if (rootElement.isNull()) - return; - - - QDomElement domFunctionTopic = rootElement.firstChildElement(QStringLiteral("functionTopic")); - while (!domFunctionTopic.isNull()) - { - FunctionTopic ft; - ft.name = getAttribute(domFunctionTopic, QStringLiteral("name")); - ft.requestTopicType = getAttribute(domFunctionTopic, QStringLiteral("requestTopicType")); - ft.replyTopicType = getAttribute(domFunctionTopic, QStringLiteral("replyTopicType")); - ft.requestTopicName = getAttribute(domFunctionTopic, QStringLiteral("requestTopicName")); - ft.replyTopicName = getAttribute(domFunctionTopic, QStringLiteral("replyTopicName")); - ft.routeInReplay = getAttributeBool(domFunctionTopic, QStringLiteral("routeInReplay"), true, false); - - m_functionTopics.append(ft); - - domFunctionTopic = domFunctionTopic.nextSiblingElement(domFunctionTopic.tagName()); - } - - for (const FunctionTopic &ft : std::as_const(m_functionTopics)) - { - const QStringList sl1 = ft.requestTopicType.split(QStringLiteral("::")); - if (sl1.size() == 2) - loadExternalTopicType(sl1.at(0), sl1.at(1)); - const QStringList sl2 = ft.replyTopicType.split(QStringLiteral("::")); - if (sl2.size() == 2) - loadExternalTopicType(sl2.at(0), sl2.at(1)); - } -} - -ColumnInformation XmlReader::parseTableColumn(const QDomElement &column, const QString &tableName) const -{ - ColumnInformation ci; - - ci.columnName = getAttribute(column, QStringLiteral("name")); - ci.datatype = getAttribute(column, QStringLiteral("datatype")); - ci.defaultValue = getAttribute(column, QStringLiteral("default"), true); - ci.comment = getAttribute(column, QStringLiteral("comment"), true); - ci.isPrimaryKey = getAttributeBool(column, QStringLiteral("isPrimaryKey"), true, false); - ci.isForeignKey = getAttributeBool(column, QStringLiteral("isForeignKey"), true, false); - ci.isOptional = getAttributeBool(column, QStringLiteral("isOptional"), true, false); - const QDomElement seq = column.firstChildElement(QStringLiteral("sequence")); - if (!seq.isNull()) - { - ci.sequenceStart = getAttributeInt(seq, QStringLiteral("start"), true, -1); - ci.sequenceIncrement = getAttributeInt(seq, QStringLiteral("increment"), true, -1); - ci.hasSequence = ci.sequenceStart >= 0 && ci.sequenceIncrement > 0; - } - - if (ci.columnName.toLower() != ci.columnName) - WARNING_LOG(m_logger) << "Column " << ci.columnName << " in Table " - << tableName << " has has upper-case chars which is not allowed!"; - - return ci; -} - -IdlColumnInformation XmlReader::parseIdlStructColumn(const QDomElement &column) const -{ - IdlColumnInformation ci; - - ci.name = getAttribute(column, QStringLiteral("name")); - ci.type = getAttribute(column, QStringLiteral("idlType")); - ci.comment = getAttribute(column, QStringLiteral("comment"), true); - ci.isKey = getAttributeBool(column, QStringLiteral("isKey"), true, false); - ci.isOptional = getAttributeBool(column, QStringLiteral("isOptional"), true, false); - ci.isTranslatable = getAttributeBool(column, QStringLiteral("isTranslatable"), true, false); - - return ci; -} - -QSharedPointer XmlReader::parseForeignKey(const QDomElement &foreignKey) const -{ - QSharedPointer fk(new ForeignKeyInformation); - - fk->name = getAttribute(foreignKey, QStringLiteral("name")); - - const QString deleteAction = getAttribute(foreignKey, QStringLiteral("referential_integrity"), true); - if (deleteAction == QLatin1String("DeleteNoAction")) - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::NoAction; - else if (deleteAction == QLatin1String("DeleteCascade")) - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Cascade; - else if (deleteAction == QLatin1String("DeleteRestrict")) - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Restrict; - else if (deleteAction == QLatin1String("DeleteSetNull")) - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::SetNull; - else if (deleteAction == QLatin1String("DeleteSetDefault")) - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::SetDefault; - else - fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Cascade; - - fk->source = parseForeignKeyEndpoint(fk->name, foreignKey.firstChildElement(QStringLiteral("source"))); - fk->destination = parseForeignKeyEndpoint(fk->name, foreignKey.firstChildElement(QStringLiteral("destination"))); - - return fk; -} - -ForeignKeyInformation::Endpoint XmlReader::parseForeignKeyEndpoint(const QString &foreignKeyName, - const QDomElement &endpoint) const -{ - if (endpoint.isNull()) - throw XmlReaderException(QLatin1String("No endpoint for foreign key ") + foreignKeyName); - - ForeignKeyInformation::Endpoint fkEndpoint; - - fkEndpoint.service = getAttribute(endpoint, QStringLiteral("service"), true); - fkEndpoint.serviceAbbr= getAttribute(endpoint, QStringLiteral("serviceAbbr"), true); - fkEndpoint.schema = getAttribute(endpoint, QStringLiteral("schema"), true); - fkEndpoint.tableName = getAttribute(endpoint, QStringLiteral("table")); - fkEndpoint.columnName = getAttribute(endpoint, QStringLiteral("column")); - - return fkEndpoint; -} - -ConstraintInformation XmlReader::parseConstraint(const QDomElement &constraint) const -{ - ConstraintInformation ret; - - ret.name = getAttribute(constraint, QStringLiteral("name"), true); - const QString type = getAttribute(constraint, QStringLiteral("type")).toLower(); - if (type == QLatin1String("unique")) - ret.type = ConstraintInformation::Type::unique; - else if (type == QLatin1String("index")) - ret.type = ConstraintInformation::Type::index; - - QDomElement domColumn = constraint.firstChildElement(QStringLiteral("column")); - if (domColumn.isNull()) - throw XmlReaderException(QLatin1String("No column for constraint") + ret.name); - while (!domColumn.isNull()) - { - ret.affectedColumns += getAttribute(domColumn, QStringLiteral("name")); - domColumn = domColumn.nextSiblingElement(domColumn.tagName()); - } - return ret; -} - -CustomServiceFunctionInformation XmlReader::parseCustomFunction(const QDomElement &customFunc, - CustomServiceFunctionInformation::Type funcType) const -{ - CustomServiceFunctionInformation ret; - ret.methodName = getAttribute(customFunc, QStringLiteral("name")); - ret.returnValue = getAttribute(customFunc, QStringLiteral("returns"), true); - ret.isConst = getAttributeBool(customFunc, QStringLiteral("isConst"), true, false); - if (ret.returnValue.isEmpty()) - ret.returnValue = QStringLiteral("bool"); - QMap> paramHelper; - QDomElement domParam = customFunc.firstChildElement(QStringLiteral("parameter")); - while (!domParam.isNull()) - { - int pos = getAttributeInt(domParam, QStringLiteral("pos")); - if (paramHelper.contains(pos)) - throw XmlReaderException(QLatin1String("Doubled position entry for custom function ") + ret.methodName); - QString paramName = getAttribute(domParam, QStringLiteral("name")); - const QString paramType = getAttribute(domParam, QStringLiteral("type")); - const QString paramDefault = getAttribute(domParam, QStringLiteral("default"), true); - if (!paramDefault.isEmpty()) - paramName.append(QLatin1String(" = ") + paramDefault); - paramHelper[pos] = qMakePair(paramName, paramType); - domParam = domParam.nextSiblingElement(domParam.tagName()); - - } - ret.paramNames.reserve(paramHelper.size()); - ret.paramTypes.reserve(paramHelper.size()); - ret.type = funcType; - QStringList signature; - for (auto it = paramHelper.constBegin(); it != paramHelper.constEnd(); ++it) - { - ret.paramNames += it.value().first; - ret.paramTypes += it.value().second; - QString tmp = it.value().second; - if (!it.value().second.endsWith(QLatin1Char('&'))) - tmp += QLatin1Char(' '); - tmp += it.value().first; - signature += tmp; - } - ret.signature += signature.join(QStringLiteral(", ")); - return ret; -} - -DbNotifcationInformation XmlReader::parseDbNotification(const QDomElement &customFunc) const -{ - DbNotifcationInformation ret(parseCustomFunction(customFunc, CustomServiceFunctionInformation::Type::DbNotify)); - - const QString attribute(getAttribute(customFunc, QStringLiteral("notificationTypes")).toLower()); - const QStringList nfTypes = attribute.split(QLatin1Char(',')); - static const QMap s_nfTypeMap = - { - { QLatin1String("beforeinsert"), DbNotifcationInformation::NotificationType::BeforeInsert }, - { QLatin1String("afterinsert"), DbNotifcationInformation::NotificationType::AfterInsert }, - { QLatin1String("beforeupdate"), DbNotifcationInformation::NotificationType::BeforeUpdate }, - { QLatin1String("afterupdate"), DbNotifcationInformation::NotificationType::AfterUpdate }, - { QLatin1String("beforedelete"), DbNotifcationInformation::NotificationType::BeforeDelete }, - { QLatin1String("afterdelete"), DbNotifcationInformation::NotificationType::AfterDelete } - }; - for (const QString &nfType : nfTypes) - { - const auto it = s_nfTypeMap.find(nfType); - if (it == s_nfTypeMap.end()) - throw XmlReaderException(QStringLiteral("Can not find notification type %2 in type map for function %1").arg(ret.methodName, nfType)); - ret.notificationType += it.value(); - } - if (ret.notificationType.isEmpty()) - throw XmlReaderException(QStringLiteral("Notification function '%1' without a valid notification type").arg(ret.methodName)); - if (ret.paramTypes.size() != 1) - throw XmlReaderException(QStringLiteral("Notification function '%1' must have exactly one parameter").arg(ret.methodName)); - - return ret; -} - -TopicTypeInformation XmlReader::loadExternalTopicType(const QString &externalServiceName, const QString &topicTypeName) -{ - DEBUG_LOG(m_logger) << "externalServiceName: " << externalServiceName << ", topicTypeName: " << topicTypeName; - - if (!loadExternalService(externalServiceName)) - { - WARNING_LOG(m_logger) << "Could not find service " << externalServiceName - << " referenced by external topic " << topicTypeName; - return TopicTypeInformation(); - } - auto extXmlReader = m_externalXmlInformations.value(externalServiceName); - if (!extXmlReader) - { - ERROR_LOG(m_logger) << "Could not find service xml file for service '" << externalServiceName << "'"; - return TopicTypeInformation(); - } - - TopicTypeInformation tti = extXmlReader->getIdlStructInformation().value(topicTypeName); - if (tti.isValid()) - { - tti.name = externalServiceName + QLatin1String("::") + tti.name; - m_externalTopicTypes += tti; - m_usedServices[externalServiceName] = true; - return tti; - } - WARNING_LOG(m_logger) << "Could not find topic " << topicTypeName - << " in external service definition for service " - << externalServiceName; - return TopicTypeInformation(); -} - -EnumInformation XmlReader::getExternalEnumeration(const QString &externalServiceName, const QString &enumName, bool verbose) -{ - DEBUG_LOG(m_logger) << "externalServiceName: " << externalServiceName << ", topicTypeName: " << enumName; - - if (!loadExternalService(externalServiceName)) - { - WARNING_LOG(m_logger) << "Could not find service '" << externalServiceName << "'" - << " referenced by external enumeration " << enumName; - return EnumInformation(); - } - auto extXmlReader = m_externalXmlInformations.value(externalServiceName); - if (!extXmlReader) - { - ERROR_LOG(m_logger) << "Could not find service xml file for service '" << externalServiceName << "'"; - return EnumInformation(); - } - - const QVector enums = extXmlReader->getEnumerations(); - for (const EnumInformation &ei : enums) - { - if (ei.enumName == enumName) - { - m_usedServices[externalServiceName] = true; - return ei; - } - } - if (verbose) - { - WARNING_LOG(m_logger) << "Could not find enumeration " << enumName - << " in external service definition for '" - << externalServiceName << "'"; - } - return EnumInformation(); -} - - -bool XmlReader::loadExternalService(const QString &serviceName) -{ - if (serviceName == getServiceNamespace()) - return false; - if (m_externalXmlInformations.contains(serviceName)) - return true; - - QString fileName = xmlFileForService(serviceName); - if (fileName.isEmpty()) - { - const QVector dirs = NGL::directories(NGL::FileType::ConfigFile); - for (const QString &dirname : dirs) - { - QDirIterator dirIt(dirname + QStringLiteral("/xml"), QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); - while (dirIt.hasNext()) - { - dirIt.next(); - if (!dirIt.fileName().endsWith(QLatin1String(".xml"))) - continue; - - fileName = dirIt.filePath(); - const QString svcNamespace = serviceNamespaceFromFile(fileName); - if (svcNamespace == serviceName) - break; - } - } - } - if (fileName.isEmpty()) - return false; - - DEBUG_LOG(m_logger) << "xml file for " << serviceName << ": " << fileName; - auto extXmlReader = QSharedPointer(new XmlReader); - if (!extXmlReader->readServiceFile(fileName, QString(), this)) - { - WARNING_LOG(m_logger) << "Error reading service file " << fileName - << " for service " << serviceName; - return false; - } - m_externalXmlInformations[serviceName] = extXmlReader; - if (!m_usedServices.contains(serviceName)) - m_usedServices[serviceName] = false; - return true; -} - -void XmlReader::loadIdlInfofile(const QString &idlServiceInfoFile) -{ - if (idlServiceInfoFile.isEmpty()) - return; - QFile f(idlServiceInfoFile); - if (!f.open(QIODevice::ReadOnly)) - { - WARNING_LOG(m_logger) << "Could not read idl service info file " << idlServiceInfoFile; - return; - } - const QList files = f.readAll().split('\n'); - for (const QByteArray &filePath : files) - { - - if (filePath.startsWith("--") || filePath.trimmed().isEmpty()) - continue; - const QString fileName = QString::fromLocal8Bit(filePath.trimmed()); - const QStringList parts = fileName.split(QStringLiteral("/")); - getServiceNameInfoFromFilePath(parts); - const auto fn = parts.last().trimmed(); - if (fn.endsWith(QLatin1String(".xml"))) - { - const auto svcAbbreveation = fn.split(QLatin1Char('.')).at(0).split(QLatin1Char('_')).at(0); - m_xmlFiles[svcAbbreveation] = fileName; - DEBUG_LOG(m_logger) << "xml: " << svcAbbreveation << " = " << fileName; + m_groupNames = groupNamesString.split(QLatin1Char(','), Qt::SkipEmptyParts); + INFO_LOG(m_logger) << "groups: " << groupNamesString; } else + m_groupNames.clear(); + + m_exerciseDependency = string2ExerciseDependency(getAttribute(domRoot, QStringLiteral("exerciseDependency"), true)); + + if (m_groupNames.contains(QStringLiteral("Core")) || m_groupNames.contains(QStringLiteral("Master"))) { - const auto svcAbbreveation = fn.split(QLatin1Char('.')).at(0).toLower(); - if (svcAbbreveation.endsWith(QLatin1String("_enums"))) - continue; - m_idlFiles[svcAbbreveation] = fileName; - DEBUG_LOG(m_logger) << "idl: " << svcAbbreveation << " = " << fileName; + if (m_exerciseDependency != ExerciseDependency::Global && + m_exerciseDependency != ExerciseDependency::GlobalAndExercise) + { + WARNING_LOG(m_logger) + << "Service " << getServiceNamespace() + << " is not marked as exercise independent but should be started in group Core/Master"; + } } - } + + INFO_LOG(m_logger) << "exerciseDependency: " << (int)m_exerciseDependency; + if (domRoot.hasAttribute(QStringLiteral("prio"))) + { + m_prio = getAttribute(domRoot, QStringLiteral("prio"), 0).toInt(); + } + try + { + parseDBSserviceStructs(domRoot.firstChildElement(QStringLiteral("dbServiceStructs"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing dbServiceStructs: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseDBTables(domRoot.firstChildElement(QStringLiteral("tables"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing dbtables: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseDBViews(domRoot.firstChildElement(QStringLiteral("views"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing dbviews: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseEnumerations(domRoot.firstChildElement(QStringLiteral("enumerations"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing enumerations: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseCustomDtcFunctions(domRoot.firstChildElement(QStringLiteral("customDtcFunctions"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing custom dtc functions: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseTopicTypes(domRoot.firstChildElement(QStringLiteral("topicTypes"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing idl strucs: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + try + { + parseFunctionTopics(domRoot.firstChildElement(QStringLiteral("functionTopics"))); + } + catch (const XmlReaderException& ex) + { + m_errorString = QLatin1String("Error parsing function topics: ") + QLatin1String(ex.what()); + ERROR_LOG(m_logger) << m_errorString; + return false; + } + + return true; } -QString XmlReader::getIdlFileForService(const QMap &data, - const QString &serviceName) const +QString XmlReader::getAttribute(const QDomElement& element, const QString& attributeName, bool bOptional) { - const QString serviceAbbr = serviceNameAbbreviation(serviceName); - return data.value(serviceAbbr); + if (!element.hasAttribute(attributeName)) + { + if (bOptional) + return QString(); + throw XmlReaderException(QLatin1String("Element ") + element.tagName() + QLatin1String(" has no attribute ") + + attributeName); + } + return element.attribute(attributeName); } - -QString XmlReader::serviceNameAbbreviation(const QString &serviceName) const +bool XmlReader::getAttributeBool(const QDomElement& element, const QString& attributeName, bool bOptional, + bool defaultValue) { - return m_fullServiceName2Abbreviation.value(serviceName); + QString str = getAttribute(element, attributeName, bOptional); + if (str.isEmpty()) + return defaultValue; + bool bOk; + bool ret = (str.toInt(&bOk) != 0); + if (!bOk) + throw XmlReaderException(QLatin1String("Can not parse boolean value: ") + str); + return ret; } -void XmlReader::getServiceNameInfoFromFilePath(const QStringList &parts) +int XmlReader::getAttributeInt(const QDomElement& element, const QString& attributeName, bool bOptional, + int defaultValue) { - if (parts.size() < 2) - return; + QString str = getAttribute(element, attributeName, bOptional); + if (str.isEmpty()) + return defaultValue; + bool bOk; + int ret = str.toInt(&bOk); + if (!bOk) + { - - const QString abbreviation = parts.last().split(QLatin1Char('.')).first().split(QLatin1Char('_')).first(); - const QString serviceName = parts.at(parts.size() - 2); - DEBUG_LOG(m_logger) << "serviceName: " << serviceName << " = " << abbreviation; - m_fullServiceName2Abbreviation[serviceName] = abbreviation; + ret = str.toUInt(&bOk, 16); + if (!bOk) + throw XmlReaderException(QLatin1String("Can not parse int value: ") + str); + } + return ret; } -ExerciseDependency XmlReader::string2ExerciseDependency(const QString &str) +void XmlReader::parseDBSserviceStructs(const QDomElement& rootElement) { - if (str.isEmpty()) - return ExerciseDependency::Undefined; - const QStringList sd = str.toLower().split(QLatin1Char(',')); - int ret = ExerciseDependency::Undefined; - for (const QString &s : sd) - { - if (s == QLatin1String("global")) - ret |= ExerciseDependency::Global; - else if (s == QLatin1String("exercise")) - ret |= ExerciseDependency::Exercise; - else if (s == QLatin1String("globalandexercise")) - ret |= ExerciseDependency::GlobalAndExercise; - } - return static_cast(ret); + if (rootElement.isNull()) + return; + + QDomElement domDbStruct = rootElement.firstChildElement(QStringLiteral("serviceStruct")); + while (!domDbStruct.isNull()) + { + ServiceStructInformation ssi; + ssi.name = getAttribute(domDbStruct, QStringLiteral("name")); + ssi.primaryTable = getAttribute(domDbStruct, QStringLiteral("table")); + ssi.hasStaticContent = getAttributeBool(domDbStruct, QStringLiteral("static"), true, false); + + QDomElement domFunc = domDbStruct.firstChildElement(QStringLiteral("function")); + while (!domFunc.isNull()) + { + m_customFunctions += parseCustomFunction(domFunc, CustomServiceFunctionInformation::Type::Db); + domFunc = domFunc.nextSiblingElement(domFunc.tagName()); + } + + QDomElement domNotify = domDbStruct.firstChildElement(QStringLiteral("notification")); + while (!domNotify.isNull()) + { + ssi.dbNotifications.append(parseDbNotification(domNotify)); + domNotify = domNotify.nextSiblingElement(domNotify.tagName()); + } + + m_structsToGenerate.push_back(ssi); + + domDbStruct = domDbStruct.nextSiblingElement(domDbStruct.tagName()); + } + std::sort(m_structsToGenerate.begin(), m_structsToGenerate.end()); + + domDbStruct = rootElement.firstChildElement(QStringLiteral("table")); + while (!domDbStruct.isNull()) + { + const QString table = getAttribute(domDbStruct, QStringLiteral("name")); + const QString parentTable = getAttribute(domDbStruct, QStringLiteral("base"), true); + m_struct2BaseClass[table] = parentTable; + + domDbStruct = domDbStruct.nextSiblingElement(domDbStruct.tagName()); + } + INFO_LOG(m_logger) << "Read " << m_structsToGenerate.size() << " database service struct(s)"; } -QString XmlReader::serviceNamespaceFromFile(const QString &fn) +void XmlReader::parseDBTables(const QDomElement& rootElement) { - QFile f(fn); - if (!f.open(QIODevice::ReadOnly)) + if (rootElement.isNull()) + return; + + QDomElement domDbTable = rootElement.firstChildElement(QStringLiteral("table")); + while (!domDbTable.isNull()) + { + QSharedPointer ti(new TableInformation); + ti->name = getAttribute(domDbTable, QStringLiteral("name")); + ti->structName = QLatin1String("t_") + ti->name; + ti->comment = getAttribute(domDbTable, QStringLiteral("comment"), true); + ti->exerciseDependency = + string2ExerciseDependency(getAttribute(domDbTable, QStringLiteral("exerciseDependency"), true)); + + QDomElement domColumn = domDbTable.firstChildElement(QStringLiteral("column")); + while (!domColumn.isNull()) + { + ti->plainColumns.append(parseTableColumn(domColumn, ti->name)); + domColumn = domColumn.nextSiblingElement(domColumn.tagName()); + } + + QDomElement domForeignKey = domDbTable.firstChildElement(QStringLiteral("foreignKey")); + while (!domForeignKey.isNull()) + { + ti->foreignKeys.append(parseForeignKey(domForeignKey)); + domForeignKey = domForeignKey.nextSiblingElement(domForeignKey.tagName()); + } + QDomElement domConstraint = domDbTable.firstChildElement(QStringLiteral("constraint")); + while (!domConstraint.isNull()) + { + ti->constraints.append(parseConstraint(domConstraint)); + domConstraint = domConstraint.nextSiblingElement(domConstraint.tagName()); + } + + m_tables.insert(ti->name, ti); + + domDbTable = domDbTable.nextSiblingElement(domDbTable.tagName()); + } + + INFO_LOG(m_logger) << "Read " << m_tables.size() << " database table(s)"; +} + +void XmlReader::parseDBViews(const QDomElement& rootElement) +{ + if (rootElement.isNull()) + return; + + QDomElement domDbView = rootElement.firstChildElement(QStringLiteral("view")); + while (!domDbView.isNull()) + { + QSharedPointer vi(new ViewInformation); + vi->name = getAttribute(domDbView, QStringLiteral("name")); + vi->structName = QLatin1String("v_") + vi->name; + vi->baseSchema = m_svcAbbr; + vi->baseTable = getAttribute(domDbView, QStringLiteral("base")); + vi->comment = getAttribute(domDbView, QStringLiteral("comment"), true); + vi->filter = getAttribute(domDbView, QStringLiteral("filter")); + vi->exerciseDependency = + string2ExerciseDependency(getAttribute(domDbView, QStringLiteral("exerciseDependency"), true)); + + DEBUG_LOG(m_logger) << "Base table = " << vi->baseTable; + + m_views.insert(vi->name, vi); + + domDbView = domDbView.nextSiblingElement(domDbView.tagName()); + } + + INFO_LOG(m_logger) << "Read " << m_views.size() << " database view(s)"; +} + +void XmlReader::parseEnumerations(const QDomElement& rootElement) +{ + if (rootElement.isNull()) + return; + + QDomElement domEnum = rootElement.firstChildElement(QStringLiteral("enumeration")); + while (!domEnum.isNull()) + { + EnumInformation enumeration; + enumeration.serviceName = getServiceNamespace(); + enumeration.enumName = getAttribute(domEnum, QStringLiteral("name")); + enumeration.tableName = getAttribute(domEnum, QStringLiteral("table"), true); + + QDomElement enumVal = domEnum.firstChildElement(QStringLiteral("attribute")); + while (!enumVal.isNull()) + { + EnumKeyValuePair evp; + evp.key = getAttribute(enumVal, QStringLiteral("key")); + evp.value = getAttributeInt(enumVal, QStringLiteral("value")); + enumeration.values.append(evp); + + enumVal = enumVal.nextSiblingElement(enumVal.tagName()); + } + + m_enumerations.push_back(enumeration); + + domEnum = domEnum.nextSiblingElement(domEnum.tagName()); + } + INFO_LOG(m_logger) << "Read " << m_enumerations.size() << " enumeration(s)"; +} + +void XmlReader::parseCustomDtcFunctions(const QDomElement& rootElement) +{ + if (rootElement.isNull()) + return; + + QDomElement domElement = rootElement.firstChildElement(QStringLiteral("customDtcFunction")); + while (!domElement.isNull()) + { + + QDomElement domFunc = domElement.firstChildElement(QStringLiteral("function")); + while (!domFunc.isNull()) + { + m_customFunctions += parseCustomFunction(domFunc, CustomServiceFunctionInformation::Type::Dtc); + domFunc = domFunc.nextSiblingElement(domFunc.tagName()); + } + domElement = domElement.nextSiblingElement(domElement.tagName()); + } + INFO_LOG(m_logger) << "Read " << m_enumerations.size() << " customDtcFunction(s)"; +} + +void XmlReader::parseTopicTypes(const QDomElement& rootElement) +{ + if (rootElement.isNull()) + return; + + QDomElement domIdlStruct = rootElement.firstChildElement(QStringLiteral("topicType")); + while (!domIdlStruct.isNull()) + { + TopicTypeInformation isi; + isi.name = getAttribute(domIdlStruct, QStringLiteral("name")); + isi.baseValueType = getAttribute(domIdlStruct, QStringLiteral("baseValueType"), true); + + const QStringList sl = isi.baseValueType.split(QStringLiteral("::")); + if (sl.size() == 2) + loadExternalTopicType(sl.at(0), sl.at(1)); + + const QString tmp = getAttribute(domIdlStruct, QStringLiteral("extensibility"), true); + +#ifdef RTI_HEADER_AVAILABLE + if (tmp.compare(QLatin1String("FINAL"), Qt::CaseInsensitive) == 0) + isi.extensibility = dds::core::xtypes::ExtensibilityKind::FINAL; + if (tmp.compare(QLatin1String("MUTABLE"), Qt::CaseInsensitive) == 0) + isi.extensibility = dds::core::xtypes::ExtensibilityKind::MUTABLE; + if (tmp.compare(QLatin1String("EXTENSIBLE"), Qt::CaseInsensitive) == 0) + isi.extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE; +#else + // RTI not available - skip extensibility parsing + Q_UNUSED(tmp) +#endif + + isi.comment = getAttribute(domIdlStruct, QStringLiteral("comment"), true); + isi.isDataObject = getAttributeBool(domIdlStruct, QStringLiteral("isDataObject"), true, false); + isi.dtsAutogen = getAttributeBool(domIdlStruct, QStringLiteral("autogenDTS"), true, true); + isi.dtcAutogen = getAttributeBool(domIdlStruct, QStringLiteral("autogenDTC"), true, true); + isi.recordTopic = getAttributeBool(domIdlStruct, QStringLiteral("recordTopic"), true, false); + isi.routeToClient = getAttributeBool(domIdlStruct, QStringLiteral("routeToClient"), true, true); + isi.routeToServer = getAttributeBool(domIdlStruct, QStringLiteral("routeToServer"), true, false); + isi.routeInReplay = getAttributeBool(domIdlStruct, QStringLiteral("routeInReplay"), true, false); + isi.autosubscribe = getAttributeBool(domIdlStruct, QStringLiteral("autosubscribe"), true, true); + + QDomElement domColumn = domIdlStruct.firstChildElement(QStringLiteral("column")); + while (!domColumn.isNull()) + { + isi.columns.append(parseIdlStructColumn(domColumn)); + domColumn = domColumn.nextSiblingElement(domColumn.tagName()); + } + + m_idlStructsToGenerate.insert(isi.name, isi); + + domIdlStruct = domIdlStruct.nextSiblingElement(domIdlStruct.tagName()); + } + + INFO_LOG(m_logger) << "Read " << m_idlStructsToGenerate.size() << " idl struct(s)"; +} + +void XmlReader::parseFunctionTopics(const QDomElement& rootElement) +{ + if (rootElement.isNull()) + return; + + QDomElement domFunctionTopic = rootElement.firstChildElement(QStringLiteral("functionTopic")); + while (!domFunctionTopic.isNull()) + { + FunctionTopic ft; + ft.name = getAttribute(domFunctionTopic, QStringLiteral("name")); + ft.requestTopicType = getAttribute(domFunctionTopic, QStringLiteral("requestTopicType")); + ft.replyTopicType = getAttribute(domFunctionTopic, QStringLiteral("replyTopicType")); + ft.requestTopicName = getAttribute(domFunctionTopic, QStringLiteral("requestTopicName")); + ft.replyTopicName = getAttribute(domFunctionTopic, QStringLiteral("replyTopicName")); + ft.routeInReplay = getAttributeBool(domFunctionTopic, QStringLiteral("routeInReplay"), true, false); + + m_functionTopics.append(ft); + + domFunctionTopic = domFunctionTopic.nextSiblingElement(domFunctionTopic.tagName()); + } + + for (const FunctionTopic& ft : std::as_const(m_functionTopics)) + { + const QStringList sl1 = ft.requestTopicType.split(QStringLiteral("::")); + if (sl1.size() == 2) + loadExternalTopicType(sl1.at(0), sl1.at(1)); + const QStringList sl2 = ft.replyTopicType.split(QStringLiteral("::")); + if (sl2.size() == 2) + loadExternalTopicType(sl2.at(0), sl2.at(1)); + } +} + +ColumnInformation XmlReader::parseTableColumn(const QDomElement& column, const QString& tableName) const +{ + ColumnInformation ci; + + ci.columnName = getAttribute(column, QStringLiteral("name")); + ci.datatype = getAttribute(column, QStringLiteral("datatype")); + ci.defaultValue = getAttribute(column, QStringLiteral("default"), true); + ci.comment = getAttribute(column, QStringLiteral("comment"), true); + ci.isPrimaryKey = getAttributeBool(column, QStringLiteral("isPrimaryKey"), true, false); + ci.isForeignKey = getAttributeBool(column, QStringLiteral("isForeignKey"), true, false); + ci.isOptional = getAttributeBool(column, QStringLiteral("isOptional"), true, false); + const QDomElement seq = column.firstChildElement(QStringLiteral("sequence")); + if (!seq.isNull()) + { + ci.sequenceStart = getAttributeInt(seq, QStringLiteral("start"), true, -1); + ci.sequenceIncrement = getAttributeInt(seq, QStringLiteral("increment"), true, -1); + ci.hasSequence = ci.sequenceStart >= 0 && ci.sequenceIncrement > 0; + } + + if (ci.columnName.toLower() != ci.columnName) + WARNING_LOG(m_logger) << "Column " << ci.columnName << " in Table " << tableName + << " has has upper-case chars which is not allowed!"; + + return ci; +} + +IdlColumnInformation XmlReader::parseIdlStructColumn(const QDomElement& column) const +{ + IdlColumnInformation ci; + + ci.name = getAttribute(column, QStringLiteral("name")); + ci.type = getAttribute(column, QStringLiteral("idlType")); + ci.comment = getAttribute(column, QStringLiteral("comment"), true); + ci.isKey = getAttributeBool(column, QStringLiteral("isKey"), true, false); + ci.isOptional = getAttributeBool(column, QStringLiteral("isOptional"), true, false); + ci.isTranslatable = getAttributeBool(column, QStringLiteral("isTranslatable"), true, false); + + return ci; +} + +QSharedPointer XmlReader::parseForeignKey(const QDomElement& foreignKey) const +{ + QSharedPointer fk(new ForeignKeyInformation); + + fk->name = getAttribute(foreignKey, QStringLiteral("name")); + + const QString deleteAction = getAttribute(foreignKey, QStringLiteral("referential_integrity"), true); + if (deleteAction == QLatin1String("DeleteNoAction")) + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::NoAction; + else if (deleteAction == QLatin1String("DeleteCascade")) + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Cascade; + else if (deleteAction == QLatin1String("DeleteRestrict")) + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Restrict; + else if (deleteAction == QLatin1String("DeleteSetNull")) + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::SetNull; + else if (deleteAction == QLatin1String("DeleteSetDefault")) + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::SetDefault; + else + fk->deleteAction = ForeignKeyInformation::OnDeleteAction::Cascade; + + fk->source = parseForeignKeyEndpoint(fk->name, foreignKey.firstChildElement(QStringLiteral("source"))); + fk->destination = parseForeignKeyEndpoint(fk->name, foreignKey.firstChildElement(QStringLiteral("destination"))); + + return fk; +} + +ForeignKeyInformation::Endpoint XmlReader::parseForeignKeyEndpoint(const QString& foreignKeyName, + const QDomElement& endpoint) const +{ + if (endpoint.isNull()) + throw XmlReaderException(QLatin1String("No endpoint for foreign key ") + foreignKeyName); + + ForeignKeyInformation::Endpoint fkEndpoint; + + fkEndpoint.service = getAttribute(endpoint, QStringLiteral("service"), true); + fkEndpoint.serviceAbbr = getAttribute(endpoint, QStringLiteral("serviceAbbr"), true); + fkEndpoint.schema = getAttribute(endpoint, QStringLiteral("schema"), true); + fkEndpoint.tableName = getAttribute(endpoint, QStringLiteral("table")); + fkEndpoint.columnName = getAttribute(endpoint, QStringLiteral("column")); + + return fkEndpoint; +} + +ConstraintInformation XmlReader::parseConstraint(const QDomElement& constraint) const +{ + ConstraintInformation ret; + + ret.name = getAttribute(constraint, QStringLiteral("name"), true); + const QString type = getAttribute(constraint, QStringLiteral("type")).toLower(); + if (type == QLatin1String("unique")) + ret.type = ConstraintInformation::Type::unique; + else if (type == QLatin1String("index")) + ret.type = ConstraintInformation::Type::index; + + QDomElement domColumn = constraint.firstChildElement(QStringLiteral("column")); + if (domColumn.isNull()) + throw XmlReaderException(QLatin1String("No column for constraint") + ret.name); + while (!domColumn.isNull()) + { + ret.affectedColumns += getAttribute(domColumn, QStringLiteral("name")); + domColumn = domColumn.nextSiblingElement(domColumn.tagName()); + } + return ret; +} + +CustomServiceFunctionInformation XmlReader::parseCustomFunction(const QDomElement& customFunc, + CustomServiceFunctionInformation::Type funcType) const +{ + CustomServiceFunctionInformation ret; + ret.methodName = getAttribute(customFunc, QStringLiteral("name")); + ret.returnValue = getAttribute(customFunc, QStringLiteral("returns"), true); + ret.isConst = getAttributeBool(customFunc, QStringLiteral("isConst"), true, false); + if (ret.returnValue.isEmpty()) + ret.returnValue = QStringLiteral("bool"); + QMap> paramHelper; + QDomElement domParam = customFunc.firstChildElement(QStringLiteral("parameter")); + while (!domParam.isNull()) + { + int pos = getAttributeInt(domParam, QStringLiteral("pos")); + if (paramHelper.contains(pos)) + throw XmlReaderException(QLatin1String("Doubled position entry for custom function ") + ret.methodName); + QString paramName = getAttribute(domParam, QStringLiteral("name")); + const QString paramType = getAttribute(domParam, QStringLiteral("type")); + const QString paramDefault = getAttribute(domParam, QStringLiteral("default"), true); + if (!paramDefault.isEmpty()) + paramName.append(QLatin1String(" = ") + paramDefault); + paramHelper[pos] = qMakePair(paramName, paramType); + domParam = domParam.nextSiblingElement(domParam.tagName()); + } + ret.paramNames.reserve(paramHelper.size()); + ret.paramTypes.reserve(paramHelper.size()); + ret.type = funcType; + QStringList signature; + for (auto it = paramHelper.constBegin(); it != paramHelper.constEnd(); ++it) + { + ret.paramNames += it.value().first; + ret.paramTypes += it.value().second; + QString tmp = it.value().second; + if (!it.value().second.endsWith(QLatin1Char('&'))) + tmp += QLatin1Char(' '); + tmp += it.value().first; + signature += tmp; + } + ret.signature += signature.join(QStringLiteral(", ")); + return ret; +} + +DbNotifcationInformation XmlReader::parseDbNotification(const QDomElement& customFunc) const +{ + DbNotifcationInformation ret(parseCustomFunction(customFunc, CustomServiceFunctionInformation::Type::DbNotify)); + + const QString attribute(getAttribute(customFunc, QStringLiteral("notificationTypes")).toLower()); + const QStringList nfTypes = attribute.split(QLatin1Char(',')); + static const QMap s_nfTypeMap = { + {QLatin1String("beforeinsert"), DbNotifcationInformation::NotificationType::BeforeInsert}, + {QLatin1String("afterinsert"), DbNotifcationInformation::NotificationType::AfterInsert}, + {QLatin1String("beforeupdate"), DbNotifcationInformation::NotificationType::BeforeUpdate}, + {QLatin1String("afterupdate"), DbNotifcationInformation::NotificationType::AfterUpdate}, + {QLatin1String("beforedelete"), DbNotifcationInformation::NotificationType::BeforeDelete}, + {QLatin1String("afterdelete"), DbNotifcationInformation::NotificationType::AfterDelete}}; + for (const QString& nfType : nfTypes) + { + const auto it = s_nfTypeMap.find(nfType); + if (it == s_nfTypeMap.end()) + throw XmlReaderException(QStringLiteral("Can not find notification type %2 in type map for function %1") + .arg(ret.methodName, nfType)); + ret.notificationType += it.value(); + } + if (ret.notificationType.isEmpty()) + throw XmlReaderException( + QStringLiteral("Notification function '%1' without a valid notification type").arg(ret.methodName)); + if (ret.paramTypes.size() != 1) + throw XmlReaderException( + QStringLiteral("Notification function '%1' must have exactly one parameter").arg(ret.methodName)); + + return ret; +} + +TopicTypeInformation XmlReader::loadExternalTopicType(const QString& externalServiceName, const QString& topicTypeName) +{ + DEBUG_LOG(m_logger) << "externalServiceName: " << externalServiceName << ", topicTypeName: " << topicTypeName; + + if (!loadExternalService(externalServiceName)) + { + WARNING_LOG(m_logger) << "Could not find service " << externalServiceName << " referenced by external topic " + << topicTypeName; + return TopicTypeInformation(); + } + auto extXmlReader = m_externalXmlInformations.value(externalServiceName); + if (!extXmlReader) + { + ERROR_LOG(m_logger) << "Could not find service xml file for service '" << externalServiceName << "'"; + return TopicTypeInformation(); + } + + TopicTypeInformation tti = extXmlReader->getIdlStructInformation().value(topicTypeName); + if (tti.isValid()) + { + tti.name = externalServiceName + QLatin1String("::") + tti.name; + m_externalTopicTypes += tti; + m_usedServices[externalServiceName] = true; + return tti; + } + WARNING_LOG(m_logger) << "Could not find topic " << topicTypeName << " in external service definition for service " + << externalServiceName; + return TopicTypeInformation(); +} + +EnumInformation XmlReader::getExternalEnumeration(const QString& externalServiceName, const QString& enumName, + bool verbose) +{ + DEBUG_LOG(m_logger) << "externalServiceName: " << externalServiceName << ", topicTypeName: " << enumName; + + if (!loadExternalService(externalServiceName)) + { + WARNING_LOG(m_logger) << "Could not find service '" << externalServiceName << "'" + << " referenced by external enumeration " << enumName; + return EnumInformation(); + } + auto extXmlReader = m_externalXmlInformations.value(externalServiceName); + if (!extXmlReader) + { + ERROR_LOG(m_logger) << "Could not find service xml file for service '" << externalServiceName << "'"; + return EnumInformation(); + } + + const QVector enums = extXmlReader->getEnumerations(); + for (const EnumInformation& ei : enums) + { + if (ei.enumName == enumName) + { + m_usedServices[externalServiceName] = true; + return ei; + } + } + if (verbose) + { + WARNING_LOG(m_logger) << "Could not find enumeration " << enumName << " in external service definition for '" + << externalServiceName << "'"; + } + return EnumInformation(); +} + +bool XmlReader::loadExternalService(const QString& serviceName) +{ + if (serviceName == getServiceNamespace()) + return false; + if (m_externalXmlInformations.contains(serviceName)) + return true; + + QString fileName = xmlFileForService(serviceName); + if (fileName.isEmpty()) + { + const QVector dirs = NGL::directories(NGL::FileType::ConfigFile); + for (const QString& dirname : dirs) + { + QDirIterator dirIt(dirname + QStringLiteral("/xml"), QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); + while (dirIt.hasNext()) + { + dirIt.next(); + if (!dirIt.fileName().endsWith(QLatin1String(".xml"))) + continue; + + fileName = dirIt.filePath(); + const QString svcNamespace = serviceNamespaceFromFile(fileName); + if (svcNamespace == serviceName) + break; + } + } + } + if (fileName.isEmpty()) + return false; + + DEBUG_LOG(m_logger) << "xml file for " << serviceName << ": " << fileName; + auto extXmlReader = QSharedPointer(new XmlReader); + if (!extXmlReader->readServiceFile(fileName, QString(), this)) + { + WARNING_LOG(m_logger) << "Error reading service file " << fileName << " for service " << serviceName; + return false; + } + m_externalXmlInformations[serviceName] = extXmlReader; + if (!m_usedServices.contains(serviceName)) + m_usedServices[serviceName] = false; + return true; +} + +void XmlReader::loadIdlInfofile(const QString& idlServiceInfoFile) +{ + if (idlServiceInfoFile.isEmpty()) + return; + QFile f(idlServiceInfoFile); + if (!f.open(QIODevice::ReadOnly)) + { + WARNING_LOG(m_logger) << "Could not read idl service info file " << idlServiceInfoFile; + return; + } + const QList files = f.readAll().split('\n'); + for (const QByteArray& filePath : files) + { + + if (filePath.startsWith("--") || filePath.trimmed().isEmpty()) + continue; + const QString fileName = QString::fromLocal8Bit(filePath.trimmed()); + const QStringList parts = fileName.split(QStringLiteral("/")); + getServiceNameInfoFromFilePath(parts); + const auto fn = parts.last().trimmed(); + if (fn.endsWith(QLatin1String(".xml"))) + { + const auto svcAbbreveation = fn.split(QLatin1Char('.')).at(0).split(QLatin1Char('_')).at(0); + m_xmlFiles[svcAbbreveation] = fileName; + DEBUG_LOG(m_logger) << "xml: " << svcAbbreveation << " = " << fileName; + } + else + { + const auto svcAbbreveation = fn.split(QLatin1Char('.')).at(0).toLower(); + if (svcAbbreveation.endsWith(QLatin1String("_enums"))) + continue; + m_idlFiles[svcAbbreveation] = fileName; + DEBUG_LOG(m_logger) << "idl: " << svcAbbreveation << " = " << fileName; + } + } +} + +QString XmlReader::getIdlFileForService(const QMap& data, const QString& serviceName) const +{ + const QString serviceAbbr = serviceNameAbbreviation(serviceName); + return data.value(serviceAbbr); +} + +QString XmlReader::serviceNameAbbreviation(const QString& serviceName) const +{ + return m_fullServiceName2Abbreviation.value(serviceName); +} + +void XmlReader::getServiceNameInfoFromFilePath(const QStringList& parts) +{ + if (parts.size() < 2) + return; + + const QString abbreviation = parts.last().split(QLatin1Char('.')).first().split(QLatin1Char('_')).first(); + const QString serviceName = parts.at(parts.size() - 2); + DEBUG_LOG(m_logger) << "serviceName: " << serviceName << " = " << abbreviation; + m_fullServiceName2Abbreviation[serviceName] = abbreviation; +} + +ExerciseDependency XmlReader::string2ExerciseDependency(const QString& str) +{ + if (str.isEmpty()) + return ExerciseDependency::Undefined; + const QStringList sd = str.toLower().split(QLatin1Char(',')); + int ret = ExerciseDependency::Undefined; + for (const QString& s : sd) + { + if (s == QLatin1String("global")) + ret |= ExerciseDependency::Global; + else if (s == QLatin1String("exercise")) + ret |= ExerciseDependency::Exercise; + else if (s == QLatin1String("globalandexercise")) + ret |= ExerciseDependency::GlobalAndExercise; + } + return static_cast(ret); +} + +QString XmlReader::serviceNamespaceFromFile(const QString& fn) +{ + QFile f(fn); + if (!f.open(QIODevice::ReadOnly)) + return QString(); + QXmlStreamReader sr(&f); + while (!sr.atEnd()) + { + sr.readNext(); + if (sr.isStartElement() && sr.name() == QLatin1String("service")) + return (sr.attributes().value(QLatin1String("namespace"))).toString(); + } return QString(); - QXmlStreamReader sr(&f); - while (!sr.atEnd()) - { - sr.readNext(); - if (sr.isStartElement() && sr.name() == QLatin1String("service")) - return (sr.attributes().value(QLatin1String("namespace"))).toString(); - } - return QString(); } - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.h old mode 100755 new mode 100644 index 7b54ed9ca..17ab28861 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/XmlReader.h @@ -31,409 +31,429 @@ class QDomElement; namespace CodeGen { -enum ExerciseDependency -{ - Undefined = 0, - Global = 0x1, - Exercise = 0x2, - GlobalAndExercise = 0x3 -}; +enum ExerciseDependency { Undefined = 0, Global = 0x1, Exercise = 0x2, GlobalAndExercise = 0x3 }; struct EnumKeyValuePair { - QString key; - int value = 0; + QString key; + int value = 0; }; struct EnumInformation { - QString enumName; - QString tableName; - QString serviceName; - QVector values; + QString enumName; + QString tableName; + QString serviceName; + QVector values; - bool isValid() const { return !enumName.isEmpty(); } + bool isValid() const + { + return !enumName.isEmpty(); + } }; struct ColumnInformation { - QString columnName; - QString datatype; - QString comment; - QString defaultValue; - bool isPrimaryKey = false; - bool isAssignmentForPrimaryTablePk = false; - bool isForeignKey = false; - bool generateSelectRemove = false; - bool canBeNull = true; - bool hasSequence = false; - bool isOptional = false; - int sequenceStart = 0; - int sequenceIncrement = 0; + QString columnName; + QString datatype; + QString comment; + QString defaultValue; + bool isPrimaryKey = false; + bool isAssignmentForPrimaryTablePk = false; + bool isForeignKey = false; + bool generateSelectRemove = false; + bool canBeNull = true; + bool hasSequence = false; + bool isOptional = false; + int sequenceStart = 0; + int sequenceIncrement = 0; }; struct IdlColumnInformation { - QString name; - QString type; - QString comment; - bool isKey = false; - bool isOptional = false; - bool isTranslatable = false; + QString name; + QString type; + QString comment; + bool isKey = false; + bool isOptional = false; + bool isTranslatable = false; }; - struct ForeignKeyInformation { - struct Endpoint - { - QString service; - QString serviceAbbr; - QString schema; - QString tableName; - QString columnName; - }; + struct Endpoint + { + QString service; + QString serviceAbbr; + QString schema; + QString tableName; + QString columnName; + }; - QString name; - Endpoint source; - Endpoint destination; - enum class OnDeleteAction - { - NoAction, - Cascade, - Restrict, - SetNull, - SetDefault - } deleteAction = OnDeleteAction::Cascade; + QString name; + Endpoint source; + Endpoint destination; + enum class OnDeleteAction { + NoAction, + Cascade, + Restrict, + SetNull, + SetDefault + } deleteAction = OnDeleteAction::Cascade; }; struct CustomServiceFunctionInformation { - QString methodName; - QString returnValue; - QString signature; - bool isConst = false; - QVector paramTypes; - QVector paramNames; - enum class Type - { - Db, - DbNotify, - Dtc - } type = Type::Db; + QString methodName; + QString returnValue; + QString signature; + bool isConst = false; + QVector paramTypes; + QVector paramNames; + enum class Type { Db, DbNotify, Dtc } type = Type::Db; }; struct DbNotifcationInformation : public CustomServiceFunctionInformation { - DbNotifcationInformation() = default; - explicit DbNotifcationInformation(const CustomServiceFunctionInformation &d) - : CustomServiceFunctionInformation(d) - {} - enum class NotificationType - { - BeforeInsert, - AfterInsert, - BeforeUpdate, - AfterUpdate, - BeforeDelete, - AfterDelete - }; - QVector notificationType; + DbNotifcationInformation() = default; + + explicit DbNotifcationInformation(const CustomServiceFunctionInformation& d) : CustomServiceFunctionInformation(d) + { + } + enum class NotificationType { BeforeInsert, AfterInsert, BeforeUpdate, AfterUpdate, BeforeDelete, AfterDelete }; + QVector notificationType; }; struct ConstraintInformation { - enum struct Type - { - unknown = 0x00, - unique = 0x01, - index = 0x02 - } type = Type::unknown; - QString name; - QStringList affectedColumns; + enum struct Type { unknown = 0x00, unique = 0x01, index = 0x02 } type = Type::unknown; + QString name; + QStringList affectedColumns; }; struct TableInformation { - QString name; - QString structName; - QString comment; - QVector plainColumns; - QVector > foreignKeys; - QVector constraints; - ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; + QString name; + QString structName; + QString comment; + QVector plainColumns; + QVector> foreignKeys; + QVector constraints; + ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; - QSharedPointer fkInformationForColumn(const QString &tableName, - const QString &columnName) const - { - for (const QSharedPointer &fki : foreignKeys) + QSharedPointer fkInformationForColumn(const QString& tableName, + const QString& columnName) const { - if (fki->source.columnName == columnName && - fki->source.tableName == tableName) - return fki; + for (const QSharedPointer& fki : foreignKeys) + { + if (fki->source.columnName == columnName && fki->source.tableName == tableName) + return fki; + } + return QSharedPointer(); } - return QSharedPointer(); - } }; struct ViewInformation { - QString name; - QString comment; - QString structName; - QString baseTable; - QString baseSchema; - QString filter; - ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; + QString name; + QString comment; + QString structName; + QString baseTable; + QString baseSchema; + QString filter; + ExerciseDependency exerciseDependency = ExerciseDependency::Undefined; }; struct ServiceStructInformation { - QString name; - QString primaryTable; - bool hasStaticContent = false; + QString name; + QString primaryTable; + bool hasStaticContent = false; - bool operator<(const ServiceStructInformation &o) const - { - if (hasStaticContent != o.hasStaticContent) - return hasStaticContent < o.hasStaticContent; - if (name != o.name) - return name < o.name; - return primaryTable < o.primaryTable; - } - QVector dbNotifications; + bool operator<(const ServiceStructInformation& o) const + { + if (hasStaticContent != o.hasStaticContent) + return hasStaticContent < o.hasStaticContent; + if (name != o.name) + return name < o.name; + return primaryTable < o.primaryTable; + } + + QVector dbNotifications; }; struct TopicTypeInformationBase { - TopicTypeInformationBase() = default; - virtual ~TopicTypeInformationBase() = default; + TopicTypeInformationBase() = default; + virtual ~TopicTypeInformationBase() = default; - QString name; - QString baseValueType; - QString comment; - bool isDataObject = false; - bool dtsAutogen = true; - bool dtcAutogen = true; - bool recordTopic = false; - bool routeToClient = true; - bool routeToServer = false; - bool routeInReplay = true; - bool autosubscribe = true; + QString name; + QString baseValueType; + QString comment; + bool isDataObject = false; + bool dtsAutogen = true; + bool dtcAutogen = true; + bool recordTopic = false; + bool routeToClient = true; + bool routeToServer = false; + bool routeInReplay = true; + bool autosubscribe = true; #ifdef RTI_DDS_AVAILABLE - dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE; + dds::core::xtypes::ExtensibilityKind extensibility = dds::core::xtypes::ExtensibilityKind::EXTENSIBLE; #else - int extensibility = 0; // Placeholder when RTI DDS is not available + int extensibility = 0; // Placeholder when RTI DDS is not available #endif - virtual bool isValid() const { return !name.isEmpty(); } + virtual bool isValid() const + { + return !name.isEmpty(); + } - bool operator<(const TopicTypeInformationBase &o) const - { - if (name != o.name) - return name < o.name; - return baseValueType < o.baseValueType; - } + bool operator<(const TopicTypeInformationBase& o) const + { + if (name != o.name) + return name < o.name; + return baseValueType < o.baseValueType; + } }; struct TopicTypeInformation : public TopicTypeInformationBase { - QVector columns; + QVector columns; }; struct FunctionTopic { - QString name; - QString requestTopicType; - QString replyTopicType; - QString requestTopicName; - QString replyTopicName; - bool routeInReplay = false; + QString name; + QString requestTopicType; + QString replyTopicType; + QString requestTopicName; + QString replyTopicName; + bool routeInReplay = false; }; - class CODEGEN_BASE_EXPORT XmlReader final { -public: - XmlReader(); + public: + XmlReader(); - bool readServiceFile(const QString &svcFile, - const QString &idlServiceInfoFile = QString(), - const XmlReader *parent = nullptr); - QString errorString() const - { - return m_errorString; - } + bool readServiceFile(const QString& svcFile, const QString& idlServiceInfoFile = QString(), + const XmlReader* parent = nullptr); - QString getServiceNamespace() const { return m_svcNamespace; } - QString getServiceAbbr() const { return m_svcAbbr; } - QStringList getGroupNames() const { return m_groupNames; } - int getPrio() const { return m_prio;} - QStringList getProcNames() const { return m_svcProcNames; } - bool hasCustomRecordReplayPlugin() const { return m_customRecordReplay; } - bool getDevMode() const { return m_svcDevMode; } - - bool isServiceExerciseIndependent() const { return m_exerciseDependency == ExerciseDependency::Global; } - ExerciseDependency defaultExerciseDependency() const { return m_exerciseDependency; } - - QMap > getDbClass2TableMapping() const { return m_dbClassTables; } - - - QMap getStruct2BaseClassRelations() const { return m_struct2BaseClass; } - QVector getStructToGenerate() const { return m_structsToGenerate; } - - - QMap getIdlStructInformation() const { return m_idlStructsToGenerate; } - QVector getIdlStructToGenerate() const - { - QVector res; - res.reserve(m_idlStructsToGenerate.size()); - auto it = m_idlStructsToGenerate.constBegin(); - while (it != m_idlStructsToGenerate.constEnd()) + QString errorString() const { - res.append(it.value()); - ++it; + return m_errorString; } - return res; - } - - QMap > getTables() const - { - return m_tables; - } - QMap > getViews() const - { - return m_views; - } - QSharedPointer getTable(const QString &table) const - { - return m_tables.value(table); - } - QVector getEnumerations() const - { - return m_enumerations; - } - QVector getIdlColumns(const QString &structName) const - { - return m_idlStructsToGenerate.value(structName).columns; - } + QString getServiceNamespace() const + { + return m_svcNamespace; + } - QVector getFunctionTopics() const - { - return m_functionTopics; - } - QVector getExternalTopicTypes() const - { - return m_externalTopicTypes; - } + QString getServiceAbbr() const + { + return m_svcAbbr; + } - QString idlFileForService(const QString &serviceName) const - { - return getIdlFileForService(m_idlFiles, serviceName); - } + QStringList getGroupNames() const + { + return m_groupNames; + } - QString xmlFileForService(const QString &serviceName) const - { - return getIdlFileForService(m_xmlFiles, serviceName); - } + int getPrio() const + { + return m_prio; + } - QMap usedServices() const - { - return m_usedServices; - } + QStringList getProcNames() const + { + return m_svcProcNames; + } - QVector getCustomFunctions() const - { - return m_customFunctions; - } + bool hasCustomRecordReplayPlugin() const + { + return m_customRecordReplay; + } + bool getDevMode() const + { + return m_svcDevMode; + } - TopicTypeInformation loadExternalTopicType(const QString &externalServiceName, const QString &topicTypeName); - EnumInformation getExternalEnumeration(const QString &externalServiceName, const QString &enumName, bool verbose); + bool isServiceExerciseIndependent() const + { + return m_exerciseDependency == ExerciseDependency::Global; + } - static ExerciseDependency string2ExerciseDependency(const QString &str); + ExerciseDependency defaultExerciseDependency() const + { + return m_exerciseDependency; + } - XmlReader(const XmlReader &) = delete; - XmlReader &operator=(const XmlReader &) = delete; + QMap> getDbClass2TableMapping() const + { + return m_dbClassTables; + } -private: - NGL::INGLLogger &m_logger; - void parseDBSserviceStructs(const QDomElement &rootElement); - void parseDBTables(const QDomElement &rootElement); - void parseDBViews(const QDomElement &rootElement); - void parseEnumerations(const QDomElement &rootElement); - void parseTopicTypes(const QDomElement &rootElement); - void parseFunctionTopics(const QDomElement &rootElement); - void parseCustomDtcFunctions(const QDomElement &rootElement); + QMap getStruct2BaseClassRelations() const + { + return m_struct2BaseClass; + } - static QString getAttribute(const QDomElement &element, - const QString &attributeName, - bool bOptional = false); - static bool getAttributeBool(const QDomElement &element, - const QString &attributeName, - bool bOptional, bool defaultValue); - static int getAttributeInt(const QDomElement &element, - const QString &attributeName, - bool bOptional = false, int defaultValue = 0); + QVector getStructToGenerate() const + { + return m_structsToGenerate; + } - ColumnInformation parseTableColumn(const QDomElement &column, const QString &tableName) const; - IdlColumnInformation parseIdlStructColumn(const QDomElement &column) const; + QMap getIdlStructInformation() const + { + return m_idlStructsToGenerate; + } - QSharedPointer parseForeignKey(const QDomElement &foreignKey) const; - ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString &foreignKeyName, - const QDomElement &endpoint) const; - ConstraintInformation parseConstraint(const QDomElement &constraint) const; - CustomServiceFunctionInformation parseCustomFunction(const QDomElement &customFunc, CustomServiceFunctionInformation::Type funcType) const; - DbNotifcationInformation parseDbNotification(const QDomElement &customFunc) const; - bool loadExternalService(const QString &serviceName); - void loadIdlInfofile(const QString &idlServiceInfoFile); - QString getIdlFileForService(const QMap &data, const QString &serviceName) const; - QString serviceNameAbbreviation(const QString &serviceName) const; - void getServiceNameInfoFromFilePath(const QStringList &parts); - static QString serviceNamespaceFromFile(const QString &fn); + QVector getIdlStructToGenerate() const + { + QVector res; + res.reserve(m_idlStructsToGenerate.size()); + auto it = m_idlStructsToGenerate.constBegin(); + while (it != m_idlStructsToGenerate.constEnd()) + { + res.append(it.value()); + ++it; + } + return res; + } - - QString m_svcNamespace; - - QString m_svcAbbr; - - QStringList m_svcProcNames; - - bool m_customRecordReplay; + QMap> getTables() const + { + return m_tables; + } - - ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise}; + QMap> getViews() const + { + return m_views; + } - - QMap > m_dbClassTables; + QSharedPointer getTable(const QString& table) const + { + return m_tables.value(table); + } - - QMap m_struct2BaseClass; - QVector m_structsToGenerate; + QVector getEnumerations() const + { + return m_enumerations; + } - QMap m_idlStructsToGenerate; + QVector getIdlColumns(const QString& structName) const + { + return m_idlStructsToGenerate.value(structName).columns; + } - QVector m_functionTopics; - QVector m_externalTopicTypes; - QVector m_customFunctions; + QVector getFunctionTopics() const + { + return m_functionTopics; + } + QVector getExternalTopicTypes() const + { + return m_externalTopicTypes; + } - QMap > m_tables; - QMap > m_views; - QVector m_enumerations; - QString m_errorString; + QString idlFileForService(const QString& serviceName) const + { + return getIdlFileForService(m_idlFiles, serviceName); + } + QString xmlFileForService(const QString& serviceName) const + { + return getIdlFileForService(m_xmlFiles, serviceName); + } - QMap > m_externalXmlInformations; - QMap m_idlFiles; - QMap m_xmlFiles; - QMap m_usedServices; - QMap m_fullServiceName2Abbreviation; + QMap usedServices() const + { + return m_usedServices; + } - QStringList m_groupNames; - int m_prio; - bool m_svcDevMode{false}; + QVector getCustomFunctions() const + { + return m_customFunctions; + } + + TopicTypeInformation loadExternalTopicType(const QString& externalServiceName, const QString& topicTypeName); + EnumInformation getExternalEnumeration(const QString& externalServiceName, const QString& enumName, bool verbose); + + static ExerciseDependency string2ExerciseDependency(const QString& str); + + XmlReader(const XmlReader&) = delete; + XmlReader& operator=(const XmlReader&) = delete; + + private: + NGL::INGLLogger& m_logger; + void parseDBSserviceStructs(const QDomElement& rootElement); + void parseDBTables(const QDomElement& rootElement); + void parseDBViews(const QDomElement& rootElement); + void parseEnumerations(const QDomElement& rootElement); + void parseTopicTypes(const QDomElement& rootElement); + void parseFunctionTopics(const QDomElement& rootElement); + void parseCustomDtcFunctions(const QDomElement& rootElement); + + static QString getAttribute(const QDomElement& element, const QString& attributeName, bool bOptional = false); + static bool getAttributeBool(const QDomElement& element, const QString& attributeName, bool bOptional, + bool defaultValue); + static int getAttributeInt(const QDomElement& element, const QString& attributeName, bool bOptional = false, + int defaultValue = 0); + + ColumnInformation parseTableColumn(const QDomElement& column, const QString& tableName) const; + IdlColumnInformation parseIdlStructColumn(const QDomElement& column) const; + + QSharedPointer parseForeignKey(const QDomElement& foreignKey) const; + ForeignKeyInformation::Endpoint parseForeignKeyEndpoint(const QString& foreignKeyName, + const QDomElement& endpoint) const; + ConstraintInformation parseConstraint(const QDomElement& constraint) const; + CustomServiceFunctionInformation parseCustomFunction(const QDomElement& customFunc, + CustomServiceFunctionInformation::Type funcType) const; + DbNotifcationInformation parseDbNotification(const QDomElement& customFunc) const; + bool loadExternalService(const QString& serviceName); + void loadIdlInfofile(const QString& idlServiceInfoFile); + QString getIdlFileForService(const QMap& data, const QString& serviceName) const; + QString serviceNameAbbreviation(const QString& serviceName) const; + void getServiceNameInfoFromFilePath(const QStringList& parts); + static QString serviceNamespaceFromFile(const QString& fn); + + QString m_svcNamespace; + + QString m_svcAbbr; + + QStringList m_svcProcNames; + + bool m_customRecordReplay; + + ExerciseDependency m_exerciseDependency{ExerciseDependency::Exercise}; + + QMap> m_dbClassTables; + + QMap m_struct2BaseClass; + QVector m_structsToGenerate; + + QMap m_idlStructsToGenerate; + + QVector m_functionTopics; + QVector m_externalTopicTypes; + QVector m_customFunctions; + + QMap> m_tables; + QMap> m_views; + QVector m_enumerations; + QString m_errorString; + + QMap> m_externalXmlInformations; + QMap m_idlFiles; + QMap m_xmlFiles; + QMap m_usedServices; + QMap m_fullServiceName2Abbreviation; + + QStringList m_groupNames; + int m_prio; + bool m_svcDevMode{false}; }; -} +} // namespace CodeGen diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/codegen_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/codegen_export.h old mode 100755 new mode 100644 index 698bad14f..4be10620b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/codegen_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/codegen_export.h @@ -5,13 +5,13 @@ #include #ifndef CODEGEN_BASE_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define CODEGEN_BASE_EXPORT -# else -# if defined(MAKE_CODEGEN_BASE_LIB) -# define CODEGEN_BASE_EXPORT Q_DECL_EXPORT -# else -# define CODEGEN_BASE_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define CODEGEN_BASE_EXPORT +#else +#if defined(MAKE_CODEGEN_BASE_LIB) +#define CODEGEN_BASE_EXPORT Q_DECL_EXPORT +#else +#define CODEGEN_BASE_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee.cpp old mode 100755 new mode 100644 index 3ee571270..dd97c4cc9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee.cpp @@ -1,172 +1,167 @@ - -#include "StructBuilder.h" -#include "XmlReader.h" +#include "CppTopicGeneratorGrantlee.h" #include "DaoGeneratorGrantlee.h" #include "DatabaseGeneratorGrantlee.h" -#include "CppTopicGeneratorGrantlee.h" #include "SqlGenerator.h" +#include "StructBuilder.h" +#include "XmlReader.h" -#include -#include -#include #include - +#include +#include +#include class CmdLineParser : public LtsCommandLineParser::LtsCommandLineParser { -public: - CmdLineParser() - : LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None) - { - addOption({ QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"), - QStringLiteral("full path to the service xml-file"), - QStringLiteral("service xml-file"), - QStringLiteral("/home") - }); - - addOption({ QStringList() << QStringLiteral("a") << QStringLiteral("action"), - QStringLiteral("the action to execute"), - QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"), - QStringLiteral("/0") - }); - - addOption({ QStringList() << QStringLiteral("o") << QStringLiteral("outdir"), - QStringLiteral("the output directory where to put the generated files"), - QStringLiteral("output directory"), - QStringLiteral("/home") - }); - - addOption({ QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"), - QStringLiteral("the info file with all available idl service files"), - QStringLiteral("info file for idl"), - QStringLiteral("/0") - }); - } - - bool init() - { - if (!LtsCommandLineParser::init()) - return false; - - if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty()) + public: + CmdLineParser() : LtsCommandLineParser(LtsCommandLineParser::LtsCommandLineParser::None) { - showHelp(); - return false; - } - return true; - } + addOption({QStringList() << QStringLiteral("s") << QStringLiteral("servicefile"), + QStringLiteral("full path to the service xml-file"), QStringLiteral("service xml-file"), + QStringLiteral("/home")}); - QString serviceFile() const { return value(QStringLiteral("s")); } - QString action() const { return value(QStringLiteral("a")); } - QString outDir() const { return value(QStringLiteral("o")); } - QString idlInfoFile() const { return value(QStringLiteral("i")); } + addOption({QStringList() << QStringLiteral("a") << QStringLiteral("action"), + QStringLiteral("the action to execute"), QStringLiteral("DATABASE|DATABASE_SERVER|IDL|DDS_TOPICS"), + QStringLiteral("/0")}); + + addOption({QStringList() << QStringLiteral("o") << QStringLiteral("outdir"), + QStringLiteral("the output directory where to put the generated files"), + QStringLiteral("output directory"), QStringLiteral("/home")}); + + addOption({QStringList() << QStringLiteral("i") << QStringLiteral("idlinfo"), + QStringLiteral("the info file with all available idl service files"), + QStringLiteral("info file for idl"), QStringLiteral("/0")}); + } + + bool init() + { + if (!LtsCommandLineParser::init()) + return false; + + if (serviceFile().isEmpty() || action().isEmpty() || outDir().isEmpty()) + { + showHelp(); + return false; + } + return true; + } + + QString serviceFile() const + { + return value(QStringLiteral("s")); + } + + QString action() const + { + return value(QStringLiteral("a")); + } + + QString outDir() const + { + return value(QStringLiteral("o")); + } + + QString idlInfoFile() const + { + return value(QStringLiteral("i")); + } }; -int main(int argc, char **argv) +int main(int argc, char** argv) { - NGLCoreApplication app(argc, argv); - app.createLogger("CodeGen", "codegen_log4cxx.props", true ); + NGLCoreApplication app(argc, argv); + app.createLogger("CodeGen", "codegen_log4cxx.props", true); - NGL::INGLLogger &m_logger = app.baseLogger(); + NGL::INGLLogger& m_logger = app.baseLogger(); - CmdLineParser options; - if (!options.init()) - return -1; + CmdLineParser options; + if (!options.init()) + return -1; - QScopedPointer reader(new CodeGen::XmlReader); + QScopedPointer reader(new CodeGen::XmlReader); - DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile(); - DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile(); - if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile())) - { - ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile() - << ": " << reader->errorString(); - return 2; - } - - QDir dir(options.outDir()); - DEBUG_LOG(m_logger) << "Directory: " << options.outDir(); - if (!dir.exists() && !dir.mkpath(options.outDir())) - { - ERROR_LOG(m_logger) << "Directory '" << options.outDir() - << "' does not exist and can not be created!"; - return 3; - } - - QScopedPointer structBuilder(new CodeGen::StructBuilder(reader.data())); - if (!structBuilder->buildStructures()) - { - ERROR_LOG(m_logger) << "Error building up structures"; - return 4; - } - - const QString action = options.action().toLower(); - - - QScopedPointer generator; - if (action == QStringLiteral("dao")) - generator.reset(new CodeGen::DaoGeneratorGrantlee); - else if (action == QStringLiteral("database")) - generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false)); - else if (action == QStringLiteral("database_server")) - generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true)); - else if (action == QStringLiteral("dds_topics")) - generator.reset(new CodeGen::CppTopicGeneratorGrantlee); - else if (action == QStringLiteral("sql")) - { - CodeGen::SqlGenerator sql(reader.data(), structBuilder.data()); - if (!sql.generateData(35)) - return 8; - - - if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise)) + DEBUG_LOG(m_logger) << "ServiceFile: " << options.serviceFile(); + DEBUG_LOG(m_logger) << "IdlInfoFile: " << options.idlInfoFile(); + if (!reader->readServiceFile(options.serviceFile(), options.idlInfoFile())) { - ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); - return 10; + ERROR_LOG(m_logger) << "Error parsing service file '" << options.serviceFile() << ": " << reader->errorString(); + return 2; } - if (!sql.generateData(42)) - return 8; - - - if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise)) + QDir dir(options.outDir()); + DEBUG_LOG(m_logger) << "Directory: " << options.outDir(); + if (!dir.exists() && !dir.mkpath(options.outDir())) { - ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); - return 10; + ERROR_LOG(m_logger) << "Directory '" << options.outDir() << "' does not exist and can not be created!"; + return 3; } - - sql.generateData(0); - if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global)) + QScopedPointer structBuilder(new CodeGen::StructBuilder(reader.data())); + if (!structBuilder->buildStructures()) { - ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); - return 10; + ERROR_LOG(m_logger) << "Error building up structures"; + return 4; + } + + const QString action = options.action().toLower(); + + QScopedPointer generator; + if (action == QStringLiteral("dao")) + generator.reset(new CodeGen::DaoGeneratorGrantlee); + else if (action == QStringLiteral("database")) + generator.reset(new CodeGen::DatabaseGeneratorGrantlee(false)); + else if (action == QStringLiteral("database_server")) + generator.reset(new CodeGen::DatabaseGeneratorGrantlee(true)); + else if (action == QStringLiteral("dds_topics")) + generator.reset(new CodeGen::CppTopicGeneratorGrantlee); + else if (action == QStringLiteral("sql")) + { + CodeGen::SqlGenerator sql(reader.data(), structBuilder.data()); + if (!sql.generateData(35)) + return 8; + + if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise)) + { + ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); + return 10; + } + + if (!sql.generateData(42)) + return 8; + + if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Exercise)) + { + ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); + return 10; + } + + sql.generateData(0); + if (!sql.writeSql(dir.absolutePath() + QLatin1Char('/'), CodeGen::ExerciseDependency::Global)) + { + ERROR_LOG(m_logger) << "Error while writing sql information for service " << sql.getServiceAbbr(); + return 10; + } + return 0; + } + else + { + ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!"; + return 5; + } + + if (!generator->init(reader.data(), structBuilder.data())) + { + ERROR_LOG(m_logger) << "Error initializing generator!"; + return 6; + } + + const auto posArgs = options.positionalArguments(); + for (const QString& file : posArgs) + { + + if (!generator->generateData(file, dir.absolutePath())) + return 7; } return 0; - } - else - { - ERROR_LOG(m_logger) << "Invalid action '" << options.action() << "' given!"; - return 5; - } - - if (!generator->init(reader.data(), structBuilder.data())) - { - ERROR_LOG(m_logger) << "Error initializing generator!"; - return 6; - } - - - - - const auto posArgs = options.positionalArguments(); - for (const QString &file : posArgs) - { - - if (!generator->generateData(file, dir.absolutePath())) - return 7; - } - return 0; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.cpp old mode 100755 new mode 100644 index 5c4574133..1c25f8fc2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.cpp @@ -1,158 +1,148 @@ - #include "main_grantlee_gui.h" -#include "ui_main_grantlee_gui.h" -#include "StructBuilder.h" -#include "XmlReader.h" + #include "CppTopicGeneratorGrantlee.h" #include "DatabaseGeneratorGrantlee.h" +#include "StructBuilder.h" +#include "XmlReader.h" +#include "ui_main_grantlee_gui.h" -#include #include #include #include #include +#include - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) - , m_xmlReader(nullptr) - , m_structBuilder(nullptr) - , m_generator(new CodeGen::CppTopicGeneratorGrantlee) - , m_engine(new Grantlee::Engine) - , m_ui(new Ui_MainGrantleeGui) +MainWindow::MainWindow(QWidget* parent) + : QMainWindow(parent), m_xmlReader(nullptr), m_structBuilder(nullptr), + m_generator(new CodeGen::CppTopicGeneratorGrantlee), m_engine(new Grantlee::Engine), m_ui(new Ui_MainGrantleeGui) { - m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt"); - m_ui->setupUi(this); - connect(m_ui->actionExit, &QAction::triggered, - this, &MainWindow::close); - connect(m_ui->actionSelect_Data_Source, &QAction::triggered, - this, &MainWindow::onSelectDataSource); - connect(m_ui->actionOpen_Template, &QAction::triggered, - this, &MainWindow::onOpenTemplate); - connect(m_ui->actionSave_Template, &QAction::triggered, - this, &MainWindow::onSaveTemplate); - connect(m_ui->pbRefresh, &QPushButton::clicked, - this, &MainWindow::onRefreshOutput); - connect(m_ui->actionDatabaseGenerator, &QAction::triggered, - this, &MainWindow::onGeneratorDb); - connect(m_ui->actionDDS_Generator, &QAction::triggered, - this, &MainWindow::onGeneratorDds); + m_idlServiceInfoFile = QStringLiteral("/home/chehrlic/TDS/TDS-build-product-clang/service_idl_files.txt"); + m_ui->setupUi(this); + connect(m_ui->actionExit, &QAction::triggered, this, &MainWindow::close); + connect(m_ui->actionSelect_Data_Source, &QAction::triggered, this, &MainWindow::onSelectDataSource); + connect(m_ui->actionOpen_Template, &QAction::triggered, this, &MainWindow::onOpenTemplate); + connect(m_ui->actionSave_Template, &QAction::triggered, this, &MainWindow::onSaveTemplate); + connect(m_ui->pbRefresh, &QPushButton::clicked, this, &MainWindow::onRefreshOutput); + connect(m_ui->actionDatabaseGenerator, &QAction::triggered, this, &MainWindow::onGeneratorDb); + connect(m_ui->actionDDS_Generator, &QAction::triggered, this, &MainWindow::onGeneratorDds); } MainWindow::~MainWindow() { - delete m_xmlReader; - delete m_structBuilder; - delete m_generator; - delete m_engine; - delete m_ui; + delete m_xmlReader; + delete m_structBuilder; + delete m_generator; + delete m_engine; + delete m_ui; } static QLatin1String s_startDir("/home/chehrlic/TDS/TDS-source-product/Lts/"); void MainWindow::onSelectDataSource() { - const QString dataSource = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)")); - if (dataSource.isEmpty()) - return; - delete m_xmlReader; - m_xmlReader = new CodeGen::XmlReader; - if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile)) - { - QMessageBox::warning(this, tr("Invalid data source"), tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString())); - return; - } - delete m_structBuilder; - m_structBuilder = new CodeGen::StructBuilder(m_xmlReader); - if (!m_structBuilder->buildStructures()) - { - QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data")); - return; - } - m_ui->teOuput->clear(); - m_generator->init(m_xmlReader, m_structBuilder); - QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source")); + const QString dataSource = + QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Service Files (*.xml)")); + if (dataSource.isEmpty()) + return; + delete m_xmlReader; + m_xmlReader = new CodeGen::XmlReader; + if (!m_xmlReader->readServiceFile(dataSource, m_idlServiceInfoFile)) + { + QMessageBox::warning(this, tr("Invalid data source"), + tr("The selected data source is not valid: %1").arg(m_xmlReader->errorString())); + return; + } + delete m_structBuilder; + m_structBuilder = new CodeGen::StructBuilder(m_xmlReader); + if (!m_structBuilder->buildStructures()) + { + QMessageBox::warning(this, tr("Invalid data source"), tr("Error building structures from data")); + return; + } + m_ui->teOuput->clear(); + m_generator->init(m_xmlReader, m_structBuilder); + QMessageBox::information(this, tr("Data source"), tr("Successfully loaded data source")); } void MainWindow::onOpenTemplate() { - const QString templateFile = QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)")); - if (templateFile.isEmpty()) - return; - QFile f(templateFile); - if (!f.open(QIODevice::ReadOnly)) - { - QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString())); - return; - } - const QString content = QString::fromUtf8(f.readAll()); - m_ui->teInput->setText(content); - m_templateFile = templateFile; + const QString templateFile = + QFileDialog::getOpenFileName(this, tr("Select data source"), s_startDir, tr("Templates (*.grantlee)")); + if (templateFile.isEmpty()) + return; + QFile f(templateFile); + if (!f.open(QIODevice::ReadOnly)) + { + QMessageBox::warning(this, tr("Error reading template file"), tr("Can not read file: %1").arg(f.errorString())); + return; + } + const QString content = QString::fromUtf8(f.readAll()); + m_ui->teInput->setText(content); + m_templateFile = templateFile; } void MainWindow::onSaveTemplate() { - QFile f(m_templateFile); - if (!f.open(QIODevice::WriteOnly)) - { - QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString())); - return; - } - f.write(m_ui->teInput->toPlainText().toUtf8()); - f.close(); - QMessageBox::information(this, tr("Saving template file"), tr("Successfully saved template to %1").arg(m_templateFile)); + QFile f(m_templateFile); + if (!f.open(QIODevice::WriteOnly)) + { + QMessageBox::warning(this, tr("Error saving template file"), tr("Can not save file: %1").arg(f.errorString())); + return; + } + f.write(m_ui->teInput->toPlainText().toUtf8()); + f.close(); + QMessageBox::information(this, tr("Saving template file"), + tr("Successfully saved template to %1").arg(m_templateFile)); } void MainWindow::onRefreshOutput() { - const QString in = m_ui->teInput->toPlainText(); - if (!m_generator->setTemplate(QString(), in)) - { - m_ui->teOuput->setText(m_generator->errorString()); - return; - } - m_ui->teOuput->setText(m_generator->render()); + const QString in = m_ui->teInput->toPlainText(); + if (!m_generator->setTemplate(QString(), in)) + { + m_ui->teOuput->setText(m_generator->errorString()); + return; + } + m_ui->teOuput->setText(m_generator->render()); } void MainWindow::onGeneratorDb() { - if (dynamic_cast(m_generator)) - return; - delete m_generator; - m_generator = new CodeGen::DatabaseGeneratorGrantlee(false); - if (m_xmlReader && m_structBuilder) - m_generator->init(m_xmlReader, m_structBuilder); + if (dynamic_cast(m_generator)) + return; + delete m_generator; + m_generator = new CodeGen::DatabaseGeneratorGrantlee(false); + if (m_xmlReader && m_structBuilder) + m_generator->init(m_xmlReader, m_structBuilder); } void MainWindow::onGeneratorDds() { - if (dynamic_cast(m_generator)) - return; - delete m_generator; - m_generator = new CodeGen::CppTopicGeneratorGrantlee; - if (m_xmlReader && m_structBuilder) - m_generator->init(m_xmlReader, m_structBuilder); + if (dynamic_cast(m_generator)) + return; + delete m_generator; + m_generator = new CodeGen::CppTopicGeneratorGrantlee; + if (m_xmlReader && m_structBuilder) + m_generator->init(m_xmlReader, m_structBuilder); } - -int main(int argc, char **argv) +int main(int argc, char** argv) { - NGLApplication app(argc, argv); - app.createLogger("CodeGen", "codegen_log4cxx.props"); + NGLApplication app(argc, argv); + app.createLogger("CodeGen", "codegen_log4cxx.props"); - NGL::INGLLogger &m_logger = app.baseLogger(); - STARTUP_LOG(m_logger); + NGL::INGLLogger& m_logger = app.baseLogger(); + STARTUP_LOG(m_logger); - int iRet = 0; - { - QScopedPointer mw(new MainWindow); - mw->show(); - iRet = app.exec(); - } + int iRet = 0; + { + QScopedPointer mw(new MainWindow); + mw->show(); + iRet = app.exec(); + } - SHUTDOWN_LOG(m_logger); - return iRet; + SHUTDOWN_LOG(m_logger); + return iRet; } - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.h old mode 100755 new mode 100644 index 204ad323f..d16f98d89 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/main_grantlee_gui.h @@ -1,40 +1,42 @@ #pragma once -#include - #include +#include namespace CodeGen { class XmlReader; class StructBuilder; class GeneratorGrantleeBase; -} +} // namespace CodeGen + namespace Grantlee { class Engine; } class Ui_MainGrantleeGui; + class MainWindow : public QMainWindow { - Q_OBJECT -public: - explicit MainWindow(QWidget *parent = nullptr); - ~MainWindow(); -private Q_SLOTS: - void onSelectDataSource(); - void onOpenTemplate(); - void onSaveTemplate(); - void onRefreshOutput(); - void onGeneratorDb(); - void onGeneratorDds(); -private: - CodeGen::XmlReader *m_xmlReader; - CodeGen::StructBuilder *m_structBuilder; - CodeGen::GeneratorGrantleeBase *m_generator; - Grantlee::Engine *m_engine; - QString m_idlServiceInfoFile; - QString m_templateFile; - Ui_MainGrantleeGui *m_ui; + Q_OBJECT + public: + explicit MainWindow(QWidget* parent = nullptr); + ~MainWindow(); + private Q_SLOTS: + void onSelectDataSource(); + void onOpenTemplate(); + void onSaveTemplate(); + void onRefreshOutput(); + void onGeneratorDb(); + void onGeneratorDds(); + + private: + CodeGen::XmlReader* m_xmlReader; + CodeGen::StructBuilder* m_structBuilder; + CodeGen::GeneratorGrantleeBase* m_generator; + Grantlee::Engine* m_engine; + QString m_idlServiceInfoFile; + QString m_templateFile; + Ui_MainGrantleeGui* m_ui; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/tests/GrantleeParserSmoke.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/tests/GrantleeParserSmoke.cpp index 185523b38..6fc9dedad 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/tests/GrantleeParserSmoke.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/CodeGen/tests/GrantleeParserSmoke.cpp @@ -1,16 +1,16 @@ #include -#include #include - +#include #include #include -int main(int argc, char **argv) +int main(int argc, char** argv) { QCoreApplication app(argc, argv); QString templatesDir = QDir::currentPath(); - if (argc > 1) { + if (argc > 1) + { templatesDir = QString::fromLocal8Bit(argv[1]); } @@ -21,7 +21,8 @@ int main(int argc, char **argv) QDir d(templatesDir); QStringList files = d.entryList(QStringList() << QStringLiteral("*.grantlee"), QDir::Files); - if (files.isEmpty()) { + if (files.isEmpty()) + { qDebug() << "No .grantlee templates found in" << templatesDir; // Treat absence as successful parse (nothing to check) to avoid failing // when directory is empty in different setups. @@ -29,21 +30,27 @@ int main(int argc, char **argv) } bool ok = true; - for (const QString &f : files) { + for (const QString& f : files) + { Grantlee::Template t; - try { + try + { t = engine.loadByName(f); - } catch (...) { + } + catch (...) + { qDebug() << "Exception while loading" << f; ok = false; continue; } - if (!t) { + if (!t) + { qDebug() << "Failed to load template" << f; ok = false; continue; } - if (t->error() != Grantlee::NoError) { + if (t->error() != Grantlee::NoError) + { qDebug() << "Parse error in" << f << ":" << t->errorString(); ok = false; continue; @@ -51,7 +58,8 @@ int main(int argc, char **argv) // Render with empty context to ensure rendering path also works. Grantlee::Context ctx; QString out = t->render(&ctx); - if (out.isNull()) { + if (out.isNull()) + { qDebug() << "Rendering produced null for" << f; ok = false; continue; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp deleted file mode 100644 index b0fc3f57e..000000000 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_gtest.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "mocks/MockCoordTrans.h" -#include - -TEST(CoordTransGTest, ForwardInverseRoundtrip) { - auto p = MockCoordTrans::forward(1.2345, 2.3456); - EXPECT_NEAR(p.first, 1.2345 * 111000.0, 1e-6); - EXPECT_NEAR(p.second, 2.3456 * 111000.0, 1e-6); - - auto inv = MockCoordTrans::inverse(p.first, p.second); - EXPECT_NEAR(inv.first, 1.2345, 1e-9); - EXPECT_NEAR(inv.second, 2.3456, 1e-9); -} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp deleted file mode 100644 index d5a177c35..000000000 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/coordTransTests_smoke.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include -#include "mocks/MockCoordTrans.h" - -class CoordTransSmoke : public QObject { - Q_OBJECT -private slots: - void testForward() { - auto p = MockCoordTrans::forward(10.0, 20.0); - QVERIFY(qFuzzyCompare(p.first, 10.0 * 111000.0)); - QVERIFY(qFuzzyCompare(p.second, 20.0 * 111000.0)); - } -}; - -QTEST_MAIN(CoordTransSmoke) -#include "coordTransTests_smoke.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h b/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h deleted file mode 100644 index 5028ddc30..000000000 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/CommonUnitTestsPlaceholder/mocks/MockCoordTrans.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include - -// Minimal realistic mock for coordinate transforms used during migration. -// Forward conversion returns approximate meters using lat/lon*111000. -class MockCoordTrans { -public: - // approximate forward: (lat, lon) -> (x_m, y_m) - static std::pair forward(double lat_deg, double lon_deg) { - return {lat_deg * 111000.0, lon_deg * 111000.0}; - } - // approximate inverse - static std::pair inverse(double x_m, double y_m) { - return {x_m / 111000.0, y_m / 111000.0}; - } -}; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp old mode 100755 new mode 100644 index affe55a6a..53c08a15e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/checker/main.cpp @@ -1,139 +1,118 @@ #include -#include - #include +#include #include #include -#include -#include #include #include - +#include #include +#include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - QCoreApplication a(argc, argv); + QCoreApplication a(argc, argv); - const QStringList args(a.arguments()); + const QStringList args(a.arguments()); - if (args.count() != 3) - { - printf("usage: %s \n", args.at(0).toStdString().c_str()); - return -1; - } - - const QString currentSrcDir(a.arguments().at(1)); - - const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2))); - QFile f(appsJsonFilePath); - - if (!f.open(QFile::ReadOnly)) - { - printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(), f.errorString().toStdString().c_str()); - return -2; - } - - printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str()); - - QStringList lastErrors; - QStringList dummy1; - QString dummy2; - LtsAppDescriptor::AppDescriptionVector adv = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2); - - if (!lastErrors.isEmpty()) - { - printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", appsJsonFilePath.toStdString().c_str(), lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str()); - return 1; - } - - - - QFileInfoList guiPluginFiles; - QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories); - - while (it.hasNext()) - { - QString filename(it.next()); - QFileInfo file(filename); - - if (file.isDir()) - continue; - - if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive)) - guiPluginFiles.append(file); - } - - QStringList filenames; - filenames.reserve(guiPluginFiles.size()); - for (const QFileInfo &fi : std::as_const(guiPluginFiles)) - { - filenames += fi.absoluteFilePath(); - } - - - QStringList guiPluginIIDs; - for (const QFileInfo &fi : std::as_const(guiPluginFiles)) - { - QFile f2(fi.absoluteFilePath()); - - if (!f2.open(QFile::ReadOnly)) - continue; - - QTextStream ts(&f2); - while (!ts.atEnd()) + if (args.count() != 3) { - QString line(ts.readLine().trimmed().simplified()); - static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA")); + printf("usage: %s \n", args.at(0).toStdString().c_str()); + return -1; + } - if (line.contains(iidIdentifier)) - { - QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))")); - QRegularExpressionMatch match = re.match(line); - if (match.hasMatch()) + const QString currentSrcDir(a.arguments().at(1)); + + const QString appsJsonFilePath(QStringLiteral("%1/%2").arg(currentSrcDir, a.arguments().at(2))); + QFile f(appsJsonFilePath); + + if (!f.open(QFile::ReadOnly)) + { + printf("LtsAppDescriptorChecker: cannot open apps.json at %s: %s\n", appsJsonFilePath.toStdString().c_str(), + f.errorString().toStdString().c_str()); + return -2; + } + + printf("LtsAppDescriptorChecker: checking %s\n", appsJsonFilePath.toStdString().c_str()); + + QStringList lastErrors; + QStringList dummy1; + QString dummy2; + LtsAppDescriptor::AppDescriptionVector adv = + LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(f.readAll(), lastErrors, dummy1, dummy2); + + if (!lastErrors.isEmpty()) + { + printf("LtsAppDescriptorChecker: apps.json at %s invalid:\n%s\n", appsJsonFilePath.toStdString().c_str(), + lastErrors.join(QStringLiteral("\r\n\r\n")).toStdString().c_str()); + return 1; + } + + QFileInfoList guiPluginFiles; + QDirIterator it(QStringLiteral("%1/../../Plugins/").arg(currentSrcDir), QDirIterator::Subdirectories); + + while (it.hasNext()) + { + QString filename(it.next()); + QFileInfo file(filename); + + if (file.isDir()) + continue; + + if (file.fileName().endsWith(QStringLiteral("_gui_plugin.h"), Qt::CaseInsensitive)) + guiPluginFiles.append(file); + } + + QStringList filenames; + filenames.reserve(guiPluginFiles.size()); + for (const QFileInfo& fi : std::as_const(guiPluginFiles)) + { + filenames += fi.absoluteFilePath(); + } + + QStringList guiPluginIIDs; + for (const QFileInfo& fi : std::as_const(guiPluginFiles)) + { + QFile f2(fi.absoluteFilePath()); + + if (!f2.open(QFile::ReadOnly)) + continue; + + QTextStream ts(&f2); + while (!ts.atEnd()) { - QString matched = match.captured(0); - - guiPluginIIDs += matched; + QString line(ts.readLine().trimmed().simplified()); + static QString iidIdentifier(QStringLiteral("Q_PLUGIN_METADATA")); + + if (line.contains(iidIdentifier)) + { + QRegularExpression re(QStringLiteral("(?<=gui:3:).*(?=\"\\))")); + QRegularExpressionMatch match = re.match(line); + if (match.hasMatch()) + { + QString matched = match.captured(0); + + guiPluginIIDs += matched; + } + break; + } } - break; - } } - } + bool ok = true; - - bool ok = true; - - for (const LtsAppDescriptor::AppDescription &appdesc : std::as_const(adv)) - { - for (const LtsAppDescriptor::PluginInfo &pi : std::as_const(appdesc.pluginInfos)) + for (const LtsAppDescriptor::AppDescription& appdesc : std::as_const(adv)) { - if (!guiPluginIIDs.contains(pi.iid)) - { - printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n", appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str()); - ok = false; - } + for (const LtsAppDescriptor::PluginInfo& pi : std::as_const(appdesc.pluginInfos)) + { + if (!guiPluginIIDs.contains(pi.iid)) + { + printf("LtsAppDescriptorChecker: apps.json at '%s' uses unknown IID '%s'\n", + appsJsonFilePath.toStdString().c_str(), pi.iid.toStdString().c_str()); + ok = false; + } + } } - } - - - return !ok; + return !ok; } - - - - - - - - - - - - - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp old mode 100755 new mode 100644 index 047d0aab1..6d2674735 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.cpp @@ -1,215 +1,206 @@ - #include "lts_app_descriptor.h" -#include +#include #include +#include #include #include #include -#include - - - namespace LtsAppDescriptor { -static void addOptionToPlugin(PluginInfo &pluginInfo, const PluginInfo::Flag &flag) +static void addOptionToPlugin(PluginInfo& pluginInfo, const PluginInfo::Flag& flag) { - pluginInfo.flags |= flag; + pluginInfo.flags |= flag; } - -static void addOptionToPlugin(QVector &pluginInfos, const PluginInfo::Flag &flag, const QString &pluginName) +static void addOptionToPlugin(QVector& pluginInfos, const PluginInfo::Flag& flag, const QString& pluginName) { - for (PluginInfo &pi : pluginInfos) - { - if (pi.iid == pluginName) + for (PluginInfo& pi : pluginInfos) { - addOptionToPlugin(pi, flag); - return; + if (pi.iid == pluginName) + { + addOptionToPlugin(pi, flag); + return; + } } - } - PluginInfo pi; - pi.iid = pluginName; - pi.type = PluginInfo::PluginType::GUI; - addOptionToPlugin(pi, flag); - pluginInfos.append(pi); + PluginInfo pi; + pi.iid = pluginName; + pi.type = PluginInfo::PluginType::GUI; + addOptionToPlugin(pi, flag); + pluginInfos.append(pi); } - -static bool addOptionsToPlugin(AppDescription &appDesc, const QString &optionIdentifier, const QStringList &ignoredPlugins, - const QJsonObject &optionsObject, const PluginInfo::Flag flag, QStringList &lastErrors, - bool atLeastOnePluginNeeded) +static bool addOptionsToPlugin(AppDescription& appDesc, const QString& optionIdentifier, + const QStringList& ignoredPlugins, const QJsonObject& optionsObject, + const PluginInfo::Flag flag, QStringList& lastErrors, bool atLeastOnePluginNeeded) { - bool hasPlugins = false; - auto optionsObjectIt = optionsObject.constFind(optionIdentifier); - if (optionsObjectIt != optionsObject.constEnd()) - { - const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray()); - - for (const auto &pluginElem : plugins) + bool hasPlugins = false; + auto optionsObjectIt = optionsObject.constFind(optionIdentifier); + if (optionsObjectIt != optionsObject.constEnd()) { - const QString pluginName = pluginElem.toString(); - if (!ignoredPlugins.contains(pluginName)) - { - addOptionToPlugin(appDesc.pluginInfos, flag, pluginName); - hasPlugins = true; - } + const QJsonArray plugins((*optionsObjectIt).toObject()[QStringLiteral("Plugins")].toArray()); + + for (const auto& pluginElem : plugins) + { + const QString pluginName = pluginElem.toString(); + if (!ignoredPlugins.contains(pluginName)) + { + addOptionToPlugin(appDesc.pluginInfos, flag, pluginName); + hasPlugins = true; + } + } } - } - if (atLeastOnePluginNeeded && !hasPlugins) - { - lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'").arg(optionIdentifier, appDesc.appName)); - return false; - } + if (atLeastOnePluginNeeded && !hasPlugins) + { + lastErrors.append(QCoreApplication::tr("No plugins specified for '%1' option for app '%2'") + .arg(optionIdentifier, appDesc.appName)); + return false; + } - return true; + return true; } - App LtsAppDescriptor::appFromInteger(int i) { - switch (i) - { - case int(App::Login): - case int(App::Situation): - case int(App::ResourceManager): - case int(App::PlanEditor): - case int(App::BuildingViewer): - case int(App::OC): - case int(App::OrgChart): - case int(App::Scripts): - - case int(App::Snapshot): - case int(App::SystemMonitor): - case int(App::Timeline): - case int(App::SymbolEditor): - case int(App::ScriptEditorEssentialsView): - case int(App::BaseDownloader): - case int(App::OnlineHelp): - case int(App::ThpSituationReplay): - case int(App::SituationTablet): - case int(App::SilhouetteEditor): - case int(App::Shootback): - case int(App::SAAs): - return static_cast(i); - } - Q_ASSERT_X(false, "LtsAppDescriptor::appFromInteger", qPrintable(QStringLiteral("Unknown app id: %1").arg(i))); - return App::Login; + switch (i) + { + case int(App::Login): + case int(App::Situation): + case int(App::ResourceManager): + case int(App::PlanEditor): + case int(App::BuildingViewer): + case int(App::OC): + case int(App::OrgChart): + case int(App::Scripts): + + case int(App::Snapshot): + case int(App::SystemMonitor): + case int(App::Timeline): + case int(App::SymbolEditor): + case int(App::ScriptEditorEssentialsView): + case int(App::BaseDownloader): + case int(App::OnlineHelp): + case int(App::ThpSituationReplay): + case int(App::SituationTablet): + case int(App::SilhouetteEditor): + case int(App::Shootback): + case int(App::SAAs): + return static_cast(i); + } + Q_ASSERT_X(false, "LtsAppDescriptor::appFromInteger", qPrintable(QStringLiteral("Unknown app id: %1").arg(i))); + return App::Login; } -AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray &jsonDocument, - QStringList &lastErrors, - const QStringList &ignoredPlugins, - QString &loginPluginIid) +AppDescriptionVector LtsAppDescriptor::getAppDescriptionVector(const QByteArray& jsonDocument, QStringList& lastErrors, + const QStringList& ignoredPlugins, + QString& loginPluginIid) { - - AppDescriptionVector appDescriptions; + AppDescriptionVector appDescriptions; - QJsonParseError parseError; - QJsonDocument appsDoc(QJsonDocument::fromJson(jsonDocument, &parseError)); + QJsonParseError parseError; + QJsonDocument appsDoc(QJsonDocument::fromJson(jsonDocument, &parseError)); - if (parseError.error != QJsonParseError::NoError) - { - - - int row = 0; - int column = 0; - QChar x = QLatin1Char('\n'); - - for (int i = 0; i < jsonDocument.count(); i++) + if (parseError.error != QJsonParseError::NoError) { - if (i == parseError.offset) - break; - if (QChar::fromLatin1(jsonDocument[i]) == x) - { - row++; - column = 0; - } - else - { - column++; - } - } + int row = 0; + int column = 0; + QChar x = QLatin1Char('\n'); + for (int i = 0; i < jsonDocument.count(); i++) + { + if (i == parseError.offset) + break; - lastErrors.append(QCoreApplication::tr("JSON: %1
Row: %2, Column: %3").arg(parseError.errorString()).arg(row+1).arg(column+1)); - return appDescriptions; - } + if (QChar::fromLatin1(jsonDocument[i]) == x) + { + row++; + column = 0; + } + else + { + column++; + } + } - const QJsonObject root(appsDoc.object()); - - loginPluginIid = root[QStringLiteral("LoginPlugin")].toString(); - - const QJsonArray appArray(root[QStringLiteral("Apps")].toArray()); - if (appArray.isEmpty()) - { - lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array")); - return appDescriptions; - } - - - for (const auto &appElem : appArray) - { - AppDescription appDesc; - const QJsonObject appObject = appElem.toObject(); - - - - appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1)); - if (appDesc.id == App::Login) - { - lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName)); - return appDescriptions; - } - - appDesc.appName = appObject.value(QStringLiteral("AppName")).toString(); - - const QJsonValue valueActive = appObject.value(QStringLiteral("Active")); - if (!valueActive.isUndefined()) - { - if (valueActive.type() != QJsonValue::Type::Bool) - { - lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)").arg(appDesc.appName).arg((int)valueActive.type())); + lastErrors.append(QCoreApplication::tr("JSON: %1
Row: %2, Column: %3") + .arg(parseError.errorString()) + .arg(row + 1) + .arg(column + 1)); return appDescriptions; - } } - appDesc.active = valueActive.toBool(false); - const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible")); - if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool) + const QJsonObject root(appsDoc.object()); + + loginPluginIid = root[QStringLiteral("LoginPlugin")].toString(); + + const QJsonArray appArray(root[QStringLiteral("Apps")].toArray()); + if (appArray.isEmpty()) { - lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)").arg(appDesc.appName).arg((int)valueVisible.type())); - return appDescriptions; + lastErrors.append(QCoreApplication::tr("Invalid json: Could not find 'Apps' array")); + return appDescriptions; } - appDesc.visible = valueVisible.toBool(true); - const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray()); - for (const QJsonValue &value : array) - appDesc.requiredAcls.append(value.toInt()); + for (const auto& appElem : appArray) + { + AppDescription appDesc; + const QJsonObject appObject = appElem.toObject(); + appDesc.id = appFromInteger(appObject.value(QStringLiteral("Id")).toInt(-1)); + if (appDesc.id == App::Login) + { + lastErrors.append(QCoreApplication::tr("App '%1': no App Id or invalid App Id given").arg(appDesc.appName)); + return appDescriptions; + } - - const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject()); + appDesc.appName = appObject.value(QStringLiteral("AppName")).toString(); - addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject, PluginInfo::Flag::PAYLOAD, lastErrors, false); - addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS, lastErrors, true ); - addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN, lastErrors, false); + const QJsonValue valueActive = appObject.value(QStringLiteral("Active")); + if (!valueActive.isUndefined()) + { + if (valueActive.type() != QJsonValue::Type::Bool) + { + lastErrors.append(QCoreApplication::tr("App '%1': value App.Active is not a bool (%2)") + .arg(appDesc.appName) + .arg((int)valueActive.type())); + return appDescriptions; + } + } + appDesc.active = valueActive.toBool(false); + const QJsonValue valueVisible = appObject.value(QStringLiteral("Visible")); + if (!valueVisible.isUndefined() && valueVisible.type() != QJsonValue::Type::Bool) + { + lastErrors.append(QCoreApplication::tr("App '%1': value App.Visible is not a bool (%2)") + .arg(appDesc.appName) + .arg((int)valueVisible.type())); + return appDescriptions; + } + appDesc.visible = valueVisible.toBool(true); - appDescriptions.append(appDesc); - - } + const QJsonArray array(appObject.value(QStringLiteral("ACLs")).toArray()); + for (const QJsonValue& value : array) + appDesc.requiredAcls.append(value.toInt()); - + const QJsonObject optionsObject(appObject.value(QStringLiteral("Options")).toObject()); - return appDescriptions; + addOptionsToPlugin(appDesc, QStringLiteral("Payloads"), ignoredPlugins, optionsObject, + PluginInfo::Flag::PAYLOAD, lastErrors, false); + addOptionsToPlugin(appDesc, QStringLiteral("Actions"), ignoredPlugins, optionsObject, PluginInfo::Flag::ACTIONS, + lastErrors, true); + addOptionsToPlugin(appDesc, QStringLiteral("Main"), ignoredPlugins, optionsObject, PluginInfo::Flag::MAIN, + lastErrors, false); + + appDescriptions.append(appDesc); + } + + return appDescriptions; } -} +} // namespace LtsAppDescriptor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h old mode 100755 new mode 100644 index 34d217f12..ab15a3ed8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor.h @@ -1,96 +1,95 @@ - #pragma once -#include #include +#include #ifndef LTSAPPDESCRIPTOR_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSAPPDESCRIPTOR_EXPORT -# else -# if defined(MAKE_LTSAPPDESCRIPTOR_LIB) -# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT -# else -# define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSAPPDESCRIPTOR_EXPORT +#else +#if defined(MAKE_LTSAPPDESCRIPTOR_LIB) +#define LTSAPPDESCRIPTOR_EXPORT Q_DECL_EXPORT +#else +#define LTSAPPDESCRIPTOR_EXPORT Q_DECL_IMPORT +#endif +#endif #endif - namespace LtsAppDescriptor { -enum class App -{ - Login = -1, - Situation = 0, - ResourceManager = 1, - PlanEditor = 2, - BuildingViewer = 3, - OC = 4, - OrgChart = 5, - Scripts = 6, - - Snapshot = 8, - SystemMonitor = 9, - Timeline = 10, - SymbolEditor = 11, - ScriptEditorEssentialsView = 12, - BaseDownloader = 13, - OnlineHelp = 14, - ThpSituationReplay = 15, - SituationTablet = 17, - SilhouetteEditor = 18, - Shootback = 19, - SAAs = 20, +enum class App { + Login = -1, + Situation = 0, + ResourceManager = 1, + PlanEditor = 2, + BuildingViewer = 3, + OC = 4, + OrgChart = 5, + Scripts = 6, + + Snapshot = 8, + SystemMonitor = 9, + Timeline = 10, + SymbolEditor = 11, + ScriptEditorEssentialsView = 12, + BaseDownloader = 13, + OnlineHelp = 14, + ThpSituationReplay = 15, + SituationTablet = 17, + SilhouetteEditor = 18, + Shootback = 19, + SAAs = 20, }; struct PluginInfo { - enum class PluginType - { - UNKNOWN, - DATA, - GUI, - }; + enum class PluginType { + UNKNOWN, + DATA, + GUI, + }; - enum class Flag - { - UNKNOWN = 1 << 0, - ACTIONS = 1 << 1, - MAIN = 1 << 2, - PAYLOAD = 1 << 3, - OPTION = 1 << 4, - }; + enum class Flag { + UNKNOWN = 1 << 0, + ACTIONS = 1 << 1, + MAIN = 1 << 2, + PAYLOAD = 1 << 3, + OPTION = 1 << 4, + }; - PluginType type = PluginType::UNKNOWN; - QString iid; - QFlags flags; - QStringList options; + PluginType type = PluginType::UNKNOWN; + QString iid; + QFlags flags; + QStringList options; }; struct AppDescription { - App id = App::Login; - bool active = false; - bool visible = true; - QString appName; - QVector requiredAcls; - QVector pluginInfos; + App id = App::Login; + bool active = false; + bool visible = true; + QString appName; + QVector requiredAcls; + QVector pluginInfos; - bool isValid() const { return !appName.isEmpty(); } + bool isValid() const + { + return !appName.isEmpty(); + } }; typedef QVector AppDescriptionVector; - -namespace LtsAppDescriptor +namespace LtsAppDescriptor { LTSAPPDESCRIPTOR_EXPORT App appFromInteger(int i); -LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray &jsonDocument, QStringList &lastErrors, - const QStringList &ignoredPlugins, QString &loginPluginIid); -} +LTSAPPDESCRIPTOR_EXPORT AppDescriptionVector getAppDescriptionVector(const QByteArray& jsonDocument, + QStringList& lastErrors, + const QStringList& ignoredPlugins, + QString& loginPluginIid); +} // namespace LtsAppDescriptor -} +} // namespace LtsAppDescriptor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp old mode 100755 new mode 100644 index d90fe9c04..0e6a4a841 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.cpp @@ -1,554 +1,533 @@ #include "lts_app_descriptor_editor.h" + #include "ui_lts_app_descriptor_editor.h" +#include #include -#include -#include #include +#include #include +#include #include -#include - -LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui_LtsAppDescriptionEditor) +LtsAppDescriptorEditor::LtsAppDescriptorEditor(QWidget* parent) : QWidget(parent), m_ui(new Ui_LtsAppDescriptionEditor) { - m_ui->setupUi(this); - m_vector = LtsAppDescriptor::AppDescriptionVector(); - m_appIndex = QModelIndex(); - m_pluginIndex = QModelIndex(); - m_fileName = QString(); - m_changed = false; + m_ui->setupUi(this); + m_vector = LtsAppDescriptor::AppDescriptionVector(); + m_appIndex = QModelIndex(); + m_pluginIndex = QModelIndex(); + m_fileName = QString(); + m_changed = false; - connect(m_ui->lvApps, SIGNAL(clicked(QModelIndex)), this, SLOT(onAppsClicked(QModelIndex))); - connect(m_ui->lvPlugins, SIGNAL(clicked(QModelIndex)), this, SLOT(onPluginsClicked(QModelIndex))); - connect(m_ui->lePluginType, SIGNAL(editingFinished()), this, SLOT(pluginTypeChanged())); - connect(m_ui->pbAddApp, SIGNAL(pressed()), this, SLOT(onAppAddClicked())); - connect(m_ui->pbAddPlugin, SIGNAL(pressed()), this, SLOT(onPluginAddClicked())); - connect(m_ui->pbDeleteApp, SIGNAL(pressed()), this, SLOT(onAppDeleteClicked())); - connect(m_ui->pbDeletePlugin, SIGNAL(pressed()), this, SLOT(onPluginDeletedClicked())); - connect(m_ui->pbUpdate, SIGNAL(pressed()), this, SLOT(onUpdateClicked())); - connect(m_ui->pbNewPlugin, SIGNAL(pressed()), this, SLOT(onNewpluginClicked())); - connect(m_ui->pbNewApp, SIGNAL(pressed()), this, SLOT(onNewAppClicked())); - connect(m_ui->lePluginName, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); - connect(m_ui->lePluginType, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); + connect(m_ui->lvApps, SIGNAL(clicked(QModelIndex)), this, SLOT(onAppsClicked(QModelIndex))); + connect(m_ui->lvPlugins, SIGNAL(clicked(QModelIndex)), this, SLOT(onPluginsClicked(QModelIndex))); + connect(m_ui->lePluginType, SIGNAL(editingFinished()), this, SLOT(pluginTypeChanged())); + connect(m_ui->pbAddApp, SIGNAL(pressed()), this, SLOT(onAppAddClicked())); + connect(m_ui->pbAddPlugin, SIGNAL(pressed()), this, SLOT(onPluginAddClicked())); + connect(m_ui->pbDeleteApp, SIGNAL(pressed()), this, SLOT(onAppDeleteClicked())); + connect(m_ui->pbDeletePlugin, SIGNAL(pressed()), this, SLOT(onPluginDeletedClicked())); + connect(m_ui->pbUpdate, SIGNAL(pressed()), this, SLOT(onUpdateClicked())); + connect(m_ui->pbNewPlugin, SIGNAL(pressed()), this, SLOT(onNewpluginClicked())); + connect(m_ui->pbNewApp, SIGNAL(pressed()), this, SLOT(onNewAppClicked())); + connect(m_ui->lePluginName, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); + connect(m_ui->lePluginType, SIGNAL(textChanged(QString)), this, SLOT(enableNewPlugin())); - m_ui->gbPlugins->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbDeleteApp->setEnabled(false); - m_ui->pbAddPlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->pbNewApp->setEnabled(false); - QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector); + m_ui->gbPlugins->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbDeleteApp->setEnabled(false); + m_ui->pbAddPlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbNewApp->setEnabled(false); + QTimer::singleShot(0, this, &LtsAppDescriptorEditor::getAppDescriptionVector); } LtsAppDescriptorEditor::~LtsAppDescriptorEditor() { - checkSave(); - delete m_ui; + checkSave(); + delete m_ui; } - void LtsAppDescriptorEditor::getAppDescriptionVector() { - m_fileName = QFileDialog::getOpenFileName(this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), - tr("JSON File (*.json)")); - if (m_fileName.isEmpty()) - return; + m_fileName = QFileDialog::getOpenFileName( + this, tr("Open JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), + tr("JSON File (*.json)")); + if (m_fileName.isEmpty()) + return; - QFile file; - file.setFileName(m_fileName); - file.open(QIODevice::ReadOnly | QIODevice::Text); - QString val(QString::fromUtf8(file.readAll())); - file.close(); + QFile file; + file.setFileName(m_fileName); + file.open(QIODevice::ReadOnly | QIODevice::Text); + QString val(QString::fromUtf8(file.readAll())); + file.close(); - QStringList errors; - m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors); + QStringList errors; + m_vector = LtsAppDescriptor::LtsAppDescriptor::getAppDescriptionVector(val.toUtf8(), errors); - updateAppModel(); + updateAppModel(); } -void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex &index) +void LtsAppDescriptorEditor::onAppsClicked(const QModelIndex& index) { - m_ui->gbPlugins->setEnabled(true); - m_ui->pbDeleteApp->setEnabled(true); - m_ui->pbAddPlugin->setEnabled(true); - m_ui->pbNewApp->setEnabled(true); - m_appIndex = index; + m_ui->gbPlugins->setEnabled(true); + m_ui->pbDeleteApp->setEnabled(true); + m_ui->pbAddPlugin->setEnabled(true); + m_ui->pbNewApp->setEnabled(true); + m_appIndex = index; - QStringList pluginList; - Q_FOREACH(const LtsAppDescriptor::PluginInfo &reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins) - { - LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type; + QStringList pluginList; + Q_FOREACH (const LtsAppDescriptor::PluginInfo& reqPlugin, m_vector.at(m_appIndex.row()).requiredPlugins) + { + LtsAppDescriptor::PluginInfo::PluginType pluginType = reqPlugin.type; + QString type; + if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) + type = QLatin1String("data"); + else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) + type = QLatin1String("gui"); + else + type = QLatin1String("unknown"); + + if (type == QLatin1String("data")) + pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid); + else + { + QString strFlags; + QFlags flags = reqPlugin.flags; + + bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); + if (actionsFlag) + strFlags.append(QLatin1String("actions ")); + bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); + if (mainFlag) + strFlags.append(QLatin1String("main ")); + bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); + if (payloadFlag) + strFlags.append(QLatin1String("payload ")); + bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION); + if (optionalFlag) + strFlags.append(QLatin1String("optional ")); + + pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags + + QLatin1String("]")); + } + } + updatePluginModel(pluginList); + + m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active); + m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName); +} + +void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex& index) +{ + m_pluginIndex = index; + m_ui->pbDeletePlugin->setEnabled(true); + m_ui->pbUpdate->setEnabled(true); + m_ui->pbNewPlugin->setEnabled(true); + + const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row()); + QString pluginName = plugin.iid; + m_ui->lePluginName->setText(pluginName); + + LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type; QString type; if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) - type = QLatin1String("data"); - else if(pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) - type = QLatin1String("gui"); + type = QLatin1String("data"); + else if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) + type = QLatin1String("gui"); else - type = QLatin1String("unknown"); + type = QLatin1String("unknown"); + m_ui->lePluginType->setText(type); - if(type == QLatin1String("data")) - pluginList << QString(type + QLatin1String(": ") +reqPlugin.iid); + if (type == QLatin1String("gui")) + { + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + + QFlags flags = plugin.flags; + bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); + m_ui->chbActions->setChecked(actionsFlag); + bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); + m_ui->chbMain->setChecked(mainFlag); + bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); + m_ui->chbPayload->setChecked(payloadFlag); + } else { - QString strFlags; - QFlags flags = reqPlugin.flags; - - bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); - if(actionsFlag) - strFlags.append(QLatin1String("actions ")); - bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); - if(mainFlag) - strFlags.append(QLatin1String("main ")); - bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); - if(payloadFlag) - strFlags.append(QLatin1String("payload ")); - bool optionalFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::OPTION); - if(optionalFlag) - strFlags.append(QLatin1String("optional ")); - - pluginList << QString(type + QLatin1String(": ") + reqPlugin.iid + QLatin1String(" [ ") + strFlags + QLatin1String("]")); + m_ui->chbActions->setChecked(false); + m_ui->chbActions->setEnabled(false); + m_ui->chbMain->setChecked(false); + m_ui->chbMain->setEnabled(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbPayload->setEnabled(false); } - - } - updatePluginModel(pluginList); - - m_ui->chbAppActive->setChecked(m_vector.at(m_appIndex.row()).active); - m_ui->leAppName->setText(m_vector.at(m_appIndex.row()).appName); -} - -void LtsAppDescriptorEditor::onPluginsClicked(const QModelIndex &index) -{ - m_pluginIndex = index; - m_ui->pbDeletePlugin->setEnabled(true); - m_ui->pbUpdate->setEnabled(true); - m_ui->pbNewPlugin->setEnabled(true); - - const LtsAppDescriptor::PluginInfo plugin = m_vector.at(m_appIndex.row()).requiredPlugins.at(m_pluginIndex.row()); - QString pluginName = plugin.iid; - m_ui->lePluginName->setText(pluginName); - - LtsAppDescriptor::PluginInfo::PluginType pluginType = plugin.type; - QString type; - if (pluginType == LtsAppDescriptor::PluginInfo::PluginType::DATA) - type = QLatin1String("data"); - else if(pluginType == LtsAppDescriptor::PluginInfo::PluginType::GUI) - type = QLatin1String("gui"); - else - type = QLatin1String("unknown"); - m_ui->lePluginType->setText(type); - - if(type == QLatin1String("gui")) - { - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - - QFlags flags = plugin.flags; - bool actionsFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS); - m_ui->chbActions->setChecked(actionsFlag); - bool mainFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN); - m_ui->chbMain->setChecked(mainFlag); - bool payloadFlag = flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD); - m_ui->chbPayload->setChecked(payloadFlag); - } - else - { - m_ui->chbActions->setChecked(false); - m_ui->chbActions->setEnabled(false); - m_ui->chbMain->setChecked(false); - m_ui->chbMain->setEnabled(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbPayload->setEnabled(false); - } } void LtsAppDescriptorEditor::pluginTypeChanged() { - if(m_ui->lePluginType->text().isEmpty()) - return; + if (m_ui->lePluginType->text().isEmpty()) + return; - if(m_ui->lePluginType->text() == QLatin1String("gui")) - { - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - } - else if(m_ui->lePluginType->text() == QLatin1String("data")) - { - m_ui->chbActions->setChecked(false); - m_ui->chbActions->setEnabled(false); - m_ui->chbMain->setChecked(false); - m_ui->chbMain->setEnabled(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbPayload->setEnabled(false); - } - else - { - QMessageBox msgBox(QMessageBox::Information, - tr("Error"), - tr("Plugin Type must either be \"gui\" or \"data\".")); - msgBox.exec(); - m_ui->lePluginType->setText(QString()); - } + if (m_ui->lePluginType->text() == QLatin1String("gui")) + { + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + } + else if (m_ui->lePluginType->text() == QLatin1String("data")) + { + m_ui->chbActions->setChecked(false); + m_ui->chbActions->setEnabled(false); + m_ui->chbMain->setChecked(false); + m_ui->chbMain->setEnabled(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbPayload->setEnabled(false); + } + else + { + QMessageBox msgBox(QMessageBox::Information, tr("Error"), + tr("Plugin Type must either be \"gui\" or \"data\".")); + msgBox.exec(); + m_ui->lePluginType->setText(QString()); + } } void LtsAppDescriptorEditor::onAppAddClicked() { - m_changed = true; + m_changed = true; - if(m_ui->leAppName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("The App needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->leAppName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The App needs to have a name.")); + msgBox.exec(); + return; + } - QStringList appList; - Q_FOREACH(const LtsAppDescriptor::AppDescription &appDesc, m_vector) - { - appList << appDesc.appName; - } + QStringList appList; + Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector) + { + appList << appDesc.appName; + } - if(appList.contains(m_ui->leAppName->text(),Qt::CaseInsensitive)) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text())); - msgBox.exec(); - return; - } + if (appList.contains(m_ui->leAppName->text(), Qt::CaseInsensitive)) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), + tr("There already exists an app named \"%1\".").arg(m_ui->leAppName->text())); + msgBox.exec(); + return; + } - LtsAppDescriptor::AppDescription newApp; - newApp.appName = m_ui->leAppName->text(); - newApp.active = m_ui->chbAppActive->isChecked(); - m_vector.append(newApp); - - updateAppModel(); + LtsAppDescriptor::AppDescription newApp; + newApp.appName = m_ui->leAppName->text(); + newApp.active = m_ui->chbAppActive->isChecked(); + m_vector.append(newApp); + updateAppModel(); } void LtsAppDescriptorEditor::onPluginAddClicked() { - m_changed = true; + m_changed = true; - if(m_ui->lePluginType->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("The Plugin needs to contain a type.")); - msgBox.exec(); - return; - } - if(m_ui->lePluginName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("The Plugin needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->lePluginType->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); + msgBox.exec(); + return; + } + if (m_ui->lePluginName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); + msgBox.exec(); + return; + } - QStringList pluginList; - Q_FOREACH(const LtsAppDescriptor::PluginInfo &pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins) - { - pluginList << pluginDesc.iid; - } + QStringList pluginList; + Q_FOREACH (const LtsAppDescriptor::PluginInfo& pluginDesc, m_vector.at(m_appIndex.row()).requiredPlugins) + { + pluginList << pluginDesc.iid; + } - if(pluginList.contains(m_ui->lePluginName->text(),Qt::CaseInsensitive)) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text())); - msgBox.exec(); - return; - } + if (pluginList.contains(m_ui->lePluginName->text(), Qt::CaseInsensitive)) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), + tr("There already exists an plugin named \"%1\".").arg(m_ui->lePluginName->text())); + msgBox.exec(); + return; + } + LtsAppDescriptor::PluginInfo newPlugin; - LtsAppDescriptor::PluginInfo newPlugin; + newPlugin.iid = m_ui->lePluginName->text(); - newPlugin.iid = m_ui->lePluginName->text(); + if (m_ui->lePluginType->text() == QLatin1String("gui")) + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; + else if (m_ui->lePluginType->text() == QLatin1String("data")) + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; + else + newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; - if(m_ui->lePluginType->text() == QLatin1String("gui")) - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; - else if(m_ui->lePluginType->text() == QLatin1String("data")) - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; - else - newPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; + if (m_ui->chbActions->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; + if (m_ui->chbMain->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; + if (m_ui->chbPayload->isChecked()) + newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - if(m_ui->chbActions->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; - if(m_ui->chbMain->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; - if(m_ui->chbPayload->isChecked()) - newPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - - m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin); - - onAppsClicked(m_appIndex); - onNewpluginClicked(); + m_vector[m_appIndex.row()].requiredPlugins.append(newPlugin); + onAppsClicked(m_appIndex); + onNewpluginClicked(); } void LtsAppDescriptorEditor::onAppDeleteClicked() { - m_changed = true; + m_changed = true; - if(!m_appIndex.isValid()) return; + if (!m_appIndex.isValid()) + return; - QMessageBox msgBox(tr("Warning"), - tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()), - QMessageBox::Warning, - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, - QMessageBox::NoButton); + QMessageBox msgBox(tr("Warning"), + tr("The App \n\"%1\" \nwill be removed. Continue?").arg(m_appIndex.data().toString()), + QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::No) - return; + if (msgBox.exec() == QMessageBox::No) + return; - m_vector.remove(m_appIndex.row()); - - updateAppModel(); + m_vector.remove(m_appIndex.row()); + updateAppModel(); } void LtsAppDescriptorEditor::onPluginDeletedClicked() { - m_changed = true; + m_changed = true; - if(!m_pluginIndex.isValid()) return; + if (!m_pluginIndex.isValid()) + return; - QMessageBox msgBox(tr("Warning"), - tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()), - QMessageBox::Warning, - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, - QMessageBox::NoButton); + QMessageBox msgBox(tr("Warning"), + tr("The Plugin \n\"%1\" \nwill be removed. Continue?").arg(m_pluginIndex.data().toString()), + QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::No) - return; + if (msgBox.exec() == QMessageBox::No) + return; - m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row()); - m_pluginIndex = QModelIndex(); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); + m_vector[m_appIndex.row()].requiredPlugins.remove(m_pluginIndex.row()); + m_pluginIndex = QModelIndex(); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); - onAppsClicked(m_appIndex); + onAppsClicked(m_appIndex); } void LtsAppDescriptorEditor::onUpdateClicked() { - m_changed = true; + m_changed = true; - if(m_ui->lePluginType->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("The Plugin needs to contain a type.")); - msgBox.exec(); - return; - } - if(m_ui->lePluginName->text().isEmpty()) - { - QMessageBox msgBox(QMessageBox::Critical, - tr("Error"), - tr("The Plugin needs to have a name.")); - msgBox.exec(); - return; - } + if (m_ui->lePluginType->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to contain a type.")); + msgBox.exec(); + return; + } + if (m_ui->lePluginName->text().isEmpty()) + { + QMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("The Plugin needs to have a name.")); + msgBox.exec(); + return; + } - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text(); + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].iid = m_ui->lePluginName->text(); - if(m_ui->lePluginType->text() == QLatin1String("gui")) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::GUI; - else if(m_ui->lePluginType->text() == QLatin1String("data")) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::DATA; - else - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; + if (m_ui->lePluginType->text() == QLatin1String("gui")) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = + LtsAppDescriptor::PluginInfo::PluginType::GUI; + else if (m_ui->lePluginType->text() == QLatin1String("data")) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = + LtsAppDescriptor::PluginInfo::PluginType::DATA; + else + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].type = + LtsAppDescriptor::PluginInfo::PluginType::UNKNOWN; - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags = QFlags(); + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags = + QFlags(); - if(m_ui->chbActions->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; - if(m_ui->chbMain->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::MAIN; - if(m_ui->chbPayload->isChecked()) - m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; + if (m_ui->chbActions->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= + LtsAppDescriptor::PluginInfo::Flag::ACTIONS; + if (m_ui->chbMain->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= + LtsAppDescriptor::PluginInfo::Flag::MAIN; + if (m_ui->chbPayload->isChecked()) + m_vector[m_appIndex.row()].requiredPlugins[m_pluginIndex.row()].flags |= + LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - onAppsClicked(m_appIndex); - onNewpluginClicked(); + onAppsClicked(m_appIndex); + onNewpluginClicked(); } void LtsAppDescriptorEditor::onNewpluginClicked() { - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setEnabled(true); - m_ui->chbMain->setEnabled(true); - m_ui->chbPayload->setEnabled(true); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setEnabled(true); + m_ui->chbMain->setEnabled(true); + m_ui->chbPayload->setEnabled(true); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); - if(m_pluginIndex.isValid()) - m_ui->lvPlugins->selectionModel()->select(m_pluginIndex,QItemSelectionModel::Deselect); - m_pluginIndex = QModelIndex(); + if (m_pluginIndex.isValid()) + m_ui->lvPlugins->selectionModel()->select(m_pluginIndex, QItemSelectionModel::Deselect); + m_pluginIndex = QModelIndex(); } void LtsAppDescriptorEditor::onNewAppClicked() { - updatePluginModel(QStringList()); + updatePluginModel(QStringList()); - m_ui->gbPlugins->setEnabled(false); - m_ui->pbDeletePlugin->setEnabled(false); - m_ui->pbDeleteApp->setEnabled(false); - m_ui->pbAddPlugin->setEnabled(false); - m_ui->pbUpdate->setEnabled(false); - m_ui->pbNewPlugin->setEnabled(false); - m_ui->leAppName->setText(QString()); - m_ui->chbAppActive->setChecked(false); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->pbNewApp->setEnabled(false); + m_ui->gbPlugins->setEnabled(false); + m_ui->pbDeletePlugin->setEnabled(false); + m_ui->pbDeleteApp->setEnabled(false); + m_ui->pbAddPlugin->setEnabled(false); + m_ui->pbUpdate->setEnabled(false); + m_ui->pbNewPlugin->setEnabled(false); + m_ui->leAppName->setText(QString()); + m_ui->chbAppActive->setChecked(false); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->pbNewApp->setEnabled(false); - if(m_appIndex.isValid()) - m_ui->lvApps->selectionModel()->select(m_appIndex,QItemSelectionModel::Deselect); - m_appIndex = QModelIndex(); + if (m_appIndex.isValid()) + m_ui->lvApps->selectionModel()->select(m_appIndex, QItemSelectionModel::Deselect); + m_appIndex = QModelIndex(); } void LtsAppDescriptorEditor::updateAppModel() { - onNewAppClicked(); - QStringList appList; - Q_FOREACH(const LtsAppDescriptor::AppDescription &appDesc, m_vector) - { - appList << appDesc.appName; - } + onNewAppClicked(); + QStringList appList; + Q_FOREACH (const LtsAppDescriptor::AppDescription& appDesc, m_vector) + { + appList << appDesc.appName; + } - if (!m_ui->lvApps->model()) - m_ui->lvApps->setModel(new QStringListModel(this)); - QStringListModel *m = qobject_cast(m_ui->lvApps->model()); - if (!m) - return; - m->setStringList(appList); + if (!m_ui->lvApps->model()) + m_ui->lvApps->setModel(new QStringListModel(this)); + QStringListModel* m = qobject_cast(m_ui->lvApps->model()); + if (!m) + return; + m->setStringList(appList); } -void LtsAppDescriptorEditor::updatePluginModel(const QStringList &list) +void LtsAppDescriptorEditor::updatePluginModel(const QStringList& list) { - if (!m_ui->lvPlugins->model()) - m_ui->lvPlugins->setModel(new QStringListModel(this)); - QStringListModel *m = qobject_cast(m_ui->lvPlugins->model()); - if (!m) - return; - m->setStringList(list); + if (!m_ui->lvPlugins->model()) + m_ui->lvPlugins->setModel(new QStringListModel(this)); + QStringListModel* m = qobject_cast(m_ui->lvPlugins->model()); + if (!m) + return; + m->setStringList(list); } void LtsAppDescriptorEditor::checkSave() { - if(m_changed) - { - QMessageBox msgBox(tr("Warning"), - tr("The Data has been modified.\nDo you want to save your changes?"), - QMessageBox::Warning, - QMessageBox::Yes | QMessageBox::Default, - QMessageBox::No | QMessageBox::Escape, - QMessageBox::NoButton); + if (m_changed) + { + QMessageBox msgBox(tr("Warning"), tr("The Data has been modified.\nDo you want to save your changes?"), + QMessageBox::Warning, QMessageBox::Yes | QMessageBox::Default, + QMessageBox::No | QMessageBox::Escape, QMessageBox::NoButton); - if (msgBox.exec() == QMessageBox::Yes) - onSaveAsClicked(); - } + if (msgBox.exec() == QMessageBox::Yes) + onSaveAsClicked(); + } } void LtsAppDescriptorEditor::onSaveAsClicked() { - QString fileName = QFileDialog::getSaveFileName(this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), - tr("JSON File (*.json)")); - if(fileName.isEmpty()) - return; + QString fileName = QFileDialog::getSaveFileName( + this, tr("Save JSON"), QLatin1Literal("/shd/CTC/TOOLS/TDS/TDS-source/Lts/Projects/Legatus/resources/"), + tr("JSON File (*.json)")); + if (fileName.isEmpty()) + return; - QByteArray jsonByteArray; - jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector); + QByteArray jsonByteArray; + jsonByteArray = LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector); - QFile f(fileName); - f.open(QIODevice::WriteOnly); - f.write(jsonByteArray); - f.close(); + QFile f(fileName); + f.open(QIODevice::WriteOnly); + f.write(jsonByteArray); + f.close(); - m_changed = false; + m_changed = false; - QMessageBox msgBox(QMessageBox::Information, - tr("Success"), - tr("Your file has been saved.")); - msgBox.exec(); + QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); + msgBox.exec(); } void LtsAppDescriptorEditor::onSaveClicked() { - const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector)); + const QByteArray jsonByteArray(LtsAppDescriptor::LtsAppDescriptor::createJson(m_vector)); - QFile f(m_fileName); - f.open(QIODevice::WriteOnly); - f.write(jsonByteArray); - f.close(); + QFile f(m_fileName); + f.open(QIODevice::WriteOnly); + f.write(jsonByteArray); + f.close(); - m_changed = false; + m_changed = false; - QMessageBox msgBox(QMessageBox::Information, - tr("Success"), - tr("Your file has been saved.")); - msgBox.exec(); + QMessageBox msgBox(QMessageBox::Information, tr("Success"), tr("Your file has been saved.")); + msgBox.exec(); } void LtsAppDescriptorEditor::onOpenClicked() { - checkSave(); - getAppDescriptionVector(); - m_changed = false; + checkSave(); + getAppDescriptionVector(); + m_changed = false; } void LtsAppDescriptorEditor::onNewClicked() { - checkSave(); - m_ui->chbActions->setChecked(false); - m_ui->chbMain->setChecked(false); - m_ui->chbPayload->setChecked(false); - m_ui->chbAppActive->setChecked(false); - m_ui->leAppName->setText(QString()); - m_ui->lePluginName->setText(QString()); - m_ui->lePluginType->setText(QString()); - m_ui->gbPlugins->setEnabled(false); + checkSave(); + m_ui->chbActions->setChecked(false); + m_ui->chbMain->setChecked(false); + m_ui->chbPayload->setChecked(false); + m_ui->chbAppActive->setChecked(false); + m_ui->leAppName->setText(QString()); + m_ui->lePluginName->setText(QString()); + m_ui->lePluginType->setText(QString()); + m_ui->gbPlugins->setEnabled(false); - m_vector = LtsAppDescriptor::AppDescriptionVector(); - - updateAppModel(); - updatePluginModel(QStringList()); + m_vector = LtsAppDescriptor::AppDescriptionVector(); + updateAppModel(); + updatePluginModel(QStringList()); } void LtsAppDescriptorEditor::enableNewPlugin() { - m_ui->pbNewPlugin->setEnabled(true); + m_ui->pbNewPlugin->setEnabled(true); } void LtsAppDescriptorEditor::onQuitClicked() { - QApplication::quit(); + QApplication::quit(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h old mode 100755 new mode 100644 index 022b9a5ab..f85ddd98c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/lts_app_descriptor_editor.h @@ -1,67 +1,65 @@ #pragma once -#include - -#include -#include - #include "lts_app_descriptor.h" +#include +#include +#include + #ifndef LTSAPPDESCRIPTOREDITOR_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSAPPDESCRIPTOREDITOR_EXPORT -# else -# if defined(MAKE_LTSAPPDESCRIPTOREDITOR_LIB) -# define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_EXPORT -# else -# define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSAPPDESCRIPTOREDITOR_EXPORT +#else +#if defined(MAKE_LTSAPPDESCRIPTOREDITOR_LIB) +#define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_EXPORT +#else +#define LTSAPPDESCRIPTOREDITOR_EXPORT Q_DECL_IMPORT +#endif +#endif #endif class Ui_LtsAppDescriptionEditor; - class LTSAPPDESCRIPTOREDITOR_EXPORT LtsAppDescriptorEditor : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit LtsAppDescriptorEditor(QWidget *parent = 0); - ~LtsAppDescriptorEditor(); + public: + explicit LtsAppDescriptorEditor(QWidget* parent = 0); + ~LtsAppDescriptorEditor(); -private: - Ui_LtsAppDescriptionEditor *m_ui; - LtsAppDescriptor::AppDescriptionVector m_vector; - QModelIndex m_appIndex; - QModelIndex m_pluginIndex; + private: + Ui_LtsAppDescriptionEditor* m_ui; + LtsAppDescriptor::AppDescriptionVector m_vector; + QModelIndex m_appIndex; + QModelIndex m_pluginIndex; - QString m_fileName; + QString m_fileName; - bool m_changed; + bool m_changed; - void getAppDescriptionVector(); - void setupMainWindow(); - void updateAppModel(); - void updatePluginModel(const QStringList &list); - void checkSave(); + void getAppDescriptionVector(); + void setupMainWindow(); + void updateAppModel(); + void updatePluginModel(const QStringList& list); + void checkSave(); -private slots: - void onAppsClicked(const QModelIndex &index); - void onPluginsClicked(const QModelIndex &index); - void pluginTypeChanged(); - void onAppAddClicked(); - void onPluginAddClicked(); - void onAppDeleteClicked(); - void onPluginDeletedClicked(); - void onUpdateClicked(); - void onNewpluginClicked(); - void onNewAppClicked(); - void enableNewPlugin(); + private slots: + void onAppsClicked(const QModelIndex& index); + void onPluginsClicked(const QModelIndex& index); + void pluginTypeChanged(); + void onAppAddClicked(); + void onPluginAddClicked(); + void onAppDeleteClicked(); + void onPluginDeletedClicked(); + void onUpdateClicked(); + void onNewpluginClicked(); + void onNewAppClicked(); + void enableNewPlugin(); -public slots: - void onSaveClicked(); - void onSaveAsClicked(); - void onOpenClicked(); - void onNewClicked(); - void onQuitClicked(); + public slots: + void onSaveClicked(); + void onSaveAsClicked(); + void onOpenClicked(); + void onNewClicked(); + void onQuitClicked(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp old mode 100755 new mode 100644 index 1904bac5c..339f7b4f0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppDescriptor/main.cpp @@ -1,56 +1,55 @@ - #include "lts_app_descriptor_editor.h" + #include #include #include #include -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - QApplication a(argc, argv); + QApplication a(argc, argv); - QMainWindow *mainWindow = new QMainWindow(); - QMenu *fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File")); + QMainWindow* mainWindow = new QMainWindow(); + QMenu* fileMenu = mainWindow->menuBar()->addMenu(QObject::tr("&File")); - QAction *openAct = new QAction(QObject::tr("&Open"), mainWindow); - openAct->setShortcuts(QKeySequence::Open); - openAct->setStatusTip(QObject::tr("Open an existing file")); - fileMenu->addAction(openAct); + QAction* openAct = new QAction(QObject::tr("&Open"), mainWindow); + openAct->setShortcuts(QKeySequence::Open); + openAct->setStatusTip(QObject::tr("Open an existing file")); + fileMenu->addAction(openAct); - QAction *newAct = new QAction(QObject::tr("&New"), mainWindow); - newAct->setShortcuts(QKeySequence::New); - newAct->setStatusTip(QObject::tr("Create a new App")); - fileMenu->addAction(newAct); + QAction* newAct = new QAction(QObject::tr("&New"), mainWindow); + newAct->setShortcuts(QKeySequence::New); + newAct->setStatusTip(QObject::tr("Create a new App")); + fileMenu->addAction(newAct); - QAction *saveAct = new QAction(QObject::tr("&Save"), mainWindow); - saveAct->setShortcuts(QKeySequence::Save); - saveAct->setStatusTip(QObject::tr("Save modified file")); - fileMenu->addAction(saveAct); + QAction* saveAct = new QAction(QObject::tr("&Save"), mainWindow); + saveAct->setShortcuts(QKeySequence::Save); + saveAct->setStatusTip(QObject::tr("Save modified file")); + fileMenu->addAction(saveAct); - QAction *saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow); - saveAsAct->setShortcuts(QKeySequence::SaveAs); - saveAsAct->setStatusTip(QObject::tr("Save modified file as")); - fileMenu->addAction(saveAsAct); + QAction* saveAsAct = new QAction(QObject::tr("&SaveAs"), mainWindow); + saveAsAct->setShortcuts(QKeySequence::SaveAs); + saveAsAct->setStatusTip(QObject::tr("Save modified file as")); + fileMenu->addAction(saveAsAct); - QAction *quitAct = new QAction(QObject::tr("&Quit"), mainWindow); - quitAct->setShortcuts(QKeySequence::Quit); - quitAct->setStatusTip(QObject::tr("Quit the Application")); - fileMenu->addAction(quitAct); + QAction* quitAct = new QAction(QObject::tr("&Quit"), mainWindow); + quitAct->setShortcuts(QKeySequence::Quit); + quitAct->setStatusTip(QObject::tr("Quit the Application")); + fileMenu->addAction(quitAct); + LtsAppDescriptorEditor* editor = new LtsAppDescriptorEditor(mainWindow); + mainWindow->setCentralWidget(editor); + QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked); + QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked); + QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked); + QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked); + QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked); - LtsAppDescriptorEditor *editor = new LtsAppDescriptorEditor(mainWindow); - mainWindow->setCentralWidget(editor); - QObject::connect(openAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onOpenClicked); - QObject::connect(newAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onNewClicked); - QObject::connect(saveAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveClicked); - QObject::connect(saveAsAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onSaveAsClicked); - QObject::connect(quitAct, &QAction::triggered, editor, &LtsAppDescriptorEditor::onQuitClicked); + mainWindow->show(); - mainWindow->show(); - - int ret = a.exec(); - delete mainWindow; - return ret; + int ret = a.exec(); + delete mainWindow; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.cpp old mode 100755 new mode 100644 index 280de0beb..df3025333 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.cpp @@ -1,35 +1,32 @@ - #include "app.h" -#include "ui_app.h" -#include "AppChooser/app_chooser_model.h" +#include "AppChooser/app_chooser_model.h" +#include "ui_app.h" namespace LtsAppManager { -CustomViewApp::CustomViewApp(QWidget *parent) - : AbstractDisplayWidget(parent) - , m_ui(new Ui::CustomViewApp) +CustomViewApp::CustomViewApp(QWidget* parent) : AbstractDisplayWidget(parent), m_ui(new Ui::CustomViewApp) { - m_ui->setupUi(this); - m_ui->image->setMenuEnabled(false); + m_ui->setupUi(this); + m_ui->image->setMenuEnabled(false); } CustomViewApp::~CustomViewApp() { - delete m_ui; + delete m_ui; } -bool CustomViewApp::init(const QModelIndex &idx) +bool CustomViewApp::init(const QModelIndex& idx) { - if (!idx.isValid()) - return false; + if (!idx.isValid()) + return false; - m_ui->lbAppName->setText(rowData(idx, AppChooserModel::Name).toString()); - - return true; + m_ui->lbAppName->setText(rowData(idx, AppChooserModel::Name).toString()); + + return true; } -} +} // namespace LtsAppManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.h old mode 100755 new mode 100644 index 0aad839bf..bd54968eb --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/CustomViews/app.h @@ -2,10 +2,8 @@ #pragma once #include - #include - namespace Ui { class CustomViewApp; @@ -16,16 +14,15 @@ namespace LtsAppManager class CustomViewApp final : public LtsDataView::AbstractDisplayWidget { - Q_OBJECT + Q_OBJECT -public: - explicit CustomViewApp(QWidget *parent = nullptr); - ~CustomViewApp(); - bool init(const QModelIndex &idx) override; - -private: - Ui::CustomViewApp* m_ui; + public: + explicit CustomViewApp(QWidget* parent = nullptr); + ~CustomViewApp(); + bool init(const QModelIndex& idx) override; + private: + Ui::CustomViewApp* m_ui; }; -} +} // namespace LtsAppManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.cpp old mode 100755 new mode 100644 index aaf658738..a7b776246 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.cpp @@ -1,93 +1,80 @@ #include "AppChooser/app_chooser.h" -#include "ui_app_chooser.h" + +#include "AppChooser/CustomViews/app.h" #include "AppChooser/app_chooser_model.h" #include "lts_app_manager.h" -#include "AppChooser/CustomViews/app.h" +#include "ui_app_chooser.h" #include - #include - namespace LtsAppManager { -AppChooser::AppChooser() - : QWidget(nullptr) - , m_ui(new Ui::AppChooser) - , m_model() - , m_madeSelection(false) +AppChooser::AppChooser() : QWidget(nullptr), m_ui(new Ui::AppChooser), m_model(), m_madeSelection(false) { - m_ui->setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); + 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); + 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_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); + m_ui->widget->seamless(); + + m_ui->widget->setModel(m_model); + m_ui->widget->hideColumn(AppChooserModel::Columns::Visible); } - AppChooser::~AppChooser() { - delete m_ui; + delete m_ui; } - void AppChooser::slotQuit() { - if (m_alreadyCloseEmitted) - return; - m_alreadyCloseEmitted = true; - emit signalLogout(); + if (m_alreadyCloseEmitted) + return; + m_alreadyCloseEmitted = true; + emit signalLogout(); } - -void AppChooser::closeEvent(QCloseEvent *) +void AppChooser::closeEvent(QCloseEvent*) { - if (!m_madeSelection) - slotQuit(); + if (!m_madeSelection) + slotQuit(); } - void AppChooser::slotAppSelected() { - const QModelIndex idx = m_ui->widget->currentIndex(); - const LtsAppDescriptor::AppDescription app = m_model->getRowData(idx.row()); + const QModelIndex idx = m_ui->widget->currentIndex(); + const LtsAppDescriptor::AppDescription app = m_model->getRowData(idx.row()); - if (!app.active) - return; + if (!app.active) + return; - hide(); - m_madeSelection = true; - emit signalAppSelected(app.id); - close(); + hide(); + m_madeSelection = true; + emit signalAppSelected(app.id); + close(); } - void AppChooser::enaDisa() { - const QModelIndexList selectedRows = m_ui->widget->selectedRows(); - const int cntSelectedRows = selectedRows.size(); + const QModelIndexList selectedRows = m_ui->widget->selectedRows(); + const int cntSelectedRows = selectedRows.size(); - m_ui->pbSelect->setEnabled(cntSelectedRows == 1); + m_ui->pbSelect->setEnabled(cntSelectedRows == 1); } -} +} // namespace LtsAppManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.h old mode 100755 new mode 100644 index 37b4539ac..fc950d201 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser.h @@ -1,16 +1,14 @@ #pragma once -#include - -#include #include +#include +#include namespace Ui { class AppChooser; } - namespace LtsAppManager { @@ -18,31 +16,30 @@ class AppChooserModel; class AppChooser : public QWidget { - Q_OBJECT + Q_OBJECT -public: - AppChooser(); - ~AppChooser(); + public: + AppChooser(); + ~AppChooser(); -private: - Ui::AppChooser *m_ui; - AppChooserModel *m_model; - bool m_madeSelection; - bool m_alreadyCloseEmitted { false }; + private: + Ui::AppChooser* m_ui; + AppChooserModel* m_model; + bool m_madeSelection; + bool m_alreadyCloseEmitted{false}; - void enaDisa(); + void enaDisa(); -protected: - void closeEvent(QCloseEvent *); + protected: + void closeEvent(QCloseEvent*); -signals: - void signalAppSelected(LtsAppDescriptor::App appId); - void signalLogout(); - -private slots: - void slotAppSelected(); - void slotQuit(); + signals: + void signalAppSelected(LtsAppDescriptor::App appId); + void signalLogout(); + private slots: + void slotAppSelected(); + void slotQuit(); }; -} +} // namespace LtsAppManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.cpp old mode 100755 new mode 100644 index 505c50c0a..00f8728cc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.cpp @@ -4,47 +4,45 @@ #include - namespace LtsAppManager { -AppChooserModel::AppChooserModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Name")}, parent) - -{} +AppChooserModel::AppChooserModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel({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 +bool AppChooserModel::initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps) { - if (role != Qt::DisplayRole || !indexIsValid(index)) + for (auto i = availableApps.constBegin(); i != availableApps.constEnd(); ++i) + { + const LtsAppDescriptor::AppDescription& appDesc = *i; + + if (!appDesc.visible) + continue; + + insertRow(appDesc); + } + + return true; +} + +QVariant AppChooserModel::data(const QModelIndex& index, int role) const +{ + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const LtsAppDescriptor::AppDescription& ad = m_vecData.at(index.row()); + + switch (index.column()) + { + case Name: + return LtsSession::LtsSession::appToString(ad.id); + case Visible: + return ad.visible; + } + return QVariant(); - - 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.h old mode 100755 new mode 100644 index ea580ec5c..5f903c4b8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/AppChooser/app_chooser_model.h @@ -1,30 +1,25 @@ #pragma once -#include - - #include #include - - +#include namespace LtsAppManager { class AppChooserModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Name = 0, - Visible, - }; + public: + enum Columns { + Name = 0, + Visible, + }; - explicit AppChooserModel(QObject *parent = nullptr); + explicit AppChooserModel(QObject* parent = nullptr); - bool initModel(const LtsAppDescriptor::AppDescriptionVector &availableApps); + bool initModel(const LtsAppDescriptor::AppDescriptionVector& availableApps); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; }; -} +} // namespace LtsAppManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.cpp old mode 100755 new mode 100644 index 33e0ed746..6721e9e0e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.cpp @@ -1,1152 +1,963 @@ #include "lts_app_manager.h" -#include + #include "AppChooser/app_chooser.h" -#include #include +#include +#include #include #include #include -#include -#include #include #include -#include +#include #include - +#include #include -#include -#include +#include #include #include -#include #include +#include #include #include +#include #include - - - +#include #ifndef LTS_VERSION_MAJOR - #define LTS_VERSION_MAJOR "undefined" +#define LTS_VERSION_MAJOR "undefined" #endif #ifndef LTS_VERSION_MINOR - #define LTS_VERSION_MINOR "undefined" +#define LTS_VERSION_MINOR "undefined" #endif #ifndef LTS_VERSION_PATCH - #define LTS_VERSION_PATCH "undefined" +#define LTS_VERSION_PATCH "undefined" #endif #ifndef JENKINS_BUILD_NUMBER - #define JENKINS_BUILD_NUMBER "unknown" +#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; + LtsAppManager ltsAppManager; }; Q_GLOBAL_STATIC(LtsAppManagerHandler, s_ltsAppManager) - -LtsAppManager *LtsAppManager::getInstance() +LtsAppManager* LtsAppManager::getInstance() { - return &s_ltsAppManager->ltsAppManager; + return &s_ltsAppManager->ltsAppManager; } - -LtsAppManager::LtsAppManager() - : m_login(nullptr) +LtsAppManager::LtsAppManager() : m_login(nullptr) { - - qRegisterMetaType("LtsAppDescriptor::App"); - slotStartDebugServer(); - connect(qApp, &QCoreApplication::aboutToQuit, this, [this] { delete m_login; m_login = nullptr; }); -} + qRegisterMetaType("LtsAppDescriptor::App"); + slotStartDebugServer(); + connect(qApp, &QCoreApplication::aboutToQuit, this, [this] { + delete m_login; + m_login = nullptr; + }); +} LtsAppManager::~LtsAppManager() { - - delete m_login; - m_login = nullptr; + + delete m_login; + m_login = nullptr; } - -void LtsAppManager::setAvailableApps(const LtsAppDescriptor::AppDescriptionVector &availableApps) +void LtsAppManager::setAvailableApps(const LtsAppDescriptor::AppDescriptionVector& availableApps) { - m_availableApps = 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")); + 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); + QStringList errors; + LtsPluginManager::LtsPluginLoader::getInstance()->checkPlugins(availableApps, errors); - if (!errors.isEmpty()) - QMessageBox::critical(nullptr, QStringLiteral("LtsAppManager"), QStringLiteral("App Requirements check failed!
- %1").arg(errors.join(QStringLiteral("
- ")))); - } + if (!errors.isEmpty()) + QMessageBox::critical( + nullptr, QStringLiteral("LtsAppManager"), + QStringLiteral("App Requirements check failed!
- %1").arg(errors.join(QStringLiteral("
- ")))); + } - - if (m_availableApps.isEmpty()) - { - QMessageBox::critical(nullptr, tr("App Manager"), tr("There are no apps available for this project.\nPlease contact Support.")); - abort(); - } + 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); + 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(sender()); - - if (server == nullptr) - return; - - QTcpSocket *client = server->nextPendingConnection(); - - if (client == nullptr) - return; - - connect(client, &QTcpSocket::readyRead, this, [this]() + if (!debugServer->listen(QHostAddress::Any, 20000)) { - QTcpSocket *client = qobject_cast(sender()); + debugServer->deleteLater(); + const int waitTryAgain = 5; +#ifdef LTS_DEBUG - if (client == nullptr) +#endif + QTimer::singleShot(waitTryAgain * 1000, this, &LtsAppManager::slotStartDebugServer); return; + } - QString commandStr(QString::fromUtf8(client->readLine(100)).remove(QStringLiteral("\r")).remove(QStringLiteral("\n"))); - - QStringList argList = commandStr.split(QLatin1Char(' '), QString::SplitBehavior::SkipEmptyParts); + connect(debugServer, &QTcpServer::newConnection, this, [this]() { + QTcpServer* server = qobject_cast(sender()); - 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 "); - 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 \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 "); - break; - } - - - - - - - - - - - client->write("not implemented yet"); - break; - } - - case 7: - { - if (argList.count() < 2) - { - client->write("Usage: voiceCommand "); - 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 - See 'Session id' in DevDialog " - "\nftcmock stop "); - }; - - 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(); + if (server == nullptr) return; - } - } - const int sessionId = argList.at(2).toInt(&k); - if (!k || sessionId < 0) - { - client->write("sessionId must be a positive integer!"); - return; - } + QTcpSocket* client = server->nextPendingConnection(); - emit signalCommand(client, argList); - break; - } + if (client == nullptr) + return; - default: - { - QString result(QStringLiteral("Unknown command '%1'").arg(command)); - client->write(result.toUtf8()); - break; - } - } + connect(client, &QTcpSocket::readyRead, this, [this]() { + QTcpSocket* client = qobject_cast(sender()); - client->write("\r\n> "); + if (client == nullptr) + return; + + QString commandStr( + QString::fromUtf8(client->readLine(100)).remove(QStringLiteral("\r")).remove(QStringLiteral("\n"))); + + QStringList argList = commandStr.split(QLatin1Char(' '), QString::SplitBehavior::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 "); + 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 \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 "); + break; + } + + client->write("not implemented yet"); + break; + } + + case 7: { + if (argList.count() < 2) + { + client->write("Usage: voiceCommand "); + 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 - See 'Session " + "id' in DevDialog " + "\nftcmock stop "); + }; + + 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> "); }); - - - 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); -} + 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, [&] + 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); - }); + 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::signalLogoffDone); - - connect(m_login, &LtsLogin::LtsLogin::signalLogoffDone, - this, &LtsAppManager::slotShowLogin, Qt::QueuedConnection); + connect(m_login, &LtsLogin::LtsLogin::signalLogoffDone, this, &LtsAppManager::slotShowLogin, + Qt::QueuedConnection); - connect(m_login, &LtsLogin::LtsLogin::signalLogout, - this, &LtsAppManager::slotLogout); + connect(m_login, &LtsLogin::LtsLogin::signalLogout, this, &LtsAppManager::slotLogout); - m_login->setLoginPlugin(m_loginPluginIid); - } + m_login->setLoginPlugin(m_loginPluginIid); + } - m_login->login(); + m_login->login(); } - -bool LtsAppManager::hasRightForApp(const LtsAppDescriptor::AppDescription &appDescription) const +bool LtsAppManager::hasRightForApp(const LtsAppDescriptor::AppDescription& appDescription) const { - const QSet &acls = LtsSessionData::LtsSessionData::getInstance()->getOperatorRights(); - for (int reqRight : appDescription.requiredAcls) - { - if (!acls.contains(reqRight)) + const QSet& acls = LtsSessionData::LtsSessionData::getInstance()->getOperatorRights(); + for (int reqRight : appDescription.requiredAcls) { - QMessageBox::critical(nullptr, tr("App Manager"), tr("The minimal required operator rights are not met. Therefore, the app cannot be started.")); - return false; + 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; + return true; } - -void LtsAppManager::taskSwitch(QObject *_caller) +void LtsAppManager::taskSwitch(QObject* _caller) { - LtsSession::LtsSession *caller = qobject_cast(_caller); + LtsSession::LtsSession* caller = qobject_cast(_caller); - if (caller == nullptr) - { - Q_ASSERT(false); - return; - } - - QVector 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) + if (caller == nullptr) { - - return; - } - x++; - - - if (it == sessions.end()) - { - - if (sessions.begin() == sessionIt) - { - + Q_ASSERT(false); return; - } - it = sessions.begin(); - } - LtsSession::LtsSession *session = *it; - - + QVector sessions; - QWidget *blw = session->baseLayoutWidget(); + for (const LtsPluginManager::LtsPluginManager* app : m_appList) + sessions += app->sessions(); - if (blw == nullptr || session->isForeverInvisible() || session == caller) + 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()) { - - continue; + + return; } - - caller->baseLayoutWidget()->hide(); - blw->showFullScreen(); - - return; - } - - while (++it != sessionIt); -} + auto it = ++sessionIt; - -void LtsAppManager::hideAllOtherBLWs(QObject *_caller) -{ - - - - - - if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) - return; - - - - - - LtsSession::LtsSession *caller = qobject_cast(_caller); - - QVector 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 ) + int x = 0; + do { - blw->hide(); - } - } + if (x > 100) + { + return; + } + x++; - + if (it == sessions.end()) + { + if (sessions.begin() == sessionIt) + { - if (caller != nullptr) - return; + return; + } + it = sessions.begin(); + } + LtsSession::LtsSession* session = *it; + QWidget* blw = session->baseLayoutWidget(); + if (blw == nullptr || session->isForeverInvisible() || session == caller) + { + continue; + } - - for (LtsSession::LtsSession *session : sessions) - { + caller->baseLayoutWidget()->hide(); + blw->showFullScreen(); - QWidget *blw = session->baseLayoutWidget(); - - if (blw == nullptr || session->isForeverInvisible()) - { - - continue; + return; } - - blw->showFullScreen(); - return; - } - - + while (++it != sessionIt); } - -bool LtsAppManager::startAppOrLetUserChoose(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams &connParams, bool force) +void LtsAppManager::hideAllOtherBLWs(QObject* _caller) { - return startAppOrLetUserChoose(getApp(appId), connParams, force); -} + if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) + return; -bool LtsAppManager::startAppOrLetUserChoose(const LtsAppDescriptor::AppDescription &appDescription, - const LtsSession::DdsConnectionParams &connParams, - bool force) -{ - if (!appDescription.active && !force) - { + LtsSession::LtsSession* caller = qobject_cast(_caller); + QVector sessions; + for (const LtsPluginManager::LtsPluginManager* app : m_appList) + sessions += app->sessions(); - 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) + for (LtsSession::LtsSession* session : sessions) { - if (createApp(appId, connParams) == nullptr) - QTimer::singleShot(100, this, &LtsAppManager::slotLogout); - }, Qt::QueuedConnection); - appChooser->show(); - return true; - } + QWidget* blw = session->baseLayoutWidget(); + if (blw != nullptr && !session->isForeverInvisible() && session != caller) + { + blw->hide(); + } + } + if (caller != nullptr) + return; - 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) + for (LtsSession::LtsSession* session : sessions) { - if (QMessageBox::Yes != QMessageBox::question(nullptr, tr("App Manager"), - tr("Are you sure you want to launch another resource-intensive app?
" - "Please note that you are currently running three apps containing the resource-intensive map componment.
" - "It may lead to potential performance issues."))) - { + + 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; - 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(sender()); - if (!app) - return; - - for (auto i = m_appList.constBegin(); i != m_appList.constEnd(); ++i) + const bool bDesiredAppHasSituationMapInstance = + LtsPluginManager::LtsPluginManager::hasSituationMapInstance(appDescription, true); + if (bDesiredAppHasSituationMapInstance) { - if (*i == app) - return; + 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?
" + "Please note that you are currently running three apps containing the " + "resource-intensive map componment.
" + "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(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); - - - - - - - - - - - - - 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; + 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()); + 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; + int numberOfSituationMapInstances = 0; + for (const LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList)) + { + if (!app) + continue; - if (app->hasSituationMapInstance()) - ++numberOfSituationMapInstances; - } + if (app->hasSituationMapInstance()) + ++numberOfSituationMapInstances; + } - return numberOfSituationMapInstances; + return numberOfSituationMapInstances; } LtsAppDescriptor::AppDescription LtsAppManager::getApp(LtsAppDescriptor::App appId) const { - for (const LtsAppDescriptor::AppDescription &app : m_availableApps) - { - + for (const LtsAppDescriptor::AppDescription& app : m_availableApps) + { - if (app.id == appId) - return app; - } + if (app.id == appId) + return app; + } - - return LtsAppDescriptor::AppDescription(); + return LtsAppDescriptor::AppDescription(); } - void LtsAppManager::setMainApp(LtsAppDescriptor::App appId) { - m_app = getApp(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); + if (LtsSessionData::LtsSessionData::getInstance()->getOperatorId() == 0) + return; - QStringList unsavedFilterPreset = LtsUtils::OperatorSettings::getInstance()->identifiers(QStringLiteral("UnsavedFilterPreset")); - for (auto i = unsavedFilterPreset.constBegin(); i != unsavedFilterPreset.constEnd(); ++i) - LtsUtils::OperatorSettings::getInstance()->removeValue(QStringLiteral("UnsavedFilterPreset"), *i); + QStringList unsavedWorkspaces = + LtsUtils::OperatorSettings::getInstance()->identifiers(QStringLiteral("UnsavedWorkspace")); + for (auto i = unsavedWorkspaces.constBegin(); i != unsavedWorkspaces.constEnd(); ++i) + LtsUtils::OperatorSettings::getInstance()->removeValue(QStringLiteral("UnsavedWorkspace"), *i); - - QJsonArray root; - for (const LtsPluginManager::LtsPluginManager *app : std::as_const(m_appList)) - { - const QVector sessions = app->sessions(); + QStringList unsavedFilterPreset = + LtsUtils::OperatorSettings::getInstance()->identifiers(QStringLiteral("UnsavedFilterPreset")); + for (auto i = unsavedFilterPreset.constBegin(); i != unsavedFilterPreset.constEnd(); ++i) + LtsUtils::OperatorSettings::getInstance()->removeValue(QStringLiteral("UnsavedFilterPreset"), *i); - const auto appId = app->appDescription().id; - - if (appId == LtsAppDescriptor::App::Login || sessions.count() < 1) - continue; - - - QJsonObject appState; - appState[QStringLiteral("id")] = static_cast(appId); - - QJsonArray sessionStates; - - for (LtsSession::LtsSession *session : sessions) + QJsonArray root; + for (const LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList)) { - if (session->baseLayout() != nullptr && session->baseLayout()->isSecondaryWidget()) - continue; + const QVector sessions = app->sessions(); - QJsonObject sessionState; + const auto appId = app->appDescription().id; - int screenId = session->screenId(); + if (appId == LtsAppDescriptor::App::Login || sessions.count() < 1) + continue; + QJsonObject appState; + appState[QStringLiteral("id")] = static_cast(appId); + QJsonArray sessionStates; - int screenContainerId = session->screenContainerId(); + for (LtsSession::LtsSession* session : sessions) + { + if (session->baseLayout() != nullptr && session->baseLayout()->isSecondaryWidget()) + continue; + QJsonObject sessionState; + int screenId = session->screenId(); - 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(); + int screenContainerId = session->screenContainerId(); - - const QString newId(QUuid::createUuid().toString()); - sessionState[QStringLiteral("workspaceId")] = newId; + 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(); - std::shared_ptr ifcOpm; - if (session->getForeignGuiInterface(ifcOpm)) - { - - ifcOpm->callWorkspaceSaveUnsaved(newId); - } + const QString newId(QUuid::createUuid().toString()); + sessionState[QStringLiteral("workspaceId")] = newId; + std::shared_ptr ifcOpm; + if (session->getForeignGuiInterface(ifcOpm)) + { + ifcOpm->callWorkspaceSaveUnsaved(newId); + } - sessionStates.append(sessionState); + sessionStates.append(sessionState); + } + + if (!sessionStates.isEmpty()) + { + appState[QStringLiteral("sessions")] = sessionStates; + root.append(appState); + } } - if (!sessionStates.isEmpty()) - { - appState[QStringLiteral("sessions")] = sessionStates; - root.append(appState); - } - } + QJsonDocument doc(root); - QJsonDocument doc(root); - - - LtsUtils::OperatorSettings::getInstance()->setValue(QStringLiteral("app"), QStringLiteral("LastAppStates"), doc.toJson(QJsonDocument::Compact)); + 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 sessions = app->sessions(); - for (LtsSession::LtsSession *session : sessions) + for (LtsPluginManager::LtsPluginManager* app : std::as_const(m_appList)) { - if (session->notifyUnsavedChanges() == false ) - return; + const QVector sessions = app->sessions(); + for (LtsSession::LtsSession* session : sessions) + { + if (session->notifyUnsavedChanges() == false) + return; + } } - } + saveState(); - saveState(); + const QVector apps = m_appList; - const QVector apps = m_appList; - - - if (apps.isEmpty() && m_login != nullptr) - m_login->logoff(); - - - for (LtsPluginManager::LtsPluginManager *app : apps) - app->deleteLater(); - - + if (apps.isEmpty() && m_login != nullptr) + m_login->logoff(); + for (LtsPluginManager::LtsPluginManager* app : apps) + app->deleteLater(); } - void LtsAppManager::slotAppDestroyed() { - LtsPluginManager::LtsPluginManager *app = static_cast(sender()); + LtsPluginManager::LtsPluginManager* app = static_cast(sender()); - m_appList.removeOne(app); - + m_appList.removeOne(app); - if (m_appList.isEmpty() && m_login != nullptr) - { - - m_login->logoff(); - } + if (m_appList.isEmpty() && m_login != nullptr) + { + + m_login->logoff(); + } } - void LtsAppManager::slotQuit() { - - QObject *object = sender(); + QObject* object = sender(); - if (!object) - qCritical() << "ERROR: LtsAppManager: slot called without object - so it cannot be deleted from the app assignments!"; + if (!object) + qCritical() + << "ERROR: LtsAppManager: slot called without object - so it cannot be deleted from the app assignments!"; - LtsPluginManager::LtsPluginManager *app = qobject_cast(object); + LtsPluginManager::LtsPluginManager* app = qobject_cast(object); - if (app == nullptr) - { - qCritical() << "ERROR: LtsAppManager: quit requested for invalid app"; - return; - } + if (app == nullptr) + { + qCritical() << "ERROR: LtsAppManager: quit requested for invalid app"; + return; + } - if (m_appList.count() == 1) - { - m_appList.removeAll(app); - saveState(); - } + if (m_appList.count() == 1) + { + m_appList.removeAll(app); + saveState(); + } - app->deleteLater(); - + app->deleteLater(); } - void LtsAppManager::slotSoftQuit() { - - QObject *object = sender(); + QObject* object = sender(); + LtsPluginManager::LtsPluginManager* app = qobject_cast(object); + if (app == nullptr) + { + qCritical() << "ERROR: LtsAppManager: quit requested for invalid app"; + return; + } + app->_softQuit(); - LtsPluginManager::LtsPluginManager *app = qobject_cast(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(); - } - - - + if (m_appList.count() == 1) + { + m_appList.removeAll(app); + saveState(); + } } - -bool LtsAppManager::otherSessionsResponsibility(LtsSession::LtsSession *thisSession, const QVector &requiredAppTypes, - const QVector &requiredPartitionTypes, const QString &menuGroup, - const QString &identifier, LtsWidgets::LayoutArea area) +bool LtsAppManager::otherSessionsResponsibility(LtsSession::LtsSession* thisSession, + const QVector& requiredAppTypes, + const QVector& requiredPartitionTypes, + const QString& menuGroup, const QString& identifier, + LtsWidgets::LayoutArea area) { - const QVector apps = LtsAppManager::LtsAppManager::getInstance()->getAppList(); - QVector worthyApps; + const QVector apps = LtsAppManager::LtsAppManager::getInstance()->getAppList(); + QVector worthyApps; - for (LtsPluginManager::LtsPluginManager *app : apps) - { - if (!requiredAppTypes.contains(static_cast(app->appDescription().id))) - continue; - - worthyApps.append(app); - } - - - - for (const LtsPluginManager::LtsPluginManager *app : std::as_const(worthyApps)) - { - const QVector sessions = app->sessions(); - for (const LtsSession::LtsSession *session : sessions) + for (LtsPluginManager::LtsPluginManager* app : apps) { - if (session->widgetExists(menuGroup, identifier, area)) - return true; + if (!requiredAppTypes.contains(static_cast(app->appDescription().id))) + continue; + + worthyApps.append(app); } - } - - - LtsMultiMonitor::LtsMultiMonitor *mm = LtsMultiMonitor::LtsMultiMonitor::getInstance(); - LtsMultiMonitor::LtsScreenBase *mainScreen = mm->mainScreen(); - - for (const LtsPluginManager::LtsPluginManager *app : std::as_const(worthyApps)) - { - const QVector sessions = app->sessions(); - for (LtsSession::LtsSession *session : sessions) + for (const LtsPluginManager::LtsPluginManager* app : std::as_const(worthyApps)) { - if (session != thisSession - && mm->widgetsScreen(session->baseLayoutWidget()) == mainScreen - && requiredPartitionTypes.contains(session->partitionType())) - return true; + const QVector sessions = app->sessions(); + for (const LtsSession::LtsSession* session : sessions) + { + if (session->widgetExists(menuGroup, identifier, area)) + return true; + } } - } - return false; + LtsMultiMonitor::LtsMultiMonitor* mm = LtsMultiMonitor::LtsMultiMonitor::getInstance(); + LtsMultiMonitor::LtsScreenBase* mainScreen = mm->mainScreen(); + + for (const LtsPluginManager::LtsPluginManager* app : std::as_const(worthyApps)) + { + const QVector 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.h old mode 100755 new mode 100644 index 7b8978762..358f13301 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsAppManager/lts_app_manager.h @@ -1,27 +1,25 @@ #pragma once -#include #include -#include -#include +#include #include -#include +#include +#include #include #include - +#include #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 +#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 { @@ -37,7 +35,7 @@ namespace LtsSession { class LtsSession; struct DdsConnectionParams; -} +} // namespace LtsSession namespace DeveloperTools { @@ -46,78 +44,93 @@ class DevDialog; class QTcpSocket; - namespace LtsAppManager { class LTSAPPMANAGER_EXPORT LtsAppManager : public QObject { - Q_OBJECT + Q_OBJECT -public: - static LtsAppManager* getInstance(); + public: + static LtsAppManager* getInstance(); - void showLogin(); - + void showLogin(); - LtsPluginManager::LtsPluginManager *createApp(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams &connParams, - const QString &workspaceId = QString(), bool hidden = false, bool force = false); - bool startAppOrLetUserChoose(LtsAppDescriptor::App appId, const LtsSession::DdsConnectionParams &connParams, bool force = false); - void setLoginPluginIid(const QString &loginPluginIid) { m_loginPluginIid = loginPluginIid; } - void setMainApp(LtsAppDescriptor::App appId = LtsAppDescriptor::App::Login); - QVector 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); + 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; + } - bool otherSessionsResponsibility(LtsSession::LtsSession *thisSession, const QVector &requiredAppTypes, - const QVector &requiredPartitionTypes, const QString &menuGroup, - const QString &identifier, LtsWidgets::LayoutArea area); + void setMainApp(LtsAppDescriptor::App appId = LtsAppDescriptor::App::Login); -private: - friend struct LtsAppManagerHandler; - friend class DeveloperTools::DevDialog; + QVector getAppList() const + { + return m_appList; + } - LtsAppManager(); - ~LtsAppManager(); + LtsAppDescriptor::AppDescriptionVector getAvailableApps() const + { + return m_availableApps; + } - 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(); + 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); - LtsAppDescriptor::AppDescriptionVector m_availableApps; - QVector m_appList; - LtsLogin::LtsLogin *m_login; - LtsAppDescriptor::AppDescription m_app; - QString m_loginPluginIid; + bool otherSessionsResponsibility(LtsSession::LtsSession* thisSession, + const QVector& requiredAppTypes, + const QVector& requiredPartitionTypes, + const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area); -public slots: - void slotLogout(); + private: + friend struct LtsAppManagerHandler; + friend class DeveloperTools::DevDialog; -private slots: - void slotQuit(); - void slotSoftQuit(); - void slotShowLogin(); - void slotAppDestroyed(); - void slotStartDebugServer(); - void hideAllOtherBLWs(QObject *_caller); - void taskSwitch(QObject *_caller); + LtsAppManager(); + ~LtsAppManager(); -signals: - void signalLoginDone(); - void signalLogoffDone(); - void signalShowLogin(); - void signalInitializationFinished(); - void signalCommand(QTcpSocket *client, const QStringList argList); + 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 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp old mode 100755 new mode 100644 index 05b334738..476efdac7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.cpp @@ -1,183 +1,180 @@ - #include "LtsCommandLineParser.h" -#include -#include + #include +#include #include #include +#include namespace LtsCommandLineParser { static constexpr int s_maxDomainId = 232; LtsCommandLineParser::LtsCommandLineParser(ProvideCommandLineParameterOptions opts) - : QCommandLineParser() - , m_enabledOptions(opts) + : QCommandLineParser(), m_enabledOptions(opts) { - if (NGL::isAppInBuildBasePath() || m_enabledOptions.testFlag(CreateDomainIdFromIp)) - { - const QList addresses = QNetworkInterface::allAddresses(); - for (const QHostAddress &address : addresses) + if (NGL::isAppInBuildBasePath() || m_enabledOptions.testFlag(CreateDomainIdFromIp)) { - if (address.isLoopback() || address.isNull()) - continue; - if (address.protocol() != QAbstractSocket::IPv4Protocol) - continue; - - - m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232; - if (m_generatedDomainId == 0) - m_generatedDomainId = s_maxDomainId; - break; + const QList addresses = QNetworkInterface::allAddresses(); + for (const QHostAddress& address : addresses) + { + if (address.isLoopback() || address.isNull()) + continue; + if (address.protocol() != QAbstractSocket::IPv4Protocol) + continue; + + m_generatedDomainId = (address.toIPv4Address() & 0x000000ff) % 232; + if (m_generatedDomainId == 0) + m_generatedDomainId = s_maxDomainId; + break; + } } - } - if (m_enabledOptions.testFlag(ExerciseId)) - addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")}, - QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"), - QStringLiteral("exerciseId"), - QStringLiteral("-1") - }); - if (m_enabledOptions.testFlag(DomainId)) - addOption({{QStringLiteral("d"), QStringLiteral("domainid")}, - QStringLiteral("Default: ") + QString::number(m_generatedDomainId), - QStringLiteral("domainId"), - QString::number(m_generatedDomainId) - }); - if (m_enabledOptions.testFlag(CustomConfigFile)) - { - const QString cf(NGL::findProjectConfigFile()); - addOption({{QStringLiteral("i"), QStringLiteral("ini")}, - QStringLiteral("Default: ") + cf, - QStringLiteral("filename"), - cf - }); - } - if (m_enabledOptions.testFlag(TcpConnectionUrl)) - { - const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400")); - addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")}, - QStringLiteral("Default: ") + defaultTcpUrl, - QStringLiteral("hostname:port"), - defaultTcpUrl - }); - } - addHelpOption(); + if (m_enabledOptions.testFlag(ExerciseId)) + addOption({{QStringLiteral("e"), QStringLiteral("exerciseid")}, + QStringLiteral("Default: -1 (invalid, get from lts-cc.conf)"), + QStringLiteral("exerciseId"), + QStringLiteral("-1")}); + if (m_enabledOptions.testFlag(DomainId)) + addOption({{QStringLiteral("d"), QStringLiteral("domainid")}, + QStringLiteral("Default: ") + QString::number(m_generatedDomainId), + QStringLiteral("domainId"), + QString::number(m_generatedDomainId)}); + if (m_enabledOptions.testFlag(CustomConfigFile)) + { + const QString cf(NGL::findProjectConfigFile()); + addOption({{QStringLiteral("i"), QStringLiteral("ini")}, + QStringLiteral("Default: ") + cf, + QStringLiteral("filename"), + cf}); + } + if (m_enabledOptions.testFlag(TcpConnectionUrl)) + { + const QString defaultTcpUrl(QStringLiteral("EXCTDS01:7400")); + addOption({{QStringLiteral("t"), QStringLiteral("tcpurl")}, + QStringLiteral("Default: ") + defaultTcpUrl, + QStringLiteral("hostname:port"), + defaultTcpUrl}); + } + addHelpOption(); - if (!m_enabledOptions.testFlag(NoVersion)) - addVersionOption(); + if (!m_enabledOptions.testFlag(NoVersion)) + addVersionOption(); } int LtsCommandLineParser::domainId() const { - if (m_domainId == 0 && m_generatedDomainId != 0 && !m_domainIdSetByFunction) - { + if (m_domainId == 0 && m_generatedDomainId != 0 && !m_domainIdSetByFunction) + { #ifdef WIN32 - - fprintf(stdout, "\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default domainid is %d\n\n", m_generatedDomainId); + + fprintf(stdout, + "\n\nAttention: using a default domain id != 0 because executable is run inside builddir - default " + "domainid is %d\n\n", + m_generatedDomainId); #else - fprintf(stdout, "\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - default domainid is %d\e[0m\n\n", m_generatedDomainId); + fprintf(stdout, + "\n\n\e[31mAttention: using a default domain id != 0 because executable is run inside builddir - " + "default domainid is %d\e[0m\n\n", + m_generatedDomainId); #endif - return m_generatedDomainId; - } - return m_domainId; + return m_generatedDomainId; + } + return m_domainId; } void LtsCommandLineParser::setDomainId(int id) { - m_domainIdSetByFunction = true; - m_domainId = id; + m_domainIdSetByFunction = true; + m_domainId = id; } bool LtsCommandLineParser::iniFileSet() const { - if (!m_enabledOptions.testFlag(CustomConfigFile)) - return false; - return isSet(QStringLiteral("i")); + if (!m_enabledOptions.testFlag(CustomConfigFile)) + return false; + return isSet(QStringLiteral("i")); } bool LtsCommandLineParser::useTcpConnection() const { - if (!m_enabledOptions.testFlag(TcpConnectionUrl)) - return false; - return isSet(QStringLiteral("t")); + if (!m_enabledOptions.testFlag(TcpConnectionUrl)) + return false; + return isSet(QStringLiteral("t")); } QUrl LtsCommandLineParser::tcpConnectionUrl() const { - if (!m_enabledOptions.testFlag(TcpConnectionUrl)) - return QUrl(); - if (!useTcpConnection()) - return QUrl(); - QString str = value(QStringLiteral("t")); - - str.replace(QLatin1String("tcpv4_lan"), QLatin1String("tcpv4lan")); - QUrl url = QUrl::fromUserInput(str); - if (url.scheme() == QLatin1String("http") || - url.scheme() == QLatin1String("file")) - url.setScheme(QStringLiteral("tcpv4lan")); - return url; + if (!m_enabledOptions.testFlag(TcpConnectionUrl)) + return QUrl(); + if (!useTcpConnection()) + return QUrl(); + QString str = value(QStringLiteral("t")); + + str.replace(QLatin1String("tcpv4_lan"), QLatin1String("tcpv4lan")); + QUrl url = QUrl::fromUserInput(str); + if (url.scheme() == QLatin1String("http") || url.scheme() == QLatin1String("file")) + url.setScheme(QStringLiteral("tcpv4lan")); + return url; } bool LtsCommandLineParser::init(bool bParseHelp) { - if (!parse(QCoreApplication::arguments())) - { - fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText())); - if (!m_unitModuleTestMode) - return false; - } - - if (m_enabledOptions.testFlag(ExerciseId)) - m_exerciseId = value(QStringLiteral("e")).toInt(); - if (m_enabledOptions.testFlag(DomainId)) - m_domainId = value(QStringLiteral("d")).toInt(); - if (m_enabledOptions.testFlag(CustomConfigFile)) - m_iniFile = value(QStringLiteral("i")); - - if (bParseHelp && isSet(QStringLiteral("h"))) - showHelp(); - if (!m_unitModuleTestMode && isSet(QStringLiteral("v"))) - showVersion(); - if (!domainIdProvided()) - { - const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile; - if (!iniFile.isEmpty()) + if (!parse(QCoreApplication::arguments())) { - QSettings s(iniFile, QSettings::IniFormat); - bool bOk; - int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk); - if (bOk && domainId > 0 && domainId <= s_maxDomainId) - m_domainId = domainId; + fprintf(stdout, "\nBad option: %s \n", qPrintable(errorText())); + if (!m_unitModuleTestMode) + return false; } - } - return true; + + if (m_enabledOptions.testFlag(ExerciseId)) + m_exerciseId = value(QStringLiteral("e")).toInt(); + if (m_enabledOptions.testFlag(DomainId)) + m_domainId = value(QStringLiteral("d")).toInt(); + if (m_enabledOptions.testFlag(CustomConfigFile)) + m_iniFile = value(QStringLiteral("i")); + + if (bParseHelp && isSet(QStringLiteral("h"))) + showHelp(); + if (!m_unitModuleTestMode && isSet(QStringLiteral("v"))) + showVersion(); + if (!domainIdProvided()) + { + const QString iniFile = m_iniFile.isEmpty() ? NGL::findProjectConfigFile() : m_iniFile; + if (!iniFile.isEmpty()) + { + QSettings s(iniFile, QSettings::IniFormat); + bool bOk; + int domainId = s.value(QStringLiteral("Global/DomainId"), m_domainId).toInt(&bOk); + if (bOk && domainId > 0 && domainId <= s_maxDomainId) + m_domainId = domainId; + } + } + return true; } void LtsCommandLineParser::showHelp(int exitCode) { - if (!m_additionalHelpStr.isEmpty()) - fprintf(stdout, "%s", qPrintable(m_additionalHelpStr)); - + if (!m_additionalHelpStr.isEmpty()) + fprintf(stdout, "%s", qPrintable(m_additionalHelpStr)); - QCommandLineParser::showHelp(exitCode); + QCommandLineParser::showHelp(exitCode); } bool LtsCommandLineParser::domainIdProvided() const { - if (!m_enabledOptions.testFlag(DomainId)) - return false; - return isSet(QStringLiteral("d")); + if (!m_enabledOptions.testFlag(DomainId)) + return false; + return isSet(QStringLiteral("d")); } bool LtsCommandLineParser::exerciseIdProvided() const { - if (!m_enabledOptions.testFlag(ExerciseId)) - return false; - return isSet(QStringLiteral("e")); + if (!m_enabledOptions.testFlag(ExerciseId)) + return false; + return isSet(QStringLiteral("e")); } - -} +} // namespace LtsCommandLineParser diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h old mode 100755 new mode 100644 index 494860f4a..48a348555 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCommandLineParser/LtsCommandLineParser.h @@ -1,56 +1,69 @@ - #pragma once -#include #include "ltscommandlineparser_export.h" +#include + class QUrl; + namespace LtsCommandLineParser { class LTSCOMMANDLINEPARSER_EXPORT LtsCommandLineParser : public QCommandLineParser { -public: - enum ProvideCommandLineParameterOptions - { - None = 0x0000, - CreateDomainIdFromIp = 0x0001, - DomainId = 0x0002, - ExerciseId = 0x0004, - CustomConfigFile = 0x0008, - TcpConnectionUrl = 0x0010, - NoVersion = 0x0020 - }; + public: + enum ProvideCommandLineParameterOptions { + None = 0x0000, + CreateDomainIdFromIp = 0x0001, + DomainId = 0x0002, + ExerciseId = 0x0004, + CustomConfigFile = 0x0008, + TcpConnectionUrl = 0x0010, + NoVersion = 0x0020 + }; - explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions(CreateDomainIdFromIp|DomainId|ExerciseId|CustomConfigFile)); - virtual ~LtsCommandLineParser() = default; - int domainId() const; - void setDomainId(int id); - int exerciseId() const { return m_exerciseId; } - QString iniFile() const { return m_iniFile; } - bool iniFileSet() const; - bool useTcpConnection() const; - QUrl tcpConnectionUrl() const; - virtual bool init(bool bParseHelp = true); + explicit LtsCommandLineParser(ProvideCommandLineParameterOptions opts = ProvideCommandLineParameterOptions( + CreateDomainIdFromIp | DomainId | ExerciseId | CustomConfigFile)); + virtual ~LtsCommandLineParser() = default; + int domainId() const; + void setDomainId(int id); - void showHelp(int exitCode = 0); - bool domainIdProvided() const; - bool exerciseIdProvided() const; + int exerciseId() const + { + return m_exerciseId; + } - void setUnitModuleTestMode(bool onOff) { m_unitModuleTestMode = onOff; } + QString iniFile() const + { + return m_iniFile; + } -protected: - QString m_additionalHelpStr; + bool iniFileSet() const; + bool useTcpConnection() const; + QUrl tcpConnectionUrl() const; + virtual bool init(bool bParseHelp = true); -private: - QFlags m_enabledOptions; - int m_exerciseId{0}; - int m_domainId{0}; - int m_generatedDomainId{0}; - bool m_domainIdSetByFunction{false}; - bool m_unitModuleTestMode{false}; - QString m_iniFile; + void showHelp(int exitCode = 0); + bool domainIdProvided() const; + bool exerciseIdProvided() const; + + void setUnitModuleTestMode(bool onOff) + { + m_unitModuleTestMode = onOff; + } + + protected: + QString m_additionalHelpStr; + + private: + QFlags m_enabledOptions; + int m_exerciseId{0}; + int m_domainId{0}; + int m_generatedDomainId{0}; + bool m_domainIdSetByFunction{false}; + bool m_unitModuleTestMode{false}; + QString m_iniFile; }; -} +} // namespace LtsCommandLineParser diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp old mode 100755 new mode 100644 index 37c15c46a..bb1f4aad7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lonlat2mgrs.cpp @@ -1,67 +1,64 @@ - -#include #include +#include #include #include -int main(int argc, char **argv) +int main(int argc, char** argv) { - if (argc < 3 || argc > 5) - { - fprintf(stderr, "Usage: %s []\n", argv[0]); - fprintf(stderr, "Usage: %s -r []\n", argv[0]); - return -1; - } - - bool lonLatInRad = false; - double lon = atof(argv[1]); - double lat = atof(argv[2]); - int prec = 5; - if (argc >= 4) - { - int precArgId = -1; - if (strcmp(argv[3], "-r") == 0) + if (argc < 3 || argc > 5) { - lonLatInRad = true; - if (argc == 5) - precArgId = 4; + fprintf(stderr, "Usage: %s []\n", argv[0]); + fprintf(stderr, "Usage: %s -r []\n", argv[0]); + return -1; } - else - precArgId = 3; - if (precArgId > 0) - prec = atoi(argv[precArgId]); - } - std::string mgrs; + bool lonLatInRad = false; + double lon = atof(argv[1]); + double lat = atof(argv[2]); + int prec = 5; + if (argc >= 4) + { + int precArgId = -1; + if (strcmp(argv[3], "-r") == 0) + { + lonLatInRad = true; + if (argc == 5) + precArgId = 4; + } + else + precArgId = 3; + if (precArgId > 0) + prec = atoi(argv[precArgId]); + } - int zone; - bool northp; - double x, y; - try - { - const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat; - const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon; - GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - } - catch (...) - { - fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon); - return -2; - } - std::string part1, part2, part3, part4; - part1 = mgrs.substr(0, 3); - part2 = mgrs.substr(3, 2); - if (prec > 0) - { - part3 = mgrs.substr(5, prec); - part4 = mgrs.substr(5 + prec, prec); - } - fprintf(stdout, "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", - lon, lat, - part1.c_str(), part2.c_str(), part3.c_str(), part4.c_str(), - zone, x, y, northp ? 'N' : 'S'); - return 0; + std::string mgrs; + + int zone; + bool northp; + double x, y; + try + { + const double latDeg = lonLatInRad ? lat * 180 / M_PI : lat; + const double lonDeg = lonLatInRad ? lon * 180 / M_PI : lon; + GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + } + catch (...) + { + fprintf(stderr, "Error converting %9.6f, %9.6f to MGRS coords\n", lat, lon); + return -2; + } + std::string part1, part2, part3, part4; + part1 = mgrs.substr(0, 3); + part2 = mgrs.substr(3, 2); + if (prec > 0) + { + part3 = mgrs.substr(5, prec); + part4 = mgrs.substr(5 + prec, prec); + } + fprintf(stdout, "%13.10f, %13.10f = %s %s %s %s (UTM: %d %.2f, %.2f %c)\n", lon, lat, part1.c_str(), part2.c_str(), + part3.c_str(), part4.c_str(), zone, x, y, northp ? 'N' : 'S'); + return 0; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp old mode 100755 new mode 100644 index 3f6e6b11c..fe81b2768 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.cpp @@ -1,446 +1,447 @@ - #include "lts_coord_trans.h" -#include #include -#include #include +#include #include #include #include #include - - -#include +#include +#include namespace LtsCoordTrans { -static long s_conversion_counter_MGRS_Forward = 0; -static long s_conversion_counter_MGRS_Reverse = 0; +static long s_conversion_counter_MGRS_Forward = 0; +static long s_conversion_counter_MGRS_Reverse = 0; -static long s_conversion_counter_WGS84_Forward = 0; -static long s_conversion_counter_WGS84_Reverse = 0; +static long s_conversion_counter_WGS84_Forward = 0; +static long s_conversion_counter_WGS84_Reverse = 0; -static long s_conversion_counter_UTMUPS_Forward = 0; -static long s_conversion_counter_UTMUPS_Reverse = 0; +static long s_conversion_counter_UTMUPS_Forward = 0; +static long s_conversion_counter_UTMUPS_Reverse = 0; - -inline void incrementCounter(long &counterRef) +inline void incrementCounter(long& counterRef) { #ifdef LTS_DEBUG - ++counterRef; + ++counterRef; #endif } - -static inline std::string cleanupMgrsString(const QString &in) +static inline std::string cleanupMgrsString(const QString& in) { - const QByteArray ba(in.toLatin1()); - std::string ret; - ret.reserve(ba.size()); - for (const char c : ba) - { - if (c != ' ') - ret += c; - } - return ret; + const QByteArray ba(in.toLatin1()); + std::string ret; + ret.reserve(ba.size()); + for (const char c : ba) + { + if (c != ' ') + ret += c; + } + return ret; } QString UtmCoordinate::mgrs(int prec, bool withSpaces) const { - if (prec < 0) - prec = 0; - if (prec > 11) - prec = 11; + if (prec < 0) + prec = 0; + if (prec > 11) + prec = 11; - std::string mgrs; - try - { - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - incrementCounter(s_conversion_counter_MGRS_Forward); - } - catch (const std::exception &e) - { - fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what()); - mgrs.clear(); - } - - QString ret; - if (withSpaces && mgrs.size() == static_cast(5 + 2 * prec)) - { - - const char *ptr = mgrs.c_str(); - - ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') + - QString::fromLatin1(ptr + 3, 2); - if (prec > 0) + std::string mgrs; + try { - ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + - QLatin1Char(' ') + QString::fromLatin1(ptr + 5 + prec, prec); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + incrementCounter(s_conversion_counter_MGRS_Forward); } - } - else - ret = QString::fromLatin1(mgrs.c_str(), mgrs.size()); - return ret; + catch (const std::exception& e) + { + fprintf(stderr, "Error while calculating mgrs from utm %d, %9.6f, %9.6f: %s\n", zone, x, y, e.what()); + mgrs.clear(); + } + + QString ret; + if (withSpaces && mgrs.size() == static_cast(5 + 2 * prec)) + { + + const char* ptr = mgrs.c_str(); + + ret = QString::fromLatin1(ptr, 3) + QLatin1Char(' ') + QString::fromLatin1(ptr + 3, 2); + if (prec > 0) + { + ret += QLatin1Char(' ') + QString::fromLatin1(ptr + 5, prec) + QLatin1Char(' ') + + QString::fromLatin1(ptr + 5 + prec, prec); + } + } + else + ret = QString::fromLatin1(mgrs.c_str(), mgrs.size()); + return ret; } QPointF UtmCoordinate::toPoint() const { - return {x,y}; + return {x, y}; } QPointF UtmCoordinate::geographic(double offsetX, double offsetY) const { - QPointF ret; - try - { - GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx()); - incrementCounter(s_conversion_counter_UTMUPS_Reverse); - } - catch (const std::exception &e) - { - fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX, y + offsetY, e.what()); - ret = QPointF(); - } - return ret * deg2rad(); + QPointF ret; + try + { + GeographicLib::UTMUPS::Reverse(zone, northp, x + offsetX, y + offsetY, ret.ry(), ret.rx()); + incrementCounter(s_conversion_counter_UTMUPS_Reverse); + } + catch (const std::exception& e) + { + fprintf(stderr, "Error while calculating geographic from utm %d, %9.6f, %9.6f: %s\n", zone, x + offsetX, + y + offsetY, e.what()); + ret = QPointF(); + } + return ret * deg2rad(); } -QPointF UtmCoordinate::geographic(const QPointF &offset) const +QPointF UtmCoordinate::geographic(const QPointF& offset) const { - return geographic(offset.x(), offset.y()); + return geographic(offset.x(), offset.y()); } -QPointF UtmCoordinate::relativeTo(const UtmCoordinate &other) const +QPointF UtmCoordinate::relativeTo(const UtmCoordinate& other) const { - if (zone == other.zone) - return QPointF(x - other.x, y - other.y); + if (zone == other.zone) + return QPointF(x - other.x, y - other.y); - UtmCoordinate otherInMyZone = fromGeographic(other.geographic(), zone); - return QPointF(x - otherInMyZone.x, y - otherInMyZone.y); + UtmCoordinate otherInMyZone = fromGeographic(other.geographic(), zone); + return QPointF(x - otherInMyZone.x, y - otherInMyZone.y); } UtmCoordinate UtmCoordinate::fromGeographic(double lon, double lat, int setZone) { - - lon *= rad2deg(); - lat *= rad2deg(); - UtmCoordinate ret; - try - { - - GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone); - incrementCounter(s_conversion_counter_UTMUPS_Forward); - } - catch (const std::exception &e) - { - fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what()); - ret = UtmCoordinate(); - } - return ret; + lon *= rad2deg(); + lat *= rad2deg(); + + UtmCoordinate ret; + try + { + + GeographicLib::UTMUPS::Forward(lat, lon, ret.zone, ret.northp, ret.x, ret.y, setZone); + incrementCounter(s_conversion_counter_UTMUPS_Forward); + } + catch (const std::exception& e) + { + fprintf(stderr, "Error while calculating mgrs base point from %9.6f, %9.6f: %s\n", lat, lon, e.what()); + ret = UtmCoordinate(); + } + return ret; } -UtmCoordinate UtmCoordinate::fromGeographic(const QPointF &lonLat, int setZone) +UtmCoordinate UtmCoordinate::fromGeographic(const QPointF& lonLat, int setZone) { - return fromGeographic(lonLat.x(), lonLat.y(), setZone); + return fromGeographic(lonLat.x(), lonLat.y(), setZone); } -UtmCoordinate UtmCoordinate::fromMgrs(const QString &mgrs) +UtmCoordinate UtmCoordinate::fromMgrs(const QString& mgrs) { - UtmCoordinate utm; - try - { - int prec; - - GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true); - incrementCounter(s_conversion_counter_MGRS_Reverse); + UtmCoordinate utm; + try + { + int prec; - } - catch (const std::exception &e) - { - fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what()); - utm = UtmCoordinate(); - } - return utm; + GeographicLib::MGRS::Reverse(cleanupMgrsString(mgrs), utm.zone, utm.northp, utm.x, utm.y, prec, true); + incrementCounter(s_conversion_counter_MGRS_Reverse); + } + catch (const std::exception& e) + { + fprintf(stderr, "Error while converting mgrs coordinate %s to utm: %s\n", qPrintable(mgrs), e.what()); + utm = UtmCoordinate(); + } + return utm; } QString mgrsFromGeographic(double lon, double lat, int prec, bool withSpaces) { - return UtmCoordinate::fromGeographic(lon, lat, -1).mgrs(prec, withSpaces); + return UtmCoordinate::fromGeographic(lon, lat, -1).mgrs(prec, withSpaces); } -QPointF geographicFromMgrs(const QString &mgrs) +QPointF geographicFromMgrs(const QString& mgrs) { - return UtmCoordinate::fromMgrs(mgrs).geographic(); + return UtmCoordinate::fromMgrs(mgrs).geographic(); } -QVector &staticDefaultSquaresHelper() +QVector& staticDefaultSquaresHelper() { - static QVector s_defaultMgrsSquares; - return s_defaultMgrsSquares; -} -UtmCoordinate &staticPreferedMgrsSquareHelper() -{ - static UtmCoordinate s_preferedMgrsSquare; - return s_preferedMgrsSquare; -} -QVector &staticMgrsSquaresWithOffsetsHelper() -{ - static QVector s_mgrsSquaresWithOffsets; - return s_mgrsSquaresWithOffsets; + static QVector s_defaultMgrsSquares; + return s_defaultMgrsSquares; } - -QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter) +UtmCoordinate& staticPreferedMgrsSquareHelper() { - double lonMin, lonMax, latMin, latMmax; - rect_LatLon_radiant.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); - - - - - - LtsCoordTrans::UtmCoordinate basePoint; - { - - const QPointF centerRad = rect_LatLon_radiant.center(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); - mgrs += QStringLiteral("00000000000000"); - - - basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); - } - - const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone)); - const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone)); - - int offsetX = marginMeter.width(); - int offsetY = marginMeter.height(); - - const QPointF topLeft(lowerLeft.geographic(-offsetX, -offsetY)); - const QPointF bottomRight(upperRight.geographic(offsetX, offsetY)); - - QRectF res = QRectF(topLeft, bottomRight); - return res; + static UtmCoordinate s_preferedMgrsSquare; + return s_preferedMgrsSquare; } - -QVector getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin) +QVector& staticMgrsSquaresWithOffsetsHelper() { - QVector ret = getMgrsSquaresInternal(rect); - - if (setAsDefaultSquares) - staticDefaultSquaresHelper() = ret; - - if (setAsPreferedSquare) - staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center()); - - if (setAsSquareWithMargin) - staticMgrsSquaresWithOffsetsHelper() = ret; - - - return ret; + static QVector s_mgrsSquaresWithOffsets; + return s_mgrsSquaresWithOffsets; } -QVector getMgrsSquaresInternal(const QRectF &rect) +QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter) { - QVector ret; - QVector tmpMgrsSquares; - - - double lonMin, lonMax, latMin, latMmax; - rect.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); + double lonMin, lonMax, latMin, latMmax; + rect_LatLon_radiant.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); - - bool withInSingleUtmSquare = true; - { - const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax)); - const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin)); - withInSingleUtmSquare = upperRight.zone == lowerLeft.zone; - } - - - - - - LtsCoordTrans::UtmCoordinate basePoint; - { - - QPointF centerRad = rect.center(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); - mgrs += QStringLiteral("00000000000000"); - - - basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); - } - - const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone)); - const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone)); - - const double maxX(upperRight.x - lowerLeft.x); - const double maxY(upperRight.y - lowerLeft.y); - - - - const int increment = withInSingleUtmSquare ? 10000 : 1000; - for (double x = 0; x <= maxX + increment; x += increment) - { - const double xOfs = std::min(x, maxX); - for (double y = 0; y <= maxY + increment; y += increment) + LtsCoordTrans::UtmCoordinate basePoint; { - const double yOfs = std::min(y, maxY); - - const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs))); - const QString mgrs(utm.mgrs(0)); - - if (!tmpMgrsSquares.contains(mgrs)) - { - tmpMgrsSquares += mgrs; - ret += utm; - } + + const QPointF centerRad = rect_LatLon_radiant.center(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); + mgrs += QStringLiteral("00000000000000"); + + basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); } - } - return ret; + + const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone)); + const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone)); + + int offsetX = marginMeter.width(); + int offsetY = marginMeter.height(); + + const QPointF topLeft(lowerLeft.geographic(-offsetX, -offsetY)); + const QPointF bottomRight(upperRight.geographic(offsetX, offsetY)); + + QRectF res = QRectF(topLeft, bottomRight); + return res; } -QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter) +QVector getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares, bool setAsPreferedSquare, + bool setAsSquareWithMargin) { - - const QVector mainUtms = getMgrsSquaresInternal(geoRect); - QStringList mainSquares; - mainSquares.reserve(mainUtms.count()); - for (const auto &utm : mainUtms) - mainSquares.append(utm.mgrs(0)); + QVector ret = getMgrsSquaresInternal(rect); - - const QRectF rectWithOffset = addMarginToArea(geoRect,offsetMeter); + if (setAsDefaultSquares) + staticDefaultSquaresHelper() = ret; - QVector mainUtmsWithOffset = getMgrsSquaresInternal(rectWithOffset); - QStringList mainSquaresWithOffset; - mainSquaresWithOffset.reserve(mainUtmsWithOffset.count()); - for (const auto &utm : std::as_const(mainUtmsWithOffset)) - mainSquaresWithOffset.append(utm.mgrs(0)); + if (setAsPreferedSquare) + staticPreferedMgrsSquareHelper() = LtsCoordTrans::UtmCoordinate::fromGeographic(rect.center()); - - QStringList surroundingSquares; - surroundingSquares.reserve(mainSquaresWithOffset.count()); - for (const auto & mgrs0 : mainSquaresWithOffset) - { - if (!mainSquares.contains(mgrs0)) - surroundingSquares.append(mgrs0); - } + if (setAsSquareWithMargin) + staticMgrsSquaresWithOffsetsHelper() = ret; - return surroundingSquares; + return ret; +} + +QVector getMgrsSquaresInternal(const QRectF& rect) +{ + QVector ret; + QVector tmpMgrsSquares; + + double lonMin, lonMax, latMin, latMmax; + rect.normalized().getCoords(&lonMin, &latMin, &lonMax, &latMmax); + + bool withInSingleUtmSquare = true; + { + const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax)); + const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin)); + withInSingleUtmSquare = upperRight.zone == lowerLeft.zone; + } + + LtsCoordTrans::UtmCoordinate basePoint; + { + + QPointF centerRad = rect.center(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerRad.x(), centerRad.y(), -1); + mgrs += QStringLiteral("00000000000000"); + + basePoint = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); + } + + const UtmCoordinate upperRight(UtmCoordinate::fromGeographic(lonMax, latMmax, basePoint.zone)); + const UtmCoordinate lowerLeft(UtmCoordinate::fromGeographic(lonMin, latMin, basePoint.zone)); + + const double maxX(upperRight.x - lowerLeft.x); + const double maxY(upperRight.y - lowerLeft.y); + + const int increment = withInSingleUtmSquare ? 10000 : 1000; + for (double x = 0; x <= maxX + increment; x += increment) + { + const double xOfs = std::min(x, maxX); + for (double y = 0; y <= maxY + increment; y += increment) + { + const double yOfs = std::min(y, maxY); + + const UtmCoordinate utm(UtmCoordinate::fromGeographic(lowerLeft.geographic(xOfs, yOfs))); + const QString mgrs(utm.mgrs(0)); + + if (!tmpMgrsSquares.contains(mgrs)) + { + tmpMgrsSquares += mgrs; + ret += utm; + } + } + } + return ret; +} + +QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter) +{ + + const QVector mainUtms = getMgrsSquaresInternal(geoRect); + QStringList mainSquares; + mainSquares.reserve(mainUtms.count()); + for (const auto& utm : mainUtms) + mainSquares.append(utm.mgrs(0)); + + const QRectF rectWithOffset = addMarginToArea(geoRect, offsetMeter); + + QVector mainUtmsWithOffset = getMgrsSquaresInternal(rectWithOffset); + QStringList mainSquaresWithOffset; + mainSquaresWithOffset.reserve(mainUtmsWithOffset.count()); + for (const auto& utm : std::as_const(mainUtmsWithOffset)) + mainSquaresWithOffset.append(utm.mgrs(0)); + + QStringList surroundingSquares; + surroundingSquares.reserve(mainSquaresWithOffset.count()); + for (const auto& mgrs0 : mainSquaresWithOffset) + { + if (!mainSquares.contains(mgrs0)) + surroundingSquares.append(mgrs0); + } + + return surroundingSquares; } QVector defaultMgrsSquareWithOffsets() { - return staticMgrsSquaresWithOffsetsHelper(); + return staticMgrsSquaresWithOffsetsHelper(); } - -void setDefaultMgrsSquares(const QVector &squares) +void setDefaultMgrsSquares(const QVector& squares) { - QVector coords; - coords.reserve(squares.size()); - for (const QString &s : squares) - coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000")); - staticDefaultSquaresHelper() = coords; + QVector coords; + coords.reserve(squares.size()); + for (const QString& s : squares) + coords += UtmCoordinate::fromMgrs(s + QStringLiteral("00000000000000")); + staticDefaultSquaresHelper() = coords; } QVector defaultMgrsSquares() { - return staticDefaultSquaresHelper(); + return staticDefaultSquaresHelper(); } UtmCoordinate preferedMgrsSquare() { - return staticPreferedMgrsSquareHelper(); + return staticPreferedMgrsSquareHelper(); } - -bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut) +bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut, double& zOut) { - - lon *= rad2deg(); - lat *= rad2deg(); - try - { - GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut); - incrementCounter(s_conversion_counter_WGS84_Forward); - } - catch (...) - { - xOut = 0; - yOut = 0; - zOut = 0; - return false; - } - return true; + lon *= rad2deg(); + lat *= rad2deg(); + + try + { + GeographicLib::Geocentric::WGS84().Forward(lat, lon, altitude, xOut, yOut, zOut); + incrementCounter(s_conversion_counter_WGS84_Forward); + } + catch (...) + { + xOut = 0; + yOut = 0; + zOut = 0; + return false; + } + return true; } -bool geocentric2LonLatAlt(double x, double y, double z, - double &lon, double &lat, double &altitude) +bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat, double& altitude) { - - - try - { - GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude); - incrementCounter(s_conversion_counter_WGS84_Reverse); - } - catch (...) - { - lon = 0; - lat = 0; - altitude = 0; - return false; - } - - lon *= deg2rad(); - lat *= deg2rad(); - return true; + + try + { + GeographicLib::Geocentric::WGS84().Reverse(x, y, z, lat, lon, altitude); + incrementCounter(s_conversion_counter_WGS84_Reverse); + } + catch (...) + { + lon = 0; + lat = 0; + altitude = 0; + return false; + } + + lon *= deg2rad(); + lat *= deg2rad(); + return true; } -double distance(const QPointF &p1, const QPointF &p2) +double distance(const QPointF& p1, const QPointF& p2) { - return distance(p1.x(), p1.y(), p2.x(), p2.y()); + return distance(p1.x(), p1.y(), p2.x(), p2.y()); } -double squareDistance(const QPointF &p1, const QPointF &p2) +double squareDistance(const QPointF& p1, const QPointF& p2) { - return squareDistance(p1.x(), p1.y(), p2.x(), p2.y()); + return squareDistance(p1.x(), p1.y(), p2.x(), p2.y()); } -std::ostream &operator<< (std::ostream &stream, - const UtmCoordinate &coord) +std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord) { - stream << "UtmCoordinate(" << std::setprecision(8) << coord.x - << "#" << std::setprecision(8) << coord.y - << " zone=" << coord.zone << ")"; - return stream; + stream << "UtmCoordinate(" << std::setprecision(8) << coord.x << "#" << std::setprecision(8) << coord.y + << " zone=" << coord.zone << ")"; + return stream; } void dumpConversionCounter() { - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n" , s_conversion_counter_MGRS_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n" , s_conversion_counter_MGRS_Reverse); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n" , s_conversion_counter_WGS84_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n" , s_conversion_counter_WGS84_Reverse); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n" , s_conversion_counter_UTMUPS_Forward); - fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n" , s_conversion_counter_UTMUPS_Reverse); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Forward : - mgrs : %ld\n", + s_conversion_counter_MGRS_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_MGRS_Reverse - fromMgrs : %ld\n", + s_conversion_counter_MGRS_Reverse); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Forward - lonLatAltToGeocentric : %ld\n", + s_conversion_counter_WGS84_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_WGS84_Reverse - geocentric2LonLatAlt : %ld\n", + s_conversion_counter_WGS84_Reverse); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Forward - fromGeographic : %ld\n", + s_conversion_counter_UTMUPS_Forward); + fprintf(stderr, "LtsCoordTrans: s_conversion_counter_UTMUPS_Reverse - geographic : %ld\n", + s_conversion_counter_UTMUPS_Reverse); } -long getConversionCounter_MGRS_Forward() { return s_conversion_counter_MGRS_Forward; } -long getConversionCounter_MGRS_Reverse() { return s_conversion_counter_MGRS_Reverse; } -long getConversionCounter_WGS84_Forward() { return s_conversion_counter_WGS84_Forward; } -long getConversionCounter_WGS84_Reverse() { return s_conversion_counter_WGS84_Reverse; } -long getConversionCounter_UTMUPS_Forward() { return s_conversion_counter_UTMUPS_Forward; } -long getConversionCounter_UTMUPS_Reverse() { return s_conversion_counter_UTMUPS_Reverse; } +long getConversionCounter_MGRS_Forward() +{ + return s_conversion_counter_MGRS_Forward; +} -} +long getConversionCounter_MGRS_Reverse() +{ + return s_conversion_counter_MGRS_Reverse; +} + +long getConversionCounter_WGS84_Forward() +{ + return s_conversion_counter_WGS84_Forward; +} + +long getConversionCounter_WGS84_Reverse() +{ + return s_conversion_counter_WGS84_Reverse; +} + +long getConversionCounter_UTMUPS_Forward() +{ + return s_conversion_counter_UTMUPS_Forward; +} + +long getConversionCounter_UTMUPS_Reverse() +{ + return s_conversion_counter_UTMUPS_Reverse; +} + +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h old mode 100755 new mode 100644 index 78d60a279..436dab573 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans.h @@ -1,13 +1,11 @@ - #pragma once -#include - -#include -#include #include +#include +#include +#include class QPointF; class QRectF; class QSize; @@ -16,175 +14,129 @@ class QString; namespace LtsCoordTrans { +inline Q_CONSTEXPR double pi() +{ + return M_PI; +} +inline Q_CONSTEXPR double deg2rad() +{ + return pi() / 180.; +} - -inline Q_CONSTEXPR double pi() { return M_PI; } -inline Q_CONSTEXPR double deg2rad() { return pi() / 180.; } -inline Q_CONSTEXPR double rad2deg() { return 1. / deg2rad(); } +inline Q_CONSTEXPR double rad2deg() +{ + return 1. / deg2rad(); +} struct LTSCOORDTRANS_EXPORT UtmCoordinate { - int zone = -1; - bool northp = true; - double x = 0.; - double y = 0.; + int zone = -1; + bool northp = true; + double x = 0.; + double y = 0.; - UtmCoordinate() = default; - UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true) - : zone(zone_) - , northp(northp_) - , x(x_) - , y(y_) - {} + UtmCoordinate() = default; - + UtmCoordinate(int zone_, double x_, double y_, bool northp_ = true) : zone(zone_), northp(northp_), x(x_), y(y_) {} - bool isValid() const { return zone > 0 && zone <= 60; } + bool isValid() const + { + return zone > 0 && zone <= 60; + } - + QString mgrs(int prec = 5, bool withSpaces = true) const; - QString mgrs(int prec = 5, bool withSpaces = true) const; + QPointF toPoint() const; - QPointF toPoint() const; + QPointF geographic(double offsetX = 0., double offsetY = 0.) const; - + QPointF geographic(const QPointF& offset) const; - QPointF geographic(double offsetX = 0., double offsetY = 0.) const; + QPointF relativeTo(const UtmCoordinate& other) const; - + static UtmCoordinate fromGeographic(double lon, double lat, int setZone = -1); - QPointF geographic(const QPointF &offset) const; + static UtmCoordinate fromGeographic(const QPointF& lonLat, int setZone = -1); - - - QPointF relativeTo(const UtmCoordinate &other) const; - - - - static UtmCoordinate fromGeographic(double lon, double lat, int setZone = -1); - - - - static UtmCoordinate fromGeographic(const QPointF &lonLat, int setZone = -1); - - - - static UtmCoordinate fromMgrs(const QString &mgrs); + static UtmCoordinate fromMgrs(const QString& mgrs); }; - - LTSCOORDTRANS_EXPORT QString mgrsFromGeographic(double lon, double lat, int prec = 5, bool withSpaces = true); +LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString& mgrs); +LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF& rect_LatLon_radiant, const QSize& marginMeter); -LTSCOORDTRANS_EXPORT QPointF geographicFromMgrs(const QString &mgrs); - - - -LTSCOORDTRANS_EXPORT QRectF addMarginToArea(const QRectF &rect_LatLon_radiant, const QSize &marginMeter); - - - -LTSCOORDTRANS_EXPORT QVector getMgrsSquares(const QRectF &rect, bool setAsDefaultSquares, bool setAsPreferedSquare, bool setAsSquareWithMargin = false); - - - -QVector getMgrsSquaresInternal(const QRectF &rect); - - - -QStringList getMgrsSurroundingSquares(const QRectF &geoRect, const QSize &offsetMeter); +LTSCOORDTRANS_EXPORT QVector getMgrsSquares(const QRectF& rect, bool setAsDefaultSquares, + bool setAsPreferedSquare, + bool setAsSquareWithMargin = false); +QVector getMgrsSquaresInternal(const QRectF& rect); +QStringList getMgrsSurroundingSquares(const QRectF& geoRect, const QSize& offsetMeter); LTSCOORDTRANS_EXPORT QVector defaultMgrsSquareWithOffsets(); - - -LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector &squares); - - +LTSCOORDTRANS_EXPORT void setDefaultMgrsSquares(const QVector& squares); LTSCOORDTRANS_EXPORT QVector defaultMgrsSquares(); - - LTSCOORDTRANS_EXPORT UtmCoordinate preferedMgrsSquare(); +LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double& xOut, double& yOut, + double& zOut); +LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z, double& lon, double& lat, + double& altitude); -LTSCOORDTRANS_EXPORT bool lonLatAltToGeocentric(double lon, double lat, double altitude, double &xOut, double &yOut, double &zOut); - - - -LTSCOORDTRANS_EXPORT bool geocentric2LonLatAlt(double x, double y, double z, - double &lon, double &lat, double &altitude); - - - - -inline double squareDistance(const UtmCoordinate &p1, const UtmCoordinate &p2) +inline double squareDistance(const UtmCoordinate& p1, const UtmCoordinate& p2) { - if (p1.zone != p2.zone) - { - Q_ASSERT(false); - return std::nan(""); - } - return std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2); + if (p1.zone != p2.zone) + { + Q_ASSERT(false); + return std::nan(""); + } + return std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2); } - - -LTSCOORDTRANS_EXPORT double squareDistance(const QPointF &p1, const QPointF &p2); - - +LTSCOORDTRANS_EXPORT double squareDistance(const QPointF& p1, const QPointF& p2); inline double squareDistance(const double lon1, const double lat1, const double lon2, const double lat2) { - const auto p1(UtmCoordinate::fromGeographic(lon1, lat1)); - const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); - return squareDistance(p1, p2); + const auto p1(UtmCoordinate::fromGeographic(lon1, lat1)); + const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); + return squareDistance(p1, p2); } - - -inline double squareDistance(const UtmCoordinate &p1, const double lon2, const double lat2) +inline double squareDistance(const UtmCoordinate& p1, const double lon2, const double lat2) { - const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); - return squareDistance(p1, p2); + const auto p2(UtmCoordinate::fromGeographic(lon2, lat2, p1.zone)); + return squareDistance(p1, p2); } - - -inline double distance(const UtmCoordinate &p1, const UtmCoordinate &p2) +inline double distance(const UtmCoordinate& p1, const UtmCoordinate& p2) { - if (p1.zone != p2.zone) - { - Q_ASSERT(false); - return std::nan(""); - } - return sqrt(squareDistance(p1, p2)); + if (p1.zone != p2.zone) + { + Q_ASSERT(false); + return std::nan(""); + } + return sqrt(squareDistance(p1, p2)); } - - -LTSCOORDTRANS_EXPORT double distance(const QPointF &p1, const QPointF &p2); - - +LTSCOORDTRANS_EXPORT double distance(const QPointF& p1, const QPointF& p2); inline double distance(const double lon1, const double lat1, const double lon2, const double lat2) { - return sqrt(squareDistance(lon1, lat1, lon2, lat2)); + return sqrt(squareDistance(lon1, lat1, lon2, lat2)); } -inline double distance(const UtmCoordinate &p1, const double lon2, const double lat2) +inline double distance(const UtmCoordinate& p1, const double lon2, const double lat2) { - return sqrt(squareDistance(p1, lon2, lat2)); + return sqrt(squareDistance(p1, lon2, lat2)); } - LTSCOORDTRANS_EXPORT void dumpConversionCounter(); LTSCOORDTRANS_EXPORT long getConversionCounter_MGRS_Forward(); @@ -194,56 +146,44 @@ LTSCOORDTRANS_EXPORT long getConversionCounter_WGS84_Reverse(); LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Forward(); LTSCOORDTRANS_EXPORT long getConversionCounter_UTMUPS_Reverse(); - -LTSCOORDTRANS_EXPORT std::ostream &operator<< (std::ostream &stream, - const UtmCoordinate &coord); - - - - - - +LTSCOORDTRANS_EXPORT std::ostream& operator<<(std::ostream& stream, const UtmCoordinate& coord); class LTSCOORDTRANS_EXPORT UtmCoordinate3D : public LtsCoordTrans::UtmCoordinate { - using BaseClass = LtsCoordTrans::UtmCoordinate; + using BaseClass = LtsCoordTrans::UtmCoordinate; -public: - UtmCoordinate3D() - { - reset(); - } + public: + UtmCoordinate3D() + { + reset(); + } - explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate &utm2d, double _zValue = std::nan("")) - :BaseClass() - { - zone = utm2d.zone; - northp = utm2d.northp; - x = utm2d.x; - y = utm2d.y; - zValue = _zValue; - } + explicit UtmCoordinate3D(const LtsCoordTrans::UtmCoordinate& utm2d, double _zValue = std::nan("")) : BaseClass() + { + zone = utm2d.zone; + northp = utm2d.northp; + x = utm2d.x; + y = utm2d.y; + zValue = _zValue; + } - void reset() - { - zone = -1; - northp = true; + void reset() + { + zone = -1; + northp = true; - - - - + x = 0.; + y = 0.; + zValue = std::nan(""); + } - x = 0.; - y = 0.; - zValue = std::nan(""); - } + double z() const + { + return zValue; + } - double z() const { return zValue; } - -protected: - double zValue{std::nan("")}; + protected: + double zValue{std::nan("")}; }; - -} +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp old mode 100755 new mode 100644 index eb5e3163d..683e72550 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.cpp @@ -1,470 +1,400 @@ - #include "lts_coord_trans_unit_test.h" -#include + #include "lts_coord_trans.h" + #include -#include #include +#include +#include QTEST_MAIN(coordtrans_test) void coordtrans_test::initTestCase() { - qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate)); + qDebug("sizeof(UtmCoordinate) = %lu", sizeof(LtsCoordTrans::UtmCoordinate)); } -void coordtrans_test::cleanupTestCase() -{} +void coordtrans_test::cleanupTestCase() {} void coordtrans_test::testFromGeographic() { - - - - LtsCoordTrans::UtmCoordinate utm; - QPointF lonlat; - lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999")); + LtsCoordTrans::UtmCoordinate utm; + QPointF lonlat; - lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000")); + lonlat = QPointF(8.6264954126, 53.1138437183) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("32U MD")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(8), QStringLiteral("32U MD 74999999 84999999")); - lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad(); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); - QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM")); - utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000")); + lonlat = QPointF(11.3003696521, 52.8224535191) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("32U PD")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(5), QStringLiteral("32U PD 55000 55000")); - - - utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000")); - QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM")); + lonlat = QPointF(54.8821607021, 24.2631973752) * LtsCoordTrans::deg2rad(); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y(), -1); + QCOMPARE(utm.mgrs(0), QStringLiteral("40R BM")); + utm = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QCOMPARE(utm.mgrs(5), QStringLiteral("40R BM 85000 85000")); + + utm = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("40R BM 00000 00000")); + QCOMPARE(utm.mgrs(0), QStringLiteral("40Q BM")); } void coordtrans_test::testMgrsFromGeographic() { - - QString mgrs; - QPointF lonlat; - lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); + QString mgrs; + QPointF lonlat; - mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false); - QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000")); + lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); + + mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 8, false); + QCOMPARE(mgrs, QStringLiteral("32UMD7450000084000000")); } void coordtrans_test::testRelativeMetricalOffet_data() { - - QTest::addColumn("offset"); - QTest::addColumn("correctMgrs"); - - QTest::newRow("set 1") << QPoint( 5, 5) << QStringLiteral("32U PD 99995 99995"); - - - QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090"); - QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490"); + QTest::addColumn("offset"); + QTest::addColumn("correctMgrs"); + + QTest::newRow("set 1") << QPoint(5, 5) << QStringLiteral("32U PD 99995 99995"); + + QTest::newRow("set 2") << QPoint(100, 100) << QStringLiteral("32U QE 00090 00090"); + QTest::newRow("set 3") << QPoint(500, 500) << QStringLiteral("32U QE 00490 00490"); } void coordtrans_test::testRelativeMetricalOffet() { - QFETCH(QPoint, offset); - QFETCH(QString, correctMgrs); + QFETCH(QPoint, offset); + QFETCH(QString, correctMgrs); - const LtsCoordTrans::UtmCoordinate &utmRef = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990")); - qDebug() << "utmRef = " << utmRef.mgrs(); + const LtsCoordTrans::UtmCoordinate& utmRef = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 99990 99990")); + qDebug() << "utmRef = " << utmRef.mgrs(); - { - LtsCoordTrans::UtmCoordinate utmRaw; - utmRaw.x = utmRef.x + offset.x(); - utmRaw.y = utmRef.y + offset.y(); - utmRaw.zone = utmRef.zone; - qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs(); + { + LtsCoordTrans::UtmCoordinate utmRaw; + utmRaw.x = utmRef.x + offset.x(); + utmRaw.y = utmRef.y + offset.y(); + utmRaw.zone = utmRef.zone; + qDebug() << "offset = " << offset << " - utmRaw = " << utmRaw.mgrs(); - QCOMPARE(utmRaw.mgrs(), correctMgrs); - } - - - - - { - const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone, - utmRef.x + offset.x(), - utmRef.y + offset.y()); - - qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs(); - QCOMPARE(utmSimple.mgrs(), correctMgrs); - } - + QCOMPARE(utmRaw.mgrs(), correctMgrs); + } + + { + const LtsCoordTrans::UtmCoordinate utmSimple(utmRef.zone, utmRef.x + offset.x(), utmRef.y + offset.y()); + + qDebug() << "offset = " << offset << " - utmSimple = " << utmSimple.mgrs(); + QCOMPARE(utmSimple.mgrs(), correctMgrs); + } } -QRectF createArea(const QString &base, - int xCenter, int yCenter, int width, int height) +QRectF createArea(const QString& base, int xCenter, int yCenter, int width, int height) { - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase( + LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - - - QRectF rect (topLeft, bottomRight); - return rect; + QRectF rect(topLeft, bottomRight); + return rect; } - void coordtrans_test::testAddMarginToArea() { - - { - qDebug() << "Altmark"; - QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000); - QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000)); - qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft()*LtsCoordTrans::rad2deg(); - qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft()*LtsCoordTrans::rad2deg(); + { + qDebug() << "Altmark"; + QRectF area = createArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000); + QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(5000, 20000)); - qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight()*LtsCoordTrans::rad2deg(); - qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() << " - degree:" << area1Increased.bottomRight()*LtsCoordTrans::rad2deg(); + qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() + << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() + << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); - QVERIFY2( area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); - QVERIFY2( area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); + qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() + << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() + << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); - QVERIFY2( area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); - QVERIFY2( area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); - } + QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); + QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); - - { - qDebug() << "Luxemburg"; - QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000); - QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000)); + QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); + QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); + } - qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() << " - degree:" << area.topLeft()*LtsCoordTrans::rad2deg(); - qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() << " - degree:" << area1Increased.topLeft()*LtsCoordTrans::rad2deg(); + { + qDebug() << "Luxemburg"; + QRectF area = createArea(QStringLiteral("32U LA 0000000000"), 100, 100, 5000, 5000); + QRectF area1Increased = LtsCoordTrans::addMarginToArea(area, QSize(50000, 20000)); - qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() << " - degree:" << area.bottomRight()*LtsCoordTrans::rad2deg(); - qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() << " - degree:" << area1Increased.bottomRight()*LtsCoordTrans::rad2deg(); + qDebug() << "topLeft : " << qSetRealNumberPrecision(15) << area.topLeft() + << " - degree:" << area.topLeft() * LtsCoordTrans::rad2deg(); + qDebug() << "topLeftInc : " << qSetRealNumberPrecision(15) << area1Increased.topLeft() + << " - degree:" << area1Increased.topLeft() * LtsCoordTrans::rad2deg(); - QVERIFY2( area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); - QVERIFY2( area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); + qDebug() << "bottomRight : " << qSetRealNumberPrecision(15) << area.bottomRight() + << " - degree:" << area.bottomRight() * LtsCoordTrans::rad2deg(); + qDebug() << "bottomRightInc : " << qSetRealNumberPrecision(15) << area1Increased.bottomRight() + << " - degree:" << area1Increased.bottomRight() * LtsCoordTrans::rad2deg(); - QVERIFY2( area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); - QVERIFY2( area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); - } + QVERIFY2(area1Increased.topLeft().x() < area.topLeft().x(), "addMarginToArea topLeft X failed"); + QVERIFY2(area1Increased.topLeft().y() < area.topLeft().y(), "addMarginToArea topLeft Y failed"); + + QVERIFY2(area1Increased.bottomRight().x() > area.bottomRight().x(), "addMarginToArea bottomRight X failed"); + QVERIFY2(area1Increased.bottomRight().y() > area.bottomRight().y(), "addMarginToArea bottomRight Y failed"); + } } void coordtrans_test::testIncreaseRect() { - - QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - LtsCoordTrans::UtmCoordinate topLeftUtm; - LtsCoordTrans::UtmCoordinate topLeftUtm2; + const LtsCoordTrans::UtmCoordinate centerPoint = + LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - - { - QPointF topLeftGeo = centerPoint.geographic(-1111, 2222); - QPointF bottomRightGeo = centerPoint.geographic( 3000, -4000); + LtsCoordTrans::UtmCoordinate topLeftUtm; + LtsCoordTrans::UtmCoordinate topLeftUtm2; - topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo); - const LtsCoordTrans::UtmCoordinate bottomRightUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo); - qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y; - qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm.y; - } + { + QPointF topLeftGeo = centerPoint.geographic(-1111, 2222); + QPointF bottomRightGeo = centerPoint.geographic(3000, -4000); - - { - topLeftUtm2.x = centerPoint.x - 1111; - topLeftUtm2.y = centerPoint.y + 2222; + topLeftUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(topLeftGeo); + const LtsCoordTrans::UtmCoordinate bottomRightUtm = + LtsCoordTrans::UtmCoordinate::fromGeographic(bottomRightGeo); + qDebug() << "topLeftUtm: " << topLeftUtm.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm.y; + qDebug() << "bottomRightUtm: " << bottomRightUtm.x << " - " << qSetRealNumberPrecision(15) + << bottomRightUtm.y; + } - LtsCoordTrans::UtmCoordinate bottomRightUtm2; - bottomRightUtm2.x = centerPoint.x + 3000; - bottomRightUtm2.y = centerPoint.y - 4000; + { + topLeftUtm2.x = centerPoint.x - 1111; + topLeftUtm2.y = centerPoint.y + 2222; - qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y; - qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15) << bottomRightUtm2.y; - } + LtsCoordTrans::UtmCoordinate bottomRightUtm2; + bottomRightUtm2.x = centerPoint.x + 3000; + bottomRightUtm2.y = centerPoint.y - 4000; - QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed"); - QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed"); + qDebug() << "topLeftUtm2: " << topLeftUtm2.x << " - " << qSetRealNumberPrecision(15) << topLeftUtm2.y; + qDebug() << "bottomRightUtm2: " << bottomRightUtm2.x << " - " << qSetRealNumberPrecision(15) + << bottomRightUtm2.y; + } + + QVERIFY2(qFuzzyCompare(topLeftUtm.x, topLeftUtm2.x), "testIncreaseRect x failed"); + QVERIFY2(qFuzzyCompare(topLeftUtm.y, topLeftUtm2.y), "testIncreaseRect y failed"); } void coordtrans_test::testIncreaseRect2() { - - QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); - QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - QRectF myRect; - QRectF myRectIncreased; + QPointF lonlat = QPointF(8.6191049344, 53.1048309844) * LtsCoordTrans::deg2rad(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(lonlat.x(), lonlat.y(), 9); + QCOMPARE(mgrs, QStringLiteral("32U MD 745000000 840000000")); - { - const LtsCoordTrans::UtmCoordinate centerPoint = LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); + QRectF myRect; + QRectF myRectIncreased; - QPointF topLeftGeo = centerPoint.geographic(-3000, 2000); - QPointF bottomRightGeo = centerPoint.geographic( 3000, -2000); - myRect = QRectF(topLeftGeo, bottomRightGeo).normalized(); + { + const LtsCoordTrans::UtmCoordinate centerPoint = + LtsCoordTrans::UtmCoordinate::fromGeographic(lonlat.x(), lonlat.y()); - qDebug() << "myRect : " << myRect; - qDebug() << "myRect center : " << myRect.center(); - qDebug() << "myRect height : " << myRect.height(); - } + QPointF topLeftGeo = centerPoint.geographic(-3000, 2000); + QPointF bottomRightGeo = centerPoint.geographic(3000, -2000); + myRect = QRectF(topLeftGeo, bottomRightGeo).normalized(); - - { - const QPointF centerGeo = myRect.center(); - const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo); + qDebug() << "myRect : " << myRect; + qDebug() << "myRect center : " << myRect.center(); + qDebug() << "myRect height : " << myRect.height(); + } - QPointF topLeftGeo = centerUtm.geographic(-6000, 4000); - QPointF bottomRightGeo = centerUtm.geographic( 6000, -4000); + { + const QPointF centerGeo = myRect.center(); + const LtsCoordTrans::UtmCoordinate centerUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(centerGeo); - myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized(); + QPointF topLeftGeo = centerUtm.geographic(-6000, 4000); + QPointF bottomRightGeo = centerUtm.geographic(6000, -4000); - qDebug() << "myRectIncreased : " << myRectIncreased; - qDebug() << "myRectIncreased center: " << myRectIncreased.center(); - qDebug() << "myRectIncreased height: " << myRectIncreased.height(); + myRectIncreased = QRectF(topLeftGeo, bottomRightGeo).normalized(); - } + qDebug() << "myRectIncreased : " << myRectIncreased; + qDebug() << "myRectIncreased center: " << myRectIncreased.center(); + qDebug() << "myRectIncreased height: " << myRectIncreased.height(); + } - - QVERIFY2( (int)(myRectIncreased.center().x()*10000) == (int)(myRect.center().x()*10000), "testIncreaseRect2 centerX failed"); - QVERIFY2( (int)(myRectIncreased.center().y()*10000) == (int)(myRect.center().y()*10000), "testIncreaseRect2 centerY failed"); - - QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed"); - QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed"); + QVERIFY2((int)(myRectIncreased.center().x() * 10000) == (int)(myRect.center().x() * 10000), + "testIncreaseRect2 centerX failed"); + QVERIFY2((int)(myRectIncreased.center().y() * 10000) == (int)(myRect.center().y() * 10000), + "testIncreaseRect2 centerY failed"); + QVERIFY2(myRectIncreased.width() > myRect.width(), "testIncreaseRect2 width failed"); + QVERIFY2(myRectIncreased.height() > myRect.height(), "testIncreaseRect2 height failed"); } - - void coordtrans_test::testGeographicFromMgrs() { - - QString mgrs(QStringLiteral("32UPD7654398765")); + QString mgrs(QStringLiteral("32UPD7654398765")); - QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs); - QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad()); + QPointF geographic = LtsCoordTrans::geographicFromMgrs(mgrs); + QCOMPARE(geographic, QPointF(11.6436815550, 53.2088411454) * LtsCoordTrans::deg2rad()); } void coordtrans_test::testMgrsSquares() { - - + checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000, + {QStringLiteral("32U PC"), QStringLiteral("32U PD")}); + checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000, + {QStringLiteral("32U MC"), QStringLiteral("32U MD")}); + checkArea(QStringLiteral("32U MD 0000000000"), 89999, 89999, 21000, 21000, + {QStringLiteral("32U MD"), QStringLiteral("32U ME"), QStringLiteral("32U ND"), QStringLiteral("32U NE")}); - checkArea(QStringLiteral("32U PD 0000000000"), 50000, 10000, 30000, 30000, { QStringLiteral("32U PC"), - QStringLiteral("32U PD") - }); - checkArea(QStringLiteral("32U MD 0000000000"), 50000, 10000, 30000, 30000, { QStringLiteral("32U MC"), - QStringLiteral("32U MD") - }); - checkArea(QStringLiteral("32U MD 0000000000"), 89999, 89999, 21000, 21000, { QStringLiteral("32U MD"), - QStringLiteral("32U ME"), - QStringLiteral("32U ND"), - QStringLiteral("32U NE") - }); - - checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000, { QStringLiteral("39Q XG"), - QStringLiteral("39R XG") - }); - checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, { QStringLiteral("40R CP") }); - checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000, { QStringLiteral("40R CN"), - QStringLiteral("40R DN") - }); - checkArea(QStringLiteral("40R DN 0000000000"), 500, 96760, 30000, 30000, { QStringLiteral("40R CN"), - QStringLiteral("40R CP"), - QStringLiteral("40R DN"), - QStringLiteral("40R DP") - }); - checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000, { QStringLiteral("40Q BM"), - QStringLiteral("40R BM") - }); + checkArea(QStringLiteral("39Q XG 0000000000"), 40000, 35000, 60000, 70000, + {QStringLiteral("39Q XG"), QStringLiteral("39R XG")}); + checkArea(QStringLiteral("40R CP 0000000000"), 94000, 9000, 7000, 16000, {QStringLiteral("40R CP")}); + checkArea(QStringLiteral("40R DN 0000000000"), 500, 95500, 12000, 7000, + {QStringLiteral("40R CN"), QStringLiteral("40R DN")}); + checkArea(QStringLiteral("40R DN 0000000000"), 500, 96760, 30000, 30000, + {QStringLiteral("40R CN"), QStringLiteral("40R CP"), QStringLiteral("40R DN"), QStringLiteral("40R DP")}); + checkArea(QStringLiteral("40R BM 0000000000"), 59000, 59500, 46000, 40000, + {QStringLiteral("40Q BM"), QStringLiteral("40R BM")}); - - - checkArea(QStringLiteral("32U LA 0000000000"), 10000, 10000, 5000, 5000, { QStringLiteral("32U LA"), - }); + checkArea(QStringLiteral("32U LA 0000000000"), 10000, 10000, 5000, 5000, + { + QStringLiteral("32U LA"), + }); - - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 60000, 60000, { QStringLiteral("31U GQ"), - QStringLiteral("31U GR"), - QStringLiteral("32U KA"), - QStringLiteral("32U KV"), - QStringLiteral("32U LA"), - QStringLiteral("32U LV") - }); - - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100,150000,150000, { QStringLiteral("31U FQ"), - QStringLiteral("31U FR"), - QStringLiteral("31U GQ"), - QStringLiteral("31U GR"), - QStringLiteral("32U KA"), - QStringLiteral("32U KV"), - QStringLiteral("32U LA"), - QStringLiteral("32U LV") - }); + checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 60000, 60000, + {QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("32U KA"), QStringLiteral("32U KV"), + QStringLiteral("32U LA"), QStringLiteral("32U LV")}); - checkArea(QStringLiteral("32U LA 0000000000"), 100, 100,200000,200000, { QStringLiteral("31U FP"), - QStringLiteral("31U FQ"), - QStringLiteral("31U FR"), - QStringLiteral("31U GP"), - QStringLiteral("31U GQ"), - QStringLiteral("31U GR"), - QStringLiteral("31U GS"), - QStringLiteral("32U KA"), - QStringLiteral("32U KB"), - QStringLiteral("32U KV"), - QStringLiteral("32U LA"), - QStringLiteral("32U LB"), - QStringLiteral("32U LV"), - QStringLiteral("32U MA"), - QStringLiteral("32U MB"), - QStringLiteral("32U MV") - }); + checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 150000, 150000, + {QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GQ"), QStringLiteral("31U GR"), + QStringLiteral("32U KA"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LV")}); + checkArea(QStringLiteral("32U LA 0000000000"), 100, 100, 200000, 200000, + {QStringLiteral("31U FP"), QStringLiteral("31U FQ"), QStringLiteral("31U FR"), QStringLiteral("31U GP"), + QStringLiteral("31U GQ"), QStringLiteral("31U GR"), QStringLiteral("31U GS"), QStringLiteral("32U KA"), + QStringLiteral("32U KB"), QStringLiteral("32U KV"), QStringLiteral("32U LA"), QStringLiteral("32U LB"), + QStringLiteral("32U LV"), QStringLiteral("32U MA"), QStringLiteral("32U MB"), QStringLiteral("32U MV")}); } - -QVector checkAreaGetMgrsSquares(const QString &base, - int xCenter, int yCenter, int width, int height) +QVector checkAreaGetMgrsSquares(const QString& base, int xCenter, int yCenter, int width, + int height) { - - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - - - const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase( + LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - QStringList src; - src.reserve(squares.size()); - for (const auto &utm : squares) - src += utm.mgrs(0); - src.sort(); - + const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); - return squares; + QStringList src; + src.reserve(squares.size()); + for (const auto& utm : squares) + src += utm.mgrs(0); + src.sort(); + + return squares; } void coordtrans_test::testMgrsSquaresWithSurrounding() { + int initialSize = 5000; + QVector squares1 = + checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize); + QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed"); + int biggerSize = initialSize + (1 * 110000); + QVector squares9 = + checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize); + QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed"); + int muchBiggerSize = initialSize + (3 * 110000); + QVector square33 = + checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize); + QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed"); + QStringList string1; + string1.reserve(squares1.size()); + for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares1)) + string1.append(item.mgrs(0)); + QStringList string9; + string9.reserve(squares9.size()); + for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(squares9)) + string9.append(item.mgrs(0)); + QStringList string33; + string33.reserve(square33.size()); + for (const LtsCoordTrans::UtmCoordinate& item : std::as_const(square33)) + string33.append(item.mgrs(0)); + { + QStringList surroundingStrings; + surroundingStrings.reserve(squares9.size()); + for (const QString& str : std::as_const(string9)) + if (!string1.contains(str)) + surroundingStrings.append(str); + QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed"); + } + { + QStringList surroundingStrings; + surroundingStrings.reserve(string33.size()); + for (const QString& str : std::as_const(string33)) + if (!string1.contains(str)) + surroundingStrings.append(str); - - - int initialSize = 5000; - - - QVector squares1 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, initialSize, initialSize); - - QVERIFY2(squares1.size() == 1, "checkAreaGetMgrsSquares failed"); - - - - - int biggerSize = initialSize + (1*110000); - QVector squares9 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, biggerSize, biggerSize); - - QVERIFY2(squares9.size() == 9, "checkAreaGetMgrsSquares biggerSize failed"); - - int muchBiggerSize = initialSize + (3*110000); - QVector square33 = checkAreaGetMgrsSquares(QStringLiteral("32U NC 0000000000"), 50000, 50000, muchBiggerSize, muchBiggerSize); - - QVERIFY2(square33.size() == 33, "checkAreaGetMgrsSquares muchBiggerSize failed"); - - - QStringList string1; - string1.reserve(squares1.size()); - for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares1)) - string1.append(item.mgrs(0)); - - QStringList string9; - string9.reserve(squares9.size()); - for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(squares9)) - string9.append(item.mgrs(0)); - - QStringList string33; - string33.reserve(square33.size()); - for (const LtsCoordTrans::UtmCoordinate &item : std::as_const(square33)) - string33.append(item.mgrs(0)); - - { - QStringList surroundingStrings; - surroundingStrings.reserve(squares9.size()); - for (const QString &str : std::as_const(string9)) - if (!string1.contains(str)) - surroundingStrings.append(str); - - QVERIFY2(surroundingStrings.size() == 8, "checkAreaGetMgrsSquares squaresDiff failed"); - } - - { - QStringList surroundingStrings; - surroundingStrings.reserve(string33.size()); - for (const QString &str : std::as_const(string33)) - if (!string1.contains(str)) - surroundingStrings.append(str); - - QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed"); - } - + QVERIFY2(surroundingStrings.size() == 32, "checkAreaGetMgrsSquares squaresDiff failed"); + } } -void coordtrans_test::checkArea(const QString &base, - int xCenter, int yCenter, int width, int height, - const QStringList &coords) +void coordtrans_test::checkArea(const QString& base, int xCenter, int yCenter, int width, int height, + const QStringList& coords) { - qDebug() << "checkArea : base: " << base; - QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); - LtsCoordTrans::UtmCoordinate utmBase(LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); - const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); - const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); - qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg(); - qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg(); + qDebug() << "checkArea : base: " << base; + QRectF areaRect = QRectF(xCenter - width / 2, yCenter - height / 2, width, height); + LtsCoordTrans::UtmCoordinate utmBase( + LtsCoordTrans::UtmCoordinate::fromGeographic(LtsCoordTrans::geographicFromMgrs(base))); + const QPointF topLeft(utmBase.geographic(areaRect.left(), areaRect.top())); + const QPointF bottomRight(utmBase.geographic(areaRect.right(), areaRect.bottom())); + qDebug() << "TopLeft: " << topLeft * LtsCoordTrans::rad2deg(); + qDebug() << "BottomRight: " << bottomRight * LtsCoordTrans::rad2deg(); - const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); + const auto squares = LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), false, false); - QStringList src; - src.reserve(squares.size()); - for (const auto &utm : squares) - src += utm.mgrs(0); - src.sort(); - qDebug() << "src: '" << src << "' expected: '" << coords << "'"; - QCOMPARE(src, coords); + QStringList src; + src.reserve(squares.size()); + for (const auto& utm : squares) + src += utm.mgrs(0); + src.sort(); + qDebug() << "src: '" << src << "' expected: '" << coords << "'"; + QCOMPARE(src, coords); } - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h old mode 100755 new mode 100644 index 9bc7183d2..bc2208f83 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_trans_unit_test.h @@ -7,28 +7,25 @@ class coordtrans_test : public QObject { - Q_OBJECT -private Q_SLOTS: - void initTestCase(); - void cleanupTestCase(); - void testFromGeographic(); - void testMgrsFromGeographic(); + Q_OBJECT + private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + void testFromGeographic(); + void testMgrsFromGeographic(); - void testRelativeMetricalOffet_data(); - void testRelativeMetricalOffet(); + void testRelativeMetricalOffet_data(); + void testRelativeMetricalOffet(); - void testAddMarginToArea(); - void testIncreaseRect(); - void testIncreaseRect2(); + void testAddMarginToArea(); + void testIncreaseRect(); + void testIncreaseRect2(); - void testGeographicFromMgrs(); - void testMgrsSquares(); + void testGeographicFromMgrs(); + void testMgrsSquares(); - void testMgrsSquaresWithSurrounding(); - -private: - void checkArea(const QString &base, - int xCenter, int yCenter, int width, int height, - const QStringList &coords); + void testMgrsSquaresWithSurrounding(); + private: + void checkArea(const QString& base, int xCenter, int yCenter, int width, int height, const QStringList& coords); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp old mode 100755 new mode 100644 index c64012c0f..668c564a1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget.cpp @@ -1,7 +1,7 @@ - #include "lts_coord_widget.h" + #include "lts_coord_widget_p.h" #include @@ -10,187 +10,178 @@ namespace LtsCoordWidget { -LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget *parent) - : QWidget(parent) - , m_displayType(dt) +LtsCoordWidget::LtsCoordWidget(DisplayType dt, QWidget* parent) : QWidget(parent), m_displayType(dt) { - setFocusPolicy(Qt::StrongFocus); - rebuildUi(); + setFocusPolicy(Qt::StrongFocus); + rebuildUi(); } -void LtsCoordWidget::setCoordinate(const QPointF &geoCoord, bool bUseAsDefaultValue) +void LtsCoordWidget::setCoordinate(const QPointF& geoCoord, bool bUseAsDefaultValue) { - if (m_coordinate != geoCoord) - emit coordinateChanged(geoCoord); - if (bUseAsDefaultValue) - m_defaultCoordinate = geoCoord; - if (m_inputWidgetHandler) - m_inputWidgetHandler->setCoordinate(geoCoord); + if (m_coordinate != geoCoord) + emit coordinateChanged(geoCoord); + if (bUseAsDefaultValue) + m_defaultCoordinate = geoCoord; + if (m_inputWidgetHandler) + m_inputWidgetHandler->setCoordinate(geoCoord); } void LtsCoordWidget::clear() { - if (m_inputWidgetHandler) - m_inputWidgetHandler->clear(); + if (m_inputWidgetHandler) + m_inputWidgetHandler->clear(); } void LtsCoordWidget::setCoordinate(double lon, double lat, bool bUseAsDefaultValue) { - setCoordinate(QPointF(lon, lat), bUseAsDefaultValue); + setCoordinate(QPointF(lon, lat), bUseAsDefaultValue); } QPointF LtsCoordWidget::coordinate() const { - if (!m_inputWidgetHandler) - return QPointF(); - return m_inputWidgetHandler->coordinate(); + if (!m_inputWidgetHandler) + return QPointF(); + return m_inputWidgetHandler->coordinate(); } - LtsCoordWidget::DisplayType LtsCoordWidget::displayType() const { - return m_displayType; + return m_displayType; } void LtsCoordWidget::setDisplayType(LtsCoordWidget::DisplayType dt) { - if (m_displayType == dt) - return; - m_displayType = dt; - rebuildUi(); + if (m_displayType == dt) + return; + m_displayType = dt; + rebuildUi(); } bool LtsCoordWidget::withResetButton() const { - return m_bWithResetButton; + return m_bWithResetButton; } void LtsCoordWidget::setWithResetButton(bool bWith) { - if (m_bWithResetButton == bWith) - return; - m_bWithResetButton = bWith; - if (m_inputWidgetHandler) - m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); + if (m_bWithResetButton == bWith) + return; + m_bWithResetButton = bWith; + if (m_inputWidgetHandler) + m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); } bool LtsCoordWidget::showToolTip() const { - return m_bShowToolTip; + return m_bShowToolTip; } void LtsCoordWidget::setShowToolTip(bool bShow) { - if (m_bShowToolTip == bShow) - return; - m_bShowToolTip = bShow; + if (m_bShowToolTip == bShow) + return; + m_bShowToolTip = bShow; - updateToolTip(); + updateToolTip(); } bool LtsCoordWidget::mgrsSquareEditable() const { - return m_bMgrsSquareEditable; + return m_bMgrsSquareEditable; } void LtsCoordWidget::setMgrsSquareEditable(bool bEditable) { - if (m_bMgrsSquareEditable == bEditable) - return; - m_bMgrsSquareEditable = bEditable; - if (m_inputWidgetHandler) - m_inputWidgetHandler->setSquaresEditable(bEditable); + if (m_bMgrsSquareEditable == bEditable) + return; + m_bMgrsSquareEditable = bEditable; + if (m_inputWidgetHandler) + m_inputWidgetHandler->setSquaresEditable(bEditable); } void LtsCoordWidget::setWithSurroundingMgrsSquares(bool bEnable) { - if (m_inputWidgetHandler) - m_inputWidgetHandler->setWithSurroundingSquare(bEnable); + if (m_inputWidgetHandler) + m_inputWidgetHandler->setWithSurroundingSquare(bEnable); } -void LtsCoordWidget::setMgrsSquares(const QVector &geoCoords) +void LtsCoordWidget::setMgrsSquares(const QVector& geoCoords) { - if (m_inputWidgetHandler) - m_inputWidgetHandler->setMgrsSquares(geoCoords); + if (m_inputWidgetHandler) + m_inputWidgetHandler->setMgrsSquares(geoCoords); } - -bool LtsCoordWidget::event(QEvent *event) +bool LtsCoordWidget::event(QEvent* event) { - if (event->type() == QEvent::ToolTip) - updateToolTip(); - return QWidget::event(event); + if (event->type() == QEvent::ToolTip) + updateToolTip(); + return QWidget::event(event); } - void LtsCoordWidget::rebuildUi() { - - - - - if (m_inputWidgetHandler) - { - m_inputWidgetHandler->cleanup(); - delete m_inputWidgetHandler; - delete layout(); - } - switch (m_displayType) - { - case DisplayType::MGRS5: - m_inputWidgetHandler = new MgrsEdit(5, this); - break; - case DisplayType::MGRS7: - m_inputWidgetHandler = new MgrsEdit(7, this); - break; - case DisplayType::UTM: - - qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__); - break; - case DisplayType::WGS84: - m_inputWidgetHandler = new Wgs84Edit(this); - break; - } - if (!m_inputWidgetHandler) - return; + if (m_inputWidgetHandler) + { + m_inputWidgetHandler->cleanup(); + delete m_inputWidgetHandler; + delete layout(); + } - m_inputWidgetHandler->setSquaresEditable(m_bMgrsSquareEditable); - m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); - connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked, - this, &LtsCoordWidget::onResetToDefaultCoordinate); - connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged, - this, &LtsCoordWidget::coordinateChanged); - connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate, - this, &LtsCoordWidget::invalidCoordinate); - if (!m_defaultCoordinate.isNull()) - m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); + switch (m_displayType) + { + case DisplayType::MGRS5: + m_inputWidgetHandler = new MgrsEdit(5, this); + break; + case DisplayType::MGRS7: + m_inputWidgetHandler = new MgrsEdit(7, this); + break; + case DisplayType::UTM: + + qt_assert("DisplayType::UTM not yet implemented", __FILE__, __LINE__); + break; + case DisplayType::WGS84: + m_inputWidgetHandler = new Wgs84Edit(this); + break; + } + if (!m_inputWidgetHandler) + return; + + m_inputWidgetHandler->setSquaresEditable(m_bMgrsSquareEditable); + m_inputWidgetHandler->resetButton()->setVisible(m_bWithResetButton); + connect(m_inputWidgetHandler->resetButton(), &QToolButton::clicked, this, + &LtsCoordWidget::onResetToDefaultCoordinate); + connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::coordinateChanged, this, + &LtsCoordWidget::coordinateChanged); + connect(m_inputWidgetHandler, &LtsCoordInputWidgetHandler::invalidCoordinate, this, + &LtsCoordWidget::invalidCoordinate); + if (!m_defaultCoordinate.isNull()) + m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); } void LtsCoordWidget::updateToolTip() { - QString tt; - if (m_bShowToolTip) - { - const QPointF p(coordinate()); - if (!p.isNull()) + QString tt; + if (m_bShowToolTip) { - const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y()); - const QPointF p2(p * LtsCoordTrans::rad2deg()); - tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10); + const QPointF p(coordinate()); + if (!p.isNull()) + { + const QString mgrs = LtsCoordTrans::mgrsFromGeographic(p.x(), p.y()); + const QPointF p2(p * LtsCoordTrans::rad2deg()); + tt = tr("MGRS: %1\nlat/lon: %2/%3").arg(mgrs).arg(p2.y(), 0, 'f', 10).arg(p2.x(), 0, 'f', 10); + } } - } - setToolTip(tt); + setToolTip(tt); } - void LtsCoordWidget::onResetToDefaultCoordinate() { - if (!m_inputWidgetHandler) - return; - if (m_defaultCoordinate.isNull()) - m_inputWidgetHandler->clear(); - m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); + if (!m_inputWidgetHandler) + return; + if (m_defaultCoordinate.isNull()) + m_inputWidgetHandler->clear(); + m_inputWidgetHandler->setCoordinate(m_defaultCoordinate); } -} +} // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp old mode 100755 new mode 100644 index a4b890911..ebc7bbb86 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.cpp @@ -1,326 +1,301 @@ - #include "lts_coord_widget_p.h" -#include +#include namespace LtsCoordWidget { - - void LtsCoordInputWidgetHandler::onCoordinateDataChanged() { - const QPointF coord(coordinate()); - if (coord.isNull()) - { - emit invalidCoordinate(); - return; - } - emit coordinateChanged(coord); + const QPointF coord(coordinate()); + if (coord.isNull()) + { + emit invalidCoordinate(); + return; + } + emit coordinateChanged(coord); } - - - -MgrsEdit::MgrsEdit(int precision, QWidget *widget) - : LtsCoordInputWidgetHandler(widget) - , m_precision(precision) - , m_ui(new Ui::Mgrs) +MgrsEdit::MgrsEdit(int precision, QWidget* widget) + : LtsCoordInputWidgetHandler(widget), m_precision(precision), m_ui(new Ui::Mgrs) { - m_ui->setupUi(widget); + m_ui->setupUi(widget); - if (m_precision < 0) - m_precision = 0; - if (m_precision > 11) - m_precision = 11; - const int upperLimit = pow(10, m_precision) - 1; - m_ui->leEast->setValidator(new QIntValidator(0, upperLimit, m_ui->leEast)); - m_ui->leNorth->setValidator(new QIntValidator(0, upperLimit, m_ui->leNorth)); - setDefaultMgrsSquares(); + if (m_precision < 0) + m_precision = 0; + if (m_precision > 11) + m_precision = 11; + const int upperLimit = pow(10, m_precision) - 1; + m_ui->leEast->setValidator(new QIntValidator(0, upperLimit, m_ui->leEast)); + m_ui->leNorth->setValidator(new QIntValidator(0, upperLimit, m_ui->leNorth)); + setDefaultMgrsSquares(); - connect(m_ui->cbxZone, QOverload::of(&QComboBox::currentIndexChanged), - this, &MgrsEdit::onCoordinateDataChanged); - connect(m_ui->leEast, &QLineEdit::editingFinished, - this, &MgrsEdit::onCoordinateDataChanged); - connect(m_ui->leNorth, &QLineEdit::editingFinished, - this, &MgrsEdit::onCoordinateDataChanged); + connect(m_ui->cbxZone, QOverload::of(&QComboBox::currentIndexChanged), this, + &MgrsEdit::onCoordinateDataChanged); + connect(m_ui->leEast, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged); + connect(m_ui->leNorth, &QLineEdit::editingFinished, this, &MgrsEdit::onCoordinateDataChanged); } MgrsEdit::~MgrsEdit() { - delete m_ui; + delete m_ui; } bool MgrsEdit::isValid() { - - const QString &east = m_ui->leEast->text(); - if (east.size() != m_precision) - return false; - const QString &north = m_ui->leNorth->text(); - if (north.size() != m_precision) - return false; + const QString& east = m_ui->leEast->text(); + if (east.size() != m_precision) + return false; - if (m_ui->cbxZone->currentIndex() < 0) - return false; + const QString& north = m_ui->leNorth->text(); + if (north.size() != m_precision) + return false; - if (m_ui->cbxZone->currentText().isEmpty()) - return false; + if (m_ui->cbxZone->currentIndex() < 0) + return false; - return true; + if (m_ui->cbxZone->currentText().isEmpty()) + return false; + + return true; } -void MgrsEdit::setCoordinate(const QPointF &geoCoord) +void MgrsEdit::setCoordinate(const QPointF& geoCoord) { - const QString mgrsString = LtsCoordTrans::mgrsFromGeographic(geoCoord.x(), geoCoord.y(), m_precision, false); - if (mgrsString.isEmpty()) - { - m_ui->leEast->clear(); - m_ui->leNorth->clear(); - return; - } - - m_ui->leEast->setText(QString()); - m_ui->leNorth->setText(QString()); + const QString mgrsString = LtsCoordTrans::mgrsFromGeographic(geoCoord.x(), geoCoord.y(), m_precision, false); + if (mgrsString.isEmpty()) + { + m_ui->leEast->clear(); + m_ui->leNorth->clear(); + return; + } - - const QString mgrsSquare = mgrsString.left(3) + QLatin1Char(' ') + mgrsString.mid(3, 2); - QString east = mgrsString.mid(5, m_precision); - QString north = mgrsString.mid(5 + m_precision, m_precision); - int idx = m_ui->cbxZone->findText(mgrsSquare); - if (idx < 0) - { - addMgrsSquare(mgrsSquare); - idx = m_ui->cbxZone->findText(mgrsSquare); - } - m_ui->cbxZone->setCurrentIndex(idx); - m_ui->leEast->setText(east); - m_ui->leNorth->setText(north); + m_ui->leEast->setText(QString()); + m_ui->leNorth->setText(QString()); + + const QString mgrsSquare = mgrsString.left(3) + QLatin1Char(' ') + mgrsString.mid(3, 2); + QString east = mgrsString.mid(5, m_precision); + QString north = mgrsString.mid(5 + m_precision, m_precision); + int idx = m_ui->cbxZone->findText(mgrsSquare); + if (idx < 0) + { + addMgrsSquare(mgrsSquare); + idx = m_ui->cbxZone->findText(mgrsSquare); + } + m_ui->cbxZone->setCurrentIndex(idx); + m_ui->leEast->setText(east); + m_ui->leNorth->setText(north); } -static inline QString getMgrsCoord(QLineEdit *le, int prec) +static inline QString getMgrsCoord(QLineEdit* le, int prec) { - QString ret = le->text(); - if (ret.isEmpty()) + QString ret = le->text(); + if (ret.isEmpty()) + return ret; + while (ret.size() < prec) + ret += QLatin1Char('0'); + le->setText(ret); return ret; - while (ret.size() < prec) - ret += QLatin1Char('0'); - le->setText(ret); - return ret; } QPointF MgrsEdit::coordinate() const { - const QString east = getMgrsCoord(m_ui->leEast, m_precision); - const QString north = getMgrsCoord(m_ui->leNorth, m_precision); - if (east.isEmpty() || north.isEmpty() || m_ui->cbxZone->currentIndex() < 0) - return QPointF(); + const QString east = getMgrsCoord(m_ui->leEast, m_precision); + const QString north = getMgrsCoord(m_ui->leNorth, m_precision); + if (east.isEmpty() || north.isEmpty() || m_ui->cbxZone->currentIndex() < 0) + return QPointF(); - const QString mgrsString(m_ui->cbxZone->currentText() + east + north); - return LtsCoordTrans::geographicFromMgrs(mgrsString); + const QString mgrsString(m_ui->cbxZone->currentText() + east + north); + return LtsCoordTrans::geographicFromMgrs(mgrsString); } -QToolButton *MgrsEdit::resetButton() +QToolButton* MgrsEdit::resetButton() { - return m_ui->tbReset; + return m_ui->tbReset; } void MgrsEdit::cleanup() { - - - delete m_ui->horizontalLayout; - delete m_ui->cbxZone; - delete m_ui->leEast; - delete m_ui->leNorth; - delete m_ui->tbReset; + + delete m_ui->horizontalLayout; + delete m_ui->cbxZone; + delete m_ui->leEast; + delete m_ui->leNorth; + delete m_ui->tbReset; } void MgrsEdit::clear() { - m_ui->cbxZone->clear(); - m_ui->leEast->clear(); - m_ui->leNorth->clear(); - setDefaultMgrsSquares(); + m_ui->cbxZone->clear(); + m_ui->leEast->clear(); + m_ui->leNorth->clear(); + setDefaultMgrsSquares(); } void MgrsEdit::setSquaresEditable(bool bEditable) { - m_ui->cbxZone->setEditable(bEditable); + m_ui->cbxZone->setEditable(bEditable); } void MgrsEdit::setWithSurroundingSquare(bool bEnabled) { - m_withMgrsSquareOffset = bEnabled; + m_withMgrsSquareOffset = bEnabled; } static QStringList defaultMgrsSquares() { - const QVector squares(LtsCoordTrans::defaultMgrsSquares()); - QStringList sl; - sl.reserve(squares.size()); - for (const LtsCoordTrans::UtmCoordinate &c : squares) - sl += c.mgrs(0); - std::sort(sl.begin(), sl.end()); - return sl; + const QVector squares(LtsCoordTrans::defaultMgrsSquares()); + QStringList sl; + sl.reserve(squares.size()); + for (const LtsCoordTrans::UtmCoordinate& c : squares) + sl += c.mgrs(0); + std::sort(sl.begin(), sl.end()); + return sl; } static QString preferedMgrsSquare() { - const LtsCoordTrans::UtmCoordinate c(LtsCoordTrans::preferedMgrsSquare()); - return c.mgrs(0); + const LtsCoordTrans::UtmCoordinate c(LtsCoordTrans::preferedMgrsSquare()); + return c.mgrs(0); } - void MgrsEdit::setDefaultMgrsSquares() { - m_ui->cbxZone->addItems(defaultMgrsSquares()); - m_ui->cbxZone->setCurrentIndex(m_ui->cbxZone->findText(preferedMgrsSquare())); + m_ui->cbxZone->addItems(defaultMgrsSquares()); + m_ui->cbxZone->setCurrentIndex(m_ui->cbxZone->findText(preferedMgrsSquare())); } -void MgrsEdit::addMgrsSquare(const QString &newMgrsSquare) +void MgrsEdit::addMgrsSquare(const QString& newMgrsSquare) { - QStringList sl = defaultMgrsSquares(); - sl += newMgrsSquare; - if (m_withMgrsSquareOffset) - { - QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets()); - - for (const auto &sq : std::as_const(squares)) - if (!sl.contains(sq)) - sl.append(sq); - } - std::sort(sl.begin(), sl.end()); - m_ui->cbxZone->clear(); - m_ui->cbxZone->addItems(sl); + QStringList sl = defaultMgrsSquares(); + sl += newMgrsSquare; + if (m_withMgrsSquareOffset) + { + QStringList squares = utmCoordsToList(LtsCoordTrans::defaultMgrsSquareWithOffsets()); + + for (const auto& sq : std::as_const(squares)) + if (!sl.contains(sq)) + sl.append(sq); + } + std::sort(sl.begin(), sl.end()); + m_ui->cbxZone->clear(); + m_ui->cbxZone->addItems(sl); } -QStringList MgrsEdit::utmCoordsToList(const QVector &coords) +QStringList MgrsEdit::utmCoordsToList(const QVector& coords) { - QStringList list; - list.reserve(coords.count()); - for (const auto &utm : coords) - list.append(utm.mgrs(0)); + QStringList list; + list.reserve(coords.count()); + for (const auto& utm : coords) + list.append(utm.mgrs(0)); - return list; + return list; } -void MgrsEdit::setMgrsSquares(const QVector &geoCoords) +void MgrsEdit::setMgrsSquares(const QVector& geoCoords) { - QStringList sl = utmCoordsToList(geoCoords); - if (sl.isEmpty()) - return; + QStringList sl = utmCoordsToList(geoCoords); + if (sl.isEmpty()) + return; - std::sort(sl.begin(), sl.end()); - m_ui->cbxZone->clear(); - m_ui->cbxZone->addItems(sl); + std::sort(sl.begin(), sl.end()); + m_ui->cbxZone->clear(); + m_ui->cbxZone->addItems(sl); } - - - -Wgs84Edit::Wgs84Edit(QWidget *widget) - : LtsCoordInputWidgetHandler(widget) - , m_ui(new Ui::Wgs84) +Wgs84Edit::Wgs84Edit(QWidget* widget) : LtsCoordInputWidgetHandler(widget), m_ui(new Ui::Wgs84) { - m_ui->setupUi(widget); + m_ui->setupUi(widget); - DoubleValidator *v = new DoubleValidator(-180, 180, 9, m_ui->leLon); - v->setNotation(QDoubleValidator::StandardNotation); - m_ui->leLon->setValidator(v); + DoubleValidator* v = new DoubleValidator(-180, 180, 9, m_ui->leLon); + v->setNotation(QDoubleValidator::StandardNotation); + m_ui->leLon->setValidator(v); - v = new DoubleValidator(-180, 180, 9, m_ui->leLat); - v->setNotation(QDoubleValidator::StandardNotation); - m_ui->leLat->setValidator(v); + v = new DoubleValidator(-180, 180, 9, m_ui->leLat); + v->setNotation(QDoubleValidator::StandardNotation); + m_ui->leLat->setValidator(v); - connect(m_ui->leLon, &QLineEdit::editingFinished, - this, &Wgs84Edit::onCoordinateDataChanged); - connect(m_ui->leLat, &QLineEdit::editingFinished, - this, &Wgs84Edit::onCoordinateDataChanged); + connect(m_ui->leLon, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged); + connect(m_ui->leLat, &QLineEdit::editingFinished, this, &Wgs84Edit::onCoordinateDataChanged); } Wgs84Edit::~Wgs84Edit() { - delete m_ui; + delete m_ui; } bool Wgs84Edit::isValid() { - - return (!m_ui->leLon->text().isEmpty()) && (!m_ui->leLat->text().isEmpty()); + + return (!m_ui->leLon->text().isEmpty()) && (!m_ui->leLat->text().isEmpty()); } -void Wgs84Edit::setCoordinate(const QPointF &geoCoord) +void Wgs84Edit::setCoordinate(const QPointF& geoCoord) { - const QPointF coord(geoCoord * LtsCoordTrans::rad2deg()); - const QLocale l; - m_ui->leLon->setText(l.toString(coord.x(), 'f', 9)); - m_ui->leLat->setText(l.toString(coord.y(), 'f', 9)); + const QPointF coord(geoCoord * LtsCoordTrans::rad2deg()); + const QLocale l; + m_ui->leLon->setText(l.toString(coord.x(), 'f', 9)); + m_ui->leLat->setText(l.toString(coord.y(), 'f', 9)); } QPointF Wgs84Edit::coordinate() const { - QPointF ret; - const QLocale l; - - - const QString lonStr = m_ui->leLon->text().remove(l.groupSeparator()); - const QString latStr = m_ui->leLat->text().remove(l.groupSeparator()); - if (lonStr.isEmpty() || latStr.isEmpty()) - return ret; + QPointF ret; + const QLocale l; - ret.rx() = l.toDouble(lonStr); - ret.ry() = l.toDouble(latStr); + const QString lonStr = m_ui->leLon->text().remove(l.groupSeparator()); + const QString latStr = m_ui->leLat->text().remove(l.groupSeparator()); + if (lonStr.isEmpty() || latStr.isEmpty()) + return ret; - return ret * LtsCoordTrans::deg2rad(); + ret.rx() = l.toDouble(lonStr); + ret.ry() = l.toDouble(latStr); + + return ret * LtsCoordTrans::deg2rad(); } -QToolButton *Wgs84Edit::resetButton() +QToolButton* Wgs84Edit::resetButton() { - return m_ui->tbReset; + return m_ui->tbReset; } void Wgs84Edit::cleanup() { - - - delete m_ui->horizontalLayout; - delete m_ui->leLon; - delete m_ui->leLat; - delete m_ui->tbReset; - delete m_ui->lblLon; - delete m_ui->lblLat; + + delete m_ui->horizontalLayout; + delete m_ui->leLon; + delete m_ui->leLat; + delete m_ui->tbReset; + delete m_ui->lblLon; + delete m_ui->lblLat; } void Wgs84Edit::clear() { - m_ui->leLon->clear(); - m_ui->leLat->clear(); + m_ui->leLon->clear(); + m_ui->leLat->clear(); } - - - -DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject *parent) - : QDoubleValidator(bottom, top, decimals, parent) -{} - -QValidator::State DoubleValidator::validate(QString &input, int &pos) const +DoubleValidator::DoubleValidator(double bottom, double top, int decimals, QObject* parent) + : QDoubleValidator(bottom, top, decimals, parent) { - const QValidator::State ret = QDoubleValidator::validate(input, pos); - if (ret != QValidator::Acceptable) - return ret; - QLocale l; - const QChar gs = l.groupSeparator().at(0); - if (gs.isNull()) - return ret; - if (input.contains(gs)) - return QValidator::Invalid; - return ret; } -} +QValidator::State DoubleValidator::validate(QString& input, int& pos) const +{ + const QValidator::State ret = QDoubleValidator::validate(input, pos); + if (ret != QValidator::Acceptable) + return ret; + QLocale l; + const QChar gs = l.groupSeparator().at(0); + if (gs.isNull()) + return ret; + if (input.contains(gs)) + return QValidator::Invalid; + return ret; +} +} // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h old mode 100755 new mode 100644 index c6ebfc2d7..57f6f090c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_p.h @@ -2,93 +2,106 @@ #pragma once -#include -#include -#include -#include -#include - #include "ui_lts_coord_widget_mgrs.h" #include "ui_lts_coord_widget_wgs84.h" +#include +#include +#include +#include +#include + namespace LtsCoordWidget { class LtsCoordInputWidgetHandler : public QObject { - Q_OBJECT -public: - explicit LtsCoordInputWidgetHandler(QObject *parent) - : QObject(parent) - {} + Q_OBJECT + public: + explicit LtsCoordInputWidgetHandler(QObject* parent) : QObject(parent) {} - virtual bool isValid() = 0; - virtual void setCoordinate(const QPointF &geoCoord) = 0; - virtual QPointF coordinate() const = 0; - virtual QToolButton *resetButton() = 0; - virtual void cleanup() = 0; - virtual void clear() = 0; - virtual void setSquaresEditable(bool bEditable) = 0; - virtual void setWithSurroundingSquare(bool bEnabled) = 0; - virtual void setMgrsSquares(const QVector &geoCoords) = 0; -protected Q_SLOTS: - void onCoordinateDataChanged(); -Q_SIGNALS: - void coordinateChanged(const QPointF &newGeoCoord); - void invalidCoordinate(); + virtual bool isValid() = 0; + virtual void setCoordinate(const QPointF& geoCoord) = 0; + virtual QPointF coordinate() const = 0; + virtual QToolButton* resetButton() = 0; + virtual void cleanup() = 0; + virtual void clear() = 0; + virtual void setSquaresEditable(bool bEditable) = 0; + virtual void setWithSurroundingSquare(bool bEnabled) = 0; + virtual void setMgrsSquares(const QVector& geoCoords) = 0; + protected Q_SLOTS: + void onCoordinateDataChanged(); + Q_SIGNALS: + void coordinateChanged(const QPointF& newGeoCoord); + void invalidCoordinate(); }; class MgrsEdit final : public LtsCoordInputWidgetHandler { - Q_OBJECT -public: - explicit MgrsEdit(int precision, QWidget *widget); - ~MgrsEdit(); + Q_OBJECT + public: + explicit MgrsEdit(int precision, QWidget* widget); + ~MgrsEdit(); - bool isValid() override; - void setCoordinate(const QPointF &geoCoord) override; - QPointF coordinate() const override; - QToolButton *resetButton() override; - void cleanup() override; - void clear() override; - void setSquaresEditable(bool bEditable) override; - void setWithSurroundingSquare(bool bEnabled) override; - void setMgrsSquares(const QVector &geoCoords) override; -private: - void setDefaultMgrsSquares(); - void addMgrsSquare(const QString &newMgrsSquare); - QStringList utmCoordsToList(const QVector &coords); -private: - int m_precision; - bool m_withMgrsSquareOffset=false; - Ui::Mgrs *m_ui; + bool isValid() override; + void setCoordinate(const QPointF& geoCoord) override; + QPointF coordinate() const override; + QToolButton* resetButton() override; + void cleanup() override; + void clear() override; + void setSquaresEditable(bool bEditable) override; + void setWithSurroundingSquare(bool bEnabled) override; + void setMgrsSquares(const QVector& geoCoords) override; + + private: + void setDefaultMgrsSquares(); + void addMgrsSquare(const QString& newMgrsSquare); + QStringList utmCoordsToList(const QVector& coords); + + private: + int m_precision; + bool m_withMgrsSquareOffset = false; + Ui::Mgrs* m_ui; }; class Wgs84Edit final : public LtsCoordInputWidgetHandler { - Q_OBJECT -public: - explicit Wgs84Edit(QWidget *widget); - ~Wgs84Edit(); + Q_OBJECT + public: + explicit Wgs84Edit(QWidget* widget); + ~Wgs84Edit(); - bool isValid() override; - void setCoordinate(const QPointF &geoCoord) override; - QPointF coordinate() const override; - QToolButton *resetButton() override; - void cleanup() override; - void clear() override; - void setSquaresEditable(bool bEditable) override { Q_UNUSED(bEditable); } - void setWithSurroundingSquare(bool bEnabled) override { Q_UNUSED(bEnabled); } - void setMgrsSquares(const QVector &geoCoords) override { Q_UNUSED(geoCoords); } -private: - Ui::Wgs84 *m_ui; + bool isValid() override; + void setCoordinate(const QPointF& geoCoord) override; + QPointF coordinate() const override; + QToolButton* resetButton() override; + void cleanup() override; + void clear() override; + + void setSquaresEditable(bool bEditable) override + { + Q_UNUSED(bEditable); + } + + void setWithSurroundingSquare(bool bEnabled) override + { + Q_UNUSED(bEnabled); + } + + void setMgrsSquares(const QVector& geoCoords) override + { + Q_UNUSED(geoCoords); + } + + private: + Ui::Wgs84* m_ui; }; class DoubleValidator final : public QDoubleValidator { - Q_OBJECT -public: - DoubleValidator(double bottom, double top, int decimals, QObject *parent = nullptr); + Q_OBJECT + public: + DoubleValidator(double bottom, double top, int decimals, QObject* parent = nullptr); - QValidator::State validate(QString &input, int &pos) const override; + QValidator::State validate(QString& input, int& pos) const override; }; -} +} // namespace LtsCoordWidget diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp old mode 100755 new mode 100644 index e9ae4075f..8aea4c88f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/lts_coord_widget_test.cpp @@ -1,115 +1,106 @@ - -#include -#include -#include -#include -#include -#include #include "lts_coord_widget.h" -static void updateLabel(const QPointF &coord, QLabel *lbl, int prec) +#include +#include +#include +#include +#include +#include + +static void updateLabel(const QPointF& coord, QLabel* lbl, int prec) { - QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec); - QString str = QStringLiteral("mgrs: %1, lon: %2, lat: %3") - .arg(mgrs) - .arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10) - .arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10); - lbl->setText(str); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(coord.x(), coord.y(), prec); + QString str = QStringLiteral("mgrs: %1, lon: %2, lat: %3") + .arg(mgrs) + .arg(coord.x() * LtsCoordTrans::rad2deg(), 0, 'f', 10) + .arg(coord.y() * LtsCoordTrans::rad2deg(), 0, 'f', 10); + lbl->setText(str); } -int main(int argc, char **argv) +int main(int argc, char** argv) { - QApplication app(argc, argv); + QApplication app(argc, argv); - LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00"))); - QPointF topLeft(base.geographic(+50000, -50000)); - QPointF bottomRight(base.geographic(-50000, 50000)); - LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true); + LtsCoordTrans::UtmCoordinate base(LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32UMD00"))); + QPointF topLeft(base.geographic(+50000, -50000)); + QPointF bottomRight(base.geographic(-50000, 50000)); + LtsCoordTrans::getMgrsSquares(QRectF(topLeft, bottomRight), true, true); - QDialog *dialog(new QDialog); - QVBoxLayout *lay(new QVBoxLayout(dialog)); + QDialog* dialog(new QDialog); + QVBoxLayout* lay(new QVBoxLayout(dialog)); + const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad()); - const QPointF defCoord(QPointF(53.0, 8.0) * LtsCoordTrans::deg2rad()); - - LtsCoordWidget::LtsCoordWidget *wMgrs5(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog)); - wMgrs5->setWithResetButton(true); - wMgrs5->setCoordinate(defCoord, true); - lay->addWidget(wMgrs5); - QLabel *lbl5(new QLabel(dialog)); - lay->addWidget(lbl5); - QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, - lbl5, [lbl5](const QPointF & coord) - { - updateLabel(coord, lbl5, 5); - }); + LtsCoordWidget::LtsCoordWidget* wMgrs5( + new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog)); + wMgrs5->setWithResetButton(true); + wMgrs5->setCoordinate(defCoord, true); + lay->addWidget(wMgrs5); + QLabel* lbl5(new QLabel(dialog)); + lay->addWidget(lbl5); + QObject::connect(wMgrs5, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, lbl5, + [lbl5](const QPointF& coord) { updateLabel(coord, lbl5, 5); }); - - LtsCoordWidget::LtsCoordWidget *wMgrs7(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog)); - wMgrs7->setWithResetButton(true); - wMgrs7->setCoordinate(defCoord, true); - lay->addWidget(wMgrs7); - QLabel *lbl7(new QLabel(dialog)); - lay->addWidget(lbl7); - QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, - wMgrs7, [lbl7](const QPointF & coord) - { - updateLabel(coord, lbl7, 7); - }); + LtsCoordWidget::LtsCoordWidget* wMgrs7( + new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7, dialog)); + wMgrs7->setWithResetButton(true); + wMgrs7->setCoordinate(defCoord, true); + lay->addWidget(wMgrs7); + QLabel* lbl7(new QLabel(dialog)); + lay->addWidget(lbl7); + QObject::connect(wMgrs7, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, wMgrs7, + [lbl7](const QPointF& coord) { updateLabel(coord, lbl7, 7); }); - - LtsCoordWidget::LtsCoordWidget *w84(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); - w84->setWithResetButton(true); - w84->setCoordinate(defCoord, true); - lay->addWidget(w84); - QLabel *lbl84(new QLabel(dialog)); - lay->addWidget(lbl84); - QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, - w84, [lbl84](const QPointF & coord) - { - updateLabel(coord, lbl84, 11); - }); + LtsCoordWidget::LtsCoordWidget* w84( + new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); + w84->setWithResetButton(true); + w84->setCoordinate(defCoord, true); + lay->addWidget(w84); + QLabel* lbl84(new QLabel(dialog)); + lay->addWidget(lbl84); + QObject::connect(w84, &LtsCoordWidget::LtsCoordWidget::coordinateChanged, w84, + [lbl84](const QPointF& coord) { updateLabel(coord, lbl84, 11); }); - - QHBoxLayout *hLay = new QHBoxLayout; - lay->addLayout(hLay); - LtsCoordWidget::LtsCoordWidget *wChange(new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); - wChange->setWithResetButton(true); - wChange->setCoordinate(defCoord, true); - hLay->addWidget(wChange); - QPushButton *pbReset(new QPushButton(QStringLiteral("With Reset"), dialog)); - hLay->addWidget(pbReset); - QObject::connect(pbReset, &QPushButton::clicked, - wChange, [wChange]() { wChange->setWithResetButton(!wChange->withResetButton());}); - QPushButton *pbNext(new QPushButton(QStringLiteral("Next Type"), dialog)); - hLay->addWidget(pbNext); - QObject::connect(pbNext, &QPushButton::clicked, - wChange, [wChange]() - { - LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType(); - switch (dt) - { - case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7; break; - case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84; break; - case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84: - dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5; break; - default: - break; - } - wChange->setDisplayType(dt); - }); + QHBoxLayout* hLay = new QHBoxLayout; + lay->addLayout(hLay); + LtsCoordWidget::LtsCoordWidget* wChange( + new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84, dialog)); + wChange->setWithResetButton(true); + wChange->setCoordinate(defCoord, true); + hLay->addWidget(wChange); + QPushButton* pbReset(new QPushButton(QStringLiteral("With Reset"), dialog)); + hLay->addWidget(pbReset); + QObject::connect(pbReset, &QPushButton::clicked, wChange, + [wChange]() { wChange->setWithResetButton(!wChange->withResetButton()); }); + QPushButton* pbNext(new QPushButton(QStringLiteral("Next Type"), dialog)); + hLay->addWidget(pbNext); + QObject::connect(pbNext, &QPushButton::clicked, wChange, [wChange]() { + LtsCoordWidget::LtsCoordWidget::DisplayType dt = wChange->displayType(); + switch (dt) + { + case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7; + break; + case LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS7: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84; + break; + case LtsCoordWidget::LtsCoordWidget::DisplayType::WGS84: + dt = LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS5; + break; + default: + break; + } + wChange->setDisplayType(dt); + }); + QPushButton* pb(new QPushButton(QStringLiteral("Quit"), dialog)); + lay->addWidget(pb); + QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit); - QPushButton *pb(new QPushButton(QStringLiteral("Quit"), dialog)); - lay->addWidget(pb); - QObject::connect(pb, &QPushButton::clicked, qApp, QCoreApplication::quit); - - dialog->show(); - int ret = app.exec(); - delete dialog; - return ret; + dialog->show(); + int ret = app.exec(); + delete dialog; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp old mode 100755 new mode 100644 index b74e2b10f..d15a8b78e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordTrans/mgrs2lonlat.cpp @@ -1,45 +1,44 @@ - -#include #include +#include #include -int main(int argc, char **argv) +int main(int argc, char** argv) { - if (argc != 2) - { - fprintf(stderr, "Usage: %s \n", argv[0]); - return -1; - } + if (argc != 2) + { + fprintf(stderr, "Usage: %s \n", argv[0]); + return -1; + } - std::string mgrs = argv[1]; - mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end()); + std::string mgrs = argv[1]; + mgrs.erase(remove_if(mgrs.begin(), mgrs.end(), isspace), mgrs.end()); - int prec; - double lonDeg, latDeg; - try - { - int zone; - bool northp; - double x, y; - GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true); - GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg); + int prec; + double lonDeg, latDeg; + try + { + int zone; + bool northp; + double x, y; + GeographicLib::MGRS::Reverse(mgrs, zone, northp, x, y, prec, true); + GeographicLib::UTMUPS::Reverse(zone, northp, x, y, latDeg, lonDeg); - GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); - GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); - } - catch (...) - { - fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str()); - return -2; - } - std::string part1, part2, part3, part4; - part1 = mgrs.substr(0, 3); - part2 = mgrs.substr(3, 2); - part3 = mgrs.substr(5, prec); - part4 = mgrs.substr(5 + prec, prec); - fprintf(stdout, "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", - part1.c_str(), part2.c_str(), part3.c_str(), part4.c_str(), lonDeg, latDeg, lonDeg / 180. * M_PI, latDeg / 180. * M_PI); - return 0; + GeographicLib::UTMUPS::Forward(latDeg, lonDeg, zone, northp, x, y); + GeographicLib::MGRS::Forward(zone, northp, x, y, prec, mgrs); + } + catch (...) + { + fprintf(stderr, "Error converting %s to Lon/Lat coords\n", mgrs.c_str()); + return -2; + } + std::string part1, part2, part3, part4; + part1 = mgrs.substr(0, 3); + part2 = mgrs.substr(3, 2); + part3 = mgrs.substr(5, prec); + part4 = mgrs.substr(5 + prec, prec); + fprintf(stdout, "%s %s %s %s = %13.10f, %13.10f ( %13.10f, %13.10f )\n", part1.c_str(), part2.c_str(), + part3.c_str(), part4.c_str(), lonDeg, latDeg, lonDeg / 180. * M_PI, latDeg / 180. * M_PI); + return 0; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.cpp old mode 100755 new mode 100644 index e5dc118ab..73a8f42b4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.cpp @@ -1,971 +1,868 @@ - #include "lts_coordinate_unit_test.h" -#include -#include -#include #include - -#include +#include +#include +#include #include #include - +#include Q_DECLARE_METATYPE(LtsUtils::QPoint3D); - -#include #include +#include -static const int s_id{4711}; -static LtsElevation::LtsElevationManager *s_eleMgr{nullptr}; - - - - - - +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); - } + using BaseClass = LtsElevation::LtsElevationManager; + public: + static LtsElevationManager* createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine) + { + return BaseClass::createInstanceUnitTest(id, filePaths_rough_to_fine); + } }; - - - UnitTestCoordinate::UnitTestCoordinate() - : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestCoordinate")) -{} - + : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestCoordinate")) +{ +} void UnitTestCoordinate::initTestCase() { - - QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif")); + QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif")); - s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath}); + s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath}); - const bool bIsValid = s_eleMgr->isValid(); - std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl; - - - { - s_eleMgr->waitForInitialization(); const bool bIsValid = s_eleMgr->isValid(); - std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl; - } + std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl; - QVERIFY2(s_eleMgr , "static LtsElevationManager does not exist"); + { + s_eleMgr->waitForInitialization(); + const bool bIsValid = s_eleMgr->isValid(); + std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl; + } - - - - using namespace std::placeholders; - LtsCoordTrans::LtsCoordinate::elevationCbFunc elevationCB = std::bind(&LtsElevation::LtsElevationManager::elevation, - s_eleMgr, _1, _2, _3, _4); - LtsCoordTrans::LtsCoordinate::setElevationCallback(elevationCB); + QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist"); - QVERIFY2(LtsCoordTrans::LtsCoordinate::hasElevationCallback() , "setElevationCallback failed"); + using namespace std::placeholders; + LtsCoordTrans::LtsCoordinate::elevationCbFunc elevationCB = + std::bind(&LtsElevation::LtsElevationManager::elevation, s_eleMgr, _1, _2, _3, _4); + LtsCoordTrans::LtsCoordinate::setElevationCallback(elevationCB); + + QVERIFY2(LtsCoordTrans::LtsCoordinate::hasElevationCallback(), "setElevationCallback failed"); } void UnitTestCoordinate::init() { - QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist"); - QVERIFY2(LtsCoordTrans::LtsCoordinate::hasElevationCallback() , "setElevationCallback failed"); + QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist"); + QVERIFY2(LtsCoordTrans::LtsCoordinate::hasElevationCallback(), "setElevationCallback failed"); } void UnitTestCoordinate::test_NaN() { - bool equal = qFuzzyCompare(std::nan(""), std::nan("")); - NOTICE_LOG(m_logger) << " qFuzzyCompare(NaN, NaN) = " << equal; + bool equal = qFuzzyCompare(std::nan(""), std::nan("")); + NOTICE_LOG(m_logger) << " qFuzzyCompare(NaN, NaN) = " << equal; - - QVERIFY2(equal == false, "qFuzzyCompare(NaN, NaN) failed"); + QVERIFY2(equal == false, "qFuzzyCompare(NaN, NaN) failed"); } void UnitTestCoordinate::test_coordinate_simple1() { - LtsCoordTrans::LtsCoordinate ltsCoord; + LtsCoordTrans::LtsCoordinate ltsCoord; - QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); + QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); - const Core::GeoPosition &geoPos = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; - QVERIFY2(qFuzzyIsNull(geoPos.lon()) , "geoPosition failed"); - QVERIFY2(qFuzzyIsNull(geoPos.lat()) , "geoPosition failed"); - QVERIFY2(std::isnan( geoPos.z() ) , "geoPosition failed"); + const Core::GeoPosition& geoPos = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; + QVERIFY2(qFuzzyIsNull(geoPos.lon()), "geoPosition failed"); + QVERIFY2(qFuzzyIsNull(geoPos.lat()), "geoPosition failed"); + QVERIFY2(std::isnan(geoPos.z()), "geoPosition failed"); - const QPointF &utm = ltsCoord.toUtmPointF(); - const QPointF &utm2 = ltsCoord.toUtm(); - const LtsCoordTrans::UtmCoordinate3D &utm3D = ltsCoord.toUtmCoordinate3D(); - NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; - NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm2; - NOTICE_LOG(m_logger) << " UtmCoordinate3D = " << utm3D; + const QPointF& utm = ltsCoord.toUtmPointF(); + const QPointF& utm2 = ltsCoord.toUtm(); + const LtsCoordTrans::UtmCoordinate3D& utm3D = ltsCoord.toUtmCoordinate3D(); + NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; + NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm2; + NOTICE_LOG(m_logger) << " UtmCoordinate3D = " << utm3D; - QVERIFY2(qFuzzyCompare(utm3D.x, 166021.44308053952), "data no equal"); - QVERIFY2(qFuzzyCompare(utm3D.y, 0.0 ), "data no equal"); - QVERIFY2( utm3D.zone == 31 , "data no equal"); - QVERIFY2(utm == utm2 , "data no equal"); + QVERIFY2(qFuzzyCompare(utm3D.x, 166021.44308053952), "data no equal"); + QVERIFY2(qFuzzyCompare(utm3D.y, 0.0), "data no equal"); + QVERIFY2(utm3D.zone == 31, "data no equal"); + QVERIFY2(utm == utm2, "data no equal"); - const Core::GeoPosition &geoPos2 = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition2 = " << geoPos2; - QVERIFY2(qFuzzyIsNull(geoPos2.lon()) , "geoPosition2 failed"); - QVERIFY2(qFuzzyIsNull(geoPos2.lat()) , "geoPosition2 failed"); - QVERIFY2(std::isnan( geoPos2.z() ) , "geoPosition2 failed"); + const Core::GeoPosition& geoPos2 = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition2 = " << geoPos2; + QVERIFY2(qFuzzyIsNull(geoPos2.lon()), "geoPosition2 failed"); + QVERIFY2(qFuzzyIsNull(geoPos2.lat()), "geoPosition2 failed"); + QVERIFY2(std::isnan(geoPos2.z()), "geoPosition2 failed"); } void UnitTestCoordinate::test_coordinate_simple2() { - Core::GeoPosition defaultGeoPos; - LtsCoordTrans::LtsCoordinate ltsCoord(defaultGeoPos); + Core::GeoPosition defaultGeoPos; + LtsCoordTrans::LtsCoordinate ltsCoord(defaultGeoPos); - QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); + QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); - const Core::GeoPosition &geoPos = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; - QVERIFY2(qFuzzyIsNull(geoPos.lon()) , "geoPosition failed"); - QVERIFY2(qFuzzyIsNull(geoPos.lat()) , "geoPosition failed"); - QVERIFY2(qFuzzyIsNull(geoPos.z() ) , "geoPosition failed"); + const Core::GeoPosition& geoPos = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; + QVERIFY2(qFuzzyIsNull(geoPos.lon()), "geoPosition failed"); + QVERIFY2(qFuzzyIsNull(geoPos.lat()), "geoPosition failed"); + QVERIFY2(qFuzzyIsNull(geoPos.z()), "geoPosition failed"); - const QPointF &utm = ltsCoord.toUtm(); - NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; + const QPointF& utm = ltsCoord.toUtm(); + NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; - - const Core::GeoPosition &geoPos2 = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition2 = " << geoPos2; - QVERIFY2(qFuzzyIsNull(geoPos2.lon()) , "geoPosition2 failed"); - QVERIFY2(qFuzzyIsNull(geoPos2.lat()) , "geoPosition2 failed"); - QVERIFY2(qFuzzyIsNull(geoPos2.z() ) , "geoPosition2 failed"); + const Core::GeoPosition& geoPos2 = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition2 = " << geoPos2; + QVERIFY2(qFuzzyIsNull(geoPos2.lon()), "geoPosition2 failed"); + QVERIFY2(qFuzzyIsNull(geoPos2.lat()), "geoPosition2 failed"); + QVERIFY2(qFuzzyIsNull(geoPos2.z()), "geoPosition2 failed"); } void UnitTestCoordinate::test_coordinate_simple3() { - static const Core::GeoPosition s_invalidPos(std::nan(""), std::nan(""), std::nan("")); + static const Core::GeoPosition s_invalidPos(std::nan(""), std::nan(""), std::nan("")); - - LtsCoordTrans::LtsCoordinate ltsCoord(s_invalidPos); + LtsCoordTrans::LtsCoordinate ltsCoord(s_invalidPos); - QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); + QVERIFY2(ltsCoord.isValid() == false, "isValid failed"); - const Core::GeoPosition &geoPos = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; - QVERIFY2(std::isnan(geoPos.lon()) , "geoPosition failed"); - QVERIFY2(std::isnan(geoPos.lat()) , "geoPosition failed"); - QVERIFY2(std::isnan(geoPos.z()) , "geoPosition failed"); + const Core::GeoPosition& geoPos = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; + QVERIFY2(std::isnan(geoPos.lon()), "geoPosition failed"); + QVERIFY2(std::isnan(geoPos.lat()), "geoPosition failed"); + QVERIFY2(std::isnan(geoPos.z()), "geoPosition failed"); - const QPointF &utm = ltsCoord.toUtm(); - NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; - QVERIFY2(utm.isNull() , "utm failed"); + const QPointF& utm = ltsCoord.toUtm(); + NOTICE_LOG(m_logger) << " utmCoordinateAsPointF = " << utm; + QVERIFY2(utm.isNull(), "utm failed"); } void UnitTestCoordinate::test_coordinate_simple4() { - LtsCoordTrans::LtsCoordinate::resetConversionCounter(); - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 0, "getConversionCounter failed"); + LtsCoordTrans::LtsCoordinate::resetConversionCounter(); + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 0, "getConversionCounter failed"); - const LtsCoordTrans::UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const double zValue = 2.3; + const LtsCoordTrans::UtmCoordinate& utmIn = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const double zValue = 2.3; - const LtsCoordTrans::LtsCoordinate ltsCoord(utmIn.geographic(), zValue); + const LtsCoordTrans::LtsCoordinate ltsCoord(utmIn.geographic(), zValue); - + const LtsCoordTrans::UtmCoordinate& utmCoord_FirstTry = ltsCoord.utmCoordinate(); + Q_UNUSED(utmCoord_FirstTry); + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); - const LtsCoordTrans::UtmCoordinate &utmCoord_FirstTry = ltsCoord.utmCoordinate(); - Q_UNUSED(utmCoord_FirstTry); - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); + const LtsCoordTrans::UtmCoordinate& utmCoord_SecondTry = ltsCoord.utmCoordinate(); + Q_UNUSED(utmCoord_SecondTry); - const LtsCoordTrans::UtmCoordinate &utmCoord_SecondTry = ltsCoord.utmCoordinate(); - Q_UNUSED(utmCoord_SecondTry); - - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); } - - void UnitTestCoordinate::test_coordinate_fromUtm() { - const LtsCoordTrans::UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const double zValue = 2.3; - NOTICE_LOG(m_logger) << " utmIn = " << utmIn; + const LtsCoordTrans::UtmCoordinate& utmIn = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const double zValue = 2.3; + NOTICE_LOG(m_logger) << " utmIn = " << utmIn; - - LtsCoordTrans::LtsCoordinate ltsCoord(utmIn.geographic(), zValue); + LtsCoordTrans::LtsCoordinate ltsCoord(utmIn.geographic(), zValue); - const LtsCoordTrans::UtmCoordinate &utmCoord = ltsCoord.utmCoordinate(); - NOTICE_LOG(m_logger) << " utmCoord = " << utmCoord; - NOTICE_LOG(m_logger) << " utmCoord = " << utmCoord.mgrs(); - QVERIFY2(utmCoord.mgrs() == QStringLiteral("32U PD 70000 10000") , "utmCoordinate failed"); + const LtsCoordTrans::UtmCoordinate& utmCoord = ltsCoord.utmCoordinate(); + NOTICE_LOG(m_logger) << " utmCoord = " << utmCoord; + NOTICE_LOG(m_logger) << " utmCoord = " << utmCoord.mgrs(); + QVERIFY2(utmCoord.mgrs() == QStringLiteral("32U PD 70000 10000"), "utmCoordinate failed"); - - const Core::GeoPosition &geoPos = ltsCoord.geoPosition(); - NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; + const Core::GeoPosition& geoPos = ltsCoord.geoPosition(); + NOTICE_LOG(m_logger) << " geoPosition = " << geoPos; - QVERIFY2(qFuzzyCompare(geoPos.lon(), 0.200706392814992), "geoPosition failed"); - QVERIFY2(qFuzzyCompare(geoPos.lat(), 0.914792952478694), "geoPosition failed"); - QVERIFY2(qFuzzyCompare(geoPos.z() , zValue ) , "geoPosition failed"); + QVERIFY2(qFuzzyCompare(geoPos.lon(), 0.200706392814992), "geoPosition failed"); + QVERIFY2(qFuzzyCompare(geoPos.lat(), 0.914792952478694), "geoPosition failed"); + QVERIFY2(qFuzzyCompare(geoPos.z(), zValue), "geoPosition failed"); - - const QPointF &utmP2D = ltsCoord.toUtm(); - NOTICE_LOG(m_logger) << " utmP2D = " << utmP2D; - QVERIFY2(qFuzzyCompare(utmP2D.x(), 670000.5), "utm1 failed"); - QVERIFY2(qFuzzyCompare(utmP2D.y(), 5810000.5), "utm2 failed"); + const QPointF& utmP2D = ltsCoord.toUtm(); + NOTICE_LOG(m_logger) << " utmP2D = " << utmP2D; + QVERIFY2(qFuzzyCompare(utmP2D.x(), 670000.5), "utm1 failed"); + QVERIFY2(qFuzzyCompare(utmP2D.y(), 5810000.5), "utm2 failed"); - const LtsUtils::QPoint3D &utmP3D = ltsCoord.toUtm(); - NOTICE_LOG(m_logger) << " utmP3D = " << utmP3D; - QVERIFY2(qFuzzyCompare(utmP3D.x(), 670000.5), "utm1 failed"); - QVERIFY2(qFuzzyCompare(utmP3D.y(), 5810000.5), "utm2 failed"); - QVERIFY2(qFuzzyCompare(utmP3D.z() , zValue ), "utm3 failed"); + const LtsUtils::QPoint3D& utmP3D = ltsCoord.toUtm(); + NOTICE_LOG(m_logger) << " utmP3D = " << utmP3D; + QVERIFY2(qFuzzyCompare(utmP3D.x(), 670000.5), "utm1 failed"); + QVERIFY2(qFuzzyCompare(utmP3D.y(), 5810000.5), "utm2 failed"); + QVERIFY2(qFuzzyCompare(utmP3D.z(), zValue), "utm3 failed"); - const LtsCoordTrans::UtmCoordinate3D &utmCoord3D = ltsCoord.toUtmCoordinate3D(); - NOTICE_LOG(m_logger) << " UtmCoordinate3D = " << utmCoord3D; - QVERIFY2(qFuzzyCompare(utmCoord3D.x, 670000.5), "utmCoord3D failed"); - QVERIFY2(qFuzzyCompare(utmCoord3D.y, 5810000.5), "utmCoord3D failed"); - QVERIFY2(qFuzzyCompare(utmCoord3D.z(), zValue ), "utmCoord3D failed"); + const LtsCoordTrans::UtmCoordinate3D& utmCoord3D = ltsCoord.toUtmCoordinate3D(); + NOTICE_LOG(m_logger) << " UtmCoordinate3D = " << utmCoord3D; + QVERIFY2(qFuzzyCompare(utmCoord3D.x, 670000.5), "utmCoord3D failed"); + QVERIFY2(qFuzzyCompare(utmCoord3D.y, 5810000.5), "utmCoord3D failed"); + QVERIFY2(qFuzzyCompare(utmCoord3D.z(), zValue), "utmCoord3D failed"); - - const LtsCoordTrans::UtmCoordinate &utmCoord2D = utmCoord3D; - NOTICE_LOG(m_logger) << " utmCoord2D = " << utmCoord2D; - QVERIFY2(qFuzzyCompare(utmCoord2D.x, 670000.5), "utmCoord2D failed"); - QVERIFY2(qFuzzyCompare(utmCoord2D.y, 5810000.5), "utmCoord2D failed"); + const LtsCoordTrans::UtmCoordinate& utmCoord2D = utmCoord3D; + NOTICE_LOG(m_logger) << " utmCoord2D = " << utmCoord2D; + QVERIFY2(qFuzzyCompare(utmCoord2D.x, 670000.5), "utmCoord2D failed"); + QVERIFY2(qFuzzyCompare(utmCoord2D.y, 5810000.5), "utmCoord2D failed"); - - const LtsCoordTrans::UtmCoordinate &utm = ltsCoord.utmCoordinate(); - QVERIFY2(utm.mgrs() == QStringLiteral("32U PD 70000 10000") , "utmCoordinate failed"); + const LtsCoordTrans::UtmCoordinate& utm = ltsCoord.utmCoordinate(); + QVERIFY2(utm.mgrs() == QStringLiteral("32U PD 70000 10000"), "utmCoordinate failed"); } void UnitTestCoordinate::test_coordinate_fromUtm2() { - const LtsCoordTrans::UtmCoordinate &utmInZone32 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LA 10000 00000")); - const double zValue = 2.3; - NOTICE_LOG(m_logger) << " utmInZone32 = " << utmInZone32; + const LtsCoordTrans::UtmCoordinate& utmInZone32 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LA 10000 00000")); + const double zValue = 2.3; + NOTICE_LOG(m_logger) << " utmInZone32 = " << utmInZone32; - const QPointF &utmInDefQPointF = utmInZone32.geographic(); + const QPointF& utmInDefQPointF = utmInZone32.geographic(); - const int zone31 = 31; - const LtsCoordTrans::UtmCoordinate &utmInZone31 = LtsCoordTrans::UtmCoordinate::fromGeographic(utmInDefQPointF, zone31); - NOTICE_LOG(m_logger) << " utmInZone31 = " << utmInZone31; + const int zone31 = 31; + const LtsCoordTrans::UtmCoordinate& utmInZone31 = + LtsCoordTrans::UtmCoordinate::fromGeographic(utmInDefQPointF, zone31); + NOTICE_LOG(m_logger) << " utmInZone31 = " << utmInZone31; - NOTICE_LOG(m_logger) << " utmInZone31.geographic() = " << utmInZone31.geographic(); - NOTICE_LOG(m_logger) << " utmInZone32.geographic() = " << utmInZone32.geographic(); + NOTICE_LOG(m_logger) << " utmInZone31.geographic() = " << utmInZone31.geographic(); + NOTICE_LOG(m_logger) << " utmInZone32.geographic() = " << utmInZone32.geographic(); - QVERIFY2(utmInZone31.geographic() == utmInZone32.geographic(), "geographic failed"); + QVERIFY2(utmInZone31.geographic() == utmInZone32.geographic(), "geographic failed"); - { - - LtsCoordTrans::LtsCoordinate ltsFromUtm31(utmInZone31.geographic(), zValue); - LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(), zValue); + { - double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); - NOTICE_LOG(m_logger) << " dist1 = " << dist; - QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); - } - { - - LtsCoordTrans::LtsCoordinate ltsFromUtm31(utmInZone31.geographic() , zValue); - LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(1, 0), zValue); + LtsCoordTrans::LtsCoordinate ltsFromUtm31(utmInZone31.geographic(), zValue); + LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(), zValue); - double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); - NOTICE_LOG(m_logger) << " dist2 = " << dist; - QVERIFY2(fabs(dist-1) < 0.00001, "distance3D"); - } + double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); + NOTICE_LOG(m_logger) << " dist1 = " << dist; + QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); + } + { - { - - - - LtsCoordTrans::LtsCoordinate ltsFromUtm31 = LtsCoordTrans::LtsCoordinate::fromUtmCoordinate(utmInZone31, zValue); - LtsCoordTrans::LtsCoordinate ltsFromUtm32 = LtsCoordTrans::LtsCoordinate::fromUtmCoordinate(utmInZone32, zValue); + LtsCoordTrans::LtsCoordinate ltsFromUtm31(utmInZone31.geographic(), zValue); + LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(1, 0), zValue); - double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); - NOTICE_LOG(m_logger) << " dist3 = " << dist; - QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); - } + double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); + NOTICE_LOG(m_logger) << " dist2 = " << dist; + QVERIFY2(fabs(dist - 1) < 0.00001, "distance3D"); + } - { - LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(), zValue); + { - const QPointF &utmP2D_def = ltsFromUtm32.toUtm(); - const QPointF &utmP2D_31 = ltsFromUtm32.toUtm(31); - NOTICE_LOG(m_logger) << " utmP2D_def = " << utmP2D_def; - NOTICE_LOG(m_logger) << " utmP2D_31 = " << utmP2D_31; + LtsCoordTrans::LtsCoordinate ltsFromUtm31 = + LtsCoordTrans::LtsCoordinate::fromUtmCoordinate(utmInZone31, zValue); + LtsCoordTrans::LtsCoordinate ltsFromUtm32 = + LtsCoordTrans::LtsCoordinate::fromUtmCoordinate(utmInZone32, zValue); - LtsCoordTrans::LtsCoordinate lts1 = LtsCoordTrans::LtsCoordinate::fromUtm(utmP2D_def, 32, 0.0); - LtsCoordTrans::LtsCoordinate lts2 = LtsCoordTrans::LtsCoordinate::fromUtm(utmP2D_31, 31, 0.0); - NOTICE_LOG(m_logger) << " lts1 = " << lts1; - NOTICE_LOG(m_logger) << " lts2 = " << lts2; + double dist = ltsFromUtm31.distanceUtm3D(ltsFromUtm32); + NOTICE_LOG(m_logger) << " dist3 = " << dist; + QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); + } - double dist = lts1.distanceUtm3D(lts2); - NOTICE_LOG(m_logger) << " dist4 = " << dist; - QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); - } + { + LtsCoordTrans::LtsCoordinate ltsFromUtm32(utmInZone32.geographic(), zValue); + + const QPointF& utmP2D_def = ltsFromUtm32.toUtm(); + const QPointF& utmP2D_31 = ltsFromUtm32.toUtm(31); + NOTICE_LOG(m_logger) << " utmP2D_def = " << utmP2D_def; + NOTICE_LOG(m_logger) << " utmP2D_31 = " << utmP2D_31; + + LtsCoordTrans::LtsCoordinate lts1 = LtsCoordTrans::LtsCoordinate::fromUtm(utmP2D_def, 32, 0.0); + LtsCoordTrans::LtsCoordinate lts2 = LtsCoordTrans::LtsCoordinate::fromUtm(utmP2D_31, 31, 0.0); + NOTICE_LOG(m_logger) << " lts1 = " << lts1; + NOTICE_LOG(m_logger) << " lts2 = " << lts2; + + double dist = lts1.distanceUtm3D(lts2); + NOTICE_LOG(m_logger) << " dist4 = " << dist; + QVERIFY2(qFuzzyCompare(dist, 0), "distance3D"); + } } - void UnitTestCoordinate::test_coordinate_elevationAt() { - const double zValue = 1.23; + const double zValue = 1.23; - const LtsCoordTrans::UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - NOTICE_LOG(m_logger) << " utmIn = " << utmIn; + const LtsCoordTrans::UtmCoordinate& utmIn = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + NOTICE_LOG(m_logger) << " utmIn = " << utmIn; - LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic(), zValue); - NOTICE_LOG(m_logger) << " ltsFromUtm1 = " << ltsFromUtm; - QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), zValue) , "geoPosition failed"); + LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic(), zValue); + NOTICE_LOG(m_logger) << " ltsFromUtm1 = " << ltsFromUtm; + QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), zValue), "geoPosition failed"); - - const double ele = ltsFromUtm.elevationAt(); - QVERIFY2(qFuzzyCompare(ele, 75), "elevationAt failed"); + const double ele = ltsFromUtm.elevationAt(); + QVERIFY2(qFuzzyCompare(ele, 75), "elevationAt failed"); - NOTICE_LOG(m_logger) << " ltsFromUtm2 = " << ltsFromUtm; - QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), zValue) , "geoPosition failed"); + NOTICE_LOG(m_logger) << " ltsFromUtm2 = " << ltsFromUtm; + QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), zValue), "geoPosition failed"); - - ltsFromUtm.setZValueAccordingElevation(); - NOTICE_LOG(m_logger) << " ltsFromUtm3 = " << ltsFromUtm; - QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), 75) , "setZValueAccordingElevation failed"); + ltsFromUtm.setZValueAccordingElevation(); + NOTICE_LOG(m_logger) << " ltsFromUtm3 = " << ltsFromUtm; + QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), 75), "setZValueAccordingElevation failed"); - - const LtsUtils::QPoint3D &utmP3D = ltsFromUtm.toUtm(); - NOTICE_LOG(m_logger) << " utmP3D_a = " << utmP3D; - QVERIFY2(qFuzzyCompare(utmP3D.z(), 75 ) , "utmCoordinateAsPoint3D failed"); + const LtsUtils::QPoint3D& utmP3D = ltsFromUtm.toUtm(); + NOTICE_LOG(m_logger) << " utmP3D_a = " << utmP3D; + QVERIFY2(qFuzzyCompare(utmP3D.z(), 75), "utmCoordinateAsPoint3D failed"); - { - - const double ele3 = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm); - NOTICE_LOG(m_logger) << " ele3 = " << ele3; - - QVERIFY2(qFuzzyCompare(ele, ele3 ), "LtsCoordinate::elevationAt failed"); - } + { - - - - - - LtsCoordTrans::UtmCoordinate utmMoved = ltsFromUtm.utmCoordinate(); - utmMoved.x += 11; - utmMoved.y += 22; - const int zValueNew = 123; - ltsFromUtm = LtsCoordTrans::LtsCoordinate(utmMoved.geographic(), zValueNew); - NOTICE_LOG(m_logger) << " ltsFromUtm4 = " << ltsFromUtm; + const double ele3 = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm); + NOTICE_LOG(m_logger) << " ele3 = " << ele3; - - const double ele2 = ltsFromUtm.elevationAt(); - NOTICE_LOG(m_logger) << " ltsFromUtm5 = " << ltsFromUtm; - QVERIFY2(ele2 != 75 , "setZValueAccordingElevation failed"); + QVERIFY2(qFuzzyCompare(ele, ele3), "LtsCoordinate::elevationAt failed"); + } + + LtsCoordTrans::UtmCoordinate utmMoved = ltsFromUtm.utmCoordinate(); + utmMoved.x += 11; + utmMoved.y += 22; + const int zValueNew = 123; + ltsFromUtm = LtsCoordTrans::LtsCoordinate(utmMoved.geographic(), zValueNew); + NOTICE_LOG(m_logger) << " ltsFromUtm4 = " << ltsFromUtm; + + const double ele2 = ltsFromUtm.elevationAt(); + NOTICE_LOG(m_logger) << " ltsFromUtm5 = " << ltsFromUtm; + QVERIFY2(ele2 != 75, "setZValueAccordingElevation failed"); } void UnitTestCoordinate::test_coordinate_elevationAt_isCovered() { - const LtsCoordTrans::UtmCoordinate &utmIn1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const LtsCoordTrans::UtmCoordinate &utmIn2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U MD 10000 10000")); + const LtsCoordTrans::UtmCoordinate& utmIn1 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const LtsCoordTrans::UtmCoordinate& utmIn2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U MD 10000 10000")); - LtsCoordTrans::LtsCoordinate ltsFromUtm1(utmIn1.geographic(), 11); - LtsCoordTrans::LtsCoordinate ltsFromUtm2(utmIn2.geographic(), 11); + LtsCoordTrans::LtsCoordinate ltsFromUtm1(utmIn1.geographic(), 11); + LtsCoordTrans::LtsCoordinate ltsFromUtm2(utmIn2.geographic(), 11); - { - bool bIsCovered = false; - double ele = ltsFromUtm1.elevationAt(-123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == true , "elevationAt1a failed"); + { + bool bIsCovered = false; + double ele = ltsFromUtm1.elevationAt(-123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == true, "elevationAt1a failed"); - - bIsCovered = false; - ele = ltsFromUtm1.elevationAt(-123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == true , "elevationAt1b failed"); + bIsCovered = false; + ele = ltsFromUtm1.elevationAt(-123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == true, "elevationAt1b failed"); + bIsCovered = false; + ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm1, -123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == true, "elevationAt2a failed"); - - bIsCovered = false; - ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm1, -123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == true , "elevationAt2a failed"); + bIsCovered = false; + ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm1, -123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == true, "elevationAt2b failed"); + } - - bIsCovered = false; - ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm1, -123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == true , "elevationAt2b failed"); - } + { + bool bIsCovered = true; + double ele = ltsFromUtm2.elevationAt(-123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == false, "elevationAt2 failed"); - { - bool bIsCovered = true; - double ele = ltsFromUtm2.elevationAt(-123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == false , "elevationAt2 failed"); - - - bIsCovered = true; - ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm2, -123, &bIsCovered); - Q_UNUSED(ele); - QVERIFY2(bIsCovered == false , "elevationAt1 failed"); - } + bIsCovered = true; + ele = LtsCoordTrans::LtsCoordinate::elevationAt(ltsFromUtm2, -123, &bIsCovered); + Q_UNUSED(ele); + QVERIFY2(bIsCovered == false, "elevationAt1 failed"); + } } void UnitTestCoordinate::test_coordinate_elevation_data() { - QTest::addColumn("mgrs"); - QTest::addColumn("elevationIn"); - QTest::addColumn("elevationRef"); + QTest::addColumn("mgrs"); + QTest::addColumn("elevationIn"); + QTest::addColumn("elevationRef"); - - QTest::newRow("elevation 10 ") << QStringLiteral("32 U PD 70000 10000") << std::nan("") << 75.0; - QTest::newRow("elevation 11 ") << QStringLiteral("32 U PD 70000 10000") << 0.0 << 75.0; - QTest::newRow("elevation 20 ") << QStringLiteral("32 U PD 72000 13000") << std::nan("") << 80.0; - QTest::newRow("elevation 21 ") << QStringLiteral("32 U PD 72000 13000") << 0.340 << 80.0; + QTest::newRow("elevation 10 ") << QStringLiteral("32 U PD 70000 10000") << std::nan("") << 75.0; + QTest::newRow("elevation 11 ") << QStringLiteral("32 U PD 70000 10000") << 0.0 << 75.0; + QTest::newRow("elevation 20 ") << QStringLiteral("32 U PD 72000 13000") << std::nan("") << 80.0; + QTest::newRow("elevation 21 ") << QStringLiteral("32 U PD 72000 13000") << 0.340 << 80.0; } + void UnitTestCoordinate::test_coordinate_elevation() { - QFETCH(QString, mgrs); - QFETCH(double, elevationIn); - QFETCH(double, elevationRef); + QFETCH(QString, mgrs); + QFETCH(double, elevationIn); + QFETCH(double, elevationRef); - const LtsCoordTrans::UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); - NOTICE_LOG(m_logger) << " utmIn = " << utmIn; + const LtsCoordTrans::UtmCoordinate& utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(mgrs); + NOTICE_LOG(m_logger) << " utmIn = " << utmIn; - LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic(), elevationIn); - NOTICE_LOG(m_logger) << " ltsFromUtm = " << ltsFromUtm; + LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic(), elevationIn); + NOTICE_LOG(m_logger) << " ltsFromUtm = " << ltsFromUtm; - - NOTICE_LOG(m_logger) << " geoPosition = " << ltsFromUtm.geoPosition(); - ltsFromUtm.replaceZValueByElevationIfValue(elevationIn); + NOTICE_LOG(m_logger) << " geoPosition = " << ltsFromUtm.geoPosition(); + ltsFromUtm.replaceZValueByElevationIfValue(elevationIn); - - NOTICE_LOG(m_logger) << " geoPosition = " << ltsFromUtm.geoPosition(); - QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), elevationRef), "elevation failed"); + NOTICE_LOG(m_logger) << " geoPosition = " << ltsFromUtm.geoPosition(); + QVERIFY2(qFuzzyCompare(ltsFromUtm.geoPosition().z(), elevationRef), "elevation failed"); - - const LtsUtils::QPoint3D &utmP3D = ltsFromUtm.toUtm(); - NOTICE_LOG(m_logger) << " utmP3D = " << utmP3D; - QVERIFY2(qFuzzyCompare(utmP3D.z(), elevationRef) , "utmCoordinateAsPoint3D failed"); + const LtsUtils::QPoint3D& utmP3D = ltsFromUtm.toUtm(); + NOTICE_LOG(m_logger) << " utmP3D = " << utmP3D; + QVERIFY2(qFuzzyCompare(utmP3D.z(), elevationRef), "utmCoordinateAsPoint3D failed"); } void UnitTestCoordinate::test_coordinate_mgrs() { - const LtsCoordTrans::UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - NOTICE_LOG(m_logger) << " utmIn = " << utmIn.mgrs(); + const LtsCoordTrans::UtmCoordinate& utmIn = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + NOTICE_LOG(m_logger) << " utmIn = " << utmIn.mgrs(); - LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic()); + LtsCoordTrans::LtsCoordinate ltsFromUtm(utmIn.geographic()); - { - const QString asMgrs = ltsFromUtm.mgrs(); - NOTICE_LOG(m_logger) << " asMgrs = " << asMgrs; - QVERIFY2(asMgrs.compare(QStringLiteral("32U PD 70000 10000")) == 0, "UtmCoordinate::mgrs failed"); - } - { - const QString asMgrs = ltsFromUtm.mgrsWithZ(); - NOTICE_LOG(m_logger) << " asMgrs = " << asMgrs; - QVERIFY2(asMgrs.compare(QStringLiteral("32U PD 70000 10000 z=75.00")) == 0, "UtmCoordinate::mgrs failed"); - } + { + const QString asMgrs = ltsFromUtm.mgrs(); + NOTICE_LOG(m_logger) << " asMgrs = " << asMgrs; + QVERIFY2(asMgrs.compare(QStringLiteral("32U PD 70000 10000")) == 0, "UtmCoordinate::mgrs failed"); + } + { + const QString asMgrs = ltsFromUtm.mgrsWithZ(); + NOTICE_LOG(m_logger) << " asMgrs = " << asMgrs; + QVERIFY2(asMgrs.compare(QStringLiteral("32U PD 70000 10000 z=75.00")) == 0, "UtmCoordinate::mgrs failed"); + } - { - const LtsCoordTrans::LtsCoordinate coord(0.200706392814992, 0.914792952478694, 123); - - - const QString str1 = coord.toString(); - NOTICE_LOG(m_logger) << " str1 cheap = " << str1; - QVERIFY2(str1.compare(QStringLiteral("LtsCoordinate(m_geo=[[lon: 0.200706392814992, lat: 0.914792952478694]z: 123], m_utm2D.x 0, m_utm2D.y 0, m_utm2D.zone -1, elevation nan)")) == 0, "toString failed"); + { + const LtsCoordTrans::LtsCoordinate coord(0.200706392814992, 0.914792952478694, 123); - - - - - const bool fullAndExpensive = true; - const QString str2 = coord.toString(fullAndExpensive); - NOTICE_LOG(m_logger) << " str2 expensive = " << str2; - QVERIFY2(str2.compare(QStringLiteral("LtsCoordinate(m_geo=[[lon: 0.200706392814992, lat: 0.914792952478694]z: 123], m_utm2D.x 670000.499999998, m_utm2D.y 5810000.5, m_utm2D.zone 32, m_utm2D.mgrs '32U PD 70000 10000', elevation 75.000)")) == 0, "toString failed"); - } + const QString str1 = coord.toString(); + NOTICE_LOG(m_logger) << " str1 cheap = " << str1; + QVERIFY2(str1.compare(QStringLiteral("LtsCoordinate(m_geo=[[lon: 0.200706392814992, lat: 0.914792952478694]z: " + "123], m_utm2D.x 0, m_utm2D.y 0, m_utm2D.zone -1, elevation nan)")) == 0, + "toString failed"); + const bool fullAndExpensive = true; + const QString str2 = coord.toString(fullAndExpensive); + NOTICE_LOG(m_logger) << " str2 expensive = " << str2; + QVERIFY2(str2.compare(QStringLiteral("LtsCoordinate(m_geo=[[lon: 0.200706392814992, lat: 0.914792952478694]z: " + "123], m_utm2D.x 670000.499999998, m_utm2D.y 5810000.5, m_utm2D.zone 32, " + "m_utm2D.mgrs '32U PD 70000 10000', elevation 75.000)")) == 0, + "toString failed"); + } } void UnitTestCoordinate::test_coordinate_distance() { - const LtsCoordTrans::UtmCoordinate &utmIn1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const LtsCoordTrans::UtmCoordinate &utmIn2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70010 10100")); - NOTICE_LOG(m_logger) << " XXutmIn1 = " << utmIn1; - NOTICE_LOG(m_logger) << " XXutmIn2 = " << utmIn2; + const LtsCoordTrans::UtmCoordinate& utmIn1 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const LtsCoordTrans::UtmCoordinate& utmIn2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70010 10100")); + NOTICE_LOG(m_logger) << " XXutmIn1 = " << utmIn1; + NOTICE_LOG(m_logger) << " XXutmIn2 = " << utmIn2; - QVERIFY2(qFuzzyCompare((utmIn2.x - utmIn1.x), 10) , "coord failed"); - QVERIFY2(qFuzzyCompare((utmIn2.y - utmIn1.y), 100) , "coord failed"); + QVERIFY2(qFuzzyCompare((utmIn2.x - utmIn1.x), 10), "coord failed"); + QVERIFY2(qFuzzyCompare((utmIn2.y - utmIn1.y), 100), "coord failed"); - const LtsCoordTrans::LtsCoordinate lts1(utmIn1.geographic(), 11); - const LtsCoordTrans::LtsCoordinate lts2(utmIn2.geographic(), 111); + const LtsCoordTrans::LtsCoordinate lts1(utmIn1.geographic(), 11); + const LtsCoordTrans::LtsCoordinate lts2(utmIn2.geographic(), 111); - { - double dist2D = lts1.distanceUtm2D(lts2); - NOTICE_LOG(m_logger) << " dist2D = " << dist2D; - QVERIFY2(std::fabs(dist2D-100.499) < 0.01, "distanceUtm2D failed"); - } + { + double dist2D = lts1.distanceUtm2D(lts2); + NOTICE_LOG(m_logger) << " dist2D = " << dist2D; + QVERIFY2(std::fabs(dist2D - 100.499) < 0.01, "distanceUtm2D failed"); + } - { - double dist3D = lts1.distanceUtm3D(lts2); - NOTICE_LOG(m_logger) << " dist3D = " << dist3D; - QVERIFY2(std::fabs(dist3D-141.774) < 0.01, "distanceUtm3D failed"); - } + { + double dist3D = lts1.distanceUtm3D(lts2); + NOTICE_LOG(m_logger) << " dist3D = " << dist3D; + QVERIFY2(std::fabs(dist3D - 141.774) < 0.01, "distanceUtm3D failed"); + } } - void UnitTestCoordinate::test_coordinate_distanceDiffZones() { - const LtsCoordTrans::UtmCoordinate &utmIn1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("31 U FR 99999 00000")); - const LtsCoordTrans::UtmCoordinate &utmIn2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LA 00000 00000")); - NOTICE_LOG(m_logger) << " XXutmIn1 = " << utmIn1; - NOTICE_LOG(m_logger) << " XXutmIn2 = " << utmIn2; + const LtsCoordTrans::UtmCoordinate& utmIn1 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("31 U FR 99999 00000")); + const LtsCoordTrans::UtmCoordinate& utmIn2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LA 00000 00000")); + NOTICE_LOG(m_logger) << " XXutmIn1 = " << utmIn1; + NOTICE_LOG(m_logger) << " XXutmIn2 = " << utmIn2; - - - LtsCoordTrans::LtsCoordinate lts1(utmIn1.geographic(), 0); - LtsCoordTrans::LtsCoordinate lts2(utmIn2.geographic(), 0); - NOTICE_LOG(m_logger) << " lts1 = " << lts1; - NOTICE_LOG(m_logger) << " lts2 = " << lts2; + LtsCoordTrans::LtsCoordinate lts1(utmIn1.geographic(), 0); + LtsCoordTrans::LtsCoordinate lts2(utmIn2.geographic(), 0); + NOTICE_LOG(m_logger) << " lts1 = " << lts1; + NOTICE_LOG(m_logger) << " lts2 = " << lts2; - double dist = lts1.distanceUtm3D(lts2); + double dist = lts1.distanceUtm3D(lts2); - NOTICE_LOG(m_logger) << " dist = " << dist; - QVERIFY2(std::fabs(dist-33382.7) < 0.1, "distance3D failed"); + NOTICE_LOG(m_logger) << " dist = " << dist; + QVERIFY2(std::fabs(dist - 33382.7) < 0.1, "distance3D failed"); } void UnitTestCoordinate::test_squareInDifferentZone() { - const LtsCoordTrans::UtmCoordinate &utm_bl = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const LtsCoordTrans::UtmCoordinate &utm_br = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 11000")); - const LtsCoordTrans::UtmCoordinate &utm_tl = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 10000")); - const LtsCoordTrans::UtmCoordinate &utm_tr = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 11000")); + const LtsCoordTrans::UtmCoordinate& utm_bl = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const LtsCoordTrans::UtmCoordinate& utm_br = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 11000")); + const LtsCoordTrans::UtmCoordinate& utm_tl = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 10000")); + const LtsCoordTrans::UtmCoordinate& utm_tr = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 11000")); - const LtsCoordTrans::LtsCoordinate lts_bl(utm_bl.geographic(), 0); - const LtsCoordTrans::LtsCoordinate lts_br(utm_br.geographic(), 0); - const LtsCoordTrans::LtsCoordinate lts_tl(utm_tl.geographic(), 0); - const LtsCoordTrans::LtsCoordinate lts_tr(utm_tr.geographic(), 0); + const LtsCoordTrans::LtsCoordinate lts_bl(utm_bl.geographic(), 0); + const LtsCoordTrans::LtsCoordinate lts_br(utm_br.geographic(), 0); + const LtsCoordTrans::LtsCoordinate lts_tl(utm_tl.geographic(), 0); + const LtsCoordTrans::LtsCoordinate lts_tr(utm_tr.geographic(), 0); - { - - QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_br), 1000.0), "distance3D 1 failed"); - QVERIFY2(qFuzzyCompare(lts_tl.distanceUtm2D(lts_tr), 1000.0), "distance3D 2 failed"); - QVERIFY2(qFuzzyCompare(lts_br.distanceUtm2D(lts_tr), 1000.0), "distance3D 3 failed"); - QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_tl), 1000.0), "distance3D 4 failed"); - - QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_tr), 1414.213562373177), "distance3D 5 failed"); - QVERIFY2(qFuzzyCompare(lts_br.distanceUtm2D(lts_tl), 1414.213562373177), "distance3D 6 failed"); - } + { - - - { - const LtsCoordTrans::UtmCoordinate &utm31_bl = LtsCoordTrans::UtmCoordinate(31, utm_bl.x, utm_bl.y); - const LtsCoordTrans::UtmCoordinate &utm31_br = LtsCoordTrans::UtmCoordinate(31, utm_br.x, utm_br.y); - const LtsCoordTrans::UtmCoordinate &utm31_tl = LtsCoordTrans::UtmCoordinate(31, utm_tl.x, utm_tl.y); - const LtsCoordTrans::UtmCoordinate &utm31_tr = LtsCoordTrans::UtmCoordinate(31, utm_tr.x, utm_tr.y); + QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_br), 1000.0), "distance3D 1 failed"); + QVERIFY2(qFuzzyCompare(lts_tl.distanceUtm2D(lts_tr), 1000.0), "distance3D 2 failed"); + QVERIFY2(qFuzzyCompare(lts_br.distanceUtm2D(lts_tr), 1000.0), "distance3D 3 failed"); + QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_tl), 1000.0), "distance3D 4 failed"); - - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_br), 1000.0), "LtsCoordTrans::distance 1 failed"); - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_tl, utm31_tr), 1000.0), "LtsCoordTrans::distance 2 failed"); - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_br, utm31_tr), 1000.0), "LtsCoordTrans::distance 3 failed"); - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_tl), 1000.0), "LtsCoordTrans::distance 4 failed"); - - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_tr), 1414.213562373095), "LtsCoordTrans::distance 5 failed"); - QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_br, utm31_tl), 1414.213562373095), "LtsCoordTrans::distance 6 failed"); - } + QVERIFY2(qFuzzyCompare(lts_bl.distanceUtm2D(lts_tr), 1414.213562373177), "distance3D 5 failed"); + QVERIFY2(qFuzzyCompare(lts_br.distanceUtm2D(lts_tl), 1414.213562373177), "distance3D 6 failed"); + } - - - - - - - + { + const LtsCoordTrans::UtmCoordinate& utm31_bl = LtsCoordTrans::UtmCoordinate(31, utm_bl.x, utm_bl.y); + const LtsCoordTrans::UtmCoordinate& utm31_br = LtsCoordTrans::UtmCoordinate(31, utm_br.x, utm_br.y); + const LtsCoordTrans::UtmCoordinate& utm31_tl = LtsCoordTrans::UtmCoordinate(31, utm_tl.x, utm_tl.y); + const LtsCoordTrans::UtmCoordinate& utm31_tr = LtsCoordTrans::UtmCoordinate(31, utm_tr.x, utm_tr.y); + + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_br), 1000.0), + "LtsCoordTrans::distance 1 failed"); + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_tl, utm31_tr), 1000.0), + "LtsCoordTrans::distance 2 failed"); + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_br, utm31_tr), 1000.0), + "LtsCoordTrans::distance 3 failed"); + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_tl), 1000.0), + "LtsCoordTrans::distance 4 failed"); + + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_bl, utm31_tr), 1414.213562373095), + "LtsCoordTrans::distance 5 failed"); + QVERIFY2(qFuzzyCompare(LtsCoordTrans::distance(utm31_br, utm31_tl), 1414.213562373095), + "LtsCoordTrans::distance 6 failed"); + } } void UnitTestCoordinate::test_coordinate_angle() { - - - const LtsCoordTrans::UtmCoordinate &utm_ul = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const LtsCoordTrans::LtsCoordinate lts_ul(utm_ul.geographic(), 0); - { - - const LtsCoordTrans::UtmCoordinate &utm_2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 11000")); - const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); - double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); - QVERIFY2(qFuzzyCompare(angle, 0.0), "angleUtm2D 1 failed"); - } + const LtsCoordTrans::UtmCoordinate& utm_ul = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const LtsCoordTrans::LtsCoordinate lts_ul(utm_ul.geographic(), 0); - { - - const LtsCoordTrans::UtmCoordinate &utm_2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 10000")); - const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); - double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); - QVERIFY2(qFuzzyCompare(angle, 90.0), "angleUtm2D 1 failed"); - } + { - { - - const LtsCoordTrans::UtmCoordinate &utm_2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 09000")); - const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); - double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); - QVERIFY2(qFuzzyCompare(angle, 180.0), "angleUtm2D 1 failed"); - } + const LtsCoordTrans::UtmCoordinate& utm_2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 11000")); + const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); + double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); + QVERIFY2(qFuzzyCompare(angle, 0.0), "angleUtm2D 1 failed"); + } - { - - const LtsCoordTrans::UtmCoordinate &utm_2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 69000 10000")); - const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); - double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); - QVERIFY2(qFuzzyCompare(angle, 270.0), "angleUtm2D 1 failed"); - } + { - - { - const LtsCoordTrans::UtmCoordinate &utm_or = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 12000")); - const LtsCoordTrans::LtsCoordinate lts_or(utm_or.geographic(), 0); - double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_or); - - QVERIFY2(qFuzzyCompare(angle, 26.565051177056659526), "angleUtm2D 1 failed"); - QVERIFY2((angle-26.5651 < 0.001), "angleUtm2D 1 failed"); - } + const LtsCoordTrans::UtmCoordinate& utm_2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 10000")); + const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); + double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); + QVERIFY2(qFuzzyCompare(angle, 90.0), "angleUtm2D 1 failed"); + } + + { + + const LtsCoordTrans::UtmCoordinate& utm_2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 09000")); + const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); + double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); + QVERIFY2(qFuzzyCompare(angle, 180.0), "angleUtm2D 1 failed"); + } + + { + + const LtsCoordTrans::UtmCoordinate& utm_2 = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 69000 10000")); + const LtsCoordTrans::LtsCoordinate lts_2(utm_2.geographic(), 0); + double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_2); + QVERIFY2(qFuzzyCompare(angle, 270.0), "angleUtm2D 1 failed"); + } + + { + const LtsCoordTrans::UtmCoordinate& utm_or = + LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 71000 12000")); + const LtsCoordTrans::LtsCoordinate lts_or(utm_or.geographic(), 0); + double angle = LtsCoordTrans::LtsCoordinate::angleDegreeUtm2D(lts_ul, lts_or); + + QVERIFY2(qFuzzyCompare(angle, 26.565051177056659526), "angleUtm2D 1 failed"); + QVERIFY2((angle - 26.5651 < 0.001), "angleUtm2D 1 failed"); + } } void UnitTestCoordinate::test_coordinate_cont() { - std::vector stdVec; - stdVec.push_back(Core::GeoPosition(0.1, 0.11, 1)); - stdVec.push_back(Core::GeoPosition(0.2, 0.22, 2)); - stdVec.push_back(Core::GeoPosition(0.3, 0.33, 3)); + std::vector stdVec; + stdVec.push_back(Core::GeoPosition(0.1, 0.11, 1)); + stdVec.push_back(Core::GeoPosition(0.2, 0.22, 2)); + stdVec.push_back(Core::GeoPosition(0.3, 0.33, 3)); - const QVector &newCont = LtsCoordTrans::convert>(stdVec); + const QVector& newCont = + LtsCoordTrans::convert>(stdVec); - NOTICE_LOG(m_logger) << " newCont.size() = " << newCont.size(); - QVERIFY2(stdVec.size() == static_cast(newCont.size()), "convert failed"); + NOTICE_LOG(m_logger) << " newCont.size() = " << newCont.size(); + QVERIFY2(stdVec.size() == static_cast(newCont.size()), "convert failed"); } using namespace LtsCoordTrans; + class ParticpantPositionStore { -public: - ParticpantPositionStore() = default; - ~ParticpantPositionStore() = default; + public: + ParticpantPositionStore() = default; + ~ParticpantPositionStore() = default; - void setGeoPosition(const Core::GeoPosition &newGeoPos) - { - m_ltsCoord = LtsCoordinate(newGeoPos); - m_ltsCoord_NoImplicitCopy.updateGeoPosition(newGeoPos); - } + void setGeoPosition(const Core::GeoPosition& newGeoPos) + { + m_ltsCoord = LtsCoordinate(newGeoPos); + m_ltsCoord_NoImplicitCopy.updateGeoPosition(newGeoPos); + } - - - - - LtsCoordinate getLtsCoord_copy() - { - return m_ltsCoord; - } + LtsCoordinate getLtsCoord_copy() + { + return m_ltsCoord; + } - - - const LtsCoordinateNoImplicitCopy& getLtsCoord_noCopy() - { - return m_ltsCoord_NoImplicitCopy; - } + const LtsCoordinateNoImplicitCopy& getLtsCoord_noCopy() + { + return m_ltsCoord_NoImplicitCopy; + } - - - - - - - - - LtsCoordinate m_ltsCoord; - LtsCoordinateNoImplicitCopy m_ltsCoord_NoImplicitCopy; + LtsCoordinate m_ltsCoord; + LtsCoordinateNoImplicitCopy m_ltsCoord_NoImplicitCopy; }; - void UnitTestCoordinate::test_coordinate_avoid_copy() { - LtsCoordTrans::LtsCoordinate::resetConversionCounter(); - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 0, "getConversionCounter failed"); + LtsCoordTrans::LtsCoordinate::resetConversionCounter(); + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 0, "getConversionCounter failed"); - ParticpantPositionStore store; + ParticpantPositionStore store; - - - - const UtmCoordinate &utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); - const LtsCoordinate ltsIn(utmIn.geographic(), 11); + const UtmCoordinate& utmIn = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U PD 70000 10000")); + const LtsCoordinate ltsIn(utmIn.geographic(), 11); - store.getLtsCoord_noCopy().updateGeoPosition(ltsIn.geoPosition()); + store.getLtsCoord_noCopy().updateGeoPosition(ltsIn.geoPosition()); - - - - - - const LtsCoordinateNoImplicitCopy &justReference = store.getLtsCoord_noCopy(); - NOTICE_LOG(m_logger) << " justReference = " << justReference.mgrs(); + const LtsCoordinateNoImplicitCopy& justReference = store.getLtsCoord_noCopy(); + NOTICE_LOG(m_logger) << " justReference = " << justReference.mgrs(); - const LtsCoordTrans::UtmCoordinate &convertedToUtm = justReference.utmCoordinate(); - NOTICE_LOG(m_logger) << " convertedToUtm = " << convertedToUtm; - QVERIFY2(qFuzzyCompare(convertedToUtm.x, 670000.5 ), "convert failed"); - QVERIFY2(qFuzzyCompare(convertedToUtm.y, 5810000.5), "convert failed"); - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); + const LtsCoordTrans::UtmCoordinate& convertedToUtm = justReference.utmCoordinate(); + NOTICE_LOG(m_logger) << " convertedToUtm = " << convertedToUtm; + QVERIFY2(qFuzzyCompare(convertedToUtm.x, 670000.5), "convert failed"); + QVERIFY2(qFuzzyCompare(convertedToUtm.y, 5810000.5), "convert failed"); + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); + const LtsCoordTrans::UtmCoordinate& convertedToUtmSecondTry = justReference.utmCoordinate(); + Q_UNUSED(convertedToUtmSecondTry) + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); - - - - const LtsCoordTrans::UtmCoordinate &convertedToUtmSecondTry = justReference.utmCoordinate(); - Q_UNUSED(convertedToUtmSecondTry) - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); + std::vector myVec; + myVec.push_back(justReference); - - std::vector myVec; - myVec.push_back(justReference); + const LtsCoordTrans::LtsCoordinateNoImplicitCopy& retrievedUtmRef = myVec.front(); + NOTICE_LOG(m_logger) << " retrievedUtm = " << retrievedUtmRef.mgrs(); - - const LtsCoordTrans::LtsCoordinateNoImplicitCopy &retrievedUtmRef = myVec.front(); - NOTICE_LOG(m_logger) << " retrievedUtm = " << retrievedUtmRef.mgrs(); + QVERIFY2(justReference.mgrs() == retrievedUtmRef.mgrs(), "getConversionCounter failed"); - - QVERIFY2(justReference.mgrs() == retrievedUtmRef.mgrs(), "getConversionCounter failed"); - - - - - - QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); - - - - - + QVERIFY2(LtsCoordTrans::LtsCoordinate::getConversionCounter() == 1, "getConversionCounter failed"); } - - - -template -void removeItem(T& map, int key) { map.erase(key); } - - -template <> -void removeItem(QMap& map, int key) { map.remove(key); } - - -template <> -void removeItem(QHash& map, int key) { map.remove(key); } - - -template -void test_references(T& map) +template void removeItem(T& map, int key) { - for (int i=2; i<10; ++i) - map[i] = i; + map.erase(key); +} - const int &ref2 = map[2]; - const int &ref3 = map[3]; - const int &ref4 = map[4]; - const int &ref5 = map[5]; - const int &ref6 = map[6]; - const int &ref7 = map[7]; - const int &ref8 = map[8]; +template <> void removeItem(QMap& map, int key) +{ + map.remove(key); +} - QVERIFY2(ref2 == 2, "ref failed"); - QVERIFY2(ref3 == 3, "ref failed"); - QVERIFY2(ref4 == 4, "ref failed"); - QVERIFY2(ref5 == 5, "ref failed"); - QVERIFY2(ref6 == 6, "ref failed"); - QVERIFY2(ref7 == 7, "ref failed"); - QVERIFY2(ref8 == 8, "ref failed"); +template <> void removeItem(QHash& map, int key) +{ + map.remove(key); +} - - removeItem(map, 1); - removeItem(map, 3); - removeItem(map, 5); +template void test_references(T& map) +{ + for (int i = 2; i < 10; ++i) + map[i] = i; + + const int& ref2 = map[2]; + const int& ref3 = map[3]; + const int& ref4 = map[4]; + const int& ref5 = map[5]; + const int& ref6 = map[6]; + const int& ref7 = map[7]; + const int& ref8 = map[8]; - { QVERIFY2(ref2 == 2, "ref failed"); - + QVERIFY2(ref3 == 3, "ref failed"); QVERIFY2(ref4 == 4, "ref failed"); - + QVERIFY2(ref5 == 5, "ref failed"); QVERIFY2(ref6 == 6, "ref failed"); QVERIFY2(ref7 == 7, "ref failed"); QVERIFY2(ref8 == 8, "ref failed"); - } - - map[0] = 0; - map[1] = 1; - const int &ref0 = map[0]; - const int &ref1 = map[1]; + removeItem(map, 1); + removeItem(map, 3); + removeItem(map, 5); - { - QVERIFY2(ref0 == 0, "ref failed"); - QVERIFY2(ref1 == 1, "ref failed"); - - QVERIFY2(ref2 == 2, "ref failed"); - - QVERIFY2(ref4 == 4, "ref failed"); - - QVERIFY2(ref6 == 6, "ref failed"); - QVERIFY2(ref7 == 7, "ref failed"); - QVERIFY2(ref8 == 8, "ref failed"); - } + { + QVERIFY2(ref2 == 2, "ref failed"); + QVERIFY2(ref4 == 4, "ref failed"); + + QVERIFY2(ref6 == 6, "ref failed"); + QVERIFY2(ref7 == 7, "ref failed"); + QVERIFY2(ref8 == 8, "ref failed"); + } + + map[0] = 0; + map[1] = 1; + const int& ref0 = map[0]; + const int& ref1 = map[1]; + + { + QVERIFY2(ref0 == 0, "ref failed"); + QVERIFY2(ref1 == 1, "ref failed"); + + QVERIFY2(ref2 == 2, "ref failed"); + + QVERIFY2(ref4 == 4, "ref failed"); + + QVERIFY2(ref6 == 6, "ref failed"); + QVERIFY2(ref7 == 7, "ref failed"); + QVERIFY2(ref8 == 8, "ref failed"); + } } void UnitTestCoordinate::test_container_references() { - - - - - - - - - { - std::unordered_map std_unordered_map; - test_references(std_unordered_map); - } - { - std::map std_map; - test_references(std_map); - } - { - QMap Qmap; - test_references(Qmap); - } - { - QHash Qhash; - test_references(Qhash); - } + { + std::unordered_map std_unordered_map; + test_references(std_unordered_map); + } + { + std::map std_map; + test_references(std_map); + } + { + QMap Qmap; + test_references(Qmap); + } + { + QHash Qhash; + test_references(Qhash); + } } - - - - void UnitTestCoordinate::test_coordVector() { - std::vector geoVec; + std::vector geoVec; - { - - QPointF utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(); - geoVec.push_back( Core::GeoPosition(utmPnt.x(), utmPnt.y(), 1.1) ); + { - utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(1, 0); - geoVec.push_back( Core::GeoPosition(utmPnt.x(), utmPnt.y(), 2.2) ); + QPointF utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(); + geoVec.push_back(Core::GeoPosition(utmPnt.x(), utmPnt.y(), 1.1)); - utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(2, 0); - geoVec.push_back( Core::GeoPosition(utmPnt.x(), utmPnt.y(), 3.3) ); - } + utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(1, 0); + geoVec.push_back(Core::GeoPosition(utmPnt.x(), utmPnt.y(), 2.2)); - const LtsCoordVector coordVec(geoVec); - QVERIFY2(coordVec.size() == 3, "size failed"); + utmPnt = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32 U LB 00001 50001")).geographic(2, 0); + geoVec.push_back(Core::GeoPosition(utmPnt.x(), utmPnt.y(), 3.3)); + } - int cnt = LtsCoordTrans::getConversionCounter_UTMUPS_Forward(); + const LtsCoordVector coordVec(geoVec); + QVERIFY2(coordVec.size() == 3, "size failed"); - { - const std::vector &utmVec = coordVec.toStdUtmCoord(32); + int cnt = LtsCoordTrans::getConversionCounter_UTMUPS_Forward(); + { + const std::vector& utmVec = coordVec.toStdUtmCoord(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); + QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 3, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const std::vector& utmVec = coordVec.toStdUtmCoord(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); + QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 3, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const std::vector& utmVec = coordVec.toStdUtmCoord(31); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const std::vector& utmVec = coordVec.toStdUtmCoord(31); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const QVector& utmVec = coordVec.toQVectorUtmCoord(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); + QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const QVector& utmVec = coordVec.toQVectorUtmCoord(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); + QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); - QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 3, "getConversionCounterUTMUPS_Forward failed"); - } - { - const std::vector &utmVec = coordVec.toStdUtmCoord(32); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); - QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 3, "getConversionCounterUTMUPS_Forward failed"); - } - - { - const std::vector &utmVec = coordVec.toStdUtmCoord(31); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - { - const std::vector &utmVec = coordVec.toStdUtmCoord(31); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - - - - - - { - const QVector &utmVec = coordVec.toQVectorUtmCoord(32); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); - QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - { - const QVector &utmVec = coordVec.toQVectorUtmCoord(32); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(utmVec.front().mgrs() == QStringLiteral("32U LB 00001 50001"), "mgrs failed"); - QVERIFY2(utmVec.back().mgrs() == QStringLiteral("32U LB 00003 50001"), "mgrs failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - - - - - - { - const QVector &utmVec = coordVec.toQVectorQPointF(32); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - { - const QVector &utmVec = coordVec.toQVectorUtmCoord(32); - QVERIFY2(utmVec.size() == 3, "size failed"); - QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, "getConversionCounterUTMUPS_Forward failed"); - } - + { + const QVector& utmVec = coordVec.toQVectorQPointF(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } + { + const QVector& utmVec = coordVec.toQVectorUtmCoord(32); + QVERIFY2(utmVec.size() == 3, "size failed"); + QVERIFY2(LtsCoordTrans::getConversionCounter_UTMUPS_Forward() - cnt == 6, + "getConversionCounterUTMUPS_Forward failed"); + } } - - - - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - NGLCoreApplication app(argc, argv); - app.createLogger("UnitTestCoordinate", "log4cxxPositionUnitTest.props"); + NGLCoreApplication app(argc, argv); + app.createLogger("UnitTestCoordinate", "log4cxxPositionUnitTest.props"); - UnitTestCoordinate tc; + UnitTestCoordinate tc; - int ret = QTest::qExec(&tc, argc, argv); + int ret = QTest::qExec(&tc, argc, argv); - - if (s_eleMgr) - { - s_eleMgr->cleanupAll(); - } + if (s_eleMgr) + { + s_eleMgr->cleanupAll(); + } - return ret; + return ret; } - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.h old mode 100755 new mode 100644 index e4d28536d..fc587132b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/UnitTest_Coordinate/lts_coordinate_unit_test.h @@ -1,85 +1,60 @@ - #pragma once -#include - -#include - #include - -#include -#include +#include #include - +#include +#include +#include using LOGGER_T = NGL::INGLLogger&; - - - class UnitTestCoordinate : public QObject { - Q_OBJECT + Q_OBJECT -public: - UnitTestCoordinate(); + public: + UnitTestCoordinate(); + private Q_SLOTS: -private Q_SLOTS: + void initTestCase(); - - - + void init(); + void test_NaN(); - void initTestCase(); + void test_coordinate_simple1(); + void test_coordinate_simple2(); + void test_coordinate_simple3(); + void test_coordinate_simple4(); - void init(); - + void test_coordinate_fromUtm(); + void test_coordinate_fromUtm2(); + void test_coordinate_elevationAt(); + void test_coordinate_elevationAt_isCovered(); - void test_NaN(); + void test_coordinate_elevation_data(); + void test_coordinate_elevation(); - void test_coordinate_simple1(); - void test_coordinate_simple2(); - void test_coordinate_simple3(); - void test_coordinate_simple4(); + void test_coordinate_mgrs(); - void test_coordinate_fromUtm(); - void test_coordinate_fromUtm2(); + void test_coordinate_distance(); + void test_coordinate_distanceDiffZones(); - void test_coordinate_elevationAt(); - void test_coordinate_elevationAt_isCovered(); + void test_squareInDifferentZone(); - void test_coordinate_elevation_data(); - void test_coordinate_elevation(); + void test_coordinate_angle(); - void test_coordinate_mgrs(); + void test_coordinate_cont(); - void test_coordinate_distance(); - void test_coordinate_distanceDiffZones(); + void test_coordinate_avoid_copy(); - void test_squareInDifferentZone(); + void test_container_references(); + void test_coordVector(); - void test_coordinate_angle(); - - void test_coordinate_cont(); - - void test_coordinate_avoid_copy(); - - - - void test_container_references(); - void test_coordVector(); - - - - -private: - - - - -NGL::INGLLogger &m_logger; + private: + NGL::INGLLogger& m_logger; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.cpp old mode 100755 new mode 100644 index f386c915d..a9e0435aa --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.cpp @@ -1,90 +1,69 @@ - - #include "lts_coord_vector.h" namespace LtsCoordTrans { -LtsCoordVector::LtsCoordVector(const std::vector &geo_coordinates) - : m_geo_coordinates(geo_coordinates) +LtsCoordVector::LtsCoordVector(const std::vector& geo_coordinates) + : m_geo_coordinates(geo_coordinates) { - } -const std::vector &LtsCoordVector::toStdUtmCoord(int zone) const +const std::vector& LtsCoordVector::toStdUtmCoord(int zone) const { - convertGeoToStdUtm(zone); - return m_utmMapStd[zone]; + convertGeoToStdUtm(zone); + return m_utmMapStd[zone]; } -const QVector &LtsCoordVector::toQVectorUtmCoord(int zone) const +const QVector& LtsCoordVector::toQVectorUtmCoord(int zone) const { - convertGeoToQVectorUtm(zone); - return m_utmMapQVector[zone]; + convertGeoToQVectorUtm(zone); + return m_utmMapQVector[zone]; } -const QVector &LtsCoordVector::toQVectorQPointF(int zone) const +const QVector& LtsCoordVector::toQVectorQPointF(int zone) const { - convertGeoToQVectorQPointF(zone); - return m_utmMapQVectorQPointF[zone]; + convertGeoToQVectorQPointF(zone); + return m_utmMapQVectorQPointF[zone]; } void LtsCoordVector::convertGeoToStdUtm(int zone) const { - const auto it = m_utmMapStd.find(zone); - if (it != m_utmMapStd.end()) - return; - convertGeoToUtmInternal(zone, m_utmMapStd[zone]); + const auto it = m_utmMapStd.find(zone); + if (it != m_utmMapStd.end()) + return; + convertGeoToUtmInternal(zone, m_utmMapStd[zone]); } void LtsCoordVector::convertGeoToQVectorUtm(int zone) const { - const auto it = m_utmMapQVector.find(zone); - if (it != m_utmMapQVector.end()) - return; + const auto it = m_utmMapQVector.find(zone); + if (it != m_utmMapQVector.end()) + return; - - + convertGeoToStdUtm(zone); + QVector& utmVectorRef = m_utmMapQVector[zone]; + utmVectorRef.clear(); + utmVectorRef.reserve(m_geo_coordinates.size()); - - convertGeoToStdUtm(zone); - QVector &utmVectorRef = m_utmMapQVector[zone]; - utmVectorRef.clear(); - utmVectorRef.reserve(m_geo_coordinates.size()); - - for (const auto &utmCoord : m_utmMapStd[zone]) - utmVectorRef.push_back(utmCoord); + for (const auto& utmCoord : m_utmMapStd[zone]) + utmVectorRef.push_back(utmCoord); } void LtsCoordVector::convertGeoToQVectorQPointF(int zone) const { - const auto it = m_utmMapQVectorQPointF.find(zone); - if (it != m_utmMapQVectorQPointF.end()) - return; + const auto it = m_utmMapQVectorQPointF.find(zone); + if (it != m_utmMapQVectorQPointF.end()) + return; - convertGeoToStdUtm(zone); - QVector &QVectorQPointFRef = m_utmMapQVectorQPointF[zone]; - QVectorQPointFRef.clear(); - QVectorQPointFRef.reserve(m_geo_coordinates.size()); + convertGeoToStdUtm(zone); + QVector& QVectorQPointFRef = m_utmMapQVectorQPointF[zone]; + QVectorQPointFRef.clear(); + QVectorQPointFRef.reserve(m_geo_coordinates.size()); - for (const auto &utmCoord : m_utmMapStd[zone]) - QVectorQPointFRef.push_back(QPointF(utmCoord.x, utmCoord.y)); + for (const auto& utmCoord : m_utmMapStd[zone]) + QVectorQPointFRef.push_back(QPointF(utmCoord.x, utmCoord.y)); } - - - - - - - - - - - - -} - - +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.h old mode 100755 new mode 100644 index 166fcf8b9..8ddba4d3e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coord_vector.h @@ -1,82 +1,62 @@ - #pragma once #include "ltscoordinate_export.h" -#include -#include -#include - -#include +#include +#include +#include #include #include -#include - #include +#include +#include #include - namespace LtsCoordTrans { - - class LTSCOORDINATE_EXPORT LtsCoordVector { -public: + public: + explicit LtsCoordVector(const std::vector& geo_coordinates); - - - explicit LtsCoordVector(const std::vector &geo_coordinates); + int size() const + { + return m_geo_coordinates.size(); + } - - - int size() const { return m_geo_coordinates.size() ; } - const std::vector &geoPosition() const { return m_geo_coordinates; } - + const std::vector& geoPosition() const + { + return m_geo_coordinates; + } - - - const std::vector &toStdUtmCoord(int zone) const; - const QVector &toQVectorUtmCoord(int zone) const; - const QVector &toQVectorQPointF(int zone) const; - + const std::vector& toStdUtmCoord(int zone) const; + const QVector& toQVectorUtmCoord(int zone) const; + const QVector& toQVectorQPointF(int zone) const; + protected: + void convertGeoToStdUtm(int zone) const; + void convertGeoToQVectorUtm(int zone) const; + void convertGeoToQVectorQPointF(int zone) const; -protected: - void convertGeoToStdUtm(int zone) const; - void convertGeoToQVectorUtm(int zone) const; - void convertGeoToQVectorQPointF(int zone) const; + template void convertGeoToUtmInternal(int zone, T& utmVectorRef) const + { - template - void convertGeoToUtmInternal(int zone, T &utmVectorRef) const - { - - utmVectorRef.clear(); - utmVectorRef.reserve(m_geo_coordinates.size()); + utmVectorRef.clear(); + utmVectorRef.reserve(m_geo_coordinates.size()); - for (const auto &geoCoord : std::as_const(m_geo_coordinates)) - utmVectorRef.push_back(LtsCoordTrans::UtmCoordinate::fromGeographic(geoCoord.lon(), geoCoord.lat(), zone)); - } + for (const auto& geoCoord : std::as_const(m_geo_coordinates)) + utmVectorRef.push_back(LtsCoordTrans::UtmCoordinate::fromGeographic(geoCoord.lon(), geoCoord.lat(), zone)); + } -protected: - std::vector m_geo_coordinates; + protected: + std::vector m_geo_coordinates; - - - - mutable std::unordered_map> m_utmMapStd; - mutable std::unordered_map> m_utmMapQVector; - mutable std::unordered_map> m_utmMapQVectorQPointF; + mutable std::unordered_map> m_utmMapStd; + mutable std::unordered_map> m_utmMapQVector; + mutable std::unordered_map> m_utmMapQVectorQPointF; }; - - - - - - -} - +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.cpp old mode 100755 new mode 100644 index 5074715bf..64b5344d7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.cpp @@ -1,178 +1,142 @@ - - #include "lts_coordinate.h" + #include namespace LtsCoordTrans { -static long s_conversion_counter = 0; - +static long s_conversion_counter = 0; std::function LtsCoordinate::m_getElevationCB; - - - -void LtsCoordinate::setElevationCallback(const elevationCbFunc &elevationCB) +void LtsCoordinate::setElevationCallback(const elevationCbFunc& elevationCB) { - m_getElevationCB = elevationCB; + m_getElevationCB = elevationCB; } bool LtsCoordinate::hasElevationCallback() { - return m_getElevationCB != nullptr; + return m_getElevationCB != nullptr; } -double LtsCoordinate::elevationAt(double defaultElevation, bool *bIsCovered) const +double LtsCoordinate::elevationAt(double defaultElevation, bool* bIsCovered) const { - - - - if (!bIsCovered) - if (!std::isnan(m_elevation)) - return m_elevation; - if (m_getElevationCB) - m_elevation = m_getElevationCB(m_geo.lon(), m_geo.lat(), defaultElevation, bIsCovered); - return m_elevation; + + if (!bIsCovered) + if (!std::isnan(m_elevation)) + return m_elevation; + if (m_getElevationCB) + m_elevation = m_getElevationCB(m_geo.lon(), m_geo.lat(), defaultElevation, bIsCovered); + return m_elevation; } void LtsCoordinate::setZValueAccordingElevation(double defaultElevation) { - m_geo.z(elevationAt(defaultElevation)); + m_geo.z(elevationAt(defaultElevation)); } -double LtsCoordinate::elevationAt(const LtsCoordinate &coordinate, double defaultElevation, bool *bIsCovered) +double LtsCoordinate::elevationAt(const LtsCoordinate& coordinate, double defaultElevation, bool* bIsCovered) { - return coordinate.elevationAt(defaultElevation, bIsCovered); + return coordinate.elevationAt(defaultElevation, bIsCovered); } void LtsCoordinate::replaceZValueByElevationIfValue(double zValueToBeReplaced, double defaultElevation) { - - - - - if ((std::isnan(zValueToBeReplaced) && std::isnan(m_geo.z())) || - qFuzzyCompare(m_geo.z(), zValueToBeReplaced)) - setZValueAccordingElevation(defaultElevation); + if ((std::isnan(zValueToBeReplaced) && std::isnan(m_geo.z())) || qFuzzyCompare(m_geo.z(), zValueToBeReplaced)) + setZValueAccordingElevation(defaultElevation); } -double LtsCoordinate::angleDegreeUtm2D(const LtsCoordinate &coord1, const LtsCoordinate &coord2) +double LtsCoordinate::angleDegreeUtm2D(const LtsCoordinate& coord1, const LtsCoordinate& coord2) { - const LtsCoordTrans::UtmCoordinate &utm1 = coord1.utmCoordinate(); - const LtsCoordTrans::UtmCoordinate &utm2 = coord2.utmCoordinateDiffZone(utm1.zone); + const LtsCoordTrans::UtmCoordinate& utm1 = coord1.utmCoordinate(); + const LtsCoordTrans::UtmCoordinate& utm2 = coord2.utmCoordinateDiffZone(utm1.zone); - const QPointF& offsetUtm = utm2.toPoint() - utm1.toPoint(); - QLineF poly(QPointF(), offsetUtm); - const double angle = poly.angle(); + const QPointF& offsetUtm = utm2.toPoint() - utm1.toPoint(); + QLineF poly(QPointF(), offsetUtm); + const double angle = poly.angle(); - - - - - - - - - - - - - - - - - - - - return fmod(angle+90.0, 360); + return fmod(angle + 90.0, 360); } -const UtmCoordinate &LtsCoordinate::utmCoordinateInternal(int zone) const +const UtmCoordinate& LtsCoordinate::utmCoordinateInternal(int zone) const { - if (zone == -1) - { - if (!hasUtm()) - convertGeoToUtm(); - return m_utm2D; - } - utmCoordinateDiffZone(zone); - return m_utm2D_differentZone; + if (zone == -1) + { + if (!hasUtm()) + convertGeoToUtm(); + return m_utm2D; + } + utmCoordinateDiffZone(zone); + return m_utm2D_differentZone; } void LtsCoordinate::convertGeoToUtm() const { - - int zone = -1; - - if (std::isnan(m_geo.lon()) || std::isnan(m_geo.lat())) - { - fprintf(stderr, "Error while fromGeographic, value is NaN\n"); - m_utm2D = LtsCoordTrans::UtmCoordinate(); - return; - } + + int zone = -1; + + if (std::isnan(m_geo.lon()) || std::isnan(m_geo.lat())) + { + fprintf(stderr, "Error while fromGeographic, value is NaN\n"); + m_utm2D = LtsCoordTrans::UtmCoordinate(); + return; + } #ifdef LTS_DEBUG - ++s_conversion_counter; -#endif + ++s_conversion_counter; +#endif - m_utm2D = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone); - Q_ASSERT_X(m_utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); + m_utm2D = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone); + Q_ASSERT_X(m_utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); } QString LtsCoordinate::mgrs(int prec, bool withSpaces) const { - utmCoordinateInternal(); - QString tmp = m_utm2D.mgrs(prec, withSpaces); - return tmp; + utmCoordinateInternal(); + QString tmp = m_utm2D.mgrs(prec, withSpaces); + return tmp; } QString LtsCoordinate::mgrsWithZ(int prec, bool withSpaces) const { - double ele = elevationAt(); - QString tmp = mgrs(prec, withSpaces) + QStringLiteral(" z=") + QString::number(ele, 'f', 2); - return tmp; + double ele = elevationAt(); + QString tmp = mgrs(prec, withSpaces) + QStringLiteral(" z=") + QString::number(ele, 'f', 2); + return tmp; } - QString LtsCoordinate::toString(bool fullAndExpensive) const { - if (fullAndExpensive) - { - utmCoordinateInternal(); - elevationAt(); - } - std::ostringstream stream; - stream << "LtsCoordinate(m_geo=" << m_geo - << ", m_utm2D.x " << m_utm2D.x << ", m_utm2D.y " << m_utm2D.y << ", m_utm2D.zone " << m_utm2D.zone; - if (!qFuzzyIsNull(m_utm2D.x) || !qFuzzyIsNull(m_utm2D.y)) - stream << ", m_utm2D.mgrs '" << m_utm2D.mgrs().toUtf8().constData() << "'"; - stream << ", elevation " << std::fixed << std::setprecision(3) << m_elevation - << ")"; - return QString::fromStdString(stream.str()); + if (fullAndExpensive) + { + utmCoordinateInternal(); + elevationAt(); + } + std::ostringstream stream; + stream << "LtsCoordinate(m_geo=" << m_geo << ", m_utm2D.x " << m_utm2D.x << ", m_utm2D.y " << m_utm2D.y + << ", m_utm2D.zone " << m_utm2D.zone; + if (!qFuzzyIsNull(m_utm2D.x) || !qFuzzyIsNull(m_utm2D.y)) + stream << ", m_utm2D.mgrs '" << m_utm2D.mgrs().toUtf8().constData() << "'"; + stream << ", elevation " << std::fixed << std::setprecision(3) << m_elevation << ")"; + return QString::fromStdString(stream.str()); } void LtsCoordinate::resetConversionCounter() { - s_conversion_counter = 0; + s_conversion_counter = 0; } + long LtsCoordinate::getConversionCounter() { - return s_conversion_counter; + return s_conversion_counter; } - - -std::ostream &operator<<(std::ostream &stream, const LtsCoordinate &value) +std::ostream& operator<<(std::ostream& stream, const LtsCoordinate& value) { - stream << value.toString().toStdString(); - return stream; + stream << value.toString().toStdString(); + return stream; } -} - - +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.h old mode 100755 new mode 100644 index ca4c0dbb1..20e9f380f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsCoordinate/lts_coordinate.h @@ -1,368 +1,297 @@ - #pragma once #include "ltscoordinate_export.h" -#include -#include -#include -#include - -#include +#include +#include +#include #include - -#include +#include +#include #include -#include - +#include +#include namespace LtsCoordTrans { using UtmCoordinate2D = LtsCoordTrans::UtmCoordinate; -using QPoint3D = LtsUtils::QPoint3D; - - - - +using QPoint3D = LtsUtils::QPoint3D; class LTSCOORDINATE_EXPORT LtsCoordinate { -public: + public: + explicit LtsCoordinate(double lon = 0, double lat = 0, double z = std::nan("")) + : m_geo(Core::GeoPosition(lon, lat, z)) + { + } - - + explicit LtsCoordinate(const QPointF& lonLat, double z = std::nan("")) + : m_geo(Core::GeoPosition(lonLat.x(), lonLat.y(), z)) + { + } - - - - explicit LtsCoordinate(double lon = 0, double lat = 0, double z = std::nan("")) - : m_geo(Core::GeoPosition(lon, lat, z)) - {} + explicit LtsCoordinate(const Core::GeoPosition& geoPos) : m_geo(geoPos) {} - explicit LtsCoordinate(const QPointF &lonLat, double z = std::nan("")) - : m_geo(Core::GeoPosition(lonLat.x(), lonLat.y(), z)) - {} + explicit LtsCoordinate(const Core::GeoPosition2D& geoPos2D) : m_geo(geoPos2D.lon(), geoPos2D.lat(), std::nan("")) {} - explicit LtsCoordinate(const Core::GeoPosition &geoPos) - : m_geo(geoPos) - {} + LtsCoordinate(const LtsCoordTrans::UtmCoordinate& utm2D, double zValue) = delete; - explicit LtsCoordinate(const Core::GeoPosition2D &geoPos2D) - : m_geo(geoPos2D.lon(), geoPos2D.lat(), std::nan("")) - {} + static LtsCoordinate fromGeoPosition(double lon, double lat, double z = std::nan("")) + { + return LtsCoordinate(lon, lat, z); + } - - - LtsCoordinate(const LtsCoordTrans::UtmCoordinate &utm2D, double zValue) = delete; + static LtsCoordinate fromUtmCoordinate(const LtsCoordTrans::UtmCoordinate& utm2D, double zValue) + { + Q_ASSERT_X(utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); - static LtsCoordinate fromGeoPosition(double lon, double lat, double z = std::nan("")) - { - return LtsCoordinate(lon, lat, z); - } + const QPointF& geoPnt = utm2D.geographic(); - - static LtsCoordinate fromUtmCoordinate(const LtsCoordTrans::UtmCoordinate &utm2D, double zValue) - { - Q_ASSERT_X(utm2D.zone > 0, "LtsCoordinate", "zone has to be set"); + return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue); + } - - - const QPointF &geoPnt = utm2D.geographic(); - - return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue); - } + static LtsCoordinate fromUtm(const QPointF& utm2d, int zone, double zValue) + { + const LtsCoordTrans::UtmCoordinate utmCoord(zone, utm2d.x(), utm2d.y()); + const QPointF& geoPnt = utmCoord.geographic(); + return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue); + } - static LtsCoordinate fromUtm(const QPointF &utm2d, int zone, double zValue) - { - const LtsCoordTrans::UtmCoordinate utmCoord(zone, utm2d.x(), utm2d.y()); - const QPointF &geoPnt = utmCoord.geographic(); - return LtsCoordinate(geoPnt.x(), geoPnt.y(), zValue); - } - + bool isValid() const + { + return hasGeo() || hasUtm(); + } + bool hasGeo() const + { + return !(valueIsNullOrNan(m_geo.lon()) || valueIsNullOrNan(m_geo.lat())); + } - - + bool hasUtm() const + { + return m_utm2D.isValid(); + } - bool isValid() const { return hasGeo() || hasUtm(); } - bool hasGeo() const { return !(valueIsNullOrNan(m_geo.lon()) || - valueIsNullOrNan(m_geo.lat())); } - bool hasUtm() const { return m_utm2D.isValid(); } + static bool valueIsNullOrNan(double value) + { + return qFuzzyIsNull(value) || std::isnan(value); + } - static bool valueIsNullOrNan(double value) { return qFuzzyIsNull(value) || std::isnan(value); } + QString mgrs(int prec = 5, bool withSpaces = true) const; + QString mgrsWithZ(int prec = 5, bool withSpaces = true) const; - QString mgrs(int prec = 5, bool withSpaces = true) const; - QString mgrsWithZ(int prec = 5, bool withSpaces = true) const; + QString toString(bool fullAndExpensive = false) const; - QString toString(bool fullAndExpensive = false) const; + static void resetConversionCounter(); + static long getConversionCounter(); + const Core::GeoPosition& geoPosition() const + { + return m_geo; + } - - static void resetConversionCounter(); - static long getConversionCounter(); - + const Core::GeoPosition2D& geoPosition2D() const + { + return m_geo; + } + const LtsCoordTrans::UtmCoordinate& utmCoordinate() const + { + if (!hasUtm()) + convertGeoToUtm(); + return m_utm2D; + } - - - const Core::GeoPosition &geoPosition() const - { - return m_geo; - } - const Core::GeoPosition2D &geoPosition2D() const - { - return m_geo; - } + double& rz() + { + return m_geo.z(); + } - const LtsCoordTrans::UtmCoordinate &utmCoordinate() const - { - if (!hasUtm()) - convertGeoToUtm(); - return m_utm2D; - } + double z() const + { + return m_geo.z(); + } - - double &rz() { return m_geo.z(); } - double z() const { return m_geo.z(); } - void setZ(double value) { m_geo.z(value); } + void setZ(double value) + { + m_geo.z(value); + } + LtsCoordTrans::UtmCoordinate utmCoordinateDiffZone(int zone) const + { - LtsCoordTrans::UtmCoordinate utmCoordinateDiffZone(int zone) const - { - - - m_utm2D_differentZone = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone); - return m_utm2D_differentZone; - } - + m_utm2D_differentZone = LtsCoordTrans::UtmCoordinate::fromGeographic(m_geo.lon(), m_geo.lat(), zone); + return m_utm2D_differentZone; + } - - + template T toUtm(int zone = -1) const + { + T obj; + helperToUtm(obj, zone); + return obj; + } - template - T toUtm(int zone = -1) const - { - T obj; - helperToUtm(obj, zone); - return obj; + QPointF toUtmPointF() const + { + return toUtm(); + } - - - } + QPoint3D toUtmPoint3D() const + { + return toUtm(); + } - QPointF toUtmPointF() const { return toUtm(); } - QPoint3D toUtmPoint3D() const { return toUtm(); } + QPointF toGeoPointF() const + { + return QPointF(m_geo.lon(), m_geo.lat()); + } - QPointF toGeoPointF() const { return QPointF (m_geo.lon(), m_geo.lat()); } - QPoint3D toGeoPoint3D() const { return QPoint3D(m_geo.lon(), m_geo.lat(), m_geo.z() ); } + QPoint3D toGeoPoint3D() const + { + return QPoint3D(m_geo.lon(), m_geo.lat(), m_geo.z()); + } + UtmCoordinate3D toUtmCoordinate3D() const + { + return UtmCoordinate3D(utmCoordinate(), m_geo.z()); + } - UtmCoordinate3D toUtmCoordinate3D() const - { - return UtmCoordinate3D(utmCoordinate(), m_geo.z()); - } - + using elevationCbFunc = std::function; + static void setElevationCallback(const elevationCbFunc& elevationCB); + static bool hasElevationCallback(); - - - using elevationCbFunc = std::function; + double elevationAt(double defaultElevation = 0.0, bool* bIsCovered = nullptr) const; + void setZValueAccordingElevation(double defaultElevation = 0.0); - - - - static void setElevationCallback(const elevationCbFunc &elevationCB); - static bool hasElevationCallback(); + static double elevationAt(const LtsCoordinate& coordinate, double defaultElevation = 0.0, + bool* bIsCovered = nullptr); - - - - double elevationAt(double defaultElevation = 0.0, bool *bIsCovered = nullptr) const; - void setZValueAccordingElevation(double defaultElevation = 0.0); + void replaceZValueByElevationIfValue(double zValueToBeReplaced = std::nan(""), double defaultElevation = 0.0); - static double elevationAt(const LtsCoordinate &coordinate, double defaultElevation = 0.0, bool *bIsCovered = nullptr); + double heightOverElevation() const + { + return m_geo.z() - elevationAt(); + } - - - - - - - + double distanceUtm2D(const LtsCoordinate& other) const + { - - - + const LtsCoordTrans::UtmCoordinate& thisUtm2D = utmCoordinate(); + const LtsCoordTrans::UtmCoordinate& otherUtm2D = other.utmCoordinateDiffZone(m_utm2D.zone); + return LtsCoordTrans::distance(thisUtm2D, otherUtm2D); + } - void replaceZValueByElevationIfValue(double zValueToBeReplaced = std::nan(""), double defaultElevation = 0.0); - + double distanceUtm3D(const LtsCoordinate& other) const + { + const QPoint3D& thisUtm3D = toUtm(); + const QPoint3D& otherUtm3D = other.toUtm(m_utm2D.zone); + const double dist3D = (thisUtm3D - otherUtm3D).length(); + Q_ASSERT_X(!std::isnan(dist3D), "LtsCoordinate", "ERROR, distance3D is NaN"); + return dist3D; + } - - + static double angleDegreeUtm2D(const LtsCoordinate& coord1, const LtsCoordinate& coord2); - double heightOverElevation() const { return m_geo.z() - elevationAt(); } + protected: + void clearGeo() const + { + clearGeoLonLat(); + m_geo.z(std::nan("")); + } + void clearGeoLonLat() const + { + m_geo.lon(0); + m_geo.lat(0); + } - double distanceUtm2D(const LtsCoordinate &other) const - { - - - const LtsCoordTrans::UtmCoordinate &thisUtm2D = utmCoordinate(); - const LtsCoordTrans::UtmCoordinate &otherUtm2D = other.utmCoordinateDiffZone(m_utm2D.zone); - return LtsCoordTrans::distance(thisUtm2D, otherUtm2D); - } + void clearUtm() const + { + m_utm2D = m_utm2D_differentZone = UtmCoordinate2D(); + } - double distanceUtm3D(const LtsCoordinate &other) const - { - - - const QPoint3D &thisUtm3D = toUtm(); - const QPoint3D &otherUtm3D = other.toUtm(m_utm2D.zone); - const double dist3D = (thisUtm3D - otherUtm3D).length(); + void clearElevation() const + { + m_elevation = std::nan(""); + } - Q_ASSERT_X(!std::isnan(dist3D), "LtsCoordinate", "ERROR, distance3D is NaN"); + void clear() const + { + clearGeo(); + clearUtm(); + clearElevation(); + } - return dist3D; - } + const LtsCoordTrans::UtmCoordinate& utmCoordinateInternal(int zone = -1) const; + void convertGeoToUtm() const; - - - - - - - - - static double angleDegreeUtm2D(const LtsCoordinate &coord1, const LtsCoordinate &coord2); + protected: + void helperToUtm(QPointF& pntRef, int zone = -1) const + { + const auto& utmTemp = utmCoordinateInternal(zone); + pntRef.rx() = utmTemp.x; + pntRef.ry() = utmTemp.y; + } + void helperToUtm(QPoint3D& pntRef, int zone = -1) const + { + const auto& utmTemp = utmCoordinateInternal(zone); + pntRef.rx() = utmTemp.x; + pntRef.ry() = utmTemp.y; + pntRef.rz() = m_geo.z(); + } - + protected: + mutable Core::GeoPosition m_geo; + mutable UtmCoordinate2D m_utm2D; + mutable UtmCoordinate2D m_utm2D_differentZone; + mutable double m_elevation{std::nan("")}; - -protected: - - void clearGeo() const { clearGeoLonLat(); m_geo.z(std::nan("")); } - void clearGeoLonLat() const { m_geo.lon(0); m_geo.lat(0); } - void clearUtm() const { m_utm2D = m_utm2D_differentZone = UtmCoordinate2D(); } - void clearElevation() const { m_elevation = std::nan(""); } - void clear() const { clearGeo(); clearUtm(); clearElevation(); } - - const LtsCoordTrans::UtmCoordinate &utmCoordinateInternal(int zone = -1) const; - void convertGeoToUtm() const; - -protected: - - void helperToUtm(QPointF &pntRef, int zone = -1) const - { - const auto &utmTemp = utmCoordinateInternal(zone); - pntRef.rx() = utmTemp.x; - pntRef.ry() = utmTemp.y; - } - void helperToUtm(QPoint3D &pntRef, int zone = -1) const - { - const auto &utmTemp = utmCoordinateInternal(zone); - pntRef.rx() = utmTemp.x; - pntRef.ry() = utmTemp.y; - pntRef.rz() = m_geo.z(); - } - -protected: - mutable Core::GeoPosition m_geo; - mutable UtmCoordinate2D m_utm2D; - mutable UtmCoordinate2D m_utm2D_differentZone; - mutable double m_elevation{std::nan("")}; - - static elevationCbFunc m_getElevationCB; + static elevationCbFunc m_getElevationCB; }; - - - class LTSCOORDINATE_EXPORT LtsCoordinateNoImplicitCopy : public LtsCoordinate { -public: - using BaseClass = LtsCoordinate; + public: + using BaseClass = LtsCoordinate; - + LtsCoordinateNoImplicitCopy() = default; + explicit LtsCoordinateNoImplicitCopy(const LtsCoordinateNoImplicitCopy&) = default; - LtsCoordinateNoImplicitCopy() = default; - explicit LtsCoordinateNoImplicitCopy (const LtsCoordinateNoImplicitCopy &) = default; + ~LtsCoordinateNoImplicitCopy() = default; - - - - - - + explicit LtsCoordinateNoImplicitCopy(const QPointF& lonLat, double z = std::nan("")) + : BaseClass(Core::GeoPosition(lonLat.x(), lonLat.y(), z)) + { + } - ~LtsCoordinateNoImplicitCopy() = default; + explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition& geoPos) : BaseClass(geoPos) {} + explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition2D& geoPos2D) : BaseClass(geoPos2D) {} - - - - - - explicit LtsCoordinateNoImplicitCopy(const QPointF &lonLat, double z = std::nan("")) - : BaseClass(Core::GeoPosition(lonLat.x(), lonLat.y(), z)) - {} - - explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition &geoPos) - : BaseClass(geoPos) - {} - - explicit LtsCoordinateNoImplicitCopy(const Core::GeoPosition2D &geoPos2D) - : BaseClass(geoPos2D) - {} - - - - - void updateGeoPosition(const Core::GeoPosition &geoPos) const - { - clear(); - m_geo = geoPos; - } + void updateGeoPosition(const Core::GeoPosition& geoPos) const + { + clear(); + m_geo = geoPos; + } }; - - - - - - - - - - - - - - - - - -template -T_OUT convert(const T_IN& contIn) +template T_OUT convert(const T_IN& contIn) { - T_OUT out; - out.reserve(contIn.size()); - for (const Core::GeoPosition &posGeo : std::as_const(contIn)) - out.push_back(LtsCoordinate(posGeo)); - return out; + T_OUT out; + out.reserve(contIn.size()); + for (const Core::GeoPosition& posGeo : std::as_const(contIn)) + out.push_back(LtsCoordinate(posGeo)); + return out; } +LTSCOORDINATE_EXPORT std::ostream& operator<<(std::ostream& stream, const LtsCoordinate& value); - -LTSCOORDINATE_EXPORT std::ostream &operator<< (std::ostream &stream, - const LtsCoordinate &value); - - -} - +} // namespace LtsCoordTrans diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.cpp old mode 100755 new mode 100644 index f4c67e4c3..a3496268b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.cpp @@ -1,230 +1,198 @@ - #include "elevation_unit_test.h" #include #include - -#include #include #include - +#include Q_DECLARE_METATYPE(LtsUtils::QPoint3D); Q_DECLARE_METATYPE(LtsElevation::LineOfSight); #include -static const int s_id{4711}; -static LtsElevation::LtsElevationManager *s_eleMgr{nullptr}; - - - - - - +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); - } + 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")) -{} - + : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTestElevation")) +{ +} void UnitTestElevation::initTestCase() { - - QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif")); + QString filePath(QStringLiteral("/usr/share/arcgis/resources/elevation/Altmark_dt1.tif")); - s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath}); + s_eleMgr = MyLtsElevationManagerBootstrap::createInstanceUnitTest(s_id, {filePath}); - const bool bIsValid = s_eleMgr->isValid(); - std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl; - - - { - s_eleMgr->waitForInitialization(); const bool bIsValid = s_eleMgr->isValid(); - std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl; - } + std::cerr << "myBootstrapMgr->isValid() 1 = " << bIsValid << std::endl; + + { + s_eleMgr->waitForInitialization(); + const bool bIsValid = s_eleMgr->isValid(); + std::cerr << "myBootstrapMgr->isValid() 2 = " << bIsValid << std::endl; + } } void UnitTestElevation::init() { - QVERIFY2(s_eleMgr , "static LtsElevationManager does not exist"); + QVERIFY2(s_eleMgr, "static LtsElevationManager does not exist"); } - - - void UnitTestElevation::test_elevation_data() { - QTest::addColumn("lonLat"); - QTest::addColumn("elevationRef"); + QTest::addColumn("lonLat"); + QTest::addColumn("elevationRef"); - - QTest::newRow("elevation 1 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic() << 75.0; - QTest::newRow("elevation 2 ") << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 72000 13000")).geographic() << 80.0; + QTest::newRow("elevation 1 ") + << LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic() << 75.0; + QTest::newRow("elevation 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; + 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); + QFETCH(QPointF, lonLat); + QFETCH(double, elevationRef); - double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y()); + double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y()); - QVERIFY2(qFuzzyCompare(elevationRef, elevation), " got wrong elevation result"); + QVERIFY2(qFuzzyCompare(elevationRef, elevation), " got wrong elevation result"); } void UnitTestElevation::test_elevation_isCovered() { - const QPointF &lonLat1 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U PD 70000 10000")).geographic(); - const QPointF &lonLat2 = LtsCoordTrans::UtmCoordinate::fromMgrs(QStringLiteral("32U MD 60000 10000")).geographic(); + const QPointF& 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"); - } + 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(); + 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::min()), " error on defaultValue"); + double elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y()); + QVERIFY2(qFuzzyCompare(elevation, std::numeric_limits::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 = 100; + elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue); + QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue"); + } - { - const double defaultValue = std::numeric_limits::max(); - elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue); - QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue"); - } + { + const double defaultValue = std::numeric_limits::max(); + elevation = s_eleMgr->elevation(lonLat.x(), lonLat.y(), defaultValue); + QVERIFY2(qFuzzyCompare(elevation, defaultValue), " error on defaultValue"); + } } - - - void UnitTestElevation::test_lineOfSightCalculation_data() { - QTest::addColumn("startGeo2D"); - QTest::addColumn("startObjH"); - QTest::addColumn("endGeo2D"); - QTest::addColumn("endObjH"); - QTest::addColumn("expectedResult"); + QTest::addColumn("startGeo2D"); + QTest::addColumn("startObjH"); + QTest::addColumn("endGeo2D"); + QTest::addColumn("endObjH"); + QTest::addColumn("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 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 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; + 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); + 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 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()); + 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 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"); - } + { + LtsElevation::LineOfSight los2 = s_eleMgr->lineOfSightCalculation(startGeo2D, startObjH, endGeo2D, endObjH); + QVERIFY2(los == los2, " got different lineOfSightCalculation result"); + } - - - QVERIFY2(los == expectedResult, " got lineOfSightCalculation result"); + QVERIFY2(los == expectedResult, " got lineOfSightCalculation result"); } - - - - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - NGLCoreApplication app(argc, argv); - app.createLogger("UnitTestElevation", "log4cxxElevationUnitTest.props"); + NGLCoreApplication app(argc, argv); + app.createLogger("UnitTestElevation", "log4cxxElevationUnitTest.props"); - UnitTestElevation tc; + UnitTestElevation tc; - int ret = QTest::qExec(&tc, argc, argv); + int ret = QTest::qExec(&tc, argc, argv); - - if (s_eleMgr) - { - s_eleMgr->cleanupAll(); - } + if (s_eleMgr) + { + s_eleMgr->cleanupAll(); + } - return ret; + return ret; } - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.h old mode 100755 new mode 100644 index 5da231892..7d6e5aef2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/UnitTest_Elevation/elevation_unit_test.h @@ -1,61 +1,38 @@ - #pragma once -#include -#include - #include - -#include -#include +#include #include - +#include +#include +#include using LOGGER_T = NGL::INGLLogger&; - - - class UnitTestElevation : public QObject { - Q_OBJECT + Q_OBJECT -public: - UnitTestElevation(); + public: + UnitTestElevation(); + private Q_SLOTS: -private Q_SLOTS: + void initTestCase(); - - - + void init(); + void test_elevation_data(); + void test_elevation(); - void initTestCase(); + void test_elevation_isCovered(); + void test_elevation_defaultValue(); - void init(); - + void test_lineOfSightCalculation_data(); + void test_lineOfSightCalculation(); - - - 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; + private: + NGL::INGLLogger& m_logger; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.cpp old mode 100755 new mode 100644 index c5b10f2fc..885ac8f86 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.cpp @@ -1,6 +1,5 @@ - #include "logger.h" #include @@ -8,25 +7,24 @@ namespace LtsElevation { -LOGGER_T getLogger(const char *name) +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); + 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(); - } + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception& ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } -} +} // namespace LtsElevation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.h old mode 100755 new mode 100644 index fa2ec1baa..e9bbe0487 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/logger.h @@ -1,18 +1,17 @@ - - #pragma once #include namespace LtsElevation { -typedef NGL::INGLLogger &LOGGER_T; +typedef NGL::INGLLogger& LOGGER_T; -LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) +LOGGER_T getLogger(const char* name); + +inline LOGGER_T getLogger(const QString& loggerName) { - return getLogger(loggerName.toUtf8().constData()); + return getLogger(loggerName.toUtf8().constData()); } -} +} // namespace LtsElevation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp old mode 100755 new mode 100644 index fad1573d5..2f4e13e01 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.cpp @@ -1,510 +1,472 @@ - #include "lts_elevation_manager.h" -#include -#include + #include - -#include -#include - -#include +#include #include -#include #include +#include +#include +#include +#include +#include - - - -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"); +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"); namespace LtsElevation { class LtsElevationManager; +using LtsElevatioMgrMapTrainingAreaId = QMap; - -using LtsElevatioMgrMapTrainingAreaId = QMap; - - -static LtsElevatioMgrMapTrainingAreaId <sElevatioMgrMapTrainingAreaId() +static LtsElevatioMgrMapTrainingAreaId& ltsElevatioMgrMapTrainingAreaId() { - static LtsElevatioMgrMapTrainingAreaId s_ltsElevatioMgrMapTrainingAreaId; - return s_ltsElevatioMgrMapTrainingAreaId; + static LtsElevatioMgrMapTrainingAreaId s_ltsElevatioMgrMapTrainingAreaId; + return s_ltsElevatioMgrMapTrainingAreaId; } static void cleanupLtsElevatioMgrMapTrainingAreaId() { - qDeleteAll(ltsElevatioMgrMapTrainingAreaId()); - ltsElevatioMgrMapTrainingAreaId().clear(); + qDeleteAll(ltsElevatioMgrMapTrainingAreaId()); + ltsElevatioMgrMapTrainingAreaId().clear(); } -LtsElevatioMgrMapTrainingAreaId &getLtsElevationMgrMapTrainingAreaId() +LtsElevatioMgrMapTrainingAreaId& getLtsElevationMgrMapTrainingAreaId() { - if (ltsElevatioMgrMapTrainingAreaId().isEmpty()) - qAddPostRoutine(cleanupLtsElevatioMgrMapTrainingAreaId); + if (ltsElevatioMgrMapTrainingAreaId().isEmpty()) + qAddPostRoutine(cleanupLtsElevatioMgrMapTrainingAreaId); - return ltsElevatioMgrMapTrainingAreaId(); + return ltsElevatioMgrMapTrainingAreaId(); } static long s_counter{0}; - - - class LtsElevationManager::Private { -public: - Private() = default; - ~Private() - { - delete m_elevationManager; - } - std::shared_ptr m_exmDtc; - std::shared_ptr m_asmDtc; + public: + Private() = default; - QStringList m_filePaths_rough_to_fine; - SituationMap::ElevationMapManager *m_elevationManager{nullptr}; + ~Private() + { + delete m_elevationManager; + } + + std::shared_ptr m_exmDtc; + std::shared_ptr m_asmDtc; + + QStringList m_filePaths_rough_to_fine; + SituationMap::ElevationMapManager* m_elevationManager{nullptr}; }; - - - - -LtsElevationManager::LtsElevationManager() - : QObject(nullptr) - , d(new Private) +LtsElevationManager::LtsElevationManager() : QObject(nullptr), d(new Private) { - ++s_counter; - 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; + ++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; + --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 &exmDtc, - const std::shared_ptr &asmDtc) +LTS_ELEVATION_MANAGER_TYPE +LtsElevationManager::createInstance(int exerciseId, const std::shared_ptr& exmDtc, + const std::shared_ptr& asmDtc) { - LOGGER_T logger = getLogger("LtsElevationManager"); - TRACE_LOG(logger) << Q_FUNC_INFO << " START, exerciseId=" << exerciseId; + 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; - } - - int trainingAreaId = -1; - - - - - - static QHash s_exIdToTaIdStore; - - const auto exTaIt = s_exIdToTaIdStore.find(exerciseId); - if (exTaIt != s_exIdToTaIdStore.end()) - { - - - trainingAreaId = *exTaIt; - - } else { - - - - if (!exmDtc || !asmDtc) + if (exerciseId < 0) { - ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for exerciseId=" << exerciseId - << ", asmDtc=" << asmDtc - << ", exmDtc=" << exmDtc; - return nullptr; + ERROR_LOG(logger) << Q_FUNC_INFO << " exerciseId invalid, exerciseId=" << exerciseId; + return nullptr; } - - trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, exmDtc); - if (trainingAreaId <= 0) + int trainingAreaId = -1; + + static QHash s_exIdToTaIdStore; + + const auto exTaIt = s_exIdToTaIdStore.find(exerciseId); + if (exTaIt != s_exIdToTaIdStore.end()) { - ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId" - << ", exerciseId=" << exerciseId - << ", trainingAreaId=" << trainingAreaId; - return nullptr; + + trainingAreaId = *exTaIt; + } + else + { + + if (!exmDtc || !asmDtc) + { + ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for exerciseId=" << exerciseId << ", asmDtc=" << asmDtc + << ", exmDtc=" << exmDtc; + return nullptr; + } + + trainingAreaId = exerciseIdToTrainingAreaId(exerciseId, exmDtc); + if (trainingAreaId <= 0) + { + ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId" + << ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId; + return nullptr; + } + + s_exIdToTaIdStore[exerciseId] = trainingAreaId; } - - s_exIdToTaIdStore[exerciseId] = trainingAreaId; + LTS_ELEVATION_MANAGER_TYPE temp = createInstanceForTrainingAreaId(trainingAreaId, asmDtc); + if (!temp) + { + ERROR_LOG(logger) << Q_FUNC_INFO << " Error on createInstanceForTrainingAreaId" + << ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId; + return nullptr; + } - } + temp->initDDS(exmDtc, 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; - } - - - temp->initDDS(exmDtc, asmDtc); - - TRACE_LOG(logger) << Q_FUNC_INFO << " END, exerciseId=" << exerciseId; - return temp; + TRACE_LOG(logger) << Q_FUNC_INFO << " END, exerciseId=" << exerciseId; + return temp; } LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::getInstance(int exerciseId) { - return LtsElevationManager::createInstance(exerciseId); + return LtsElevationManager::createInstance(exerciseId); } -LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceForTrainingAreaId(int trainingAreaId, - const std::shared_ptr &asmDtc) +LTS_ELEVATION_MANAGER_TYPE +LtsElevationManager::createInstanceForTrainingAreaId(int trainingAreaId, + const std::shared_ptr& asmDtc) { - LOGGER_T logger = getLogger("LtsElevationManager"); - TRACE_LOG(logger) << Q_FUNC_INFO << " START, trainingAreaId=" << trainingAreaId; + 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; - } + if (trainingAreaId < 0) + { + ERROR_LOG(logger) << Q_FUNC_INFO << " trainingAreaId invalid, trainingAreaId=" << trainingAreaId; + return nullptr; + } + LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId(); + QMap::iterator it = map.find(trainingAreaId); - LtsElevatioMgrMapTrainingAreaId &map = getLtsElevationMgrMapTrainingAreaId(); - QMap::iterator it = map.find(trainingAreaId); + if (it != map.end()) + { + DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size(); + return it.value(); + } - - 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; + } - - if (!asmDtc) - { - ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs for trainingAreaId=" << trainingAreaId - << ", asmDtc=" << asmDtc; - return nullptr; - } + LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager(); - LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager(); + temp->initDDS(nullptr, asmDtc); - - 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; + } - 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; + } - - 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); - map.insert(trainingAreaId, temp); + DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size(); - DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size(); - - TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << trainingAreaId; - return map[trainingAreaId]; + TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << trainingAreaId; + return map[trainingAreaId]; } - - - -LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceUnitTest(int id, const QStringList &filePaths_rough_to_fine) +LTS_ELEVATION_MANAGER_TYPE LtsElevationManager::createInstanceUnitTest(int id, + const QStringList& filePaths_rough_to_fine) { - LOGGER_T logger = getLogger("LtsElevationManager"); + LOGGER_T logger = getLogger("LtsElevationManager"); - LtsElevatioMgrMapTrainingAreaId &map = getLtsElevationMgrMapTrainingAreaId(); - QMap::iterator it = map.find(id); + LtsElevatioMgrMapTrainingAreaId& map = getLtsElevationMgrMapTrainingAreaId(); + QMap::iterator it = map.find(id); - - if (it != map.end()) - { - DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size(); - return it.value(); - } + if (it != map.end()) + { + DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances: " << map.size(); + return it.value(); + } - - LTS_ELEVATION_MANAGER_TYPE temp = new LtsElevationManager(); + 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; - } + 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); + map.insert(id, temp); - DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size(); + DEBUG_LOG(logger) << " LtsElevationMgrMap contains instances now: " << map.size(); - TRACE_LOG(logger) << Q_FUNC_INFO << " END, trainingAreaId=" << id; - return map[id]; - - - + 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"; + LOGGER_T logger = getLogger("LtsElevationManager"); + TRACE_LOG(logger) << Q_FUNC_INFO << " START"; + cleanupLtsElevatioMgrMapTrainingAreaId(); + TRACE_LOG(logger) << Q_FUNC_INFO << " END"; } -void LtsElevationManager::initDDS(const std::shared_ptr &exmDtc, const std::shared_ptr &asmDtc) +void LtsElevationManager::initDDS(const std::shared_ptr& exmDtc, + const std::shared_ptr& asmDtc) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - d->m_exmDtc = exmDtc; - if (d->m_exmDtc) - d->m_exmDtc->waitForHistoricalDataExercise(1000); + 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); + d->m_asmDtc = asmDtc; + if (d->m_asmDtc) + d->m_asmDtc->waitForHistoricalDataTrainingArea(1000); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } QStringList LtsElevationManager::getFilenamesForExercise(int exerciseId) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + 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 {}; - } + 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 {}; - } + 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); + 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; + 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"; + 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) + if (!d->m_asmDtc) { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error on s_asmDtc->trainingArea" - << ", trainingAreaId=" << trainingAreaId; - return {}; + ERROR_LOG(m_logger) << Q_FUNC_INFO << " no dtcs" + << ", trainingAreaId=" << trainingAreaId; + return {}; } - const std::vector &mdVec = ta.elevation(); - filePaths_rough_to_fine.reserve(mdVec.size()); - for (const AssetManagement::MapDescription &md : std::as_const(mdVec)) + QStringList filePaths_rough_to_fine; { - - QUrl url(QString::fromStdString(md.url())); - QString filePathAbs = url.toLocalFile(); - if (QDir::isRelativePath(filePathAbs)) - filePathAbs = SituationMap::getResourcePath() + QStringLiteral("/elevation/") + filePathAbs; + 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& mdVec = ta.elevation(); + filePaths_rough_to_fine.reserve(mdVec.size()); - filePaths_rough_to_fine.append(filePathAbs); + 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; + TRACE_LOG(m_logger) << Q_FUNC_INFO + << " END, filePaths_rough_to_fine=" << filePaths_rough_to_fine.join(QStringLiteral(";")); + return filePaths_rough_to_fine; } -bool LtsElevationManager::init(const QStringList &filePaths_rough_to_fine) +bool LtsElevationManager::init(const QStringList& filePaths_rough_to_fine) { - delete d->m_elevationManager; + delete d->m_elevationManager; - d->m_elevationManager = new SituationMap::ElevationMapManager(); - int cnt = d->m_elevationManager->init(filePaths_rough_to_fine); + 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 !!!"; - 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; + if (cnt != filePaths_rough_to_fine.size()) + { + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + FATAL_LOG(m_logger) << Q_FUNC_INFO << " ERROR, not all files could be loaded !!!"; + return false; + } + return true; } -int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId, const std::shared_ptr &exmDtc) +int LtsElevationManager::exerciseIdToTrainingAreaId(int exerciseId, + const std::shared_ptr& exmDtc) { - LOGGER_T logger = getLogger("LtsElevationManager"); + LOGGER_T logger = getLogger("LtsElevationManager"); - if (!exmDtc) - { - ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs" - << ", exerciseId=" << exerciseId; - return {}; - } - - - int trainingAreaId = -1; - { - exmDtc->waitForHistoricalDataExercise(1000); - - const ExerciseManagement::Exercise &exm = exmDtc->exercise(exerciseId); - if (exm.id() != exerciseId) + if (!exmDtc) { - ERROR_LOG(logger) << Q_FUNC_INFO << " Error on m_exmDtc->exercise" - << ", exerciseId=" << exerciseId; - return {}; + ERROR_LOG(logger) << Q_FUNC_INFO << " no dtcs" + << ", exerciseId=" << exerciseId; + return {}; } - trainingAreaId = exm.trainingAreaId(); - if (trainingAreaId <= 0) + int trainingAreaId = -1; { - ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId" - << ", exerciseId=" << exerciseId - << ", trainingAreaId=" << trainingAreaId; - return -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 {}; + } + trainingAreaId = exm.trainingAreaId(); + + if (trainingAreaId <= 0) + { + ERROR_LOG(logger) << Q_FUNC_INFO << " Error getting trainingAreaId" + << ", exerciseId=" << exerciseId << ", trainingAreaId=" << trainingAreaId; + return -1; + } } - } - return trainingAreaId; + return trainingAreaId; } bool LtsElevationManager::waitForInitialization() { - if (!d->m_elevationManager) - return false; - return d->m_elevationManager->waitForInitialization(); + if (!d->m_elevationManager) + return false; + return d->m_elevationManager->waitForInitialization(); } bool LtsElevationManager::isValid() const { - if (!d->m_elevationManager) - return false; - return d->m_elevationManager->isValid(); + if (!d->m_elevationManager) + return false; + return d->m_elevationManager->isValid(); } -double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool *bIsCovered) const +double LtsElevationManager::elevation(double lon_rad, double lat_rad, double defaultValue, bool* bIsCovered) const { - if (!d->m_elevationManager) - return defaultValue; - return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered); + if (!d->m_elevationManager) + return defaultValue; + return d->m_elevationManager->elevation(lon_rad, lat_rad, defaultValue, bIsCovered); } -LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D &startPointGeo_absZ, - const LtsUtils::QPoint3D &endPointGeo_absZ) +LineOfSight LtsElevationManager::lineOfSightCalculation(const LtsUtils::QPoint3D& startPointGeo_absZ, + const LtsUtils::QPoint3D& endPointGeo_absZ) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << ", startPointGeo_absZ = " << startPointGeo_absZ << ", endPointGeo_absZ = " << endPointGeo_absZ; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" + << ", startPointGeo_absZ = " << startPointGeo_absZ + << ", endPointGeo_absZ = " << endPointGeo_absZ; - if (!isValid()) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error, LtsElevationManager not valid"; - return LineOfSight::LOS_ERROR; - } + 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); + SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult = + d->m_elevationManager->lineOfSightCalculation(startPointGeo_absZ, endPointGeo_absZ); - - LtsElevation::LineOfSight result = static_cast(eleMapMgrResult); + LtsElevation::LineOfSight result = static_cast(eleMapMgrResult); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" << ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ - << " -> LineOfSight " << result; - return result; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" + << ", startPointGeo = " << startPointGeo_absZ << ", endPointGeo = " << endPointGeo_absZ + << " -> LineOfSight " << result; + return result; } -LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF &startPointGeo, double startHat, const QPointF &endPointGeo, double endHat) +LineOfSight LtsElevationManager::lineOfSightCalculation(const QPointF& startPointGeo, double startHat, + const QPointF& endPointGeo, double endHat) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat - << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat; + 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); + SituationMap::ElevationMapManager::LineOfSight eleMapMgrResult = + d->m_elevationManager->lineOfSightCalculation(startPointGeo, startHat, endPointGeo, endHat); - - LtsElevation::LineOfSight result = static_cast(eleMapMgrResult); + LtsElevation::LineOfSight result = static_cast(eleMapMgrResult); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" - << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat - << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat - << " -> LineOfSight " << static_cast(eleMapMgrResult); - return result; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" + << ", startPointGeo = " << startPointGeo << ", startHat = " << startHat + << ", endPointGeo = " << endPointGeo << ", endHat = " << endHat << " -> LineOfSight " + << static_cast(eleMapMgrResult); + return result; } - -const QString toString(const LineOfSight &value) +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"); + 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) +std::ostream& operator<<(std::ostream& stream, const LineOfSight value) { - stream << toString(value).toStdString(); - return stream; + stream << toString(value).toStdString(); + return stream; } -} +} // namespace LtsElevation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h old mode 100755 new mode 100644 index d409a8f9e..c5315d739 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsElevation/lts_elevation_manager.h @@ -1,28 +1,22 @@ - #pragma once #include "logger.h" #include "ltselevation_export.h" + #include - - - +#include #include #include #include -#include - -#include #include - - +#include namespace LtsSession { class LtsSessionDataDds; -} +} namespace ExerciseManagement { @@ -30,7 +24,7 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace AssetManagement { @@ -38,92 +32,67 @@ namespace Interface { class Dtc; } -} - +} // namespace AssetManagement namespace LtsElevation { -enum class LineOfSight { LOS_UNDEFINED, - LOS_ERROR, - LOS_VISIBLE, - LOS_INVISIBLE }; +enum class LineOfSight { LOS_UNDEFINED, LOS_ERROR, LOS_VISIBLE, LOS_INVISIBLE }; class LtsElevationManager; using LTS_ELEVATION_MANAGER_TYPE = QPointer; - - - class LTSELEVATION_EXPORT LtsElevationManager : public QObject { -public: + public: + static LTS_ELEVATION_MANAGER_TYPE + createInstance(int exerciseId, const std::shared_ptr& exmDtc = {}, + const std::shared_ptr& asmDtc = {}); - + static LTS_ELEVATION_MANAGER_TYPE getInstance(int exerciseId); - + static LTS_ELEVATION_MANAGER_TYPE + createInstanceForTrainingAreaId(int trainingAreaId, + const std::shared_ptr& asmDtc = nullptr); - static LTS_ELEVATION_MANAGER_TYPE createInstance(int exerciseId, - const std::shared_ptr &exmDtc = {}, - const std::shared_ptr &asmDtc = {}); + static void cleanupAll(); + virtual ~LtsElevationManager(); - static LTS_ELEVATION_MANAGER_TYPE getInstance(int exerciseId); + bool waitForInitialization(); + bool isValid() const; + double elevation(double lon_rad, double lat_rad, double defaultValue = std::numeric_limits::min(), + bool* bIsCovered = nullptr) const; - static LTS_ELEVATION_MANAGER_TYPE createInstanceForTrainingAreaId(int trainingAreaId, - const std::shared_ptr &asmDtc = nullptr); + 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& exmDtc, + const std::shared_ptr& asmDtc); + bool init(const QStringList& filePaths_rough_to_fine); + static int exerciseIdToTrainingAreaId(int exerciseId, + const std::shared_ptr& exmDtc); - static void cleanupAll(); - virtual ~LtsElevationManager(); + QStringList getFilenamesForExercise(int exerciseId); + QStringList getFilenamesForTrainingArea(int trainingAreaId); + static LTS_ELEVATION_MANAGER_TYPE createInstanceUnitTest(int id, const QStringList& filePaths_rough_to_fine); - bool waitForInitialization(); - bool isValid() const; + private: + class Private; - double elevation(double lon_rad, double lat_rad, double defaultValue = std::numeric_limits::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 &exmDtc, - const std::shared_ptr &asmDtc); - bool init(const QStringList &filePaths_rough_to_fine); - static int exerciseIdToTrainingAreaId(int exerciseId, const std::shared_ptr &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; + Private* d; + LOGGER_T m_logger; }; -LTSELEVATION_EXPORT const QString toString(const LtsElevation::LineOfSight &value); +LTSELEVATION_EXPORT const QString toString(const LtsElevation::LineOfSight& value); -LTSELEVATION_EXPORT std::ostream &operator<< (std::ostream &stream, - const LtsElevation::LineOfSight value); +LTSELEVATION_EXPORT std::ostream& operator<<(std::ostream& stream, const LtsElevation::LineOfSight value); - - -} +} // namespace LtsElevation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp old mode 100755 new mode 100644 index 59e117898..9c0f5d444 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.cpp @@ -1,232 +1,185 @@ - #include "aes_crypt.h" -#include -#include -#include + #include +#include +#include +#include namespace LtsLicence { struct AesCryptPrivate { - AesCryptPrivate() - : passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)) - , logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt")) - { - qsrand(time(nullptr)); + AesCryptPrivate() + : passPhrase(QLatin1String("LTS " LTS_VERSION_MAJOR "." LTS_VERSION_MINOR)), + logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicenceLib.AesCrypt")) + { + qsrand(time(nullptr)); #if OPENSSL_VERSION_NUMBER < 0x1010000fL - ERR_load_crypto_strings(); + ERR_load_crypto_strings(); #endif - } - ~AesCryptPrivate() - { -#if OPENSSL_VERSION_NUMBER < 0x1010000fL - ERR_free_strings(); -#endif - } + } - QString passPhrase; - NGL::INGLLogger &logger; + ~AesCryptPrivate() + { +#if OPENSSL_VERSION_NUMBER < 0x1010000fL + ERR_free_strings(); +#endif + } + + QString passPhrase; + NGL::INGLLogger& logger; }; Q_GLOBAL_STATIC(AesCryptPrivate, s_Private) -void setPassPhrase(const QString &passPhrase) +void setPassPhrase(const QString& passPhrase) { - s_Private->passPhrase = passPhrase; + s_Private->passPhrase = passPhrase; } QString passPhrase() { - return s_Private->passPhrase; + return s_Private->passPhrase; } -QByteArray decryptData(const QByteArray &dataToDecrypt, - const QString &pw, - bool *bOk) +QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw, bool* bOk) { - if (bOk) - *bOk = false; + if (bOk) + *bOk = false; - int ret; - int outSize1 = 0; - int outSize2 = 0; - unsigned char key[32]; + int ret; + int outSize1 = 0; + int outSize2 = 0; + unsigned char key[32]; - - const QByteArray baPassword = pw.toUtf8(); - const unsigned char *dataPw = reinterpret_cast(baPassword.data()); - int i = EVP_BytesToKey(EVP_aes_256_cbc(), - EVP_sha1(), - nullptr, - dataPw, - baPassword.size(), - 5, - key, - nullptr); - if (i != 32) - { - ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits" ; - return QByteArray(); - } + const QByteArray baPassword = pw.toUtf8(); + const unsigned char* dataPw = reinterpret_cast(baPassword.data()); + int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr); + if (i != 32) + { + ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; + return QByteArray(); + } - const QByteArray baSalt = dataToDecrypt.left(EVP_MAX_IV_LENGTH); - const unsigned char *salt = reinterpret_cast(baSalt.data()); + const QByteArray baSalt = dataToDecrypt.left(EVP_MAX_IV_LENGTH); + const unsigned char* salt = reinterpret_cast(baSalt.data()); - const QByteArray bufEncrypted = dataToDecrypt.mid(EVP_MAX_IV_LENGTH); + const QByteArray bufEncrypted = dataToDecrypt.mid(EVP_MAX_IV_LENGTH); + + EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); + ret = EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed"; + return QByteArray(); + } + + QByteArray bufDecrypted; + bufDecrypted.resize(bufEncrypted.size() + EVP_CIPHER_CTX_block_size(ctx)); + const unsigned char* dataIn = reinterpret_cast(bufEncrypted.data()); + unsigned char* dataOut = reinterpret_cast(bufDecrypted.data()); + + ret = EVP_DecryptUpdate(ctx, dataOut, &outSize1, dataIn, bufEncrypted.size()); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed"; + return QByteArray(); + } + + ret = EVP_DecryptFinal_ex(ctx, dataOut + outSize1, &outSize2); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed"; + return QByteArray(); + } - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - ret = EVP_DecryptInit_ex(ctx, - EVP_aes_256_cbc(), - nullptr, - key, - salt); - if (ret == 0) - { EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptInit_ex failed" ; - return QByteArray(); - } - - QByteArray bufDecrypted; - bufDecrypted.resize(bufEncrypted.size() + EVP_CIPHER_CTX_block_size(ctx)); - const unsigned char *dataIn = reinterpret_cast(bufEncrypted.data()); - unsigned char *dataOut = reinterpret_cast(bufDecrypted.data()); + bufDecrypted.resize(outSize1 + outSize2); - ret = EVP_DecryptUpdate(ctx, - dataOut, - &outSize1, - dataIn, - bufEncrypted.size()); - if (ret == 0) - { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptUpdate failed" ; - return QByteArray(); - } - - ret = EVP_DecryptFinal_ex(ctx, - dataOut + outSize1, - &outSize2); - if (ret == 0) - { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_DecryptFinal_ex failed" ; - return QByteArray(); - } - - EVP_CIPHER_CTX_free(ctx); - - bufDecrypted.resize(outSize1 + outSize2); - - if (bOk) - *bOk = true; - return bufDecrypted; + if (bOk) + *bOk = true; + return bufDecrypted; } - -QByteArray encryptData(const QByteArray &dataToEncrypt, - const QString &pw, - bool *bOk) +QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw, bool* bOk) { - if (bOk) - *bOk = false; + if (bOk) + *bOk = false; - int ret; - int outSize1 = 0; - int outSize2 = 0; - unsigned char key[32]; - QByteArray bufEncrypted; + int ret; + int outSize1 = 0; + int outSize2 = 0; + unsigned char key[32]; + QByteArray bufEncrypted; - - const QByteArray baPassword = pw.toUtf8(); - const unsigned char *dataPw = reinterpret_cast(baPassword.data()); - int i = EVP_BytesToKey(EVP_aes_256_cbc(), - EVP_sha1(), - nullptr, - dataPw, - baPassword.size(), - 5, - key, - nullptr); - if (i != 32) - { - ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits" ; - return QByteArray(); - } + const QByteArray baPassword = pw.toUtf8(); + const unsigned char* dataPw = reinterpret_cast(baPassword.data()); + int i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), nullptr, dataPw, baPassword.size(), 5, key, nullptr); + if (i != 32) + { + ERROR_LOG(s_Private->logger) << "Wrong key size - should be 256 bits"; + return QByteArray(); + } - - QByteArray baSalt(EVP_MAX_IV_LENGTH, 0); - for (int i = 0; i < EVP_MAX_IV_LENGTH; ++i) - baSalt[i] = qrand(); - const unsigned char *salt = reinterpret_cast(baSalt.data()); + QByteArray baSalt(EVP_MAX_IV_LENGTH, 0); + for (int i = 0; i < EVP_MAX_IV_LENGTH; ++i) + baSalt[i] = qrand(); + const unsigned char* salt = reinterpret_cast(baSalt.data()); + + EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); + ret = EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, salt); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed"; + return QByteArray(); + } + + bufEncrypted = QByteArray::fromRawData(reinterpret_cast(salt), EVP_MAX_IV_LENGTH); + bufEncrypted.resize(bufEncrypted.size() + dataToEncrypt.size() + EVP_CIPHER_CTX_block_size(ctx)); + const unsigned char* dataIn = reinterpret_cast(dataToEncrypt.data()); + unsigned char* dataOut = reinterpret_cast(bufEncrypted.data()); + dataOut += baSalt.size(); + ret = EVP_EncryptUpdate(ctx, dataOut, &outSize1, dataIn, dataToEncrypt.size()); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed"; + return QByteArray(); + } + + ret = EVP_EncryptFinal_ex(ctx, dataOut + outSize1, &outSize2); + if (ret == 0) + { + EVP_CIPHER_CTX_free(ctx); + char errbuf[256]; + ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); + ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed"; + return QByteArray(); + } - - EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - ret = EVP_EncryptInit_ex(ctx, - EVP_aes_256_cbc(), - nullptr, - key, - salt); - if (ret == 0) - { EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptInit_ex failed" ; - return QByteArray(); - } - - bufEncrypted = QByteArray::fromRawData(reinterpret_cast(salt), EVP_MAX_IV_LENGTH); - bufEncrypted.resize(bufEncrypted.size() + - dataToEncrypt.size() + - EVP_CIPHER_CTX_block_size(ctx)); - const unsigned char *dataIn = reinterpret_cast(dataToEncrypt.data()); - unsigned char *dataOut = reinterpret_cast(bufEncrypted.data()); - dataOut += baSalt.size(); - ret = EVP_EncryptUpdate(ctx, - dataOut, - &outSize1, - dataIn, - dataToEncrypt.size()); - if (ret == 0) - { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptUpdate failed" ; - return QByteArray(); - } + bufEncrypted.resize(outSize1 + outSize2 + baSalt.size()); - - ret = EVP_EncryptFinal_ex(ctx, - dataOut + outSize1, - &outSize2); - if (ret == 0) - { - EVP_CIPHER_CTX_free(ctx); - char errbuf[256]; - ERR_error_string_n(ERR_get_error(), errbuf, sizeof(errbuf)); - ERROR_LOG(s_Private->logger) << "EVP_EncryptFinal_ex failed" ; - return QByteArray(); - } - - EVP_CIPHER_CTX_free(ctx); - - bufEncrypted.resize(outSize1 + outSize2 + baSalt.size()); - - if (bOk) - *bOk = true; - return bufEncrypted; + if (bOk) + *bOk = true; + return bufEncrypted; } -} +} // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h old mode 100755 new mode 100644 index ca3ec5991..43c457194 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt.h @@ -1,22 +1,20 @@ - #pragma once -#include #include "ltslicence_export.h" +#include + namespace LtsLicence { -LTSLICENCE_EXPORT void setPassPhrase(const QString &passPhrase); +LTSLICENCE_EXPORT void setPassPhrase(const QString& passPhrase); LTSLICENCE_EXPORT QString passPhrase(); -LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray &dataToDecrypt, - const QString &pw = passPhrase(), - bool *bOk = nullptr); +LTSLICENCE_EXPORT QByteArray decryptData(const QByteArray& dataToDecrypt, const QString& pw = passPhrase(), + bool* bOk = nullptr); -LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray &dataToEncrypt, - const QString &pw = passPhrase(), - bool *bOk = nullptr); -} +LTSLICENCE_EXPORT QByteArray encryptData(const QByteArray& dataToEncrypt, const QString& pw = passPhrase(), + bool* bOk = nullptr); +} // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp old mode 100755 new mode 100644 index 1c68bc31d..f1d983370 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.cpp @@ -1,54 +1,53 @@ - -#include -#include -#include -#include +#include "aes_crypt_test.h" #include "aes_crypt.h" -#include "aes_crypt_test.h" + +#include +#include +#include +#include QTEST_MAIN(aes_crypt_test) void aes_crypt_test::initTestCase() { - NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); + NGL::NGLLoggerBootstrap::createNGLRootLogger("log4cxx.props", false); } void aes_crypt_test::truePassTest() { - qDebug("Simple TestCase"); - bool bOk; - const QByteArray content("30.06.2013"); - const QString pw(QStringLiteral("aes_crypt_test")); - const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - - QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size()); - const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - QCOMPARE(dec, content); + qDebug("Simple TestCase"); + bool bOk; + const QByteArray content("30.06.2013"); + const QString pw(QStringLiteral("aes_crypt_test")); + const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + QCOMPARE(((content.size() + 15 + EVP_MAX_IV_LENGTH) / 18) * 16, enc.size()); + const QByteArray dec = LtsLicence::decryptData(enc, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + QCOMPARE(dec, content); - const QByteArray bigContent(12345, '1'); - const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - - QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size()); + const QByteArray bigContent(12345, '1'); + const QByteArray bigEnc = LtsLicence::encryptData(bigContent, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + + QCOMPARE(((bigContent.size() + 15 + EVP_MAX_IV_LENGTH) / 16) * 16, bigEnc.size()); } void aes_crypt_test::falsePassTest() { - qDebug("False Password TestCase"); - bool bOk; - const QByteArray content("30.06.2013"); - const QString pw(QStringLiteral("aes_crypt_test")); - const QString pw2(QStringLiteral("aes_crypt_test2")); - const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); - QVERIFY2(bOk, "Error encrypting data..."); - QVERIFY2(enc.size() != 20, "Error encrypting data..."); - const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk); - QVERIFY2(!bOk, "Error encrypting data..."); - QVERIFY2(dec.isEmpty(), "decrypted data is not empty..."); + qDebug("False Password TestCase"); + bool bOk; + const QByteArray content("30.06.2013"); + const QString pw(QStringLiteral("aes_crypt_test")); + const QString pw2(QStringLiteral("aes_crypt_test2")); + const QByteArray enc = LtsLicence::encryptData(content, pw, &bOk); + QVERIFY2(bOk, "Error encrypting data..."); + QVERIFY2(enc.size() != 20, "Error encrypting data..."); + const QByteArray dec = LtsLicence::decryptData(enc, pw2, &bOk); + QVERIFY2(!bOk, "Error encrypting data..."); + QVERIFY2(dec.isEmpty(), "decrypted data is not empty..."); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h old mode 100755 new mode 100644 index 7569be6f4..253615c7e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/aes_crypt_test.h @@ -1,16 +1,14 @@ - #pragma once #include - #include class aes_crypt_test : public QObject { - Q_OBJECT -private Q_SLOTS: - void initTestCase(); - void truePassTest(); - void falsePassTest(); + Q_OBJECT + private Q_SLOTS: + void initTestCase(); + void truePassTest(); + void falsePassTest(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp old mode 100755 new mode 100644 index 575eb2031..2e01bde21 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.cpp @@ -1,173 +1,150 @@ - - #include "lts_licence.h" -#include + #include +#include #include namespace LtsLicence { -static bool extractLicence(const QDomElement &licenceElement, QVector &licenceVec); -static NGL::INGLLogger &getLogger() +static bool extractLicence(const QDomElement& licenceElement, QVector& licenceVec); + +static NGL::INGLLogger& getLogger() { - return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicence"); + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsLicence"); } -QVector readLicences(const QByteArray &unencryptedXmlData) +QVector readLicences(const QByteArray& unencryptedXmlData) { - QVector licenceVec; + QVector licenceVec; - QDomDocument xmlDoc; - QString errorMsg; - int errorLine = 0; - int errorColumn = 0; + QDomDocument xmlDoc; + QString errorMsg; + int errorLine = 0; + int errorColumn = 0; - if (!xmlDoc.setContent(unencryptedXmlData, &errorMsg, &errorLine, &errorColumn)) - { - ERROR_LOG(getLogger()) << "Error reading xml data, " << "error in line " << errorLine - << ", column " << errorColumn - << ", message: " << errorMsg; - return licenceVec; - } - - INFO_LOG(getLogger()) << "Try to extract licences"; - - QDomElement licenceElement = xmlDoc.documentElement().firstChildElement(QLatin1String("licence")); - - while (!licenceElement.isNull()) - { - if (!extractLicence(licenceElement, licenceVec)) + if (!xmlDoc.setContent(unencryptedXmlData, &errorMsg, &errorLine, &errorColumn)) { - licenceVec.clear(); - return licenceVec; + ERROR_LOG(getLogger()) << "Error reading xml data, " + << "error in line " << errorLine << ", column " << errorColumn + << ", message: " << errorMsg; + return licenceVec; } - licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence")); - } - return licenceVec; -} + INFO_LOG(getLogger()) << "Try to extract licences"; + QDomElement licenceElement = xmlDoc.documentElement().firstChildElement(QLatin1String("licence")); -QByteArray writeUnencryptedLicences(const QVector &licences) + while (!licenceElement.isNull()) + { + if (!extractLicence(licenceElement, licenceVec)) + { + licenceVec.clear(); + return licenceVec; + } + + licenceElement = licenceElement.nextSiblingElement(QLatin1String("licence")); + } + return licenceVec; +} + +QByteArray writeUnencryptedLicences(const QVector& licences) { - QDomDocument xmlDoc; + QDomDocument xmlDoc; - QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction(QLatin1String("xml"), - QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'")); - xmlDoc.appendChild(instr); + QDomProcessingInstruction instr = xmlDoc.createProcessingInstruction( + QLatin1String("xml"), QLatin1String("version='1.0' encoding='UTF-8' standalone='yes'")); + xmlDoc.appendChild(instr); - QDomElement root = xmlDoc.createElement(QLatin1String("licences")); - xmlDoc.appendChild(root); + QDomElement root = xmlDoc.createElement(QLatin1String("licences")); + xmlDoc.appendChild(root); - for (int i = 0; i < licences.size(); ++i) - { - QDomElement lic = xmlDoc.createElement(QLatin1String("licence")); - root.appendChild(lic); + for (int i = 0; i < licences.size(); ++i) + { + QDomElement lic = xmlDoc.createElement(QLatin1String("licence")); + root.appendChild(lic); - - QDomElement element = xmlDoc.createElement(QLatin1String("name")); - QDomText text = xmlDoc.createTextNode(licences[i].name); - element.appendChild(text); - lic.appendChild(element); + QDomElement element = xmlDoc.createElement(QLatin1String("name")); + QDomText text = xmlDoc.createTextNode(licences[i].name); + element.appendChild(text); + lic.appendChild(element); - - element = xmlDoc.createElement(QLatin1String("ignoreMaxCount")); - text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("ignoreMaxCount")); + text = xmlDoc.createTextNode(QString::number(licences[i].ignoreMaxCount)); + element.appendChild(text); + lic.appendChild(element); - - element = xmlDoc.createElement(QLatin1String("ignoreExpiration")); - text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("ignoreExpiration")); + text = xmlDoc.createTextNode(QString::number(licences[i].ignoreExpiration)); + element.appendChild(text); + lic.appendChild(element); - - element = xmlDoc.createElement(QLatin1String("maxCount")); - text = xmlDoc.createTextNode(QString::number(licences[i].maxCount)); - element.appendChild(text); - lic.appendChild(element); + element = xmlDoc.createElement(QLatin1String("maxCount")); + text = xmlDoc.createTextNode(QString::number(licences[i].maxCount)); + element.appendChild(text); + lic.appendChild(element); + + const QLatin1String format("dd.MM.yyyy hh:mm:ss"); + const QString qs = licences[i].expiration.toString(format); + + element = xmlDoc.createElement(QLatin1String("expiration")); + text = xmlDoc.createTextNode(qs); + element.appendChild(text); + lic.appendChild(element); + } + INFO_LOG(getLogger()) << "Generated XML Data...\n" << xmlDoc.toByteArray(); + return xmlDoc.toByteArray(); +} + +bool extractLicence(const QDomElement& licenceElement, QVector& licenceVec) +{ + Licence licence; + + QDomElement tag = licenceElement.firstChildElement(QLatin1String("name")); + licence.name = tag.text(); + + tag = licenceElement.firstChildElement(QLatin1String("ignoreMaxCount")); + licence.ignoreMaxCount = tag.text().toInt(); + + tag = licenceElement.firstChildElement(QLatin1String("ignoreExpiration")); + licence.ignoreExpiration = tag.text().toInt(); + + tag = licenceElement.firstChildElement(QLatin1String("maxCount")); + licence.maxCount = tag.text().toInt(); + + tag = licenceElement.firstChildElement(QLatin1String("expiration")); + + const QString qs(tag.text()); - const QLatin1String format("dd.MM.yyyy hh:mm:ss"); - const QString qs = licences[i].expiration.toString(format); + const QDateTime qdt = QDateTime::fromString(qs, format); - - element = xmlDoc.createElement(QLatin1String("expiration")); - text = xmlDoc.createTextNode(qs); - element.appendChild(text); - lic.appendChild(element); - } - INFO_LOG(getLogger()) << "Generated XML Data...\n" << xmlDoc.toByteArray(); - return xmlDoc.toByteArray(); -} - - -bool extractLicence(const QDomElement &licenceElement, QVector &licenceVec) -{ - Licence licence; - - - QDomElement tag = licenceElement.firstChildElement(QLatin1String("name")); - licence.name = tag.text(); - - - tag = licenceElement.firstChildElement(QLatin1String("ignoreMaxCount")); - licence.ignoreMaxCount = tag.text().toInt(); - - - tag = licenceElement.firstChildElement(QLatin1String("ignoreExpiration")); - licence.ignoreExpiration = tag.text().toInt(); - - - tag = licenceElement.firstChildElement(QLatin1String("maxCount")); - licence.maxCount = tag.text().toInt(); - - - tag = licenceElement.firstChildElement(QLatin1String("expiration")); - - const QString qs(tag.text()); - - - const QLatin1String format("dd.MM.yyyy hh:mm:ss"); - const QDateTime qdt = QDateTime::fromString(qs, format); - - if (!qdt.isValid()) - { - ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs - << " used format: " << format - ; - return false; - } - - licence.expiration = qdt; - INFO_LOG(getLogger()) << "Read licence for:'" << licence.name << "'" - << " IgnoreMaxCount: " << licence.ignoreMaxCount - << " IgnoreExpiration: " << licence.ignoreExpiration - << " MaxCount: " << licence.maxCount - << " Expiration: " << licence.expiration.date().toString() - << " " << licence.expiration.time().toString() - << " RefCount: " << licence.licenceRefCount - ; - - licenceVec.append(licence); - return true; -} + if (!qdt.isValid()) + { + ERROR_LOG(getLogger()) << "Invalid expiration format! " << qs << " used format: " << format; + return false; + } + licence.expiration = qdt; + INFO_LOG(getLogger()) << "Read licence for:'" << licence.name << "'" + << " IgnoreMaxCount: " << licence.ignoreMaxCount + << " IgnoreExpiration: " << licence.ignoreExpiration << " MaxCount: " << licence.maxCount + << " Expiration: " << licence.expiration.date().toString() << " " + << licence.expiration.time().toString() << " RefCount: " << licence.licenceRefCount; + licenceVec.append(licence); + return true; +} QString Licence::toString() const { - return QObject::tr("Name: %1, Count: %2, ExpireDate: %3, Expires: %4, UseMaxCount: %5") - .arg(name) - .arg(maxCount) - .arg(expiration.toString()) - .arg(ignoreExpiration) - .arg(ignoreMaxCount); + return QObject::tr("Name: %1, Count: %2, ExpireDate: %3, Expires: %4, UseMaxCount: %5") + .arg(name) + .arg(maxCount) + .arg(expiration.toString()) + .arg(ignoreExpiration) + .arg(ignoreMaxCount); } - - -} +} // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h old mode 100755 new mode 100644 index a4f2fca02..311ac537a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLicence/lts_licence.h @@ -1,33 +1,29 @@ - #pragma once #include "ltslicence_export.h" + +#include #include #include -#include namespace LtsLicence { struct LTSLICENCE_EXPORT Licence { - QString name; - bool ignoreMaxCount = false; - bool ignoreExpiration = false; - int maxCount = 0; - QDateTime expiration; - int licenceRefCount = 0; + QString name; + bool ignoreMaxCount = false; + bool ignoreExpiration = false; + int maxCount = 0; + QDateTime expiration; + int licenceRefCount = 0; - QString toString() const; + QString toString() const; }; +LTSLICENCE_EXPORT QVector readLicences(const QByteArray& unencryptedXmlData); - -LTSLICENCE_EXPORT QVector readLicences(const QByteArray &unencryptedXmlData); - - - -LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector &licences); -} +LTSLICENCE_EXPORT QByteArray writeUnencryptedLicences(const QVector& licences); +} // namespace LtsLicence diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.cpp old mode 100755 new mode 100644 index 4861822d4..128d91574 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.cpp @@ -1,94 +1,92 @@ - #include "logout_info_dialog.h" + #include "ui_logout_info_dialog.h" #include - 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) +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.underlying()) - { - 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; - } + m_ui->setupUi(this); + QString actionText; + switch (shutdownAction.underlying()) + { + 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)); + 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); + 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); + m_timer->setInterval(1000); } LogoutInformationDialog::~LogoutInformationDialog() { - delete m_ui; + delete m_ui; } -void LogoutInformationDialog::setText(const QString &text) +void LogoutInformationDialog::setText(const QString& text) { - m_ui->lblLogoutText->setText(text); + m_ui->lblLogoutText->setText(text); } void LogoutInformationDialog::onTimerTimeout() { - if (m_secsLeft > 0) - { - m_secsLeft--; - setCloseButtonText(m_secsLeft); - } - else - { - acceptClicked(); - } + if (m_secsLeft > 0) + { + m_secsLeft--; + setCloseButtonText(m_secsLeft); + } + else + { + acceptClicked(); + } } void LogoutInformationDialog::acceptClicked() { - m_timer->stop(); - accept(); + m_timer->stop(); + accept(); } void LogoutInformationDialog::closeClicked() { - m_timer->stop(); - reject(); - + m_timer->stop(); + reject(); } void LogoutInformationDialog::setCloseButtonText(int secsLeft) { - m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort [%1]").arg(secsLeft)); + m_ui->buttonBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort [%1]").arg(secsLeft)); } -void LogoutInformationDialog::showEvent(QShowEvent *event) +void LogoutInformationDialog::showEvent(QShowEvent* event) { - m_secsLeft = m_timeOut; - setCloseButtonText(m_secsLeft); - m_timer->start(); - LtsWidgets::LtsFramelessDialog::showEvent(event); + m_secsLeft = m_timeOut; + setCloseButtonText(m_secsLeft); + m_timer->start(); + LtsWidgets::LtsFramelessDialog::showEvent(event); } -} +} // namespace LtsLogin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.h old mode 100755 new mode 100644 index 2fa8a72e3..e763e525f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/logout_info_dialog.h @@ -1,44 +1,44 @@ - #pragma once -#include - -#include #include +#include +#include class QTimer; -namespace Ui { class LogoutInformationDialog; } +namespace Ui +{ +class LogoutInformationDialog; +} namespace LtsLogin { class LogoutInformationDialog : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget *parent = nullptr); - ~LogoutInformationDialog(); + public: + LogoutInformationDialog(int timeOut, AssetManagement::ShutdownAction shutdownAction, QWidget* parent = nullptr); + ~LogoutInformationDialog(); -private slots: - void onTimerTimeout(); - void acceptClicked(); - void closeClicked(); + private slots: + void onTimerTimeout(); + void acceptClicked(); + void closeClicked(); -private: - void setText(const QString &text); - void setCloseButtonText(int secsLeft); + private: + void setText(const QString& text); + void setCloseButtonText(int secsLeft); - Ui::LogoutInformationDialog *m_ui; - QTimer *m_timer; - int m_timeOut; - int m_secsLeft; + Ui::LogoutInformationDialog* m_ui; + QTimer* m_timer; + int m_timeOut; + int m_secsLeft; - -protected: - void showEvent(QShowEvent *event) override final; + protected: + void showEvent(QShowEvent* event) override final; }; -} +} // namespace LtsLogin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.cpp old mode 100755 new mode 100644 index ac04484f0..f64476751 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.cpp @@ -1,312 +1,282 @@ #include "lts_login.h" + #include "logout_info_dialog.h" -#include #include -#include +#include #include #include -#include +#include #include #include - +#include #include -#include -#include #include #include - +#include +#include namespace LtsLogin { -const int logoutShutdownTimeout = 2 * 60; +const int logoutShutdownTimeout = 2 * 60; LtsLogin::LtsLogin() - : m_loginApp(nullptr) - , m_shutdownAction(AssetManagement::ShutdownAction::NoAction) - , m_isInLogoutDialog(false) -{} - + : m_loginApp(nullptr), m_shutdownAction(AssetManagement::ShutdownAction::NoAction), m_isInLogoutDialog(false) +{ +} LtsLogin::~LtsLogin() { - delete m_loginApp; - m_loginApp = nullptr; + delete m_loginApp; + m_loginApp = nullptr; } - void LtsLogin::login() { - LtsAppDescriptor::PluginInfo opmDataPlugin; - opmDataPlugin.iid = QStringLiteral("opm"); - opmDataPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::DATA; + 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 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 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 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; + LtsAppDescriptor::PluginInfo guiPlugin; + guiPlugin.iid = m_loginPluginIid; + guiPlugin.type = LtsAppDescriptor::PluginInfo::PluginType::GUI; + guiPlugin.flags |= LtsAppDescriptor::PluginInfo::Flag::PAYLOAD; - QVector plugins; - plugins.append(opmDataPlugin); - plugins.append(pdmDataPlugin); - plugins.append(asmDataPlugin); - plugins.append(srmDataPlugin); - plugins.append(guiPlugin); + QVector 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; + 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; + 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) + m_loginApp = new LtsPluginManager::LtsPluginManager(); + bool result = m_loginApp->startApp(app, true, connParams); + if (!result) { - qCritical() << "I cannot find the Admin Session :( - abort!"; - QMessageBox::critical(nullptr, tr("Error loading login app"), tr("Could not load login app - abort.")); - abort(); + qWarning() << "no login plugin - probably an offline project"; + emit signalLoginDone(); + return; } - if (session->isInitializationDone()) - QMetaObject::invokeMethod(this, &LtsLogin::slotLoginDone); - else - connect(session, &LtsSession::LtsSession::signalDoneInitializingSession, - this, &LtsLogin::slotLoginDone, Qt::UniqueConnection); - }); -} + 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(); + LtsSession::LtsSession* session = getAdminSession(); - if (session != nullptr) - { - disconnect(session, &LtsSession::LtsSession::signalDoneInitializingSession, - this, &LtsLogin::slotLoginDone); - - if (session->getDtc(m_asmDtc)) + if (session != nullptr) { - m_asmDtc->enableWorkstationLogout(); - connect(m_asmDtc.get(), &AssetManagement::Interface::Dtc::workstationLogoutChanged, - this, &LtsLogin::slotLogoutShutdown); + disconnect(session, &LtsSession::LtsSession::signalDoneInitializingSession, this, &LtsLogin::slotLoginDone); + + if (session->getDtc(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 - 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(); - } + { + qCritical() << "LtsLogin: no admin session for login!!"; + QMessageBox::critical(nullptr, tr("Login error"), tr("Could not finalize login - abort.")); + abort(); + } - emit signalLoginDone(); + emit signalLoginDone(); } - void LtsLogin::showLogoutInformationDialog(AssetManagement::ShutdownAction action) { - LogoutInformationDialog *lid = new LogoutInformationDialog(logoutShutdownTimeout, action, nullptr); - connect(lid, &LogoutInformationDialog::accepted, - this, [this, action]() - { - m_shutdownAction = action; - m_isInLogoutDialog = false; - emit signalLogout(); - }); + 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; - }); + connect(lid, &LogoutInformationDialog::rejected, this, [this]() { m_isInLogoutDialog = false; }); - lid->show(); + lid->show(); } - -void LtsLogin::slotLogoutShutdown(const AssetManagement::WorkstationLogout &data, DataModification modType) +void LtsLogin::slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType) { - if (m_isInLogoutDialog) - return; + if (m_isInLogoutDialog) + return; - if (m_asmDtc == nullptr || modType != DataModification::eAdded) - 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) + if (!m_asmDtc->isAssetEnabled()) + m_asmDtc->enableAsset(); + for (int id : data.ids()) { - m_isInLogoutDialog = true; - showLogoutInformationDialog(data.shutdownAction()); - break; + 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() +LtsSession::LtsSession* LtsLogin::getAdminSession() { - return m_loginApp->m_sessionManager->getSession(IDL::PartitionType::Global, 0); + return m_loginApp->m_sessionManager->getSession(IDL::PartitionType::Global, 0); } - void LtsLogin::logoff() { - 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 opmFtc; - if (operatorId == -1 || - !datSession->getFtc(opmFtc) - ) - { - - } - else - { - try + if (m_loginApp == nullptr) { - - LtsUtils::OperatorSettings *os = LtsUtils::OperatorSettings::getInstance(); - - const QByteArray settings = os->exportSettings(); - - - const auto vec(LtsUtils::convert>(settings)); - os->clear(); - opmFtc->operatorGetSetSettingsRequest(OperatorManagement::OperatorGetSetSettingsRequest(operatorId, vec)); - } - catch (const std::runtime_error &err) - { - qCritical() << "Saving operator settings failed!" << err.what(); + qCritical() << "LtsLogin::logoff: missing login app!"; + return; } - - std::shared_ptr srmIfc; - if (datSession->getForeignDataInterface(srmIfc)) - { - try - { - srmIfc->removeReplayPartitionsWorkstation(workstationId); - } - catch (const std::runtime_error &err) - { - qCritical() << "Removing reply partitions from this workstation failed!" << err.what(); - } + LtsSession::LtsSession* datSession = getAdminSession(); - try - { - srmIfc->removeReplayPartitionsOperator(operatorId); - } - catch (const std::runtime_error &err) - { - qCritical() << "Removing reply partitions from this operator failed!" << err.what(); - } + if (!datSession) + { + qCritical() << "LtsLogin::logoff: no admin session for logout!"; + abort(); } - - try + int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + int workstationId = LtsSessionData::LtsSessionData::getInstance()->getWorkstationId(); + + LtsSessionData::LtsSessionData::getInstance()->clear(); + + std::shared_ptr opmFtc; + if (operatorId == -1 || !datSession->getFtc(opmFtc)) { - opmFtc->operatorLogoutRequest(OperatorManagement::OperatorLogoutRequest(operatorId)); } - catch (const std::runtime_error &err) + else { - qCritical() << "Logout failed!" << err.what(); + try + { + + LtsUtils::OperatorSettings* os = LtsUtils::OperatorSettings::getInstance(); + + const QByteArray settings = os->exportSettings(); + + const auto vec(LtsUtils::convert>(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 srmIfc; + if (datSession->getForeignDataInterface(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; - m_loginApp->deleteLater(); - m_loginApp = nullptr; - - QString cmd; - switch (m_shutdownAction.underlying()) - { - case AssetManagement::ShutdownAction_def::Shutdown: + QString cmd; + switch (m_shutdownAction.underlying()) + { + case AssetManagement::ShutdownAction_def::Shutdown: #ifdef LTS_DEBUG - cmd = QStringLiteral("xeyes"); + cmd = QStringLiteral("xeyes"); #else - cmd = QStringLiteral("systemctl poweroff"); + cmd = QStringLiteral("systemctl poweroff"); #endif - break; - case AssetManagement::ShutdownAction_def::Reboot: + break; + case AssetManagement::ShutdownAction_def::Reboot: #ifdef LTS_DEBUG - cmd = QStringLiteral("kcalc"); + cmd = QStringLiteral("kcalc"); #else - cmd = QStringLiteral("systemctl reboot"); + cmd = QStringLiteral("systemctl reboot"); #endif - break; - case AssetManagement::ShutdownAction_def::Logout: - case AssetManagement::ShutdownAction_def::NoAction: - emit signalLogoffDone(); - break; - } + break; + case AssetManagement::ShutdownAction_def::Logout: + case AssetManagement::ShutdownAction_def::NoAction: + emit signalLogoffDone(); + break; + } - if (!cmd.isEmpty()) - { - QProcess::startDetached(cmd); - QCoreApplication::quit(); - } + if (!cmd.isEmpty()) + { + QProcess::startDetached(cmd); + QCoreApplication::quit(); + } } -} +} // namespace LtsLogin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.h old mode 100755 new mode 100644 index 7251ba2a9..c214269bd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsLogin/lts_login.h @@ -1,27 +1,26 @@ #pragma once - - -#include +#include #include #include -#include - #include - +#include namespace LtsPluginManager { class LtsPluginManager; } + namespace LtsUtils { class RequestHelper; } + namespace LtsSession { class LtsSession; } + namespace DeveloperTools { class DevDialog; @@ -32,38 +31,41 @@ namespace LtsLogin class LTSLOGIN_EXPORT LtsLogin : public QObject { - Q_OBJECT + Q_OBJECT -public: - LtsLogin(); - ~LtsLogin(); + public: + LtsLogin(); + ~LtsLogin(); - void login(); - void logoff(); - void setLoginPlugin(const QString &loginPluginIid) { m_loginPluginIid = loginPluginIid; } + void login(); + void logoff(); -private: - friend class DeveloperTools::DevDialog; + void setLoginPlugin(const QString& loginPluginIid) + { + m_loginPluginIid = loginPluginIid; + } - LtsSession::LtsSession *getAdminSession(); - void showLogoutInformationDialog(AssetManagement::ShutdownAction action); + private: + friend class DeveloperTools::DevDialog; - LtsPluginManager::LtsPluginManager *m_loginApp; - AssetManagement::ShutdownAction m_shutdownAction; - std::shared_ptr m_asmDtc; - QString m_loginPluginIid; - bool m_isInLogoutDialog; + LtsSession::LtsSession* getAdminSession(); + void showLogoutInformationDialog(AssetManagement::ShutdownAction action); -private slots: - void slotLoginDone(); - void slotLogoutShutdown(const AssetManagement::WorkstationLogout &data, DataModification modType); + LtsPluginManager::LtsPluginManager* m_loginApp; + AssetManagement::ShutdownAction m_shutdownAction; + std::shared_ptr m_asmDtc; + QString m_loginPluginIid; + bool m_isInLogoutDialog; -signals: - void signalLogout(); - void signalStopBlock(); - void signalLoginDone(); - void signalLogoffDone(); + private slots: + void slotLoginDone(); + void slotLogoutShutdown(const AssetManagement::WorkstationLogout& data, DataModification modType); + signals: + void signalLogout(); + void signalStopBlock(); + void signalLoginDone(); + void signalLogoffDone(); }; -} +} // namespace LtsLogin diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.cpp old mode 100755 new mode 100644 index 476c08e82..4d52a7e25 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.cpp @@ -1,44 +1,35 @@ #include "lts_dummy_widget.h" #include - -#include - -#include #include - +#include +#include namespace LtsMultiMonitor { FullscreenVideoDummyWidget::FullscreenVideoDummyWidget() { - setWindowIcon(LtsUtils::iconFromSvg(QStringLiteral(":/style/mobile_video.svg"))); - setWindowTitle(tr("Fullscreen Video Helper")); - - - - + setWindowIcon(LtsUtils::iconFromSvg(QStringLiteral(":/style/mobile_video.svg"))); + setWindowTitle(tr("Fullscreen Video Helper")); } - void FullscreenVideoDummyWidget::hideVideo() { - qWarning() << "FullscreenVideoDummyWidget::hideVideo()"; - emit signalHideVideo(); + qWarning() << "FullscreenVideoDummyWidget::hideVideo()"; + emit signalHideVideo(); } void FullscreenVideoDummyWidget::showVideo() { - emit signalShowVideo(); + emit signalShowVideo(); } - -bool FullscreenVideoDummyWidget::event(QEvent *event) +bool FullscreenVideoDummyWidget::event(QEvent* event) { - if (event->type() == QEvent::Type::Show) - assert(false); - return QWidget::event(event); + if (event->type() == QEvent::Type::Show) + assert(false); + return QWidget::event(event); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.h old mode 100755 new mode 100644 index cd5ddc0b7..b3ea24bb4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_dummy_widget.h @@ -1,44 +1,39 @@ #pragma once -#include - #include "ltsmultimonitor_export.h" +#include #include - class QEvent; - namespace LtsMultiMonitor { class LTSMULTIMONITOR_EXPORT SecondaryWidget : public QWidget { - Q_OBJECT -public: - SecondaryWidget() = default; - virtual ~SecondaryWidget() = default; + Q_OBJECT + public: + SecondaryWidget() = default; + virtual ~SecondaryWidget() = default; }; - - class LTSMULTIMONITOR_EXPORT FullscreenVideoDummyWidget : public SecondaryWidget { - Q_OBJECT + Q_OBJECT -public: - FullscreenVideoDummyWidget(); + public: + FullscreenVideoDummyWidget(); - void hideVideo(); - void showVideo(); + void hideVideo(); + void showVideo(); -protected: - bool event(QEvent *); + protected: + bool event(QEvent*); -signals: - void signalWidgetPlaced(const QRect &globalGeometry); - void signalHideVideo(); - void signalShowVideo(); + signals: + void signalWidgetPlaced(const QRect& globalGeometry); + void signalHideVideo(); + void signalShowVideo(); }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.cpp old mode 100755 new mode 100644 index 00e7a93e5..7b9d783c6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.cpp @@ -1,88 +1,63 @@ #include "lts_magic_corner.h" #include - -#include +#include #include #include #include +#include #include -#include - #include - -#define SMOL 48 +#define SMOL 48 #define SWOLE 100 - using namespace std::chrono_literals; - namespace LtsMultiMonitor { -LtsMagicCorner::LtsMagicCorner(const QRect &neogeo) - : m_neogeo(neogeo) - , m_shrinkTimer(new QTimer(this)) - , m_label(new QLabel(this)) +LtsMagicCorner::LtsMagicCorner(const QRect& neogeo) + : m_neogeo(neogeo), m_shrinkTimer(new QTimer(this)), m_label(new QLabel(this)) { - - m_shrinkTimer->setInterval(1500ms); - m_shrinkTimer->setSingleShot(true); + m_shrinkTimer->setInterval(1500ms); + m_shrinkTimer->setSingleShot(true); - connect(m_shrinkTimer, &QTimer::timeout, - this, &LtsMagicCorner::makeSmol); + connect(m_shrinkTimer, &QTimer::timeout, this, &LtsMagicCorner::makeSmol); - makeSmol(); + makeSmol(); - - setWindowFlags(windowFlags() | Qt::FramelessWindowHint); - setMouseTracking(true); - setContentsMargins(0, 0, 0, 0); - setWindowFlag(Qt::WindowType::WindowStaysOnTopHint); - setWindowFlag(Qt::WindowType::X11BypassWindowManagerHint); - activateWindow(); + setWindowFlags(windowFlags() | Qt::FramelessWindowHint); + setMouseTracking(true); + setContentsMargins(0, 0, 0, 0); + setWindowFlag(Qt::WindowType::WindowStaysOnTopHint); + setWindowFlag(Qt::WindowType::X11BypassWindowManagerHint); + activateWindow(); + auto* t = new QTimer(this); + connect(t, &QTimer::timeout, this, [this]() { + if (!isVisible()) + return; - - auto *t = new QTimer(this); - connect(t, &QTimer::timeout, - this, [this]() - { - if (!isVisible()) - return; + raise(); + }); + t->setInterval(750ms); + t->start(); - raise(); - - - - }); - t->setInterval(750ms); - t->start(); - - - m_label->setMinimumSize(SWOLE, SWOLE); - m_label->setMaximumSize(SWOLE, SWOLE); - m_label->setGeometry(0, 0, SWOLE, SWOLE); - m_label->setText(QStringLiteral("")); - m_label->setAlignment(Qt::AlignmentFlag::AlignCenter); - - - - - - + m_label->setMinimumSize(SWOLE, SWOLE); + m_label->setMaximumSize(SWOLE, SWOLE); + m_label->setGeometry(0, 0, SWOLE, SWOLE); + m_label->setText(QStringLiteral("")); + m_label->setAlignment(Qt::AlignmentFlag::AlignCenter); } - void LtsMagicCorner::setActiveWidgetType(LtsScreenBase::WidgetType widgetType) { - m_activeWidgetType = widgetType; - if (widgetType == LtsScreenBase::WidgetType::MainWidget) - m_label->setPixmap(m_mainPixmap); - else - m_label->setPixmap(m_secondaryPixmap); + m_activeWidgetType = widgetType; + if (widgetType == LtsScreenBase::WidgetType::MainWidget) + m_label->setPixmap(m_mainPixmap); + else + m_label->setPixmap(m_secondaryPixmap); } void LtsMagicCorner::setFreezed(bool freezed) @@ -90,125 +65,66 @@ void LtsMagicCorner::setFreezed(bool freezed) setVisible(!freezed); } - -void LtsMagicCorner::setIcon(const QIcon &icon, LtsScreenBase::WidgetType widgetType) +void LtsMagicCorner::setIcon(const QIcon& icon, LtsScreenBase::WidgetType widgetType) { - QPixmap p(LtsUtils::pixmapFromIcon(icon)); + QPixmap p(LtsUtils::pixmapFromIcon(icon)); - if (widgetType == LtsScreenBase::WidgetType::MainWidget) - m_mainPixmap = p; - else - m_secondaryPixmap = p; + if (widgetType == LtsScreenBase::WidgetType::MainWidget) + m_mainPixmap = p; + else + m_secondaryPixmap = p; - if (widgetType != m_activeWidgetType) - m_label->setPixmap(p); - - - - - - - - - - - - + if (widgetType != m_activeWidgetType) + m_label->setPixmap(p); } - -void LtsMagicCorner::mousePressEvent(QMouseEvent *event) +void LtsMagicCorner::mousePressEvent(QMouseEvent* event) { - m_mousePressed = (event->button() == Qt::MouseButton::LeftButton); + m_mousePressed = (event->button() == Qt::MouseButton::LeftButton); } - -void LtsMagicCorner::mouseReleaseEvent(QMouseEvent *event) +void LtsMagicCorner::mouseReleaseEvent(QMouseEvent* event) { - if (!m_mousePressed) - return; + if (!m_mousePressed) + return; - m_mousePressed = false; + m_mousePressed = false; - if (event->button() != Qt::MouseButton::LeftButton) - return; + if (event->button() != Qt::MouseButton::LeftButton) + return; - m_shrinkTimer->start(); - emit toggle(); + m_shrinkTimer->start(); + emit toggle(); } - void LtsMagicCorner::makeSmol() { - setAttribute(Qt::WA_TranslucentBackground); - setGeometry(m_neogeo.x(), m_neogeo.y(), SMOL, SMOL); - setMinimumSize(SMOL, SMOL); - setMaximumSize(SMOL, SMOL); - m_label->hide(); + setAttribute(Qt::WA_TranslucentBackground); + setGeometry(m_neogeo.x(), m_neogeo.y(), SMOL, SMOL); + setMinimumSize(SMOL, SMOL); + setMaximumSize(SMOL, SMOL); + m_label->hide(); } - void LtsMagicCorner::makeSwole() { - if (!isVisible()) - return; + if (!isVisible()) + return; - setAttribute(Qt::WA_TranslucentBackground, false); - setAttribute(Qt::WA_NoSystemBackground, false); - setGeometry(m_neogeo.x(), m_neogeo.y(), SWOLE, SWOLE); - setMinimumSize(SWOLE, SWOLE); - setMaximumSize(SWOLE, SWOLE); - m_label->show(); - m_shrinkTimer->start(); - update(); + setAttribute(Qt::WA_TranslucentBackground, false); + setAttribute(Qt::WA_NoSystemBackground, false); + setGeometry(m_neogeo.x(), m_neogeo.y(), SWOLE, SWOLE); + setMinimumSize(SWOLE, SWOLE); + setMaximumSize(SWOLE, SWOLE); + m_label->show(); + m_shrinkTimer->start(); + update(); } - -void LtsMagicCorner::mouseMoveEvent(QMouseEvent *) +void LtsMagicCorner::mouseMoveEvent(QMouseEvent*) { - - emit signalMakeAllSwole(); + + emit signalMakeAllSwole(); } -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.h old mode 100755 new mode 100644 index 76c55f80c..7c466e729 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_magic_corner.h @@ -1,56 +1,52 @@ #pragma once -#include - #include "lts_screen_base.h" #include +#include #include - class QMouseEvent; class QPaintEvent; class QLabel; class QTimer; - namespace LtsMultiMonitor { class LtsMagicCorner : public QDialog { - Q_OBJECT + Q_OBJECT -public: - explicit LtsMagicCorner(const QRect &neogeo); + public: + explicit LtsMagicCorner(const QRect& neogeo); - void setIcon(const QIcon &icon, LtsScreenBase::WidgetType widgetType); - void setActiveWidgetType(LtsScreenBase::WidgetType widgetType); - - - void setFreezed(bool freezed); + void setIcon(const QIcon& icon, LtsScreenBase::WidgetType widgetType); + void setActiveWidgetType(LtsScreenBase::WidgetType widgetType); -protected: - void mouseMoveEvent(QMouseEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; + void setFreezed(bool freezed); -signals: - void toggle(); - void signalMakeAllSwole(); + protected: + void mouseMoveEvent(QMouseEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; -private slots: - void makeSmol(); + signals: + void toggle(); + void signalMakeAllSwole(); -public slots: - void makeSwole(); + private slots: + void makeSmol(); -private: - QRect m_neogeo; - QTimer *m_shrinkTimer; - bool m_mousePressed { false }; - bool m_freezed = false; - QLabel *m_label; - QPixmap m_mainPixmap; - QPixmap m_secondaryPixmap; - LtsScreenBase::WidgetType m_activeWidgetType; + public slots: + void makeSwole(); + + private: + QRect m_neogeo; + QTimer* m_shrinkTimer; + bool m_mousePressed{false}; + bool m_freezed = false; + QLabel* m_label; + QPixmap m_mainPixmap; + QPixmap m_secondaryPixmap; + LtsScreenBase::WidgetType m_activeWidgetType; }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.cpp old mode 100755 new mode 100644 index daebbc8d6..bdf63bfaa --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.cpp @@ -1,697 +1,602 @@ - #include "lts_multi_monitor.h" -#include + +#include "lts_dummy_widget.h" #include "lts_multi_monitor_selector_normal.h" #include "lts_multi_monitor_selector_wide.h" +#include "lts_screen_container.h" #include "lts_screen_normal.h" #include "lts_screen_wide.h" -#include "lts_dummy_widget.h" -#include "lts_screen_container.h" -#include -#include #include - -#include -#include -#include -#include -#include -#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include #ifdef Q_OS_WIN #include #endif - namespace LtsMultiMonitor { -static LtsMultiMonitor *s_ltsMultiMonitor = nullptr; +static LtsMultiMonitor* s_ltsMultiMonitor = nullptr; - -LtsMultiMonitor *LtsMultiMonitor::getInstance() +LtsMultiMonitor* LtsMultiMonitor::getInstance() { - if (!s_ltsMultiMonitor) - { - s_ltsMultiMonitor = new LtsMultiMonitor; - qAddPostRoutine(&cleanupLtsMultiMonitor); - } - return s_ltsMultiMonitor; + if (!s_ltsMultiMonitor) + { + s_ltsMultiMonitor = new LtsMultiMonitor; + qAddPostRoutine(&cleanupLtsMultiMonitor); + } + return s_ltsMultiMonitor; } void LtsMultiMonitor::cleanupLtsMultiMonitor() { - delete s_ltsMultiMonitor; - s_ltsMultiMonitor = nullptr; + delete s_ltsMultiMonitor; + s_ltsMultiMonitor = nullptr; } - LtsMultiMonitor::LtsMultiMonitor() - : QObject(nullptr) - , m_mainScreen(nullptr) - , m_active(false) - , m_initialized(false) - , m_skipScreenId(-1) - , m_subSkipScreenId(-1) - - , m_overlapBaseLayouts(false) - , m_debugMargins(false) -{} + : QObject(nullptr), m_mainScreen(nullptr), m_active(false), m_initialized(false), m_skipScreenId(-1), + m_subSkipScreenId(-1) + , + m_overlapBaseLayouts(false), m_debugMargins(false) +{ +} LtsMultiMonitor::~LtsMultiMonitor() { - - - for (auto i = m_screens.begin(); i != m_screens.end(); ++i) - { - LtsScreenBase *screen = *i; - disconnect(screen, &QObject::destroyed, this, &LtsMultiMonitor::screenDied); - screen->deleteLater(); - } - - - - + for (auto i = m_screens.begin(); i != m_screens.end(); ++i) + { + LtsScreenBase* screen = *i; + disconnect(screen, &QObject::destroyed, this, &LtsMultiMonitor::screenDied); + screen->deleteLater(); + } } - void LtsMultiMonitor::screenDied() { - - Q_ASSERT(false); -} + Q_ASSERT(false); +} void LtsMultiMonitor::init() { - - if (LtsSessionData::LtsSessionData::getInstance()->isTablet()) - { - m_overlapBaseLayouts = true; + + if (LtsSessionData::LtsSessionData::getInstance()->isTablet()) + { + m_overlapBaseLayouts = true; + m_initialized = true; + return; + } + + if (m_initialized || !m_active) + return; + + QList screenList = QGuiApplication::screens(); + const QScreen& mainScreen = *QGuiApplication::primaryScreen(); + + for (auto i = screenList.constBegin(); i != screenList.constEnd(); ++i) + { + const QScreen& screen = **i; + + bool found = false; + + for (LtsScreenBase* ltsScreen : std::as_const(m_screens)) + { + if (ltsScreen->serialNumber() == screen.name()) + { + found = true; + break; + } + } + + if (found) + continue; + + int screenId = m_nextScreenId++; + + QRect screenGeo(screen.geometry()); + + if (screenId == m_skipScreenId) + { + if (m_subSkipScreenId == 0) + { + + QRect newScreenGeo(screenGeo); + + newScreenGeo.moveLeft(screenGeo.x() + (screenGeo.width() / 2)); + newScreenGeo.setWidth(screenGeo.width() / 2); + + screenGeo = newScreenGeo; + } + else if (m_subSkipScreenId == 1) + { + + QRect newScreenGeo(screenGeo); + + newScreenGeo.setWidth(screenGeo.width() / 2); + + screenGeo = newScreenGeo; + } + else + { + + continue; + } + } + + bool isUltraWideView = (screenGeo.width() > 3000); + + LtsScreenBase* newScreen; + if (isUltraWideView) + { + newScreen = new LtsScreenWide(screenGeo, screenId, m_debugMargins, screen.name()); + } + else + { + auto* newScreenNormal = new LtsScreenNormal(std::move(screenGeo), screenId, m_debugMargins, screen.name()); + newScreen = newScreenNormal; + + connect(newScreenNormal, &LtsScreenNormal::signalMakeAllSwole, this, &LtsMultiMonitor::signalMakeAllSwole); + connect(this, &LtsMultiMonitor::signalMakeAllSwole, newScreenNormal, &LtsScreenNormal::signalMakeSwole); + } + + connect(newScreen, &QObject::destroyed, this, &LtsMultiMonitor::screenDied); + + if ((&mainScreen) == (&screen)) + m_mainScreen = newScreen; + + m_screens.append(newScreen); + } + if (m_screens.isEmpty()) + { + QMessageBox::critical(nullptr, QString(), tr("No screens found - cannot start application.")); + abort(); + } + + if (m_mainScreen == nullptr) + m_mainScreen = m_screens.first(); + m_initialized = true; - return; - } - - if (m_initialized || !m_active) - return; - - QList screenList = QGuiApplication::screens(); - const QScreen &mainScreen = *QGuiApplication::primaryScreen(); - - - - - for (auto i = screenList.constBegin(); i != screenList.constEnd(); ++i) - { - const QScreen &screen = **i; - - - bool found = false; - - for (LtsScreenBase *ltsScreen : std::as_const(m_screens)) - { - if (ltsScreen->serialNumber() == screen.name()) - { - found = true; - break; - } - } - - if (found) - continue; - - - int screenId = m_nextScreenId++; - - - QRect screenGeo(screen.geometry()); - - if (screenId == m_skipScreenId) - { - if (m_subSkipScreenId == 0) - { - - QRect newScreenGeo(screenGeo); - - newScreenGeo.moveLeft(screenGeo.x() + (screenGeo.width() / 2)); - newScreenGeo.setWidth(screenGeo.width() / 2); - - screenGeo = newScreenGeo; - } - else if (m_subSkipScreenId == 1) - { - - QRect newScreenGeo(screenGeo); - - newScreenGeo.setWidth(screenGeo.width() / 2); - - screenGeo = newScreenGeo; - } - else - { - - continue; - } - } - - - - bool isUltraWideView = (screenGeo.width() > 3000); - - LtsScreenBase *newScreen; - if (isUltraWideView) - { - newScreen = new LtsScreenWide(screenGeo, screenId, m_debugMargins, screen.name()); - } - else - { - auto *newScreenNormal = new LtsScreenNormal(std::move(screenGeo), screenId, m_debugMargins, screen.name()); - newScreen = newScreenNormal; - - - connect(newScreenNormal, &LtsScreenNormal::signalMakeAllSwole, - this, &LtsMultiMonitor::signalMakeAllSwole); - connect(this, &LtsMultiMonitor::signalMakeAllSwole, - newScreenNormal, &LtsScreenNormal::signalMakeSwole); - } - - connect(newScreen, &QObject::destroyed, this, &LtsMultiMonitor::screenDied); - - if ((&mainScreen) == (&screen)) - m_mainScreen = newScreen; - - m_screens.append(newScreen); - } - if (m_screens.isEmpty()) - { - QMessageBox::critical(nullptr, QString(), tr("No screens found - cannot start application.")); - abort(); - } - - if (m_mainScreen == nullptr) - m_mainScreen = m_screens.first(); - - m_initialized = true; - emit signalScreenCountChanged(screenCount()); + emit signalScreenCountChanged(screenCount()); } - int LtsMultiMonitor::screenCount() const { - return m_screens.count(); + return m_screens.count(); } - -bool LtsMultiMonitor::cancelAndProcessIfInactive(QWidget *widget) const +bool LtsMultiMonitor::cancelAndProcessIfInactive(QWidget* widget) const { - if (m_active) - return false; + if (m_active) + return false; - widget->activateWindow(); - widget->show(); + widget->activateWindow(); + widget->show(); - place(widget); - - return true; -} - - -void LtsMultiMonitor::place(QWidget *widget) -{ - - - auto *blw = qobject_cast(widget); - if (blw != nullptr) - emit blw->signalSuccessfullyPlaced(); -} - - -bool LtsMultiMonitor::putScreen(QWidget *widget, int screenId, int screenPart) -{ - Q_ASSERT(widget != nullptr); - if (widget == nullptr) - return false; - - if (cancelAndProcessIfInactive(widget)) - return true; - - init(); - - if (overlapBaseLayouts(widget)) - return true; - - - bool isSecondary = isWidgetSecondary(widget); - qWarning() << "putScreen: isSecondary" << isSecondary; - - for (LtsScreenBase *screen : std::as_const(m_screens)) - { - if (screen->screenId() != screenId) - continue; - - screen->switchToTemp(isSecondary ? LtsScreenBase::WidgetType::SecondaryWidget : LtsScreenBase::WidgetType::MainWidget); - - try - { - screen->putWidget(widget, screenPart); - } - catch (...) - { - screen->revertSwitch(); - - return selectScreen(widget); - } - - screen->check(); - place(widget); - screen->finalizeSwitch(); - return true; - } - - return selectScreen(widget); + return true; } -bool LtsMultiMonitor::putScreenAutomatically(QWidget *widget) +void LtsMultiMonitor::place(QWidget* widget) { - if (widget == nullptr) - return false; - if (cancelAndProcessIfInactive(widget)) - return true; - - init(); - - if (overlapBaseLayouts(widget)) - return true; - - for (LtsScreenBase *screen : std::as_const(m_screens)) - { - if (screen->screenId() == m_skipScreenId || !screen->isEmpty()) - continue; - - screen->switchToTemp(LtsScreenBase::WidgetType::SecondaryWidget); - - try - { - screen->putWidget(widget, 1); - } - catch (...) - { - try - { - screen->putWidget(widget, 2); - } - catch (...) - { - screen->revertSwitch(); - continue; - } - } - - screen->check(); - place(widget); - screen->finalizeSwitch(); - - return true; - } - - return false; + auto* blw = qobject_cast(widget); + if (blw != nullptr) + emit blw->signalSuccessfullyPlaced(); } +bool LtsMultiMonitor::putScreen(QWidget* widget, int screenId, int screenPart) +{ + Q_ASSERT(widget != nullptr); + if (widget == nullptr) + return false; + + if (cancelAndProcessIfInactive(widget)) + return true; + + init(); + + if (overlapBaseLayouts(widget)) + return true; + + bool isSecondary = isWidgetSecondary(widget); + qWarning() << "putScreen: isSecondary" << isSecondary; + + for (LtsScreenBase* screen : std::as_const(m_screens)) + { + if (screen->screenId() != screenId) + continue; + + screen->switchToTemp(isSecondary ? LtsScreenBase::WidgetType::SecondaryWidget + : LtsScreenBase::WidgetType::MainWidget); + + try + { + screen->putWidget(widget, screenPart); + } + catch (...) + { + screen->revertSwitch(); + + return selectScreen(widget); + } + + screen->check(); + + place(widget); + screen->finalizeSwitch(); + return true; + } + + return selectScreen(widget); +} + +bool LtsMultiMonitor::putScreenAutomatically(QWidget* widget) +{ + if (widget == nullptr) + return false; + + if (cancelAndProcessIfInactive(widget)) + return true; + + init(); + + if (overlapBaseLayouts(widget)) + return true; + + for (LtsScreenBase* screen : std::as_const(m_screens)) + { + if (screen->screenId() == m_skipScreenId || !screen->isEmpty()) + continue; + + screen->switchToTemp(LtsScreenBase::WidgetType::SecondaryWidget); + + try + { + screen->putWidget(widget, 1); + } + catch (...) + { + try + { + screen->putWidget(widget, 2); + } + catch (...) + { + screen->revertSwitch(); + continue; + } + } + + screen->check(); + place(widget); + screen->finalizeSwitch(); + + return true; + } + + return false; +} bool LtsMultiMonitor::isOverlapBaseLayouts() const { - return (m_overlapBaseLayouts ); + return (m_overlapBaseLayouts); } - void LtsMultiMonitor::freezeMagicCorner(int screenId) { - for (auto *screen : std::as_const(m_screens)) - { - - if (screen->screenId() == screenId) + for (auto* screen : std::as_const(m_screens)) { - LtsScreenNormal* normalScreen = qobject_cast(screen); - if(normalScreen->child()->hasMainWidget() && normalScreen->child()->hasSecondaryWidget()) - { - normalScreen->hideMagicCorner(true); - if(normalScreen->child()->activeWidgetType() == LtsScreenBase::WidgetType::MainWidget) - normalScreen->child()->toggle(); - } + + if (screen->screenId() == screenId) + { + LtsScreenNormal* normalScreen = qobject_cast(screen); + if (normalScreen->child()->hasMainWidget() && normalScreen->child()->hasSecondaryWidget()) + { + normalScreen->hideMagicCorner(true); + if (normalScreen->child()->activeWidgetType() == LtsScreenBase::WidgetType::MainWidget) + normalScreen->child()->toggle(); + } + } } - } } void LtsMultiMonitor::unfreezeMagicCorner(int screenId) { - for (auto *screen : std::as_const(m_screens)) - { - - if (screen->screenId() == screenId) + for (auto* screen : std::as_const(m_screens)) { - LtsScreenNormal* normalScreen = qobject_cast(screen); - if(normalScreen->child()->hasMainWidget() && normalScreen->child()->hasSecondaryWidget()) - normalScreen->hideMagicCorner(false); + + if (screen->screenId() == screenId) + { + LtsScreenNormal* normalScreen = qobject_cast(screen); + if (normalScreen->child()->hasMainWidget() && normalScreen->child()->hasSecondaryWidget()) + normalScreen->hideMagicCorner(false); + } } - } } - -bool LtsMultiMonitor::overlapBaseLayouts(QWidget *widget) +bool LtsMultiMonitor::overlapBaseLayouts(QWidget* widget) { - if (!isOverlapBaseLayouts()) - return false; - - - - - Q_ASSERT(qobject_cast(widget) == nullptr); - if (qobject_cast(widget) != nullptr) - { - - return false; - } - - - - - - - - - - - - + if (!isOverlapBaseLayouts()) + return false; + Q_ASSERT(qobject_cast(widget) == nullptr); + if (qobject_cast(widget) != nullptr) + { + return false; + } #ifdef Q_OS_WIN - widget->winId(); - QWindowsWindowFunctions::setHasBorderInFullScreen(widget->windowHandle(), true); + widget->winId(); + QWindowsWindowFunctions::setHasBorderInFullScreen(widget->windowHandle(), true); #endif - widget->activateWindow(); - widget->showFullScreen(); + widget->activateWindow(); + widget->showFullScreen(); - place(widget); + place(widget); - return true; + return true; } - -bool LtsMultiMonitor::selectAndSwap(QWidget *widget) +bool LtsMultiMonitor::selectAndSwap(QWidget* widget) { - if (!m_active) - return false; + if (!m_active) + return false; - Q_ASSERT(!isOverlapBaseLayouts()); - if (isOverlapBaseLayouts()) - return false; + Q_ASSERT(!isOverlapBaseLayouts()); + if (isOverlapBaseLayouts()) + return false; - - - LtsScreenContainer *oldContainer = nullptr; - for (LtsScreenBase *_screen : std::as_const(m_screens)) - { - try + LtsScreenContainer* oldContainer = nullptr; + for (LtsScreenBase* _screen : std::as_const(m_screens)) { - oldContainer = _screen->containerOfWidget(widget); + try + { + oldContainer = _screen->containerOfWidget(widget); + } + catch (...) + { + } } - catch (...){} - } - if (oldContainer == nullptr) - { - - LtsWidgets::LtsMessageDialog::showMessage(widget, tr("Could not determine screen id for this swap!
Swapping not possible, please try again later.")); - return false; - } + if (oldContainer == nullptr) + { - + LtsWidgets::LtsMessageDialog::showMessage( + widget, + tr("Could not determine screen id for this swap!
Swapping not possible, please try again later.")); + return false; + } - - return selectScreen(widget, oldContainer); + return selectScreen(widget, oldContainer); } - -LtsScreenBase *LtsMultiMonitor::widgetsScreen(QWidget *widget) +LtsScreenBase* LtsMultiMonitor::widgetsScreen(QWidget* widget) { - for (LtsScreenBase *screen : std::as_const(m_screens)) - if (screen->hasWidget(widget)) - return screen; - return nullptr; + for (LtsScreenBase* screen : std::as_const(m_screens)) + if (screen->hasWidget(widget)) + return screen; + return nullptr; } - -bool LtsMultiMonitor::isWidgetSecondary(QWidget *widget) +bool LtsMultiMonitor::isWidgetSecondary(QWidget* widget) { #ifndef GUEZ_MODE - return false; + return false; #endif - auto *blw = qobject_cast(widget); - auto *secondaryWidget = qobject_cast(widget); + auto* blw = qobject_cast(widget); + auto* secondaryWidget = qobject_cast(widget); - bool isSecondaryWidget = ((blw != nullptr && blw->isSecondaryWidget()) || secondaryWidget != nullptr); + bool isSecondaryWidget = ((blw != nullptr && blw->isSecondaryWidget()) || secondaryWidget != nullptr); - - - return isSecondaryWidget; + return isSecondaryWidget; } - class StupidDeleter { -public: - explicit StupidDeleter(LtsScreenBase *screen) - : m_screen(screen) - {} + public: + explicit StupidDeleter(LtsScreenBase* screen) : m_screen(screen) {} - ~StupidDeleter() - { - - if (m_screen != nullptr) + ~StupidDeleter() { - - m_screen->revertSwitch(); + + if (m_screen != nullptr) + { + + m_screen->revertSwitch(); + } } - - } - void reset() - { - - m_screen = nullptr; - } + void reset() + { + m_screen = nullptr; + } -private: - LtsScreenBase *m_screen; + private: + LtsScreenBase* m_screen; }; - -bool LtsMultiMonitor::selectScreen(QWidget *widget, LtsScreenContainer *swap, bool putOnMainIfFree, bool ltsScreenNormalOnly, const QVector &irreplacableWidgets) +bool LtsMultiMonitor::selectScreen(QWidget* widget, LtsScreenContainer* swap, bool putOnMainIfFree, + bool ltsScreenNormalOnly, const QVector& irreplacableWidgets) { - Q_ASSERT(widget != nullptr); - if (widget == nullptr) - return false; + Q_ASSERT(widget != nullptr); + if (widget == nullptr) + return false; - if (cancelAndProcessIfInactive(widget)) - return true; + if (cancelAndProcessIfInactive(widget)) + return true; - init(); + init(); - if (overlapBaseLayouts(widget)) - return true; + if (overlapBaseLayouts(widget)) + return true; - bool isSecondary = isWidgetSecondary(widget); - + bool isSecondary = isWidgetSecondary(widget); - if (!isSecondary) - { - bool allEmpty = putOnMainIfFree; - for (LtsScreenBase *screen : std::as_const(m_screens)) + if (!isSecondary) { - screen->switchToTemp(LtsScreenBase::WidgetType::MainWidget); - bool isEmpty = screen->isEmpty(); - screen->revertSwitch(); + bool allEmpty = putOnMainIfFree; + for (LtsScreenBase* screen : std::as_const(m_screens)) + { + screen->switchToTemp(LtsScreenBase::WidgetType::MainWidget); + bool isEmpty = screen->isEmpty(); + screen->revertSwitch(); - if (isEmpty) - continue; + if (isEmpty) + continue; - allEmpty = false; - break; - } + allEmpty = false; + break; + } - + if (allEmpty) + { - if (allEmpty) - { - + m_mainScreen->switchToTemp(LtsScreenBase::WidgetType::MainWidget); - - m_mainScreen->switchToTemp(LtsScreenBase::WidgetType::MainWidget); - - try - { - m_mainScreen->putWidget(widget); - } - catch (...) - { - qWarning() << "failed - reverting"; - m_mainScreen->revertSwitch(); - - Q_ASSERT_X(false, __FUNCTION__, "screen promised to be empty but 'putWidgetSomewhere' method failed regardless"); - - - auto *blw = qobject_cast(widget); - if (blw != nullptr) - emit blw->signalClose(); - else - widget->deleteLater(); - - return false; - } - - m_mainScreen->check(); - place(widget); - m_mainScreen->finalizeSwitch(); - return true; - } - } - - - auto *selectionProcessWatcher = new QObject; - - - bool minOnce = false; - - for (auto i = m_screens.begin(); i != m_screens.end(); ++i) - { - LtsScreenBase *screen = *i; - - screen->switchToTemp(isSecondary ? LtsScreenBase::WidgetType::SecondaryWidget : LtsScreenBase::WidgetType::MainWidget); - - StupidDeleter _(screen); - - if (screen->isIrreplaceable()) - { - - continue; - } - - bool skip = false; - for (QWidget *widget : std::as_const(irreplacableWidgets)) - { - - if (screen->hasWidget(widget)) - { - - skip = true; - continue; - } - - - } - - if (skip) - continue; - - MultiMonitorSelectorBase *mms; - if (qobject_cast(screen) != nullptr) - { - auto *screenNormal = static_cast(screen); - mms = new MultiMonitorSelectorNormal(screenNormal, isSecondary, irreplacableWidgets); - } - else if (qobject_cast(screen) != nullptr && !ltsScreenNormalOnly) - { - auto *screenWide = static_cast(screen); - mms = new MultiMonitorSelectorWide(screenWide, nullptr, irreplacableWidgets); - } - else - continue; - - - QPointer widgetPtr(widget); - - - connect(widget, &QWidget::destroyed, - mms, &MultiMonitorSelectorBase::close); - connect(mms, &MultiMonitorSelectorBase::rejected, - this, [widgetPtr, swap]() + try { - + m_mainScreen->putWidget(widget); + } + catch (...) + { + qWarning() << "failed - reverting"; + m_mainScreen->revertSwitch(); - if (!widgetPtr || swap != nullptr) + Q_ASSERT_X(false, __FUNCTION__, + "screen promised to be empty but 'putWidgetSomewhere' method failed regardless"); + + auto* blw = qobject_cast(widget); + if (blw != nullptr) + emit blw->signalClose(); + else + widget->deleteLater(); + + return false; + } + + m_mainScreen->check(); + place(widget); + m_mainScreen->finalizeSwitch(); + return true; + } + } + + auto* selectionProcessWatcher = new QObject; + + bool minOnce = false; + + for (auto i = m_screens.begin(); i != m_screens.end(); ++i) + { + LtsScreenBase* screen = *i; + + screen->switchToTemp(isSecondary ? LtsScreenBase::WidgetType::SecondaryWidget + : LtsScreenBase::WidgetType::MainWidget); + + StupidDeleter _(screen); + + if (screen->isIrreplaceable()) + { + + continue; + } + + bool skip = false; + for (QWidget* widget : std::as_const(irreplacableWidgets)) + { + + if (screen->hasWidget(widget)) + { + + skip = true; + continue; + } + } + + if (skip) + continue; + + MultiMonitorSelectorBase* mms; + if (qobject_cast(screen) != nullptr) + { + auto* screenNormal = static_cast(screen); + mms = new MultiMonitorSelectorNormal(screenNormal, isSecondary, irreplacableWidgets); + } + else if (qobject_cast(screen) != nullptr && !ltsScreenNormalOnly) + { + auto* screenWide = static_cast(screen); + mms = new MultiMonitorSelectorWide(screenWide, nullptr, irreplacableWidgets); + } + else + continue; + + QPointer widgetPtr(widget); + + connect(widget, &QWidget::destroyed, mms, &MultiMonitorSelectorBase::close); + connect(mms, &MultiMonitorSelectorBase::rejected, this, [widgetPtr, swap]() { + if (!widgetPtr || swap != nullptr) return; - - - - - auto *blw = qobject_cast(widgetPtr.data()); - if (blw != nullptr) + auto* blw = qobject_cast(widgetPtr.data()); + if (blw != nullptr) emit blw->signalClose(); - else + else widgetPtr->deleteLater(); - }); - connect(mms, &MultiMonitorSelectorBase::signalSelected, - this, [this, mms, widgetPtr]() - { - - - for (LtsScreenBase *screen : std::as_const(m_screens)) + }); + connect(mms, &MultiMonitorSelectorBase::signalSelected, this, [this, mms, widgetPtr]() { + for (LtsScreenBase* screen : std::as_const(m_screens)) screen->check(); - - - if (widgetPtr) + if (widgetPtr) place(widgetPtr.data()); - + mms->deleteLater(); + emit signalSelected(); + }); + connect(mms, &MultiMonitorSelectorBase::destroyed, selectionProcessWatcher, &QObject::deleteLater); + connect(selectionProcessWatcher, &QObject::destroyed, mms, &MultiMonitorSelectorBase::close); - mms->deleteLater(); - emit signalSelected(); + mms->setSwap(swap); + mms->setWidget(widget); + mms->show(); + _.reset(); + minOnce = true; + } - - }); - connect(mms, &MultiMonitorSelectorBase::destroyed, - selectionProcessWatcher, &QObject::deleteLater); - connect(selectionProcessWatcher, &QObject::destroyed, - mms, &MultiMonitorSelectorBase::close); + if (!minOnce) + { + selectionProcessWatcher->deleteLater(); + auto* blw = qobject_cast(widget); + if (blw != nullptr) + emit blw->signalClose(); + else + widget->deleteLater(); - mms->setSwap(swap); - mms->setWidget(widget); - mms->show(); - _.reset(); - minOnce = true; - } + LtsWidgets::LtsMessageDialog::showMessage(m_mainScreen->screenDialog(), + tr("There are no free screens available to select from.")); + return false; + } - if (!minOnce) - { - selectionProcessWatcher->deleteLater(); - auto *blw = qobject_cast(widget); - if (blw != nullptr) - emit blw->signalClose(); - else - widget->deleteLater(); - - LtsWidgets::LtsMessageDialog::showMessage(m_mainScreen->screenDialog(), tr("There are no free screens available to select from.")); - return false; - } - - return true; + return true; } - -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.h old mode 100755 new mode 100644 index e5bb7afb4..ee85e035e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor.h @@ -4,82 +4,92 @@ #include #include - #include - namespace LtsMultiMonitor { class LtsScreenBase; class MultiMonitorSelectorBase; class LtsScreenContainer; - class LTSMULTIMONITOR_EXPORT LtsMultiMonitor : public QObject { - Q_OBJECT + Q_OBJECT -public: - static LtsMultiMonitor *getInstance(); + public: + static LtsMultiMonitor* getInstance(); - + bool selectScreen(QWidget* widget, LtsScreenContainer* swap = nullptr, bool putOnMainIfFree = true, + bool ltsScreenNormalOnly = false, const QVector& irreplacableWidgets = {}); + bool selectAndSwap(QWidget* widget); - bool selectScreen(QWidget *widget, LtsScreenContainer *swap = nullptr, bool putOnMainIfFree = true, bool ltsScreenNormalOnly = false, const QVector &irreplacableWidgets = {}); - bool selectAndSwap(QWidget *widget); + void setEnableMultiMonitorMode() + { + m_active = true; + } + void setDebugMultiMonitorMode() + { + m_debugMargins = true; + } - void setEnableMultiMonitorMode() { m_active = true; } - void setDebugMultiMonitorMode() { m_debugMargins = true; } - bool isActive() const { return m_active; } + bool isActive() const + { + return m_active; + } - LtsScreenBase *widgetsScreen(QWidget *widget); + LtsScreenBase* widgetsScreen(QWidget* widget); - + void freezeMagicCorner(int screenId); + void unfreezeMagicCorner(int screenId); + bool putScreen(QWidget* widget, int screenId, int screenPart); + bool putScreenAutomatically(QWidget* widget); + static void place(QWidget* widget); - void freezeMagicCorner(int screenId); - void unfreezeMagicCorner(int screenId); + void setSkipScreen(int screenId, int subScreenId = -1) + { + m_skipScreenId = screenId; + m_subSkipScreenId = subScreenId; + } - bool putScreen(QWidget *widget, int screenId, int screenPart); - bool putScreenAutomatically(QWidget *widget); - static void place(QWidget *widget); - void setSkipScreen(int screenId, int subScreenId = -1) { m_skipScreenId = screenId; m_subSkipScreenId = subScreenId; } - LtsScreenBase *mainScreen() const { return m_mainScreen; } - int screenCount() const; + LtsScreenBase* mainScreen() const + { + return m_mainScreen; + } -private slots: - void screenDied(); + int screenCount() const; -private: - LtsMultiMonitor(); - ~LtsMultiMonitor(); - static void cleanupLtsMultiMonitor(); - void init(); - bool cancelAndProcessIfInactive(QWidget *widget) const; - static bool isWidgetSecondary(QWidget *widget) ; + private slots: + void screenDied(); - + private: + LtsMultiMonitor(); + ~LtsMultiMonitor(); + static void cleanupLtsMultiMonitor(); + void init(); + bool cancelAndProcessIfInactive(QWidget* widget) const; + static bool isWidgetSecondary(QWidget* widget); - bool overlapBaseLayouts(QWidget *widget); - bool isOverlapBaseLayouts() const; + bool overlapBaseLayouts(QWidget* widget); + bool isOverlapBaseLayouts() const; - QVector m_screens; - int m_nextScreenId { 0 }; - LtsScreenBase *m_mainScreen; - bool m_active; - bool m_initialized; - int m_skipScreenId; - int m_subSkipScreenId; - - bool m_overlapBaseLayouts; - bool m_debugMargins; + QVector m_screens; + int m_nextScreenId{0}; + LtsScreenBase* m_mainScreen; + bool m_active; + bool m_initialized; + int m_skipScreenId; + int m_subSkipScreenId; -signals: - void signalQuitLoop(); - void signalSelected(); - void signalScreenCountChanged(int); - void signalMakeAllSwole(); + bool m_overlapBaseLayouts; + bool m_debugMargins; + signals: + void signalQuitLoop(); + void signalSelected(); + void signalScreenCountChanged(int); + void signalMakeAllSwole(); }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_export.h old mode 100755 new mode 100644 index 973af8a09..0cfa34c00 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_export.h @@ -5,13 +5,13 @@ #include #ifndef LTSMULTIMONITOR_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSMULTIMONITOR_EXPORT -# else -# if defined(MAKE_LTSMULTIMONITOR_LIB) -# define LTSMULTIMONITOR_EXPORT Q_DECL_EXPORT -# else -# define LTSMULTIMONITOR_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSMULTIMONITOR_EXPORT +#else +#if defined(MAKE_LTSMULTIMONITOR_LIB) +#define LTSMULTIMONITOR_EXPORT Q_DECL_EXPORT +#else +#define LTSMULTIMONITOR_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.cpp old mode 100755 new mode 100644 index 8cb65fbe1..df1e8aff2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.cpp @@ -1,24 +1,22 @@ #include "lts_multi_monitor_selector_base.h" + #include "lts_multi_monitor.h" #include "lts_screen_base.h" #include "lts_screen_container.h" -#include #include - -#include +#include #include -#include -#include -#include +#include +#include +#include #include #include -#include - -#include - +#include +#include +#include namespace LtsMultiMonitor { @@ -26,393 +24,320 @@ int MultiMonitorSelectorBase::s_margin = 10; int MultiMonitorSelectorBase::s_offset = 6; int MultiMonitorSelectorBase::s_buttonSize = 20; - -MultiMonitorSelectorBase::MultiMonitorSelectorBase(LtsScreenBase *screen, const QVector &irreplacableWidgets, QWidget *) - : QDialog(nullptr) - , m_irreplacableWidgets(irreplacableWidgets) - , m_screen(screen) - , m_screenIsIrreplaceable(screen->isIrreplaceable()) +MultiMonitorSelectorBase::MultiMonitorSelectorBase(LtsScreenBase* screen, const QVector& irreplacableWidgets, + QWidget*) + : QDialog(nullptr), m_irreplacableWidgets(irreplacableWidgets), m_screen(screen), + m_screenIsIrreplaceable(screen->isIrreplaceable()) { - setGeometry(screen->screenRect()); - setMouseTracking(true); - setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint ); - setAttribute(Qt::WA_TranslucentBackground); - setAttribute(Qt::WA_DeleteOnClose); + setGeometry(screen->screenRect()); + setMouseTracking(true); + setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); + setAttribute(Qt::WA_TranslucentBackground); + setAttribute(Qt::WA_DeleteOnClose); } - -bool MultiMonitorSelectorBase::isNullSwap(LtsScreenContainer *container) +bool MultiMonitorSelectorBase::isNullSwap(LtsScreenContainer* container) { - if (container == m_swap) - { - - return true; - } + if (container == m_swap) + { - - return false; + return true; + } + + return false; } - -void MultiMonitorSelectorBase::closeEvent(QCloseEvent *event) +void MultiMonitorSelectorBase::closeEvent(QCloseEvent* event) { - - qWarning() << "closeEvent"; + qWarning() << "closeEvent"; - if (!m_selected && !m_reverted) - { - qWarning() << "closeEvent: not selected and not reverted! reverting!"; - m_screen->revertSwitch(); - } - + if (!m_selected && !m_reverted) + { + qWarning() << "closeEvent: not selected and not reverted! reverting!"; + m_screen->revertSwitch(); + } - - - event->accept(); + event->accept(); } - -bool MultiMonitorSelectorBase::killOrSwapOldBLW(LtsScreenContainer *container ) noexcept(false) +bool MultiMonitorSelectorBase::killOrSwapOldBLW(LtsScreenContainer* container) noexcept(false) { - - - - + if (isNullSwap(container)) + return true; - - - if (isNullSwap(container)) - return true; - + if (m_swap != nullptr) + { + QWidget* oldSwapWidget; + try + { + oldSwapWidget = m_swap->stealWidget(); + } + catch (...) + { - - if (m_swap != nullptr) - { - QWidget *oldSwapWidget; + throw; + } + + if (!container->isEmpty()) + { + + QWidget* oldContainerWidget; + try + { + + oldContainerWidget = container->stealWidget(); + } + catch (...) + { + + throw; + } + + m_swap->setWidget(oldContainerWidget); + } + + container->setWidget(oldSwapWidget); + + if (m_swap->activeWidgetType() == LtsScreenBase::WidgetType::SecondaryWidget && !m_swap->hasSecondaryWidget() && + m_swap->hasMainWidget()) + m_swap->toggle(); + else if (m_swap->activeWidgetType() == LtsScreenBase::WidgetType::MainWidget && !m_swap->hasMainWidget() && + m_swap->hasSecondaryWidget()) + m_swap->toggle(); + + return true; + } + + QWidget* oldWidget; try { - - oldSwapWidget = m_swap->stealWidget(); - + oldWidget = container->widget(); } catch (...) { - - throw; + + return false; } - + auto* oldBLW = qobject_cast(oldWidget); - - - if (!container->isEmpty()) + if (oldBLW == nullptr) { - - QWidget *oldContainerWidget; - try - { - - oldContainerWidget = container->stealWidget(); + container->stealWidget()->deleteLater(); - - } - catch (...) - { - - throw; - } - - - m_swap->setWidget(oldContainerWidget); + return false; } + if (!oldBLW->slotClose()) + { - - container->setWidget(oldSwapWidget); + throw "MultiMonitorSelectorBase::killOrSwapOldBLW: failed to close old blw"; + } - - if(m_swap->activeWidgetType() == LtsScreenBase::WidgetType::SecondaryWidget && !m_swap->hasSecondaryWidget() && m_swap->hasMainWidget()) - m_swap->toggle(); - else if(m_swap->activeWidgetType() == LtsScreenBase::WidgetType::MainWidget && !m_swap->hasMainWidget() && m_swap->hasSecondaryWidget()) - m_swap->toggle(); - - - return true; - } - - - - QWidget *oldWidget; - try - { - - oldWidget = container->widget(); - - } - catch (...) - { - - return false; - } - - - - auto *oldBLW = qobject_cast(oldWidget); - - if (oldBLW == nullptr) - { - container->stealWidget()->deleteLater(); - + container->stealWidget(); return false; - } - - - - if (!oldBLW->slotClose()) - { - - throw "MultiMonitorSelectorBase::killOrSwapOldBLW: failed to close old blw"; - } - - container->stealWidget(); - return false; - } - -void MultiMonitorSelectorBase::setWidget(QWidget *widget) +void MultiMonitorSelectorBase::setWidget(QWidget* widget) { - m_widget = widget; + m_widget = widget; } - -void MultiMonitorSelectorBase::mouseMoveEvent(QMouseEvent *event) +void MultiMonitorSelectorBase::mouseMoveEvent(QMouseEvent* event) { - m_cursorPos = event->pos(); - update(); + m_cursorPos = event->pos(); + update(); } - -void MultiMonitorSelectorBase::mousePressEvent(QMouseEvent *event) +void MultiMonitorSelectorBase::mousePressEvent(QMouseEvent* event) { - const QRect abortButtonRect(QRect(centeredRect().topRight() + QPoint(s_buttonSize, s_buttonSize), QSize(s_buttonSize, s_buttonSize))); - auto pos = event->pos(); + const QRect abortButtonRect( + QRect(centeredRect().topRight() + QPoint(s_buttonSize, s_buttonSize), QSize(s_buttonSize, s_buttonSize))); + auto pos = event->pos(); - Q_ASSERT(m_widget != nullptr); + Q_ASSERT(m_widget != nullptr); + if (abortButtonRect.contains(pos) || m_widget == nullptr) + { + qWarning() << "X pressed!"; + m_reverted = true; + m_screen->revertSwitch(); + reject(); + return; + } - if (abortButtonRect.contains(pos) || m_widget == nullptr) - { - qWarning() << "X pressed!"; - m_reverted = true; - m_screen->revertSwitch(); - reject(); - return; - } - - if (processSelection(pos)) - { - qWarning() << "process!"; - m_screen->finalizeSwitch(); - selected(); - return; - } + if (processSelection(pos)) + { + qWarning() << "process!"; + m_screen->finalizeSwitch(); + selected(); + return; + } } - void MultiMonitorSelectorBase::selected() { - m_widget = nullptr; - m_selected = true; - emit signalSelected(); + m_widget = nullptr; + m_selected = true; + emit signalSelected(); } - QRect MultiMonitorSelectorBase::centeredRect() const { - - if (m_cachedCenteredRect.isValid()) + + if (m_cachedCenteredRect.isValid()) + return m_cachedCenteredRect; + + const QSize thisSize(size()); + const QSize newSize(thisSize.width() * 0.20, thisSize.height() * 0.20); + m_cachedCenteredRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, newSize, rect()); + return m_cachedCenteredRect; - - - const QSize thisSize(size()); - const QSize newSize(thisSize.width() * 0.20, thisSize.height() * 0.20); - m_cachedCenteredRect = QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, newSize, rect()); - - return m_cachedCenteredRect; } - -void MultiMonitorSelectorBase::setColors(QPainter &p, const QRect checkSelection, bool occupied, bool countEdge) +void MultiMonitorSelectorBase::setColors(QPainter& p, const QRect checkSelection, bool occupied, bool countEdge) { - if (occupied) - { - p.setBrush(QColor("silver")); - p.setPen(QPen(QColor("white"), 2)); - return; - } - - - if (checkSelection.contains(m_cursorPos, countEdge)) - { - - p.setBrush(QColor("grey")); - p.setPen(QPen(QColor("white"), 2)); - return; - } - - - - p.setBrush(QColor("black")); - p.setPen(QPen(p.brush(), 1)); -} - - -void MultiMonitorSelectorBase::drawBase(QPainter &p, bool drawSelector, bool occupied, bool isSecondary, bool isInactiveWidgetOccupied) -{ - bool showReplacementIndicator = true; -#ifndef GUEZ_MODE - isSecondary = false; - showReplacementIndicator = false; -#endif - - - p.save(); - p.setRenderHint(QPainter::Antialiasing, true); - - - - p.setBrush(QColor(53, 53, 53, 150)); - p.drawRect(geometry()); - - - - const QRect centered(centeredRect()); - p.setBrush(QColor("silver")); - p.setPen(QPen(QColor("black"), 0.5)); - - - - if (isSecondary && isInactiveWidgetOccupied) - { - const QRect r(centered.adjusted(12, 12, 12, 12)); - setColors(p, r, true); - p.drawRoundedRect(r, 7, 7); - } - - - - if (drawSelector) - { - if (!m_screenIsIrreplaceable) + if (occupied) { - - setColors(p, centered, occupied); + p.setBrush(QColor("silver")); + p.setPen(QPen(QColor("white"), 2)); + return; } - p.drawRoundedRect(centered, 7, 7); - } + if (checkSelection.contains(m_cursorPos, countEdge)) + { + p.setBrush(QColor("grey")); + p.setPen(QPen(QColor("white"), 2)); + return; + } - const int cX = centered.x(); - const int cW = centered.width(); - const int cY = centered.y(); - const int cH = centered.height(); + p.setBrush(QColor("black")); + p.setPen(QPen(p.brush(), 1)); +} +void MultiMonitorSelectorBase::drawBase(QPainter& p, bool drawSelector, bool occupied, bool isSecondary, + bool isInactiveWidgetOccupied) +{ + bool showReplacementIndicator = true; +#ifndef GUEZ_MODE + isSecondary = false; + showReplacementIndicator = false; +#endif + + p.save(); + p.setRenderHint(QPainter::Antialiasing, true); + + p.setBrush(QColor(53, 53, 53, 150)); + p.drawRect(geometry()); + + const QRect centered(centeredRect()); + p.setBrush(QColor("silver")); + p.setPen(QPen(QColor("black"), 0.5)); + + if (isSecondary && isInactiveWidgetOccupied) + { + const QRect r(centered.adjusted(12, 12, 12, 12)); + setColors(p, r, true); + p.drawRoundedRect(r, 7, 7); + } + + if (drawSelector) + { + if (!m_screenIsIrreplaceable) + { + + setColors(p, centered, occupied); + } + + p.drawRoundedRect(centered, 7, 7); + } + + const int cX = centered.x(); + const int cW = centered.width(); + const int cY = centered.y(); + const int cH = centered.height(); + + if (isSecondary) + { + QPen pen(p.pen()); + QColor pc(pen.color()); + const QColor c(255 - pc.red(), 255 - pc.green(), 255 - pc.blue()); + pen.setColor(c); + p.setPen(pen); + + QFont f(p.font()); + f.setBold(true); + f.setPixelSize(cH / 2); + p.setFont(f); + + const QString text(tr("S", "Secondary (German: 'H' for 'Hilfsansicht')")); + + p.drawText(centered, Qt::AlignCenter, text); + } + + const QRect abortButtonRect( + QRect(centered.topRight() + QPoint(s_buttonSize, s_buttonSize), QSize(s_buttonSize, s_buttonSize))); + const QPoint topRight(abortButtonRect.topLeft()); + setColors(p, abortButtonRect, false, false); - - if (isSecondary) - { QPen pen(p.pen()); - QColor pc(pen.color()); - const QColor c(255 - pc.red(), 255 - pc.green(), 255 - pc.blue()); - pen.setColor(c); + pen.setWidth(5.0); p.setPen(pen); - QFont f(p.font()); - f.setBold(true); - f.setPixelSize(cH / 2); - p.setFont(f); + p.drawLines(QVector() << QLine(topRight, topRight + QPoint(s_buttonSize, s_buttonSize)) + << QLine(topRight + QPoint(0, s_buttonSize), topRight + QPoint(s_buttonSize, 0))); - const QString text(tr("S", "Secondary (German: 'H' for 'Hilfsansicht')")); + if (showReplacementIndicator && occupied) + { + p.setBrush(QColor("silver")); + p.setPen(QPen(QColor("white"), 2)); - p.drawText(centered, Qt::AlignCenter, text); - } + const QRect secondRect(centered.adjusted(cW + 70, 0, cW + 70, 0)); + p.drawRoundedRect(secondRect, 7, 7); + p.drawLine(cX + cW + 15, cY + (cH / 2), cX + cW + 55, cY + (cH / 2)); - - const QRect abortButtonRect(QRect(centered.topRight() + QPoint(s_buttonSize, s_buttonSize), QSize(s_buttonSize, s_buttonSize))); - const QPoint topRight(abortButtonRect.topLeft() ); - setColors(p, abortButtonRect, false, false); - - QPen pen(p.pen()); - pen.setWidth(5.0); - p.setPen(pen); - - p.drawLines(QVector() - << QLine(topRight , topRight + QPoint(s_buttonSize, s_buttonSize)) - << QLine(topRight + QPoint(0, s_buttonSize), topRight + QPoint(s_buttonSize, 0)) - ); - - - - if (showReplacementIndicator && occupied) - { - p.setBrush(QColor("silver")); - p.setPen(QPen(QColor("white"), 2)); - - const QRect secondRect(centered.adjusted(cW + 70, 0, cW + 70, 0)); - p.drawRoundedRect(secondRect, 7, 7); - - - p.drawLine(cX + cW + 15, cY + (cH / 2), - cX + cW + 55, cY + (cH / 2)); - - - p.drawPolygon(QPolygon( - { - QPoint(cX + cW + 56, cY + (cH / 2)), + p.drawPolygon(QPolygon({ + QPoint(cX + cW + 56, cY + (cH / 2)), QPoint(cX + cW + 46, cY + (cH / 2) - 10), QPoint(cX + cW + 46, cY + (cH / 2) + 10), })); - const int srX = secondRect.x(); - const int srY = secondRect.y(); - const int srH = secondRect.height(); - const int diameter = srH - 50; - const int widthByTwo = (secondRect.width() / 2); - const int diameterByTwo = (diameter / 2); - const int lineX1 = srX + widthByTwo - diameterByTwo; - const int lineY1 = srY + 25; - - p.drawEllipse(lineX1, lineY1, diameter, diameter); + const int srX = secondRect.x(); + const int srY = secondRect.y(); + const int srH = secondRect.height(); + const int diameter = srH - 50; + const int widthByTwo = (secondRect.width() / 2); + const int diameterByTwo = (diameter / 2); + const int lineX1 = srX + widthByTwo - diameterByTwo; + const int lineY1 = srY + 25; - - if (isSecondary) - { - QFont f(p.font()); - f.setBold(true); - f.setPixelSize(srH / 2); - p.setFont(f); + p.drawEllipse(lineX1, lineY1, diameter, diameter); - const QString text(tr("S", "Secondary (German: 'H' for 'Hilfsansicht')")); + if (isSecondary) + { + QFont f(p.font()); + f.setBold(true); + f.setPixelSize(srH / 2); + p.setFont(f); - p.drawText(secondRect, Qt::AlignCenter, text); + const QString text(tr("S", "Secondary (German: 'H' for 'Hilfsansicht')")); + + p.drawText(secondRect, Qt::AlignCenter, text); + } + + const int lineX2 = lineX1 + diameter; + const int lineY2 = lineY1 + diameter; + p.drawLine(lineX1, lineY1, lineX2, lineY2); + p.drawLine(lineX2, lineY1, lineX1, lineY2); } - - const int lineX2 = lineX1 + diameter; - const int lineY2 = lineY1 + diameter; - p.drawLine(lineX1, lineY1, lineX2, lineY2); - p.drawLine(lineX2, lineY1, lineX1, lineY2); - } - - - p.restore(); + p.restore(); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.h old mode 100755 new mode 100644 index 30419c873..f3fdbb362 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_base.h @@ -1,9 +1,7 @@ #pragma once -#include - #include #include - +#include class QScreen; class QPainter; @@ -11,7 +9,6 @@ class QPaintEvent; class QMouseEvent; class QCloseEvent; - namespace LtsMultiMonitor { class LtsScreenBase; @@ -19,47 +16,57 @@ class LtsScreenContainer; class MultiMonitorSelectorBase : public QDialog { - Q_OBJECT + Q_OBJECT -public: - explicit MultiMonitorSelectorBase(LtsScreenBase *screen, const QVector &irreplacableWidgets, QWidget *); - virtual ~MultiMonitorSelectorBase() {} + public: + explicit MultiMonitorSelectorBase(LtsScreenBase* screen, const QVector& irreplacableWidgets, QWidget*); - void setSwap(LtsScreenContainer *swap) { m_swap = swap; } - void setWidget(QWidget *widget); - LtsScreenBase *screen() const { return m_screen; } + virtual ~MultiMonitorSelectorBase() {} -signals: - void signalSelected(); + void setSwap(LtsScreenContainer* swap) + { + m_swap = swap; + } -protected: - static int s_offset; - static int s_margin; - static int s_buttonSize; + void setWidget(QWidget* widget); - LtsScreenContainer *m_swap { nullptr }; - QWidget *m_widget { nullptr }; - mutable QRect m_cachedCenteredRect; - QVector m_irreplacableWidgets; + LtsScreenBase* screen() const + { + return m_screen; + } - void drawBase(QPainter &p, bool drawSelector = true, bool occupied = false, bool isSecondary = false, bool isInactiveWidgetOccupied = false); - bool killOrSwapOldBLW(LtsScreenContainer *container) noexcept(false); - bool isNullSwap(LtsScreenContainer *container); - QRect centeredRect() const; - void setColors(QPainter &p, const QRect checkSelection, bool occupied = false, bool countEdge = false); - void selected(); - virtual bool processSelection(const QPoint &selection) = 0; + signals: + void signalSelected(); -private: - QPoint m_cursorPos; - bool m_selected { false }; - LtsScreenBase *m_screen; - bool m_screenIsIrreplaceable; - bool m_reverted { false }; + protected: + static int s_offset; + static int s_margin; + static int s_buttonSize; - void closeEvent(QCloseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; + LtsScreenContainer* m_swap{nullptr}; + QWidget* m_widget{nullptr}; + mutable QRect m_cachedCenteredRect; + QVector m_irreplacableWidgets; + + void drawBase(QPainter& p, bool drawSelector = true, bool occupied = false, bool isSecondary = false, + bool isInactiveWidgetOccupied = false); + bool killOrSwapOldBLW(LtsScreenContainer* container) noexcept(false); + bool isNullSwap(LtsScreenContainer* container); + QRect centeredRect() const; + void setColors(QPainter& p, const QRect checkSelection, bool occupied = false, bool countEdge = false); + void selected(); + virtual bool processSelection(const QPoint& selection) = 0; + + private: + QPoint m_cursorPos; + bool m_selected{false}; + LtsScreenBase* m_screen; + bool m_screenIsIrreplaceable; + bool m_reverted{false}; + + void closeEvent(QCloseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.cpp old mode 100755 new mode 100644 index dc5908d4b..4b383a5a7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.cpp @@ -1,100 +1,81 @@ -#include "lts_multi_monitor.h" #include "lts_multi_monitor_selector_normal.h" + +#include "lts_dummy_widget.h" +#include "lts_multi_monitor.h" #include "lts_screen_container.h" #include "lts_screen_normal.h" -#include "lts_dummy_widget.h" #include - +#include +#include #include -#include -#include -#include #include #include -#include - -#include - +#include +#include +#include namespace LtsMultiMonitor { -MultiMonitorSelectorNormal::MultiMonitorSelectorNormal(LtsScreenNormal *screen, bool isSecondary, const QVector &irreplacableWidgets) - : MultiMonitorSelectorBase(screen, irreplacableWidgets, nullptr) - , m_screen(screen) - , m_screenIsEmpty(screen->isEmpty()) - , m_isSecondary(isSecondary) - , m_isInactiveWidgetOccupied(screen->child()->isInactiveWidgetOccupied()) +MultiMonitorSelectorNormal::MultiMonitorSelectorNormal(LtsScreenNormal* screen, bool isSecondary, + const QVector& irreplacableWidgets) + : MultiMonitorSelectorBase(screen, irreplacableWidgets, nullptr), m_screen(screen), + m_screenIsEmpty(screen->isEmpty()), m_isSecondary(isSecondary), + m_isInactiveWidgetOccupied(screen->child()->isInactiveWidgetOccupied()) { - } +MultiMonitorSelectorNormal::~MultiMonitorSelectorNormal() {} -MultiMonitorSelectorNormal::~MultiMonitorSelectorNormal() +bool MultiMonitorSelectorNormal::processSelection(const QPoint& selection) { - -} - -bool MultiMonitorSelectorNormal::processSelection(const QPoint &selection) -{ - - - - if (!centeredRect().contains(selection)) - { - - return false; - } - - if (m_screen->isIrreplaceable()) - { - - - return false; - } - - try - { - if (m_irreplacableWidgets.contains(m_screen->child()->widget())) - return false; - } - catch(...){} - - - - - - try - { - if (killOrSwapOldBLW(m_screen->child())) + if (!centeredRect().contains(selection)) { - - return true; + + return false; } - } - catch (...) - { - return false; - } - + if (m_screen->isIrreplaceable()) + { - - m_screen->putWidgetUnmanaged(m_widget); - + return false; + } - return true; + try + { + if (m_irreplacableWidgets.contains(m_screen->child()->widget())) + return false; + } + catch (...) + { + } + + try + { + if (killOrSwapOldBLW(m_screen->child())) + { + + return true; + } + } + catch (...) + { + return false; + } + + m_screen->putWidgetUnmanaged(m_widget); + + return true; } - -void MultiMonitorSelectorNormal::paintEvent(QPaintEvent *) +void MultiMonitorSelectorNormal::paintEvent(QPaintEvent*) { - QPainter p(this); - drawBase(p, true, !m_screenIsEmpty, m_isSecondary, m_isInactiveWidgetOccupied); + QPainter p(this); + drawBase(p, true, !m_screenIsEmpty, m_isSecondary, m_isInactiveWidgetOccupied); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.h old mode 100755 new mode 100644 index 802dfbe91..d1bafeccd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_normal.h @@ -1,17 +1,14 @@ #pragma once -#include - #include "lts_multi_monitor_selector_base.h" #include #include - +#include class QScreen; class QPaintEvent; class QMouseEvent; - namespace LtsMultiMonitor { class LtsScreenBase; @@ -19,20 +16,21 @@ class LtsScreenNormal; class MultiMonitorSelectorNormal : public MultiMonitorSelectorBase { - Q_OBJECT + Q_OBJECT -public: - explicit MultiMonitorSelectorNormal(LtsScreenNormal *screen, bool isSecondary, const QVector &irreplacableWidgets = {}); - ~MultiMonitorSelectorNormal(); + public: + explicit MultiMonitorSelectorNormal(LtsScreenNormal* screen, bool isSecondary, + const QVector& irreplacableWidgets = {}); + ~MultiMonitorSelectorNormal(); -private: - LtsScreenNormal *m_screen; - bool m_screenIsEmpty; - bool m_isSecondary; - bool m_isInactiveWidgetOccupied; + private: + LtsScreenNormal* m_screen; + bool m_screenIsEmpty; + bool m_isSecondary; + bool m_isInactiveWidgetOccupied; - bool processSelection(const QPoint &selection) override; - void paintEvent(QPaintEvent *event) override; + bool processSelection(const QPoint& selection) override; + void paintEvent(QPaintEvent* event) override; }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.cpp old mode 100755 new mode 100644 index 54e7f100b..72ded42c4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.cpp @@ -1,323 +1,280 @@ +#include "lts_multi_monitor_selector_wide.h" + #include "lts_multi_monitor.h" -#include "lts_multi_monitor_selector_wide.h" #include "lts_screen_container.h" #include "lts_screen_wide.h" +#include #include -#include -#include -#include - #include #include -#include - - - +#include +#include +#include namespace LtsMultiMonitor { -MultiMonitorSelectorWide::MultiMonitorSelectorWide(LtsScreenWide *screen, QWidget *, const QVector &irreplacableWidgets) - : MultiMonitorSelectorBase(screen, irreplacableWidgets, nullptr ) - , m_screen(screen) -{} - +MultiMonitorSelectorWide::MultiMonitorSelectorWide(LtsScreenWide* screen, QWidget*, + const QVector& irreplacableWidgets) + : MultiMonitorSelectorBase(screen, irreplacableWidgets, nullptr), m_screen(screen) +{ +} bool MultiMonitorSelectorWide::isDrawOnlyOneSelector() { - + bool res = + ((m_screen->childMain()->isEmpty() && m_screen->childLeft()->isEmpty() && m_screen->childRight()->isEmpty()) || + (!m_screen->childMain()->isEmpty() && m_swap != nullptr && m_screen->childMain() == m_swap)); - bool res = ((m_screen->childMain()->isEmpty() && m_screen->childLeft()->isEmpty() && m_screen->childRight()->isEmpty()) - || (!m_screen->childMain()->isEmpty() && m_swap != nullptr && m_screen->childMain() == m_swap)); - - - - - return res; + return res; } - -bool MultiMonitorSelectorWide::processSelection(const QPoint &selection) +bool MultiMonitorSelectorWide::processSelection(const QPoint& selection) { - - + LtsScreenContainer* main = m_screen->childMain(); + LtsScreenContainer* left = m_screen->childLeft(); + LtsScreenContainer* right = m_screen->childRight(); + bool singleSelector = isDrawOnlyOneSelector(); - LtsScreenContainer *main = m_screen->childMain(); - LtsScreenContainer *left = m_screen->childLeft(); - LtsScreenContainer *right = m_screen->childRight(); - - bool singleSelector = isDrawOnlyOneSelector(); - - if (singleSelector) - { - if (main->isIrreplaceable()) + if (singleSelector) { - - return false; - } - - try - { - if (m_irreplacableWidgets.contains(main->widget())) - return false; - } - catch(...){} - - - - if (isNullSwap(m_screen->childMain())) - { - - return true; - } - - if (centeredRect().contains(selection)) - { - try - { - if (killOrSwapOldBLW(m_screen->childMain())) + if (main->isIrreplaceable()) { - - return true; + + return false; } - } - catch (...) - { - - return false; - } - - m_screen->putWidgetUnmanagedMain(m_widget); - - return true; + try + { + if (m_irreplacableWidgets.contains(main->widget())) + return false; + } + catch (...) + { + } + + if (isNullSwap(m_screen->childMain())) + { + + return true; + } + + if (centeredRect().contains(selection)) + { + try + { + if (killOrSwapOldBLW(m_screen->childMain())) + { + + return true; + } + } + catch (...) + { + + return false; + } + + m_screen->putWidgetUnmanagedMain(m_widget); + + return true; + } + + return false; + } + + bool leftContains = leftSide().contains(selection); + bool rightContains = rightSide().contains(selection); + + if (leftContains) + { + if (left->isIrreplaceable()) + { + + return false; + } + + try + { + if (m_irreplacableWidgets.contains(left->widget())) + return false; + } + catch (...) + { + } + + try + { + + QWidget* oldWidget = main->stealWidget(); + + m_screen->putWidgetUnmanagedRight(oldWidget); + } + catch (...) + { + } + + try + { + if (killOrSwapOldBLW(left)) + { + + return true; + } + } + catch (...) + { + + return false; + } + + m_screen->putWidgetUnmanagedLeft(m_widget); + return true; + } + else if (rightContains) + { + if (right->isIrreplaceable()) + { + + return false; + } + + try + { + if (m_irreplacableWidgets.contains(right->widget())) + return false; + } + catch (...) + { + } + + try + { + + QWidget* oldWidget = main->stealWidget(); + + m_screen->putWidgetUnmanagedLeft(oldWidget); + } + catch (...) + { + } + + try + { + if (killOrSwapOldBLW(right)) + { + + return true; + } + } + catch (...) + { + + return false; + } + + m_screen->putWidgetUnmanagedRight(m_widget); + return true; } - return false; - } - - - bool leftContains = leftSide().contains(selection); - bool rightContains = rightSide().contains(selection); - - - - - - if (leftContains) - { - if (left->isIrreplaceable()) - { - - return false; - } - - try - { - if (m_irreplacableWidgets.contains(left->widget())) - return false; - } - catch(...){} - - - - try - { - - QWidget *oldWidget = main->stealWidget(); - - - m_screen->putWidgetUnmanagedRight(oldWidget); - } - catch (...) {} - - - - - try - { - if (killOrSwapOldBLW(left)) - { - - return true; - } - } - catch (...) - { - - return false; - } - - - - m_screen->putWidgetUnmanagedLeft(m_widget); - return true; - } - else if (rightContains) - { - if (right->isIrreplaceable()) - { - - return false; - } - - try - { - if (m_irreplacableWidgets.contains(right->widget())) - return false; - } - catch(...){} - - - - try - { - - QWidget *oldWidget = main->stealWidget(); - - - m_screen->putWidgetUnmanagedLeft(oldWidget); - } - catch (...) {} - - - - - - try - { - if (killOrSwapOldBLW(right)) - { - - return true; - } - } - catch (...) - { - - return false; - } - - - m_screen->putWidgetUnmanagedRight(m_widget); - return true; - } - - return false; } - QRect MultiMonitorSelectorWide::leftSide() const { - QRect centered = centeredRect(); + QRect centered = centeredRect(); - return QRect(centered.x() + s_margin, - centered.y() + s_margin, - (centered.width() / 2) - (s_margin*2), - centered.height() - (s_margin*2)); + return QRect(centered.x() + s_margin, centered.y() + s_margin, (centered.width() / 2) - (s_margin * 2), + centered.height() - (s_margin * 2)); } - QRect MultiMonitorSelectorWide::rightSide() const { - QRect centered = centeredRect(); + QRect centered = centeredRect(); - return QRect(centered.x() + (centered.width() / 2) + s_margin, - centered.y() + s_margin, - (centered.width() / 2) - (s_margin*2), - centered.height() - (s_margin*2)); + return QRect(centered.x() + (centered.width() / 2) + s_margin, centered.y() + s_margin, + (centered.width() / 2) - (s_margin * 2), centered.height() - (s_margin * 2)); } - -void MultiMonitorSelectorWide::paintEvent(QPaintEvent *) +void MultiMonitorSelectorWide::paintEvent(QPaintEvent*) { - QPainter p(this); - p.save(); + QPainter p(this); + p.save(); - p.setRenderHint(QPainter::Antialiasing, true); + p.setRenderHint(QPainter::Antialiasing, true); - const QRect centered(centeredRect()); + const QRect centered(centeredRect()); - bool drawOnlyOneSelector = isDrawOnlyOneSelector(); - drawBase(p, drawOnlyOneSelector, false ); + bool drawOnlyOneSelector = isDrawOnlyOneSelector(); + drawBase(p, drawOnlyOneSelector, false); - - - if (!drawOnlyOneSelector) - { - p.setBrush(QColor("silver")); - p.setPen(QPen(QColor("black"), 0.5)); - p.drawRoundedRect(centered, 7, 7); - - - bool leftIrreplacable = false; - try + if (!drawOnlyOneSelector) { - leftIrreplacable = m_irreplacableWidgets.contains(m_screen->childLeft()->widget()); - } - catch(...){} + p.setBrush(QColor("silver")); + p.setPen(QPen(QColor("black"), 0.5)); + p.drawRoundedRect(centered, 7, 7); - if (!m_screen->childLeft()->isIrreplaceable() && !leftIrreplacable) - { - - const QRect leftSide(centered.x() + s_margin, - centered.y() + s_margin, - (centered.width() / 2) - (s_margin*2), - centered.height() - (s_margin*2)); + bool leftIrreplacable = false; + try + { + leftIrreplacable = m_irreplacableWidgets.contains(m_screen->childLeft()->widget()); + } + catch (...) + { + } - setColors(p, leftSide, !m_screen->childLeft()->isEmpty()); + if (!m_screen->childLeft()->isIrreplaceable() && !leftIrreplacable) + { - p.drawRoundedRect(leftSide, 6, 6); + const QRect leftSide(centered.x() + s_margin, centered.y() + s_margin, + (centered.width() / 2) - (s_margin * 2), centered.height() - (s_margin * 2)); + + setColors(p, leftSide, !m_screen->childLeft()->isEmpty()); + + p.drawRoundedRect(leftSide, 6, 6); + } + + bool rightIrreplacable = false; + try + { + rightIrreplacable = m_irreplacableWidgets.contains(m_screen->childRight()->widget()); + } + catch (...) + { + } + + if (!m_screen->childRight()->isIrreplaceable() && !rightIrreplacable) + { + + const QRect rightSide(centered.x() + (centered.width() / 2) + s_margin, centered.y() + s_margin, + (centered.width() / 2) - (s_margin * 2), centered.height() - (s_margin * 2)); + + setColors(p, rightSide, !m_screen->childRight()->isEmpty()); + + p.drawRoundedRect(rightSide, 6, 6); + } } + static int buttonSize = 20; + const QRect abortButtonRect( + QRect(centered.topRight() + QPoint(buttonSize, buttonSize), QSize(buttonSize, buttonSize))); + const QPoint topRight(abortButtonRect.topLeft()); + setColors(p, abortButtonRect, false, false); - bool rightIrreplacable = false; - try - { - rightIrreplacable = m_irreplacableWidgets.contains(m_screen->childRight()->widget()); - } - catch(...){} + QPen pen(p.pen()); + pen.setWidth(5.0); + p.setPen(pen); - if (!m_screen->childRight()->isIrreplaceable() && !rightIrreplacable) - { - - const QRect rightSide(centered.x() + (centered.width() / 2) + s_margin, - centered.y() + s_margin, - (centered.width() / 2) - (s_margin*2), - centered.height() - (s_margin*2)); + p.drawLines(QVector() << QLine(topRight, topRight + QPoint(buttonSize, buttonSize)) + << QLine(topRight + QPoint(0, buttonSize), topRight + QPoint(buttonSize, 0))); - setColors(p, rightSide, !m_screen->childRight()->isEmpty()); - - p.drawRoundedRect(rightSide, 6, 6); - } - } - - - - static int buttonSize = 20; - const QRect abortButtonRect(QRect(centered.topRight() + QPoint(buttonSize, buttonSize), QSize(buttonSize, buttonSize))); - const QPoint topRight(abortButtonRect.topLeft() ); - setColors(p, abortButtonRect, false, false); - - - QPen pen(p.pen()); - pen.setWidth(5.0); - p.setPen(pen); - - p.drawLines(QVector() - << QLine(topRight , topRight + QPoint(buttonSize, buttonSize)) - << QLine(topRight + QPoint(0, buttonSize), topRight + QPoint(buttonSize, 0)) - ); - - - p.restore(); + p.restore(); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.h old mode 100755 new mode 100644 index b7342da45..b7b16c95f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_multi_monitor_selector_wide.h @@ -1,17 +1,14 @@ #pragma once -#include - #include "LtsMultiMonitor/lts_multi_monitor_selector_base.h" #include #include - +#include class QScreen; class QPaintEvent; class QMouseEvent; - namespace LtsMultiMonitor { class LtsScreenWide; @@ -19,19 +16,20 @@ class LtsScreenBase; class MultiMonitorSelectorWide : public MultiMonitorSelectorBase { - Q_OBJECT + Q_OBJECT -public: - explicit MultiMonitorSelectorWide(LtsScreenWide *screen, QWidget *superParent, const QVector &irreplacableWidgets); + public: + explicit MultiMonitorSelectorWide(LtsScreenWide* screen, QWidget* superParent, + const QVector& irreplacableWidgets); -private: - LtsScreenWide *m_screen; + private: + LtsScreenWide* m_screen; - bool isDrawOnlyOneSelector(); - QRect leftSide() const; - QRect rightSide() const; - bool processSelection(const QPoint &selection) override; - void paintEvent(QPaintEvent *event) override; + bool isDrawOnlyOneSelector(); + QRect leftSide() const; + QRect rightSide() const; + bool processSelection(const QPoint& selection) override; + void paintEvent(QPaintEvent* event) override; }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.cpp old mode 100755 new mode 100644 index 1772c1899..a25a33205 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.cpp @@ -1,70 +1,52 @@ #include "lts_screen_base.h" + #include "lts_dummy_widget.h" -#include #include - -#include -#include -#include +#include #include +#include +#include +#include #ifdef Q_OS_WIN #include #endif - class NoCloseWidget : public QWidget { - void closeEvent(QCloseEvent *event) override - { - event->ignore(); - } + void closeEvent(QCloseEvent* event) override + { + event->ignore(); + } }; - namespace LtsMultiMonitor { -LtsScreenBase::LtsScreenBase(QRect screenGeo, int screenId, bool debugMargins, const QString &serial) - : m_screenDialog(new NoCloseWidget()) - , m_screenId(screenId) - , m_serial(serial) - , m_screenRect(screenGeo) +LtsScreenBase::LtsScreenBase(QRect screenGeo, int screenId, bool debugMargins, const QString& serial) + : m_screenDialog(new NoCloseWidget()), m_screenId(screenId), m_serial(serial), m_screenRect(screenGeo) { - connect(this, &LtsScreenBase::destroyed, - m_screenDialog, &QWidget::deleteLater); + connect(this, &LtsScreenBase::destroyed, m_screenDialog, &QWidget::deleteLater); - if (debugMargins) - { - qWarning() << "LtsScreenBase: screen rect adjusted for dev machines!"; - m_screenRect.adjust(+50, +50, -100, -100); - } + if (debugMargins) + { + qWarning() << "LtsScreenBase: screen rect adjusted for dev machines!"; + m_screenRect.adjust(+50, +50, -100, -100); + } - - m_screenDialog->setWindowFlags(Qt::FramelessWindowHint); - m_screenDialog->setGeometry(m_screenRect); - m_screenDialog->setMinimumSize(m_screenRect.width(), m_screenRect.height()); - m_screenDialog->setMaximumSize(m_screenRect.width(), m_screenRect.height()); - m_screenDialog->setContentsMargins(0, 0, 0, 0); - m_screenDialog->setWindowFlag(Qt::WindowType::WindowStaysOnBottomHint); + m_screenDialog->setWindowFlags(Qt::FramelessWindowHint); + m_screenDialog->setGeometry(m_screenRect); + m_screenDialog->setMinimumSize(m_screenRect.width(), m_screenRect.height()); + m_screenDialog->setMaximumSize(m_screenRect.width(), m_screenRect.height()); + m_screenDialog->setContentsMargins(0, 0, 0, 0); + m_screenDialog->setWindowFlag(Qt::WindowType::WindowStaysOnBottomHint); #ifdef Q_OS_WIN - m_screenDialog->winId(); - QWindowsWindowFunctions::setHasBorderInFullScreen(m_screenDialog->windowHandle(), true); + m_screenDialog->winId(); + QWindowsWindowFunctions::setHasBorderInFullScreen(m_screenDialog->windowHandle(), true); #endif - - - - - - - - - - - m_screenDialog->activateWindow(); - m_screenDialog->show(); + m_screenDialog->activateWindow(); + m_screenDialog->show(); } - -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.h old mode 100755 new mode 100644 index b09a86b22..250c72a69 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_base.h @@ -1,60 +1,79 @@ #pragma once -#include - #include "ltsmultimonitor_export.h" -#include +#include #include +#include class QSplitter; class QHBoxLayout; -namespace LtsUtils { class Promise; } +namespace LtsUtils +{ +class Promise; +} namespace LtsMultiMonitor { class LtsScreenContainer; - - class LTSMULTIMONITOR_EXPORT LtsScreenBase : public QObject { - Q_OBJECT + Q_OBJECT -public: - enum WidgetType - { - MainWidget, - SecondaryWidget, - None, - }; + public: + enum WidgetType { + MainWidget, + SecondaryWidget, + None, + }; - LtsScreenBase(QRect screenGeo, int screenId, bool debugMargins, const QString &serial); + LtsScreenBase(QRect screenGeo, int screenId, bool debugMargins, const QString& serial); - const QRect &screenRect() const { return m_screenRect; } - int screenId() const { return m_screenId; } - const QString serialNumber() const { return m_serial; } - QWidget *screenDialog() const { return m_screenDialog; } + const QRect& screenRect() const + { + return m_screenRect; + } - virtual int screenType() const = 0; - virtual int containerIdOfWidget(QWidget *widget) const noexcept(false) = 0; - virtual LtsScreenContainer *putWidget(QWidget *widget, int screenPart = -1 ) noexcept(false) = 0; - virtual LtsScreenContainer *containerOfWidget(QWidget *widget) noexcept(false) = 0; - virtual bool isEmpty() const = 0; - virtual bool isIrreplaceable() const = 0; - virtual void check() {} - virtual bool hasWidget(QWidget *widget) const = 0; - virtual void switchToTemp(WidgetType ) {} - virtual void finalizeSwitch() {} - virtual void revertSwitch() {} + int screenId() const + { + return m_screenId; + } -protected: - QWidget *m_screenDialog; + const QString serialNumber() const + { + return m_serial; + } -private: - int m_screenId; - QString m_serial; - QRect m_screenRect; + QWidget* screenDialog() const + { + return m_screenDialog; + } + + virtual int screenType() const = 0; + virtual int containerIdOfWidget(QWidget* widget) const noexcept(false) = 0; + virtual LtsScreenContainer* putWidget(QWidget* widget, int screenPart = -1) noexcept(false) = 0; + virtual LtsScreenContainer* containerOfWidget(QWidget* widget) noexcept(false) = 0; + virtual bool isEmpty() const = 0; + virtual bool isIrreplaceable() const = 0; + + virtual void check() {} + + virtual bool hasWidget(QWidget* widget) const = 0; + + virtual void switchToTemp(WidgetType) {} + + virtual void finalizeSwitch() {} + + virtual void revertSwitch() {} + + protected: + QWidget* m_screenDialog; + + private: + int m_screenId; + QString m_serial; + QRect m_screenRect; }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.cpp old mode 100755 new mode 100644 index 219d6b63f..f4d86d284 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.cpp @@ -1,555 +1,416 @@ #include "lts_screen_container.h" + #include "lts_dummy_widget.h" #include - -#include -#include -#include -#include - - - #include - - +#include +#include +#include +#include namespace LtsMultiMonitor { QString LtsScreenContainer::geoStr() const { - return QStringLiteral("%1:%2:") - .arg(QString::number(m_screenGeo.x()).rightJustified(4, QLatin1Char(' '))) - .arg(QString::number(m_screenGeo.y()).rightJustified(4, QLatin1Char(' '))) - ; + return QStringLiteral("%1:%2:") + .arg(QString::number(m_screenGeo.x()).rightJustified(4, QLatin1Char(' '))) + .arg(QString::number(m_screenGeo.y()).rightJustified(4, QLatin1Char(' '))); } -LtsScreenContainer::LtsScreenContainer(QRect screenGeo) - : m_layout(new QHBoxLayout) - , m_screenGeo(screenGeo) +LtsScreenContainer::LtsScreenContainer(QRect screenGeo) : m_layout(new QHBoxLayout), m_screenGeo(screenGeo) { - - m_layout->setContentsMargins(0, 0, 0, 0); - m_layout->setSpacing(0); - m_layout->setStretch(0, 999); - setContentsMargins(0, 0, 0, 0); - vanish(); - setLayout(m_layout); + m_layout->setContentsMargins(0, 0, 0, 0); + m_layout->setSpacing(0); + m_layout->setStretch(0, 999); + setContentsMargins(0, 0, 0, 0); + vanish(); + setLayout(m_layout); - - QTimer *t = new QTimer(this); - t->setInterval(3000); + QTimer* t = new QTimer(this); + t->setInterval(3000); #ifdef LTS_DEBUG - t->start(); + t->start(); #endif - connect(t, &QTimer::timeout, - this, [this, screenGeo]() - { - QString old(QStringLiteral("<#!UNKNOWN!#>")); + connect(t, &QTimer::timeout, this, [this, screenGeo]() { + QString old(QStringLiteral("<#!UNKNOWN!#>")); - if (m_oldActiveWidget == nullptr) - old = QStringLiteral("null"); - else if (m_oldActiveWidget == &m_mainWidget) - old = QStringLiteral("MAIN"); - else if (m_oldActiveWidget == &m_secondaryWidget) - old = QStringLiteral("SECONDARY"); - - - }); + if (m_oldActiveWidget == nullptr) + old = QStringLiteral("null"); + else if (m_oldActiveWidget == &m_mainWidget) + old = QStringLiteral("MAIN"); + else if (m_oldActiveWidget == &m_secondaryWidget) + old = QStringLiteral("SECONDARY"); + }); } - bool LtsScreenContainer::isInactiveWidgetOccupied() const { - if (m_activeWidget == &m_mainWidget && m_secondaryWidget != nullptr) - return true; - if (m_activeWidget == &m_secondaryWidget && m_mainWidget != nullptr) - return true; - return false; + if (m_activeWidget == &m_mainWidget && m_secondaryWidget != nullptr) + return true; + if (m_activeWidget == &m_secondaryWidget && m_mainWidget != nullptr) + return true; + return false; } - QIcon LtsScreenContainer::mainWindowIcon() const { - if (m_mainWidget != nullptr) - return m_mainWidget->windowIcon(); - return {}; + if (m_mainWidget != nullptr) + return m_mainWidget->windowIcon(); + return {}; } - QIcon LtsScreenContainer::secondaryWindowIcon() const { - if (m_secondaryWidget != nullptr) - return m_secondaryWidget->windowIcon(); - return {}; + if (m_secondaryWidget != nullptr) + return m_secondaryWidget->windowIcon(); + return {}; } - bool LtsScreenContainer::mainAndSecondaryOccupied() const { - return (m_mainWidget != nullptr && m_secondaryWidget != nullptr); + return (m_mainWidget != nullptr && m_secondaryWidget != nullptr); } - LtsScreenBase::WidgetType LtsScreenContainer::activeWidgetType() const { - if (m_activeWidget == &m_mainWidget) - return LtsScreenBase::WidgetType::MainWidget; - if (m_activeWidget == &m_secondaryWidget) - return LtsScreenBase::WidgetType::SecondaryWidget; + if (m_activeWidget == &m_mainWidget) + return LtsScreenBase::WidgetType::MainWidget; + if (m_activeWidget == &m_secondaryWidget) + return LtsScreenBase::WidgetType::SecondaryWidget; - assert(false); - return LtsScreenBase::WidgetType::None; + assert(false); + return LtsScreenBase::WidgetType::None; } - void LtsScreenContainer::toggle() { - - switchToTemp((*m_activeWidget == m_mainWidget) ? LtsScreenBase::WidgetType::SecondaryWidget : LtsScreenBase::WidgetType::MainWidget); - QWidget *w = activeWidget(); + switchToTemp((*m_activeWidget == m_mainWidget) ? LtsScreenBase::WidgetType::SecondaryWidget + : LtsScreenBase::WidgetType::MainWidget); - assert(w != nullptr); - if (w == nullptr) - { - revertSwitch(); - return; - } + QWidget* w = activeWidget(); - if (!tryPutDummyUnmanaged(w)) - w->show(); + assert(w != nullptr); + if (w == nullptr) + { + revertSwitch(); + return; + } - finalizeSwitch(); + if (!tryPutDummyUnmanaged(w)) + w->show(); + + finalizeSwitch(); } - bool LtsScreenContainer::isIrreplaceable() const { - if (m_activeWidget == nullptr) - return false; + if (m_activeWidget == nullptr) + return false; - auto *blw = qobject_cast(activeWidget()); - if (blw == nullptr) - return false; + auto* blw = qobject_cast(activeWidget()); + if (blw == nullptr) + return false; - return blw->isIrreplaceable(); + return blw->isIrreplaceable(); } - -QWidget *LtsScreenContainer::activeWidget() const +QWidget* LtsScreenContainer::activeWidget() const { - assert(m_activeWidget != nullptr); + assert(m_activeWidget != nullptr); - - - - - - return *m_activeWidget; + return *m_activeWidget; } - -QWidget **LtsScreenContainer::activeWidgetPtr() +QWidget** LtsScreenContainer::activeWidgetPtr() { - assert(m_activeWidget != nullptr); + assert(m_activeWidget != nullptr); - - - - - - return m_activeWidget; + return m_activeWidget; } - void LtsScreenContainer::vanish() { - return; + return; - - - - - - - - - - m_layout->setParent(nullptr); + m_layout->setParent(nullptr); } - void LtsScreenContainer::reappear() { - return; + return; + setAttribute(Qt::WA_TranslucentBackground, false); - - - setAttribute(Qt::WA_TranslucentBackground, false); - - - - - - if (m_layout->parent() == nullptr) - setLayout(m_layout); + if (m_layout->parent() == nullptr) + setLayout(m_layout); } - - - - - - - - - - - - -QWidget *LtsScreenContainer::stealWidget() noexcept(false) +QWidget* LtsScreenContainer::stealWidget() noexcept(false) { - - QWidget **widgetPtr = activeWidgetPtr(); - QWidget *widget = *widgetPtr; + QWidget** widgetPtr = activeWidgetPtr(); + QWidget* widget = *widgetPtr; - if (widget == nullptr) - { - - throw "stealWidget: no widget to steal"; - } + if (widget == nullptr) + { - + throw "stealWidget: no widget to steal"; + } - - widget->setParent(nullptr); - vanish(); + widget->setParent(nullptr); + vanish(); - - disconnect(widget, &QWidget::destroyed, - this, &LtsScreenContainer::slotChildDestroyed); + disconnect(widget, &QWidget::destroyed, this, &LtsScreenContainer::slotChildDestroyed); + QWidget* oldWidget = widget; + *widgetPtr = nullptr; - - - - - - - QWidget *oldWidget = widget; - *widgetPtr = nullptr; - - return oldWidget; + return oldWidget; } - -bool LtsScreenContainer::hasWidget(QWidget *widget) const +bool LtsScreenContainer::hasWidget(QWidget* widget) const { - if (m_mainWidget != nullptr && m_mainWidget == widget) - return true; - if (m_secondaryWidget != nullptr && m_secondaryWidget == widget) - return true; - return false; + if (m_mainWidget != nullptr && m_mainWidget == widget) + return true; + if (m_secondaryWidget != nullptr && m_secondaryWidget == widget) + return true; + return false; } - bool LtsScreenContainer::isEmpty() const { - QWidget **currentWidgetPtr = m_activeWidget; - if (currentWidgetPtr == nullptr) - return true; - return (*currentWidgetPtr == nullptr); + QWidget** currentWidgetPtr = m_activeWidget; + if (currentWidgetPtr == nullptr) + return true; + return (*currentWidgetPtr == nullptr); } bool LtsScreenContainer::hasMainWidget() { - return m_mainWidget != nullptr; + return m_mainWidget != nullptr; } bool LtsScreenContainer::hasSecondaryWidget() { - return m_secondaryWidget != nullptr; + return m_secondaryWidget != nullptr; } -bool LtsScreenContainer::tryPutDummyUnmanaged(QWidget *widget) +bool LtsScreenContainer::tryPutDummyUnmanaged(QWidget* widget) { - auto *dummy = qobject_cast(widget); + auto* dummy = qobject_cast(widget); - if (dummy == nullptr) - return false; + if (dummy == nullptr) + return false; + QRect r(mapToGlobal(rect().topLeft()), rect().size()); + emit dummy->signalWidgetPlaced(r); + emit signalSetCornerIcons(); - - - QRect r(mapToGlobal(rect().topLeft()), rect().size()); - - emit dummy->signalWidgetPlaced(r); - - - - - - - - - - emit signalSetCornerIcons(); - - return true; + return true; } - void LtsScreenContainer::switchToTemp(LtsScreenBase::WidgetType widgetType) { + Q_ASSERT(widgetType != LtsScreenBase::WidgetType::None); - Q_ASSERT(widgetType != LtsScreenBase::WidgetType::None); + if ((m_activeWidget == &m_mainWidget && widgetType == LtsScreenBase::WidgetType::MainWidget) || + (m_activeWidget == &m_secondaryWidget && widgetType == LtsScreenBase::WidgetType::SecondaryWidget)) + { - if ((m_activeWidget == &m_mainWidget && widgetType == LtsScreenBase::WidgetType::MainWidget) || - (m_activeWidget == &m_secondaryWidget && widgetType == LtsScreenBase::WidgetType::SecondaryWidget)) - { + m_nullSwitchActive = true; + return; + } - - m_nullSwitchActive = true; - return; - } - - if (widgetType == LtsScreenBase::WidgetType::MainWidget) - m_oldActiveWidget = &m_secondaryWidget; - else if (widgetType == LtsScreenBase::WidgetType::SecondaryWidget) - m_oldActiveWidget = &m_mainWidget; - else - Q_ASSERT(false); - - - - - m_activeWidget = (widgetType == LtsScreenBase::WidgetType::SecondaryWidget ? &m_secondaryWidget : &m_mainWidget); - + if (widgetType == LtsScreenBase::WidgetType::MainWidget) + m_oldActiveWidget = &m_secondaryWidget; + else if (widgetType == LtsScreenBase::WidgetType::SecondaryWidget) + m_oldActiveWidget = &m_mainWidget; + else + Q_ASSERT(false); + m_activeWidget = (widgetType == LtsScreenBase::WidgetType::SecondaryWidget ? &m_secondaryWidget : &m_mainWidget); } - void LtsScreenContainer::finalizeSwitch() { + QWidget** oldActiveWidget = m_oldActiveWidget; + m_oldActiveWidget = nullptr; - QWidget **oldActiveWidget = m_oldActiveWidget; - m_oldActiveWidget = nullptr; - + if (m_nullSwitchActive) + { - if (m_nullSwitchActive) - { - - m_nullSwitchActive = false; - return; - } + m_nullSwitchActive = false; + return; + } - if (oldActiveWidget == nullptr) - { - - return; - } + if (oldActiveWidget == nullptr) + { - if (*oldActiveWidget == nullptr) - { - - return; - } + return; + } - + if (*oldActiveWidget == nullptr) + { + return; + } + QWidget* widget = *oldActiveWidget; + auto* dummy = qobject_cast(widget); + if (dummy != nullptr) + { + dummy->hideVideo(); + } + else + { + widget->hide(); + } + QWidget* widget2 = *m_activeWidget; + auto* dummy2 = qobject_cast(widget2); + if (dummy2 != nullptr) + { + dummy2->showVideo(); + } - - - - QWidget *widget = *oldActiveWidget; - auto *dummy = qobject_cast(widget); - if (dummy != nullptr) - { - - dummy->hideVideo(); - } - else - { - - widget->hide(); - } - - QWidget *widget2 = *m_activeWidget; - auto *dummy2 = qobject_cast(widget2); - if (dummy2 != nullptr) - { - dummy2->showVideo(); - } - - emit signalSetCornerIcons(); + emit signalSetCornerIcons(); } - void LtsScreenContainer::revertSwitch() { + QWidget** oldActiveWidgetBackup = m_oldActiveWidget; + m_oldActiveWidget = nullptr; - QWidget **oldActiveWidgetBackup = m_oldActiveWidget; - m_oldActiveWidget = nullptr; - + if (m_nullSwitchActive) + { - if (m_nullSwitchActive) - { - - m_nullSwitchActive = false; - return; - } + m_nullSwitchActive = false; + return; + } - - - if (oldActiveWidgetBackup == nullptr) - return; - - m_activeWidget = oldActiveWidgetBackup; - + if (oldActiveWidgetBackup == nullptr) + return; + + m_activeWidget = oldActiveWidgetBackup; } - -void LtsScreenContainer::setWidget(QWidget *widget) +void LtsScreenContainer::setWidget(QWidget* widget) { + QWidget** widgetPtr = activeWidgetPtr(); - + qWarning() << geoStr() << "setWidget: m_activeWidget" << m_activeWidget; - QWidget **widgetPtr = activeWidgetPtr(); + QWidget* currentWidget = *widgetPtr; - qWarning() << geoStr() << "setWidget: m_activeWidget" << m_activeWidget; + Q_ASSERT(currentWidget == nullptr); - QWidget *currentWidget = *widgetPtr; + *widgetPtr = widget; + reappear(); - Q_ASSERT(currentWidget == nullptr); + connect(widget, &QWidget::destroyed, this, &LtsScreenContainer::slotChildDestroyed, Qt::UniqueConnection); + if (tryPutDummyUnmanaged(widget)) + return; + m_layout->addWidget(widget); - + widget->show(); - *widgetPtr = widget; - reappear(); - - connect(widget, &QWidget::destroyed, - this, &LtsScreenContainer::slotChildDestroyed, - Qt::UniqueConnection); - - if (tryPutDummyUnmanaged(widget)) - return; - - - - - - - m_layout->addWidget(widget); - - - - - - - - - widget->show(); - - emit signalSetCornerIcons(); + emit signalSetCornerIcons(); } - void LtsScreenContainer::slotChildDestroyed() { - if (sender() == static_cast(m_mainWidget)) - { - m_mainWidget = nullptr; - qWarning() << geoStr() << "m_mainWidget set to nullptr!"; - - if (*m_activeWidget == m_mainWidget) + if (sender() == static_cast(m_mainWidget)) { - qWarning() << "slotChildDestroyed: switching to sec"; - switchToTemp(LtsScreenBase::WidgetType::SecondaryWidget); + m_mainWidget = nullptr; + qWarning() << geoStr() << "m_mainWidget set to nullptr!"; - QWidget *widget = activeWidget(); - - if (widget != nullptr) - { - auto *dummy = qobject_cast(widget); - if (dummy != nullptr) + if (*m_activeWidget == m_mainWidget) { - QRect r(mapToGlobal(rect().topLeft()), rect().size()); - qWarning() << geoStr() << "LtsScreenContainer::slotChildDestroyed => (main) dummy->signalWidgetPlaced"; - emit dummy->signalWidgetPlaced(r); - } - else - { - widget->show(); - } - } + qWarning() << "slotChildDestroyed: switching to sec"; + switchToTemp(LtsScreenBase::WidgetType::SecondaryWidget); - finalizeSwitch(); + QWidget* widget = activeWidget(); + + if (widget != nullptr) + { + auto* dummy = qobject_cast(widget); + if (dummy != nullptr) + { + QRect r(mapToGlobal(rect().topLeft()), rect().size()); + qWarning() << geoStr() + << "LtsScreenContainer::slotChildDestroyed => (main) dummy->signalWidgetPlaced"; + emit dummy->signalWidgetPlaced(r); + } + else + { + widget->show(); + } + } + + finalizeSwitch(); + } } - } - else if (sender() == static_cast(m_secondaryWidget)) - { - m_secondaryWidget = nullptr; - qWarning() << geoStr() << "m_secondaryWidget set to nullptr!"; - - if (*m_activeWidget == m_secondaryWidget) + else if (sender() == static_cast(m_secondaryWidget)) { - qWarning() << "slotChildDestroyed: switching to main"; - switchToTemp(LtsScreenBase::WidgetType::MainWidget); + m_secondaryWidget = nullptr; + qWarning() << geoStr() << "m_secondaryWidget set to nullptr!"; - QWidget *widget = activeWidget(); - - if (widget != nullptr) - { - auto *dummy = qobject_cast(widget); - if (dummy != nullptr) + if (*m_activeWidget == m_secondaryWidget) { - QRect r(mapToGlobal(rect().topLeft()), rect().size()); - qWarning() << geoStr() << "LtsScreenContainer::slotChildDestroyed => (sec) dummy->signalWidgetPlaced"; - emit dummy->signalWidgetPlaced(r); - } - else - { - widget->show(); - } - } + qWarning() << "slotChildDestroyed: switching to main"; + switchToTemp(LtsScreenBase::WidgetType::MainWidget); - finalizeSwitch(); + QWidget* widget = activeWidget(); + + if (widget != nullptr) + { + auto* dummy = qobject_cast(widget); + if (dummy != nullptr) + { + QRect r(mapToGlobal(rect().topLeft()), rect().size()); + qWarning() << geoStr() + << "LtsScreenContainer::slotChildDestroyed => (sec) dummy->signalWidgetPlaced"; + emit dummy->signalWidgetPlaced(r); + } + else + { + widget->show(); + } + } + + finalizeSwitch(); + } + } + else + { + qWarning() << geoStr() << "slotChildDestroyed NOT received from any known widget !!"; + Q_ASSERT(false); } - } - else - { - qWarning() << geoStr() << "slotChildDestroyed NOT received from any known widget !!"; - Q_ASSERT(false); - } - vanish(); - emit check(); + vanish(); + emit check(); } - -QWidget *LtsScreenContainer::widget() noexcept(false) +QWidget* LtsScreenContainer::widget() noexcept(false) { - QWidget **widgetPtr = m_activeWidget; - if (widgetPtr != nullptr && *widgetPtr != nullptr) - return *widgetPtr; - throw "no widget in container"; + QWidget** widgetPtr = m_activeWidget; + if (widgetPtr != nullptr && *widgetPtr != nullptr) + return *widgetPtr; + throw "no widget in container"; } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.h old mode 100755 new mode 100644 index 6e008d30f..c5532c3c0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_container.h @@ -1,69 +1,65 @@ #pragma once +#include "lts_screen_base.h" +#include "ltsmultimonitor_export.h" + #include - -#include "lts_screen_base.h" - -#include "ltsmultimonitor_export.h" - -#include #include - +#include class QHBoxLayout; - namespace LtsMultiMonitor { class LTSMULTIMONITOR_EXPORT LtsScreenContainer : public QWidget { - Q_OBJECT + Q_OBJECT -public: - LtsScreenContainer(QRect screenGeo); + public: + LtsScreenContainer(QRect screenGeo); - bool isIrreplaceable() const; - bool isEmpty() const; - bool hasMainWidget(); - bool hasSecondaryWidget(); - void setWidget(QWidget *widget); - bool hasWidget(QWidget *widget) const; - QWidget *widget() noexcept(false); - QWidget *stealWidget() noexcept(false); - void switchToTemp(LtsScreenBase::WidgetType widgetType); - void finalizeSwitch(); - void revertSwitch(); - bool mainAndSecondaryOccupied() const; - QIcon mainWindowIcon() const; - QIcon secondaryWindowIcon() const; - LtsScreenBase::WidgetType activeWidgetType() const; - bool isInactiveWidgetOccupied() const; + bool isIrreplaceable() const; + bool isEmpty() const; + bool hasMainWidget(); + bool hasSecondaryWidget(); + void setWidget(QWidget* widget); + bool hasWidget(QWidget* widget) const; + QWidget* widget() noexcept(false); + QWidget* stealWidget() noexcept(false); + void switchToTemp(LtsScreenBase::WidgetType widgetType); + void finalizeSwitch(); + void revertSwitch(); + bool mainAndSecondaryOccupied() const; + QIcon mainWindowIcon() const; + QIcon secondaryWindowIcon() const; + LtsScreenBase::WidgetType activeWidgetType() const; + bool isInactiveWidgetOccupied() const; -signals: - void check(); - void signalSetCornerIcons(); + signals: + void check(); + void signalSetCornerIcons(); -private: - QHBoxLayout *m_layout { nullptr }; - QWidget *m_mainWidget { nullptr }; - QWidget *m_secondaryWidget { nullptr }; - QWidget **m_activeWidget { nullptr }; - QWidget **m_oldActiveWidget { nullptr }; - bool m_nullSwitchActive { false }; - QRect m_screenGeo; + private: + QHBoxLayout* m_layout{nullptr}; + QWidget* m_mainWidget{nullptr}; + QWidget* m_secondaryWidget{nullptr}; + QWidget** m_activeWidget{nullptr}; + QWidget** m_oldActiveWidget{nullptr}; + bool m_nullSwitchActive{false}; + QRect m_screenGeo; - QString geoStr() const; - bool tryPutDummyUnmanaged(QWidget *widget); - void vanish(); - void reappear(); - QWidget *activeWidget() const; - QWidget **activeWidgetPtr(); + QString geoStr() const; + bool tryPutDummyUnmanaged(QWidget* widget); + void vanish(); + void reappear(); + QWidget* activeWidget() const; + QWidget** activeWidgetPtr(); -public slots: - void toggle(); + public slots: + void toggle(); -private slots: - - void slotChildDestroyed(); + private slots: + + void slotChildDestroyed(); }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.cpp old mode 100755 new mode 100644 index 0b074f0bf..5d5791a66 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.cpp @@ -1,200 +1,135 @@ #include "lts_screen_normal.h" + #include "lts_dummy_widget.h" -#include "lts_screen_container.h" #include "lts_magic_corner.h" +#include "lts_screen_container.h" #include - #include -#include #include - +#include #ifdef Q_OS_WIN #include #endif - namespace LtsMultiMonitor { -LtsScreenNormal::LtsScreenNormal(QRect screenGeo, int screenId, bool debugMargins, const QString &serial) - : LtsScreenBase(screenGeo, screenId, debugMargins, serial) - , m_childContainer(new LtsScreenContainer(screenGeo)) - , m_corner(new LtsMagicCorner(screenGeo)) +LtsScreenNormal::LtsScreenNormal(QRect screenGeo, int screenId, bool debugMargins, const QString& serial) + : LtsScreenBase(screenGeo, screenId, debugMargins, serial), m_childContainer(new LtsScreenContainer(screenGeo)), + m_corner(new LtsMagicCorner(screenGeo)) { - - connect(m_childContainer, &LtsScreenContainer::check, - this, &LtsScreenNormal::check); - auto *theLayout = new QHBoxLayout; + connect(m_childContainer, &LtsScreenContainer::check, this, &LtsScreenNormal::check); - theLayout->setContentsMargins(0, 0, 0, 0); - theLayout->setSpacing(0); - theLayout->setStretch(0, 999); - theLayout->addWidget(m_childContainer); + auto* theLayout = new QHBoxLayout; - m_screenDialog->setLayout(theLayout); + theLayout->setContentsMargins(0, 0, 0, 0); + theLayout->setSpacing(0); + theLayout->setStretch(0, 999); + theLayout->addWidget(m_childContainer); - m_corner->hide(); - connect(m_corner, &LtsMagicCorner::toggle, - this, [this]() - { - m_childContainer->toggle(); - m_corner->setActiveWidgetType(m_childContainer->activeWidgetType()); - setCornerIcons(); - }); + m_screenDialog->setLayout(theLayout); - connect(m_corner, &LtsMagicCorner::signalMakeAllSwole, - this, &LtsScreenNormal::signalMakeAllSwole); - connect(this, &LtsScreenNormal::signalMakeSwole, - m_corner, &LtsMagicCorner::makeSwole); + m_corner->hide(); + connect(m_corner, &LtsMagicCorner::toggle, this, [this]() { + m_childContainer->toggle(); + m_corner->setActiveWidgetType(m_childContainer->activeWidgetType()); + setCornerIcons(); + }); - connect(m_childContainer, &LtsScreenContainer::signalSetCornerIcons, - this, &LtsScreenNormal::setCornerIcons); + connect(m_corner, &LtsMagicCorner::signalMakeAllSwole, this, &LtsScreenNormal::signalMakeAllSwole); + connect(this, &LtsScreenNormal::signalMakeSwole, m_corner, &LtsMagicCorner::makeSwole); + + connect(m_childContainer, &LtsScreenContainer::signalSetCornerIcons, this, &LtsScreenNormal::setCornerIcons); } - LtsScreenNormal::~LtsScreenNormal() { - m_corner->deleteLater(); + m_corner->deleteLater(); } - void LtsScreenNormal::setCornerIcons() { - m_corner->setActiveWidgetType(m_childContainer->activeWidgetType()); - m_corner->setIcon(m_childContainer->mainWindowIcon(), LtsScreenBase::WidgetType::MainWidget); - m_corner->setIcon(m_childContainer->secondaryWindowIcon(), LtsScreenBase::WidgetType::SecondaryWidget); - + m_corner->setActiveWidgetType(m_childContainer->activeWidgetType()); + m_corner->setIcon(m_childContainer->mainWindowIcon(), LtsScreenBase::WidgetType::MainWidget); + m_corner->setIcon(m_childContainer->secondaryWindowIcon(), LtsScreenBase::WidgetType::SecondaryWidget); } - void LtsScreenNormal::check() { - m_childContainer->mainAndSecondaryOccupied() ? m_corner->show() : m_corner->hide(); + m_childContainer->mainAndSecondaryOccupied() ? m_corner->show() : m_corner->hide(); } - -LtsScreenContainer *LtsScreenNormal::containerOfWidget(QWidget *widget) +LtsScreenContainer* LtsScreenNormal::containerOfWidget(QWidget* widget) { - if (m_childContainer->hasWidget(widget)) - return m_childContainer; - throw "widget is not present on this container"; + if (m_childContainer->hasWidget(widget)) + return m_childContainer; + throw "widget is not present on this container"; } void LtsScreenNormal::hideMagicCorner(bool hide) { - m_corner->setFreezed(hide); + m_corner->setFreezed(hide); } - bool LtsScreenNormal::isIrreplaceable() const { - return m_childContainer->isIrreplaceable(); + return m_childContainer->isIrreplaceable(); } - -int LtsScreenNormal::containerIdOfWidget(QWidget *widget) const noexcept(false) +int LtsScreenNormal::containerIdOfWidget(QWidget* widget) const noexcept(false) { - if (m_childContainer->hasWidget(widget)) - return 0; - throw "widget not on this screen"; + if (m_childContainer->hasWidget(widget)) + return 0; + throw "widget not on this screen"; } - -LtsScreenContainer *LtsScreenNormal::putWidget(QWidget *widget, int ) noexcept(false) +LtsScreenContainer* LtsScreenNormal::putWidget(QWidget* widget, int) noexcept(false) { - if (!isEmpty()) - throw "cannot put widget as container is non-empty"; - putWidgetUnmanaged(widget); - return m_childContainer; + if (!isEmpty()) + throw "cannot put widget as container is non-empty"; + putWidgetUnmanaged(widget); + return m_childContainer; } - -bool LtsScreenNormal::hasWidget(QWidget *widget) const +bool LtsScreenNormal::hasWidget(QWidget* widget) const { - return (m_childContainer->hasWidget(widget)); + return (m_childContainer->hasWidget(widget)); } - -void LtsScreenNormal::putWidgetUnmanaged(QWidget *widget) +void LtsScreenNormal::putWidgetUnmanaged(QWidget* widget) { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - m_childContainer->setWidget(widget); - - - - - setCornerIcons(); - - - - + m_childContainer->setWidget(widget); + setCornerIcons(); } - void LtsScreenNormal::slotOverlayDestroyed() { - m_screenDialog->show(); + m_screenDialog->show(); } - bool LtsScreenNormal::isEmpty() const { - return m_childContainer->isEmpty(); + return m_childContainer->isEmpty(); } - void LtsScreenNormal::switchToTemp(LtsScreenBase::WidgetType widgetType) { - m_childContainer->switchToTemp(widgetType); + m_childContainer->switchToTemp(widgetType); } - void LtsScreenNormal::finalizeSwitch() { - m_childContainer->finalizeSwitch(); + m_childContainer->finalizeSwitch(); } - void LtsScreenNormal::revertSwitch() { - m_childContainer->revertSwitch(); + m_childContainer->revertSwitch(); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.h old mode 100755 new mode 100644 index 4e2378bab..7d61788de --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_normal.h @@ -1,59 +1,63 @@ #pragma once -#include - #include "lts_screen_base.h" - #include "ltsmultimonitor_export.h" -#include +#include #include - +#include class QSplitter; class QHBoxLayout; - namespace LtsMultiMonitor { class LtsMagicCorner; - class LTSMULTIMONITOR_EXPORT LtsScreenNormal : public LtsScreenBase { - Q_OBJECT + Q_OBJECT -public: - LtsScreenNormal(QRect screenGeo, int screenId, bool debugMargins, const QString &serial); - ~LtsScreenNormal(); - int screenType() const override { return 0; } - int containerIdOfWidget(QWidget *widget) const noexcept(false) override; - LtsScreenContainer *child() const { return m_childContainer; } - LtsScreenContainer *putWidget(QWidget *widget, int) noexcept(false) override; - LtsScreenContainer *containerOfWidget(QWidget *widget) noexcept(false) override; - void hideMagicCorner(bool hide); - bool isEmpty() const override; - bool isIrreplaceable() const override; - void putWidgetUnmanaged(QWidget *widget); - bool hasWidget(QWidget *widget) const override; - void switchToTemp(WidgetType widgetType) override; - void finalizeSwitch() override; - void revertSwitch() override; - void check() override; + public: + LtsScreenNormal(QRect screenGeo, int screenId, bool debugMargins, const QString& serial); + ~LtsScreenNormal(); -private: - LtsScreenContainer *m_childContainer { nullptr }; - LtsMagicCorner *m_corner; - + int screenType() const override + { + return 0; + } - void swapLeftRight(); - bool tryPutDummyUnmanaged(QWidget *widget); + int containerIdOfWidget(QWidget* widget) const noexcept(false) override; -signals: - void signalMakeAllSwole(); - void signalMakeSwole(); + LtsScreenContainer* child() const + { + return m_childContainer; + } -private slots: - void slotOverlayDestroyed(); - void setCornerIcons(); + LtsScreenContainer* putWidget(QWidget* widget, int) noexcept(false) override; + LtsScreenContainer* containerOfWidget(QWidget* widget) noexcept(false) override; + void hideMagicCorner(bool hide); + bool isEmpty() const override; + bool isIrreplaceable() const override; + void putWidgetUnmanaged(QWidget* widget); + bool hasWidget(QWidget* widget) const override; + void switchToTemp(WidgetType widgetType) override; + void finalizeSwitch() override; + void revertSwitch() override; + void check() override; + + private: + LtsScreenContainer* m_childContainer{nullptr}; + LtsMagicCorner* m_corner; + + void swapLeftRight(); + bool tryPutDummyUnmanaged(QWidget* widget); + + signals: + void signalMakeAllSwole(); + void signalMakeSwole(); + + private slots: + void slotOverlayDestroyed(); + void setCornerIcons(); }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.cpp old mode 100755 new mode 100644 index 1a0111717..6ad1e419b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.cpp @@ -1,12 +1,12 @@ #include "lts_screen_wide.h" + #include "lts_dummy_widget.h" #include "lts_screen_container.h" #include - #include -#include #include +#include #include #ifdef Q_OS_WIN #include @@ -15,221 +15,185 @@ namespace LtsMultiMonitor { -LtsScreenWide::LtsScreenWide(const QRect &screenGeo, int screenId, bool debugMargins, const QString &serial) - : LtsScreenBase(screenGeo, screenId, debugMargins, serial) - , m_childContainerMain(new LtsScreenContainer(screenGeo)) - , m_childContainerLeft(new LtsScreenContainer(screenGeo)) - , m_childContainerRight(new LtsScreenContainer(screenGeo)) +LtsScreenWide::LtsScreenWide(const QRect& screenGeo, int screenId, bool debugMargins, const QString& serial) + : LtsScreenBase(screenGeo, screenId, debugMargins, serial), m_childContainerMain(new LtsScreenContainer(screenGeo)), + m_childContainerLeft(new LtsScreenContainer(screenGeo)), m_childContainerRight(new LtsScreenContainer(screenGeo)) { - - connect(m_childContainerMain, &LtsScreenContainer::check, - this, &LtsScreenWide::check); - connect(m_childContainerLeft, &LtsScreenContainer::check, - this, &LtsScreenWide::check); - connect(m_childContainerRight, &LtsScreenContainer::check, - this, &LtsScreenWide::check); - auto *theLayout = new QHBoxLayout; + connect(m_childContainerMain, &LtsScreenContainer::check, this, &LtsScreenWide::check); + connect(m_childContainerLeft, &LtsScreenContainer::check, this, &LtsScreenWide::check); + connect(m_childContainerRight, &LtsScreenContainer::check, this, &LtsScreenWide::check); - theLayout->setContentsMargins(0, 0, 0, 0); - theLayout->setSpacing(0); - theLayout->setStretch(0, 9999); + auto* theLayout = new QHBoxLayout; - m_splitter = new QSplitter; - m_splitter->setContentsMargins(0, 0, 0, 0); + theLayout->setContentsMargins(0, 0, 0, 0); + theLayout->setSpacing(0); + theLayout->setStretch(0, 9999); - m_splitter->addWidget(m_childContainerLeft); - m_splitter->addWidget(m_childContainerRight); + m_splitter = new QSplitter; + m_splitter->setContentsMargins(0, 0, 0, 0); - theLayout->addWidget(m_splitter); - theLayout->addWidget(m_childContainerMain); + m_splitter->addWidget(m_childContainerLeft); + m_splitter->addWidget(m_childContainerRight); - m_screenDialog->setLayout(theLayout); + theLayout->addWidget(m_splitter); + theLayout->addWidget(m_childContainerMain); - m_splitter->hide(); + m_screenDialog->setLayout(theLayout); + + m_splitter->hide(); } - -void LtsScreenWide::putWidgetUnmanagedMain(QWidget *widget) +void LtsScreenWide::putWidgetUnmanagedMain(QWidget* widget) { - - m_childContainerMain->setWidget(widget); + + m_childContainerMain->setWidget(widget); } - -void LtsScreenWide::putWidgetUnmanagedRight(QWidget *widget) +void LtsScreenWide::putWidgetUnmanagedRight(QWidget* widget) { - - m_childContainerRight->setWidget(widget); + + m_childContainerRight->setWidget(widget); } - -void LtsScreenWide::putWidgetUnmanagedLeft(QWidget *widget) +void LtsScreenWide::putWidgetUnmanagedLeft(QWidget* widget) { - - m_childContainerLeft->setWidget(widget); + + m_childContainerLeft->setWidget(widget); } - -bool LtsScreenWide::hasWidget(QWidget *widget) const +bool LtsScreenWide::hasWidget(QWidget* widget) const { - return (m_childContainerMain->hasWidget(widget) || - m_childContainerLeft->hasWidget(widget) || - m_childContainerRight->hasWidget(widget)); + return (m_childContainerMain->hasWidget(widget) || m_childContainerLeft->hasWidget(widget) || + m_childContainerRight->hasWidget(widget)); } - bool LtsScreenWide::isIrreplaceable() const { - return (childLeft()->isIrreplaceable() && childRight()->isIrreplaceable() && childMain()->isIrreplaceable()); + return (childLeft()->isIrreplaceable() && childRight()->isIrreplaceable() && childMain()->isIrreplaceable()); } - bool LtsScreenWide::isEmpty() const { - return (m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty() && m_childContainerMain->isEmpty()); + return (m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty() && m_childContainerMain->isEmpty()); } - -int LtsScreenWide::containerIdOfWidget(QWidget *widget) const noexcept(false) +int LtsScreenWide::containerIdOfWidget(QWidget* widget) const noexcept(false) { - if (m_childContainerMain->hasWidget(widget)) - return 0; - if (m_childContainerLeft->hasWidget(widget)) - return 1; - if (m_childContainerRight->hasWidget(widget)) - return 2; - throw "widget not on this screen"; + if (m_childContainerMain->hasWidget(widget)) + return 0; + if (m_childContainerLeft->hasWidget(widget)) + return 1; + if (m_childContainerRight->hasWidget(widget)) + return 2; + throw "widget not on this screen"; } - -LtsScreenContainer *LtsScreenWide::containerOfWidget(QWidget *widget) noexcept(false) +LtsScreenContainer* LtsScreenWide::containerOfWidget(QWidget* widget) noexcept(false) { - if (m_childContainerMain->hasWidget(widget)) - return m_childContainerMain; - if (m_childContainerLeft->hasWidget(widget)) - return m_childContainerLeft; - if (m_childContainerRight->hasWidget(widget)) - return m_childContainerRight; - throw "widget is not present on this container"; + if (m_childContainerMain->hasWidget(widget)) + return m_childContainerMain; + if (m_childContainerLeft->hasWidget(widget)) + return m_childContainerLeft; + if (m_childContainerRight->hasWidget(widget)) + return m_childContainerRight; + throw "widget is not present on this container"; } - -LtsScreenContainer *LtsScreenWide::putWidget(QWidget *widget, int screenPart) noexcept(false) +LtsScreenContainer* LtsScreenWide::putWidget(QWidget* widget, int screenPart) noexcept(false) { - if (screenPart == -1) - { - if (!isEmpty()) - throw "cannot put widget as at least one container is occupied and screen part was not specified"; - - putWidgetUnmanagedMain(widget); - return m_childContainerMain; - } - - switch (screenPart) - { - case 0: + if (screenPart == -1) { - if (!m_childContainerMain->isEmpty()) - throw "cannot put widget as main container is already occupied"; + if (!isEmpty()) + throw "cannot put widget as at least one container is occupied and screen part was not specified"; - putWidgetUnmanagedMain(widget); - return m_childContainerMain; + putWidgetUnmanagedMain(widget); + return m_childContainerMain; } - case 1: + switch (screenPart) { - if (!m_childContainerLeft->isEmpty()) - throw "cannot put widget as left container is already occupied"; + case 0: { + if (!m_childContainerMain->isEmpty()) + throw "cannot put widget as main container is already occupied"; - + putWidgetUnmanagedMain(widget); + return m_childContainerMain; + } - if (!m_childContainerMain->isEmpty()) - putWidgetUnmanagedRight(m_childContainerMain->stealWidget()); + case 1: { + if (!m_childContainerLeft->isEmpty()) + throw "cannot put widget as left container is already occupied"; - putWidgetUnmanagedLeft(widget); - return m_childContainerLeft; + if (!m_childContainerMain->isEmpty()) + putWidgetUnmanagedRight(m_childContainerMain->stealWidget()); + + putWidgetUnmanagedLeft(widget); + return m_childContainerLeft; + } + + case 2: { + if (!m_childContainerRight->isEmpty()) + throw "cannot put widget as right container is already occupied"; + + if (!m_childContainerMain->isEmpty()) + putWidgetUnmanagedLeft(m_childContainerMain->stealWidget()); + + putWidgetUnmanagedRight(widget); + return m_childContainerRight; + } + + default: { + throw "unknown screen part id"; + } } - - case 2: - { - if (!m_childContainerRight->isEmpty()) - throw "cannot put widget as right container is already occupied"; - - - - if (!m_childContainerMain->isEmpty()) - putWidgetUnmanagedLeft(m_childContainerMain->stealWidget()); - - putWidgetUnmanagedRight(widget); - return m_childContainerRight; - } - - default: - { - throw "unknown screen part id"; - } - } } - void LtsScreenWide::check() { - + Q_ASSERT( + (!m_childContainerMain->isEmpty() && m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty()) || + m_childContainerMain->isEmpty()); - - - Q_ASSERT( (!m_childContainerMain->isEmpty() && m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty()) || m_childContainerMain->isEmpty() ); - - - - if (m_childContainerMain->isEmpty()) - { - if (m_childContainerLeft->isEmpty() && !m_childContainerRight->isEmpty()) + if (m_childContainerMain->isEmpty()) { - try - { - QWidget *widget = m_childContainerRight->stealWidget(); - m_childContainerMain->setWidget(widget); - } - catch(...) - { - - - } + if (m_childContainerLeft->isEmpty() && !m_childContainerRight->isEmpty()) + { + try + { + QWidget* widget = m_childContainerRight->stealWidget(); + m_childContainerMain->setWidget(widget); + } + catch (...) + { + } + } + else if (!m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty()) + { + try + { + QWidget* widget = m_childContainerLeft->stealWidget(); + m_childContainerMain->setWidget(widget); + } + catch (...) + { + } + } } - else if (!m_childContainerLeft->isEmpty() && m_childContainerRight->isEmpty()) + + if (!m_childContainerMain->isEmpty()) { - try - { - QWidget *widget = m_childContainerLeft->stealWidget(); - m_childContainerMain->setWidget(widget); - } - catch(...) - { - - - } + + m_childContainerMain->show(); + m_splitter->hide(); + return; } - } - - - if (!m_childContainerMain->isEmpty()) - { - - m_childContainerMain->show(); - m_splitter->hide(); - return; - } - - - - m_childContainerMain->hide(); - m_splitter->setVisible(!m_childContainerLeft->isEmpty() || !m_childContainerRight->isEmpty()); - m_childContainerLeft->setVisible(!m_childContainerLeft->isEmpty()); - m_childContainerRight->setVisible(!m_childContainerRight->isEmpty()); + m_childContainerMain->hide(); + m_splitter->setVisible(!m_childContainerLeft->isEmpty() || !m_childContainerRight->isEmpty()); + m_childContainerLeft->setVisible(!m_childContainerLeft->isEmpty()); + m_childContainerRight->setVisible(!m_childContainerRight->isEmpty()); } -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.h old mode 100755 new mode 100644 index c17248967..ac37732d1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsMultiMonitor/lts_screen_wide.h @@ -1,52 +1,65 @@ #pragma once -#include - #include "lts_screen_base.h" - #include "ltsmultimonitor_export.h" -#include +#include #include - +#include class QSplitter; class QHBoxLayout; - namespace LtsMultiMonitor { class LTSMULTIMONITOR_EXPORT LtsScreenWide : public LtsScreenBase { - Q_OBJECT + Q_OBJECT -public: - LtsScreenWide(const QRect &screenGeo, int screenId, bool debugMargins, const QString &serial); + public: + LtsScreenWide(const QRect& screenGeo, int screenId, bool debugMargins, const QString& serial); - int screenType() const override { return 1; } - LtsScreenContainer *containerOfWidget(QWidget *widget) noexcept(false) override; - bool isEmpty() const override; - LtsScreenContainer *childLeft() const { return m_childContainerLeft; } - LtsScreenContainer *childRight() const { return m_childContainerRight; } - LtsScreenContainer *childMain() const { return m_childContainerMain; } - void putWidgetUnmanagedMain(QWidget *widget); - void putWidgetUnmanagedLeft(QWidget *widget); - void putWidgetUnmanagedRight(QWidget *widget); - bool isIrreplaceable() const override; - bool hasWidget(QWidget *widget) const override; - LtsScreenContainer *putWidget(QWidget *widget, int screenPart) noexcept(false) override; - int containerIdOfWidget(QWidget *widget) const noexcept(false) override; + int screenType() const override + { + return 1; + } -public slots: - void check() override; + LtsScreenContainer* containerOfWidget(QWidget* widget) noexcept(false) override; + bool isEmpty() const override; -private: - LtsScreenContainer *m_childContainerMain; - LtsScreenContainer *m_childContainerLeft; - LtsScreenContainer *m_childContainerRight; - QSplitter *m_splitter; + LtsScreenContainer* childLeft() const + { + return m_childContainerLeft; + } - void swapLeftRight(); + LtsScreenContainer* childRight() const + { + return m_childContainerRight; + } + + LtsScreenContainer* childMain() const + { + return m_childContainerMain; + } + + void putWidgetUnmanagedMain(QWidget* widget); + void putWidgetUnmanagedLeft(QWidget* widget); + void putWidgetUnmanagedRight(QWidget* widget); + bool isIrreplaceable() const override; + bool hasWidget(QWidget* widget) const override; + LtsScreenContainer* putWidget(QWidget* widget, int screenPart) noexcept(false) override; + int containerIdOfWidget(QWidget* widget) const noexcept(false) override; + + public slots: + void check() override; + + private: + LtsScreenContainer* m_childContainerMain; + LtsScreenContainer* m_childContainerLeft; + LtsScreenContainer* m_childContainerRight; + QSplitter* m_splitter; + + void swapLeftRight(); }; -} +} // namespace LtsMultiMonitor diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp old mode 100755 new mode 100644 index aae0c0465..995b87780 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.cpp @@ -1,92 +1,64 @@ #include "lts_notification.h" + #include "lts_notification_ctl.h" #include - namespace LtsNotification { -LtsNotification::LtsNotification(LtsNotificationController *ctl) - : QObject() - , m_controller(ctl) +LtsNotification::LtsNotification(LtsNotificationController* ctl) : QObject(), m_controller(ctl) { - connect(ctl, &LtsNotificationController::destroyed, - this, &LtsNotification::slotCtlDestroyed); + connect(ctl, &LtsNotificationController::destroyed, this, &LtsNotification::slotCtlDestroyed); } - LtsNotification::~LtsNotification() { - delete m_controller; + delete m_controller; } - void LtsNotification::setIcon(const QIcon& icon) { - m_controller->setIcon(icon); + m_controller->setIcon(icon); } - -void LtsNotification::setAction(const std::function &action) +void LtsNotification::setAction(const std::function& action) { - m_controller->setAction(action); + m_controller->setAction(action); } - -void LtsNotification::setToolTip(const QString &toolTip) +void LtsNotification::setToolTip(const QString& toolTip) { - m_controller->setToolTip(toolTip); + m_controller->setToolTip(toolTip); } - -const QString &LtsNotification::tooltip() const +const QString& LtsNotification::tooltip() const { - return m_controller->tooltip(); + return m_controller->tooltip(); } - void LtsNotification::setCount(const int count) { - m_controller->setCount(count); + m_controller->setCount(count); } void LtsNotification::setEnabled(bool enable) { - m_controller->setEnabled(enable); + m_controller->setEnabled(enable); } void LtsNotification::setBackground(const int r, const int g, const int b) { - m_controller->setBackground(r, g, b); + m_controller->setBackground(r, g, b); } - - - - - - - - - - - - - - - - - - - -void LtsNotification::slotCtlDestroyed(QObject *obj) +void LtsNotification::slotCtlDestroyed(QObject* obj) { - (void)obj; + (void)obj; - m_controller = nullptr; + m_controller = nullptr; } -} +} // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h old mode 100755 new mode 100644 index a6487e3f0..21a6ff0ea --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification.h @@ -6,52 +6,40 @@ #include #include -#include #include - +#include namespace LtsSession { class LtsSession; } - namespace LtsNotification { class LtsNotificationController; - - class LTSNOTIFICATION_EXPORT LtsNotification : public QObject { - Q_OBJECT + Q_OBJECT -public: - - explicit LtsNotification(LtsNotificationController *ctl); - ~LtsNotification(); + public: + explicit LtsNotification(LtsNotificationController* ctl); + ~LtsNotification(); - void setIcon(const QIcon &icon); - void setAction(const std::function &action); - void setToolTip(const QString &toolTip); - void setCount(const int count); - void setEnabled(bool enable); - void setBackground(const int r, const int g, const int b); + void setIcon(const QIcon& icon); + void setAction(const std::function& action); + void setToolTip(const QString& toolTip); + void setCount(const int count); + void setEnabled(bool enable); + void setBackground(const int r, const int g, const int b); - const QString &tooltip() const; + const QString& tooltip() const; - - - - -private: - LtsNotificationController *m_controller; - - - -private slots: - void slotCtlDestroyed(QObject *obj); + private: + LtsNotificationController* m_controller; + private slots: + void slotCtlDestroyed(QObject* obj); }; -} +} // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp old mode 100755 new mode 100644 index dfe462899..5c57270bc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.cpp @@ -1,173 +1,155 @@ #include "lts_notification_ctl.h" -#include -#include -#include -#include -#include #include #include - +#include +#include +#include +#include +#include namespace LtsNotification { -LtsNotificationController::LtsNotificationController(const QString &identifier) - : QObject() - , m_count(0) - , m_identifier(QStringLiteral("LtsNotification%1").arg(identifier)) -{} - +LtsNotificationController::LtsNotificationController(const QString& identifier) + : QObject(), m_count(0), m_identifier(QStringLiteral("LtsNotification%1").arg(identifier)) +{ +} LtsNotificationController::~LtsNotificationController() { - qDeleteAll(m_notiList); + qDeleteAll(m_notiList); } - void LtsNotificationController::setIcon(const QIcon& icon) { - m_icon = icon; + m_icon = icon; - setAllIcons(); + setAllIcons(); } - void LtsNotificationController::setCount(const int count) { - m_count = count; + m_count = count; - setAllIcons(); + setAllIcons(); } - - void LtsNotificationController::setBackground(const int r, const int g, const int b) { - for (QToolButton *tb : std::as_const(m_notiList)) - { + for (QToolButton* tb : std::as_const(m_notiList)) + { - QString stylesheet; + QString stylesheet; - if(r == -1 && g == -1 && b == -1) - stylesheet = QStringLiteral(""); - else - stylesheet = QStringLiteral("QToolButton {background-color: rgb(") + - QString::number(r) + QStringLiteral(",") + - QString::number(g) + QStringLiteral(",") + - QString::number(b) + QStringLiteral(");}"); + if (r == -1 && g == -1 && b == -1) + stylesheet = QStringLiteral(""); + else + stylesheet = QStringLiteral("QToolButton {background-color: rgb(") + QString::number(r) + + QStringLiteral(",") + QString::number(g) + QStringLiteral(",") + QString::number(b) + + QStringLiteral(");}"); - tb->setStyleSheet(stylesheet); - } + tb->setStyleSheet(stylesheet); + } } void LtsNotificationController::setEnabled(bool enable) { - m_enable = enable; + m_enable = enable; - setAllIcons(); + setAllIcons(); } - -void LtsNotificationController::setAction(const std::function &action) +void LtsNotificationController::setAction(const std::function& action) { - m_action = action; + m_action = action; } - -void LtsNotificationController::setToolTip(const QString &toolTip) +void LtsNotificationController::setToolTip(const QString& toolTip) { - m_toolTip = toolTip; + m_toolTip = toolTip; - for (QToolButton *tb : std::as_const(m_notiList)) - { - tb->setToolTip(toolTip); - tb->setIconSize(QSize(30,30)); - } + for (QToolButton* tb : std::as_const(m_notiList)) + { + tb->setToolTip(toolTip); + tb->setIconSize(QSize(30, 30)); + } } - void LtsNotificationController::setAllIcons() { - if (m_icon.isNull()) - return; + if (m_icon.isNull()) + return; - - QIcon icon = modifyIcon(m_icon); + QIcon icon = modifyIcon(m_icon); - for (QToolButton *tb : std::as_const(m_notiList)) - { - tb->setIcon(icon); - tb->setIconSize(QSize(30,30)); - tb->setEnabled(m_enable); - } + for (QToolButton* tb : std::as_const(m_notiList)) + { + tb->setIcon(icon); + tb->setIconSize(QSize(30, 30)); + tb->setEnabled(m_enable); + } } - #define SIZE 40 -QIcon LtsNotificationController::modifyIcon(const QIcon &icon) +QIcon LtsNotificationController::modifyIcon(const QIcon& icon) { - + if (m_count < 1) + return icon; - if (m_count < 1) - return icon; + QPixmap iconImage(icon.pixmap(SIZE * 8 / 10, SIZE * 8 / 10)); + QPainter painter(&iconImage); - QPixmap iconImage(icon.pixmap(SIZE * 8 / 10, SIZE * 8 / 10)); - QPainter painter(&iconImage); + painter.save(); + painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.save(); - painter.setRenderHints(QPainter::TextAntialiasing | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + QFont f; + f.setFamily(QStringLiteral("Monospace")); + f.setPointSize(16); + f.setBold(true); + painter.setFont(f); - QFont f; - f.setFamily(QStringLiteral("Monospace")); - f.setPointSize(16); - f.setBold(true); - painter.setFont(f); + QColor color(Qt::red); + painter.setBrush(color); + painter.setPen(QPen(color, 3.1)); + painter.drawText(QRect(0, 0, 30, 30), QString::number(m_count)); + painter.restore(); - QColor color(Qt::red); - painter.setBrush(color); - painter.setPen(QPen(color, 3.1)); - painter.drawText(QRect(0, 0, 30, 30), QString::number(m_count)); - painter.restore(); - - return iconImage; + return iconImage; } - -QToolButton *LtsNotificationController::createWidget() +QToolButton* LtsNotificationController::createWidget() { - QToolButton *b = new QToolButton(); - b->setToolButtonStyle(Qt::ToolButtonIconOnly); - b->setObjectName(m_identifier); - + QToolButton* b = new QToolButton(); + b->setToolButtonStyle(Qt::ToolButtonIconOnly); + b->setObjectName(m_identifier); - - b->setMinimumSize(SIZE, SIZE); - b->setMaximumSize(SIZE, SIZE); + b->setMinimumSize(SIZE, SIZE); + b->setMaximumSize(SIZE, SIZE); - connect(b, &QToolButton::destroyed, - this, &LtsNotificationController::slotNotiWidgetDestroyed); - connect(b, &QToolButton::clicked, - this, [this](){ if (m_action) m_action(); }); + connect(b, &QToolButton::destroyed, this, &LtsNotificationController::slotNotiWidgetDestroyed); + connect(b, &QToolButton::clicked, this, [this]() { + if (m_action) + m_action(); + }); - if (!m_icon.isNull()) - b->setIcon(modifyIcon(m_icon)); + if (!m_icon.isNull()) + b->setIcon(modifyIcon(m_icon)); - b->setToolTip(m_toolTip); + b->setToolTip(m_toolTip); - m_notiList.append(b); - return b; + m_notiList.append(b); + return b; } - -void LtsNotificationController::slotNotiWidgetDestroyed(QObject *obj) +void LtsNotificationController::slotNotiWidgetDestroyed(QObject* obj) { - m_notiList.removeAll(static_cast(obj)); + m_notiList.removeAll(static_cast(obj)); } -} +} // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h old mode 100755 new mode 100644 index 106d447d8..2aca6466f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_ctl.h @@ -4,12 +4,11 @@ #include "ltsnotification_export.h" +#include #include #include -#include -#include #include - +#include class QToolButton; @@ -18,50 +17,53 @@ namespace LtsSession class LtsSession; } - namespace LtsNotification { class LtsNotificationWidget; - - class LTSNOTIFICATION_EXPORT LtsNotificationController : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit LtsNotificationController(const QString &identifier); - ~LtsNotificationController(); + public: + explicit LtsNotificationController(const QString& identifier); + ~LtsNotificationController(); - QToolButton *createWidget(); + QToolButton* createWidget(); - void setIcon(const QIcon& icon); - void setAction(const std::function &action); - void setToolTip(const QString &toolTip); - void setCount(const int count); - void setBackground(const int r, const int g, const int b); - const QString &identifier() const { return m_identifier; } - const QString &tooltip() const { return m_toolTip; } + void setIcon(const QIcon& icon); + void setAction(const std::function& action); + void setToolTip(const QString& toolTip); + void setCount(const int count); + void setBackground(const int r, const int g, const int b); - void setEnabled(bool enable); + const QString& identifier() const + { + return m_identifier; + } -private: - QList m_notiList; - + const QString& tooltip() const + { + return m_toolTip; + } - QIcon m_icon; - std::function m_action; - QString m_toolTip; - int m_count; - bool m_enable{true}; - QString m_identifier; + void setEnabled(bool enable); - void setAllIcons(); - QIcon modifyIcon(const QIcon &icon); + private: + QList m_notiList; -private slots: - void slotNotiWidgetDestroyed(QObject *obj); + QIcon m_icon; + std::function m_action; + QString m_toolTip; + int m_count; + bool m_enable{true}; + QString m_identifier; + void setAllIcons(); + QIcon modifyIcon(const QIcon& icon); + + private slots: + void slotNotiWidgetDestroyed(QObject* obj); }; -} +} // namespace LtsNotification diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_export.h old mode 100755 new mode 100644 index 92853b0c3..c8f3b356c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsNotification/lts_notification_export.h @@ -1,19 +1,17 @@ - #pragma once #include #ifndef LTSNOTIFICATION_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSNOTIFICATION_EXPORT -# else -# if defined(MAKE_LTSNOTIFICATION_LIB) -# define LTSNOTIFICATION_EXPORT Q_DECL_EXPORT -# else -# define LTSNOTIFICATION_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSNOTIFICATION_EXPORT +#else +#if defined(MAKE_LTSNOTIFICATION_LIB) +#define LTSNOTIFICATION_EXPORT Q_DECL_EXPORT +#else +#define LTSNOTIFICATION_EXPORT Q_DECL_IMPORT +#endif +#endif #endif - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.cpp old mode 100755 new mode 100644 index def518bb4..f98191136 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.cpp @@ -1,102 +1,93 @@ - #include "lts_plugin_manager_dialog.h" + +#include "../lts_plugin_manager.h" #include "lts_plugin_manager_widget.h" #include "ui_lts_plugin_manager_dialog.h" -#include "../lts_plugin_manager.h" #include -#include #include - +#include namespace LtsPluginManager { -LtsPluginManagerDialog::LtsPluginManagerDialog(QWidget *parent) - : QDialog(parent) - , m_ui(new Ui::LtsPluginManagerDialog) +LtsPluginManagerDialog::LtsPluginManagerDialog(QWidget* parent) : QDialog(parent), m_ui(new Ui::LtsPluginManagerDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->pluginsWidget), 20); - m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->lwErrorLog), 0); + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->pluginsWidget), 20); + m_ui->masterSplitter->setStretchFactor(m_ui->masterSplitter->indexOf(m_ui->lwErrorLog), 0); } - LtsPluginManagerDialog::~LtsPluginManagerDialog() { - delete m_ui; + delete m_ui; } - -void LtsPluginManagerDialog::setServiceMissing(const QString &newPluginFilename, const QString &missingPluginName) +void LtsPluginManagerDialog::setServiceMissing(const QString& newPluginFilename, const QString& missingPluginName) { - m_ui->lwErrorLog->addItem(tr("ERROR: Plugin '%1' needs the plugin '%2', which is not available!").arg(newPluginFilename, missingPluginName)); - getPluginWidget(newPluginFilename)->setStatus(LtsPluginWidget::MISSING_SERVICE); + m_ui->lwErrorLog->addItem(tr("ERROR: Plugin '%1' needs the plugin '%2', which is not available!") + .arg(newPluginFilename, missingPluginName)); + getPluginWidget(newPluginFilename)->setStatus(LtsPluginWidget::MISSING_SERVICE); - if (!isVisible()) - show(); + if (!isVisible()) + show(); - QCoreApplication::processEvents(); + QCoreApplication::processEvents(); } - -void LtsPluginManagerDialog::setOptionalServiceMissing(const QString &newPluginFilename, const QString &missingPluginName) +void LtsPluginManagerDialog::setOptionalServiceMissing(const QString& newPluginFilename, + const QString& missingPluginName) { - m_ui->lwErrorLog->addItem(tr("INFO: Plugin %1 asked for plugin %2, which is not available!").arg(newPluginFilename, missingPluginName)); + m_ui->lwErrorLog->addItem( + tr("INFO: Plugin %1 asked for plugin %2, which is not available!").arg(newPluginFilename, missingPluginName)); - if (!isVisible()) - show(); + if (!isVisible()) + show(); - QCoreApplication::processEvents(); + QCoreApplication::processEvents(); } - -void LtsPluginManagerDialog::setInvalidPlugin(const QString &newPluginFilename) +void LtsPluginManagerDialog::setInvalidPlugin(const QString& newPluginFilename) { - m_ui->lwErrorLog->addItem(tr("INFO: Invalid plugin '%1'").arg(newPluginFilename)); + m_ui->lwErrorLog->addItem(tr("INFO: Invalid plugin '%1'").arg(newPluginFilename)); } - -LtsPluginWidget *LtsPluginManagerDialog::getPluginWidget(const QString &filename) +LtsPluginWidget* LtsPluginManagerDialog::getPluginWidget(const QString& filename) { - LtsPluginWidget *pluginWidget = findChild(filename); + LtsPluginWidget* pluginWidget = findChild(filename); - if (!pluginWidget) - { - pluginWidget = new LtsPluginWidget(filename); - pluginWidget->setObjectName(filename); - qobject_cast(m_ui->pluginsWidget->layout())->insertWidget(0, pluginWidget); - } + if (!pluginWidget) + { + pluginWidget = new LtsPluginWidget(filename); + pluginWidget->setObjectName(filename); + qobject_cast(m_ui->pluginsWidget->layout())->insertWidget(0, pluginWidget); + } - return pluginWidget; + return pluginWidget; } - -void LtsPluginManagerDialog::setPluginLogStatus(const QString &filename, const LtsPluginWidget::Status &status) +void LtsPluginManagerDialog::setPluginLogStatus(const QString& filename, const LtsPluginWidget::Status& status) { - getPluginWidget(filename)->setStatus(status); + getPluginWidget(filename)->setStatus(status); - QCoreApplication::processEvents(); + QCoreApplication::processEvents(); } - -void LtsPluginManagerDialog::setPluginLogType(const QString &filename, const QString &type) +void LtsPluginManagerDialog::setPluginLogType(const QString& filename, const QString& type) { - getPluginWidget(filename)->setType(type); + getPluginWidget(filename)->setType(type); - QCoreApplication::processEvents(); + QCoreApplication::processEvents(); } - -void LtsPluginManagerDialog::setPluginLogIdent(const QString &filename, const QString &ident) +void LtsPluginManagerDialog::setPluginLogIdent(const QString& filename, const QString& ident) { - getPluginWidget(filename)->setIdent(ident); + getPluginWidget(filename)->setIdent(ident); - QCoreApplication::processEvents(); + QCoreApplication::processEvents(); } -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.h old mode 100755 new mode 100644 index f1f03f9eb..e1b75a5fc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_dialog.h @@ -1,13 +1,11 @@ #pragma once -#include - -#include "ltspluginmanager_export.h" #include "lts_plugin_manager_widget.h" +#include "ltspluginmanager_export.h" #include - +#include namespace Ui { @@ -18,22 +16,22 @@ namespace LtsPluginManager { class LTSPLUGINMANAGER_EXPORT LtsPluginManagerDialog : public QDialog { - Q_OBJECT -public: - explicit LtsPluginManagerDialog(QWidget *parent = nullptr); - ~LtsPluginManagerDialog(); + Q_OBJECT + public: + explicit LtsPluginManagerDialog(QWidget* parent = nullptr); + ~LtsPluginManagerDialog(); - void setServiceMissing(const QString &newPluginFilename, const QString &missingPluginName); - void setOptionalServiceMissing(const QString &newPluginFilename, const QString &missingPluginName); - void setInvalidPlugin(const QString &newPluginFilename); + void setServiceMissing(const QString& newPluginFilename, const QString& missingPluginName); + void setOptionalServiceMissing(const QString& newPluginFilename, const QString& missingPluginName); + void setInvalidPlugin(const QString& newPluginFilename); - void setPluginLogStatus(const QString &filename, const LtsPluginWidget::Status &status); - void setPluginLogType(const QString &filename, const QString &type); - void setPluginLogIdent(const QString &filename, const QString &ident); + void setPluginLogStatus(const QString& filename, const LtsPluginWidget::Status& status); + void setPluginLogType(const QString& filename, const QString& type); + void setPluginLogIdent(const QString& filename, const QString& ident); -private: - Ui::LtsPluginManagerDialog *m_ui; + private: + Ui::LtsPluginManagerDialog* m_ui; - LtsPluginWidget *getPluginWidget(const QString &filename); + LtsPluginWidget* getPluginWidget(const QString& filename); }; -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.cpp old mode 100755 new mode 100644 index f575f4d89..5c4aae4dc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.cpp @@ -1,130 +1,117 @@ - #include "lts_plugin_manager_widget.h" + #include "ui_lts_plugin_manager_widget.h" using namespace LtsPluginManager; -LtsPluginWidget::LtsPluginWidget(const QString &filename, QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::LtsPluginWidget) +LtsPluginWidget::LtsPluginWidget(const QString& filename, QWidget* parent) + : QWidget(parent), m_ui(new Ui::LtsPluginWidget) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_ui->leFilename->setText(filename); - setStatus(UNKNOWN); - setType(); - setIdent(); + m_ui->leFilename->setText(filename); + setStatus(UNKNOWN); + setType(); + setIdent(); - - m_ui->lbGuiPlugins->hide(); + m_ui->lbGuiPlugins->hide(); - m_ui->lbDtc->hide(); - m_ui->lwDtcs->hide(); + m_ui->lbDtc->hide(); + m_ui->lwDtcs->hide(); - m_ui->lbFtc->hide(); - m_ui->lwFtcs->hide(); + m_ui->lbFtc->hide(); + m_ui->lwFtcs->hide(); } LtsPluginWidget::~LtsPluginWidget() { - delete m_ui; + delete m_ui; } void LtsPluginWidget::setStatus(Status status) { - QString statusText; + QString statusText; - switch (status) - { - case INVALID: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("Invalid"); - break; - } - case LOADED: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(124, 189, 124);")); - statusText = tr("Loaded"); - break; - } - case CONFLICT: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("CONFLICT!"); - break; - } - case UNLOADED: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(100, 100, 100);")); - statusText = tr("Unloaded"); - break; - } - case INIT_FAILED: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("INIT FAILED!"); - break; - } - case MISSING_SERVICE: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("MISSING SERVICE!"); - break; - } - case OBLIBATORY_INTERFACES_MISSING: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("OBLIGATORY INTERFACES MISSING!"); - break; - } - case INVALID_PLUGIN_VERSION: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); - statusText = tr("INVALID PLUGIN VERSION!"); - break; - } - default: - { - m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(100, 100, 100);")); - statusText = tr("Unknown (%1)").arg(status); - break; - } - } + switch (status) + { + case INVALID: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("Invalid"); + break; + } + case LOADED: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(124, 189, 124);")); + statusText = tr("Loaded"); + break; + } + case CONFLICT: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("CONFLICT!"); + break; + } + case UNLOADED: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(100, 100, 100);")); + statusText = tr("Unloaded"); + break; + } + case INIT_FAILED: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("INIT FAILED!"); + break; + } + case MISSING_SERVICE: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("MISSING SERVICE!"); + break; + } + case OBLIBATORY_INTERFACES_MISSING: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("OBLIGATORY INTERFACES MISSING!"); + break; + } + case INVALID_PLUGIN_VERSION: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(189, 106, 98);")); + statusText = tr("INVALID PLUGIN VERSION!"); + break; + } + default: { + m_ui->frStatus->setStyleSheet(QLatin1String("background-color: rgb(100, 100, 100);")); + statusText = tr("Unknown (%1)").arg(status); + break; + } + } - m_ui->leStatus->setText(statusText); + m_ui->leStatus->setText(statusText); } - -void LtsPluginWidget::setType(const QString &type) +void LtsPluginWidget::setType(const QString& type) { - if (type.isEmpty()) - { - m_ui->leType->hide(); - m_ui->lbType->hide(); - } - else - { - m_ui->leType->show(); - m_ui->lbType->show(); - m_ui->leType->setText(type); - } + if (type.isEmpty()) + { + m_ui->leType->hide(); + m_ui->lbType->hide(); + } + else + { + m_ui->leType->show(); + m_ui->lbType->show(); + m_ui->leType->setText(type); + } } - -void LtsPluginWidget::setIdent(const QString &ident) +void LtsPluginWidget::setIdent(const QString& ident) { - if (ident.isEmpty()) - { - m_ui->leIdent->hide(); - m_ui->lbIdent->hide(); - } - else - { - m_ui->leIdent->show(); - m_ui->lbIdent->show(); - m_ui->leIdent->setText(ident); - } + if (ident.isEmpty()) + { + m_ui->leIdent->hide(); + m_ui->lbIdent->hide(); + } + else + { + m_ui->leIdent->show(); + m_ui->lbIdent->show(); + m_ui->leIdent->setText(ident); + } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.h old mode 100755 new mode 100644 index ae4dfd17a..4ea3ad682 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/Ui/lts_plugin_manager_widget.h @@ -1,13 +1,9 @@ - #pragma once #include - - -#include #include - +#include namespace Ui { @@ -18,29 +14,28 @@ namespace LtsPluginManager { class LtsPluginWidget : public QWidget { - Q_OBJECT -public: - enum Status - { - UNKNOWN = 0, - INVALID, - LOADED, - CONFLICT, - UNLOADED, - INIT_FAILED, - MISSING_SERVICE, - OBLIBATORY_INTERFACES_MISSING, - INVALID_PLUGIN_VERSION, - }; + Q_OBJECT + public: + enum Status { + UNKNOWN = 0, + INVALID, + LOADED, + CONFLICT, + UNLOADED, + INIT_FAILED, + MISSING_SERVICE, + OBLIBATORY_INTERFACES_MISSING, + INVALID_PLUGIN_VERSION, + }; - explicit LtsPluginWidget(const QString &filename, QWidget *parent = nullptr); - ~LtsPluginWidget(); + explicit LtsPluginWidget(const QString& filename, QWidget* parent = nullptr); + ~LtsPluginWidget(); - void setStatus(Status status); - void setType(const QString &type = QString()); - void setIdent(const QString &ident = QString()); + void setStatus(Status status); + void setType(const QString& type = QString()); + void setIdent(const QString& ident = QString()); -private: - Ui::LtsPluginWidget *m_ui; + private: + Ui::LtsPluginWidget* m_ui; }; -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.cpp old mode 100755 new mode 100644 index 0eaa17304..a2c41c5e0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.cpp @@ -1,450 +1,416 @@  - #include "lts_plugin_loader.h" -#include -#include #include - +#include #include +#include #include #include #include -#include #include - -#include - +#include +#include namespace LtsPluginManager { struct LtsPluginLoaderHandler { - LtsPluginLoader ltsPluginLoader; - static NGL::INGLLogger &logger() { return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsPluginLoader"); } - static void cleanupPluginLoader(); + LtsPluginLoader ltsPluginLoader; + + static NGL::INGLLogger& logger() + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsPluginLoader"); + } + + static void cleanupPluginLoader(); }; Q_GLOBAL_STATIC(LtsPluginLoaderHandler, s_ltsPluginLoader) void LtsPluginLoaderHandler::cleanupPluginLoader() { - if (s_ltsPluginLoader.exists()) - s_ltsPluginLoader->ltsPluginLoader.unloadAllPlugins(); + if (s_ltsPluginLoader.exists()) + s_ltsPluginLoader->ltsPluginLoader.unloadAllPlugins(); } - -LtsPluginLoader *LtsPluginLoader::getInstance() +LtsPluginLoader* LtsPluginLoader::getInstance() { - if (!s_ltsPluginLoader.exists()) - qAddPostRoutine(&LtsPluginLoaderHandler::cleanupPluginLoader); - return &s_ltsPluginLoader->ltsPluginLoader; + if (!s_ltsPluginLoader.exists()) + qAddPostRoutine(&LtsPluginLoaderHandler::cleanupPluginLoader); + return &s_ltsPluginLoader->ltsPluginLoader; } - LtsPluginLoader::~LtsPluginLoader() { - unloadAllPlugins(); + unloadAllPlugins(); } void LtsPluginLoader::unloadAllPlugins() { - for (auto &pi : std::as_const(m_loadedPlugins)) - { - QPluginLoader *pluginLoader = pi.pluginLoader; + for (auto& pi : std::as_const(m_loadedPlugins)) + { + QPluginLoader* pluginLoader = pi.pluginLoader; - delete pluginLoader->instance(); + delete pluginLoader->instance(); - if (!pluginLoader->unload()) - qWarning() << "~LtsPluginLoader: could not unload" << pi.pluginName << pluginLoader->errorString(); + if (!pluginLoader->unload()) + qWarning() << "~LtsPluginLoader: could not unload" << pi.pluginName << pluginLoader->errorString(); - delete pluginLoader; - } - m_loadedPlugins.clear(); + delete pluginLoader; + } + m_loadedPlugins.clear(); } - -void LtsPluginLoader::checkPlugins(const QVector &appVector, - QStringList &errors ) +void LtsPluginLoader::checkPlugins(const QVector& appVector, QStringList& errors) { - NGL::INGLLogger &logger = LtsPluginLoaderHandler::logger(); + NGL::INGLLogger& logger = LtsPluginLoaderHandler::logger(); - if (appVector.isEmpty()) - { - errors += QStringLiteral("No Apps available"); - return; - } - - - QVector dataPlugins; - QVector guiPlugins; - auto addDataPluginFn = [&](const PluginInstance &pi) - { - dataPlugins.append(pi); - return true; - }; - auto addGuiPluginFn = [&](const PluginInstance &pi) - { - guiPlugins.append(pi); - return true; - }; - - if (!loadPlugins(PluginType::DATA, addDataPluginFn)) - { - errors += QStringLiteral("failed to load data plugins"); - return; - } - - if (!loadPlugins(PluginType::GUI, addGuiPluginFn)) - { - errors += QStringLiteral("failed to load gui plugins"); - return; - } - - - - - auto checkDuplicateIidsFn = [&](const QVector &plugins, const QString &pluginType) - { - typedef QMap IidMap; - IidMap iids; - - for (auto i3 = plugins.constBegin(); i3 != plugins.constEnd(); ++i3) + if (appVector.isEmpty()) { - const PluginInstance &pin = *i3; - auto iidFound = iids.constFind(pin.pluginName); - - if (iidFound != iids.constEnd()) - errors += QStringLiteral("Iid duplicate for %1 plugin '%2'").arg(pluginType, pin.pluginName); - else - iids.insert(pin.pluginName, pin.fullFileName); + errors += QStringLiteral("No Apps available"); + return; } - }; - checkDuplicateIidsFn(dataPlugins, QStringLiteral("data")); - checkDuplicateIidsFn(guiPlugins, QStringLiteral("gui")); + QVector dataPlugins; + QVector guiPlugins; + auto addDataPluginFn = [&](const PluginInstance& pi) { + dataPlugins.append(pi); + return true; + }; + auto addGuiPluginFn = [&](const PluginInstance& pi) { + guiPlugins.append(pi); + return true; + }; - - - QVector plugins(dataPlugins + guiPlugins); - - - - for (auto i1 = appVector.constBegin(); i1 != appVector.constEnd(); ++i1) - { - const LtsAppDescriptor::AppDescription &app = *i1; - - - - const QVector &piVector = app.pluginInfos; - - for (auto i2 = piVector.constBegin(); i2 != piVector.constEnd(); i2++) + if (!loadPlugins(PluginType::DATA, addDataPluginFn)) { - const LtsAppDescriptor::PluginInfo &pi = *i2; - bool found = false; + errors += QStringLiteral("failed to load data plugins"); + return; + } - for (auto i3 = plugins.constBegin(); i3 != plugins.constEnd(); ++i3) - { - const PluginInstance &pin = *i3; + if (!loadPlugins(PluginType::GUI, addGuiPluginFn)) + { + errors += QStringLiteral("failed to load gui plugins"); + return; + } - if (pi.iid == pin.pluginName) + auto checkDuplicateIidsFn = [&](const QVector& plugins, const QString& pluginType) { + typedef QMap IidMap; + IidMap iids; + + for (auto i3 = plugins.constBegin(); i3 != plugins.constEnd(); ++i3) { - found = true; - break; + const PluginInstance& pin = *i3; + auto iidFound = iids.constFind(pin.pluginName); + + if (iidFound != iids.constEnd()) + errors += QStringLiteral("Iid duplicate for %1 plugin '%2'").arg(pluginType, pin.pluginName); + else + iids.insert(pin.pluginName, pin.fullFileName); } - } + }; - if (!found) - { - ERROR_LOG(logger) << "Plugin with iid '" << pi.iid << "' was requested but was not loaded!"; - errors += QStringLiteral("App '%1' requires plugin '%2' that could not be found.").arg(app.appName, pi.iid); - } + checkDuplicateIidsFn(dataPlugins, QStringLiteral("data")); + checkDuplicateIidsFn(guiPlugins, QStringLiteral("gui")); + + QVector plugins(dataPlugins + guiPlugins); + + for (auto i1 = appVector.constBegin(); i1 != appVector.constEnd(); ++i1) + { + const LtsAppDescriptor::AppDescription& app = *i1; + + const QVector& piVector = app.pluginInfos; + + for (auto i2 = piVector.constBegin(); i2 != piVector.constEnd(); i2++) + { + const LtsAppDescriptor::PluginInfo& pi = *i2; + bool found = false; + + for (auto i3 = plugins.constBegin(); i3 != plugins.constEnd(); ++i3) + { + const PluginInstance& pin = *i3; + + if (pi.iid == pin.pluginName) + { + found = true; + break; + } + } + + if (!found) + { + ERROR_LOG(logger) << "Plugin with iid '" << pi.iid << "' was requested but was not loaded!"; + errors += + QStringLiteral("App '%1' requires plugin '%2' that could not be found.").arg(app.appName, pi.iid); + } + } } - } - return; + return; } - bool LtsPluginLoader::loadPlugins(PluginType requestedPluginType, - const std::function &loadPlugin, - const QStringList &requiredPlugins, - const QString &specialTopicTypeFilter, - const QStringList &optionalPlugins) + const std::function& loadPlugin, + const QStringList& requiredPlugins, const QString& specialTopicTypeFilter, + const QStringList& optionalPlugins) { - NGL::INGLLogger &logger = LtsPluginLoaderHandler::logger(); - Q_ASSERT(requestedPluginType != PluginType::UNKNOWN); + NGL::INGLLogger& logger = LtsPluginLoaderHandler::logger(); + Q_ASSERT(requestedPluginType != PluginType::UNKNOWN); - QStringList requiredPluginsList = requiredPlugins; - QStringList optionalPluginsList = optionalPlugins; - bool checkPluginsLists = (!requiredPluginsList.isEmpty()) || (!optionalPluginsList.isEmpty()); + QStringList requiredPluginsList = requiredPlugins; + QStringList optionalPluginsList = optionalPlugins; + bool checkPluginsLists = (!requiredPluginsList.isEmpty()) || (!optionalPluginsList.isEmpty()); - if (checkPluginsLists && !m_loadedPlugins.isEmpty()) - { + if (checkPluginsLists && !m_loadedPlugins.isEmpty()) { - QMutableListIterator i1(requiredPluginsList); - - while (i1.hasNext()) - { - const QString pluginName = i1.next().toLower(); - - QMap::iterator i2 = m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); - - if (i2 != m_loadedPlugins.end()) { - DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance"; + QMutableListIterator i1(requiredPluginsList); - if (loadPlugin) - loadPlugin(i2.value()); + while (i1.hasNext()) + { + const QString pluginName = i1.next().toLower(); - i1.remove(); + QMap::iterator i2 = + m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); + + if (i2 != m_loadedPlugins.end()) + { + DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance"; + + if (loadPlugin) + loadPlugin(i2.value()); + + i1.remove(); + } + } + } + + { + QMutableListIterator i1(optionalPluginsList); + + while (i1.hasNext()) + { + const QString pluginName = i1.next().toLower(); + + QMap::iterator i2 = + m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); + + if (i2 != m_loadedPlugins.end()) + { + DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance"; + + if (loadPlugin) + loadPlugin(i2.value()); + + i1.remove(); + } + } } - } } - + QFileInfo libPathInfo(QCoreApplication::applicationDirPath() + QStringLiteral("/../lib/")); + QString libPath(libPathInfo.absolutePath()); + if (!libPathInfo.exists()) { - QMutableListIterator i1(optionalPluginsList); - while (i1.hasNext()) - { - const QString pluginName = i1.next().toLower(); - - QMap::iterator i2 = m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); - - if (i2 != m_loadedPlugins.end()) - { - DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance"; - - if (loadPlugin) - loadPlugin(i2.value()); - - i1.remove(); - } - } + libPathInfo.setFile(QCoreApplication::applicationFilePath()); + libPath = libPathInfo.absolutePath(); } - } - - - QFileInfo libPathInfo(QCoreApplication::applicationDirPath() + QStringLiteral("/../lib/")); - QString libPath(libPathInfo.absolutePath()); - if (!libPathInfo.exists()) - { - - - libPathInfo.setFile(QCoreApplication::applicationFilePath()); - libPath = libPathInfo.absolutePath(); - } #ifdef Q_OS_WIN - const QStringList nameFilter = QStringList(QStringLiteral("*Plugin*.dll")); + const QStringList nameFilter = QStringList(QStringLiteral("*Plugin*.dll")); #else - const QStringList nameFilter = QStringList(QStringLiteral("*Plugin*.so")); + const QStringList nameFilter = QStringList(QStringLiteral("*Plugin*.so")); #endif - static const QStringList pluginTypes({QStringLiteral("data"), - QStringLiteral("gui"), - QStringLiteral("topic_type"), - QStringLiteral("project"), - QStringLiteral("style"), - QStringLiteral("special")}); + static const QStringList pluginTypes({QStringLiteral("data"), QStringLiteral("gui"), QStringLiteral("topic_type"), + QStringLiteral("project"), QStringLiteral("style"), + QStringLiteral("special")}); - QDirIterator pluginDir(libPath, nameFilter, QDir::Files); - while (pluginDir.hasNext()) - { - pluginDir.next(); - const QString filename = pluginDir.fileName(); - if (filename.contains(QStringLiteral("PluginInterface"), Qt::CaseSensitive)) - continue; - - const QString absoluteFilePath = pluginDir.filePath(); - - DEBUG_LOG(logger) << "File Path: " << absoluteFilePath; - - - - - - - - - QScopedPointer pluginLoader(new QPluginLoader); - pluginLoader->setFileName(absoluteFilePath); - - const QJsonObject jObj = pluginLoader->metaData(); - QJsonObject::const_iterator iid = jObj.find(QStringLiteral("IID")); - - if (iid == jObj.end()) + QDirIterator pluginDir(libPath, nameFilter, QDir::Files); + while (pluginDir.hasNext()) { - DEBUG_LOG(logger) << "Plugin '" << filename << "' has no IID !"; - continue; - } + pluginDir.next(); + const QString filename = pluginDir.fileName(); + if (filename.contains(QStringLiteral("PluginInterface"), Qt::CaseSensitive)) + continue; - const QString jsonIid = iid.value().toString().toLower(); - const QStringList iidParameters = QString(jsonIid).split(QLatin1Char(':')); + const QString absoluteFilePath = pluginDir.filePath(); - DEBUG_LOG(logger) << "Plugin " << absoluteFilePath << " provides iid '" << jsonIid; + DEBUG_LOG(logger) << "File Path: " << absoluteFilePath; - if (iidParameters.count() != 3) - { - WARNING_LOG(logger) << "Invalid iid "< pluginLoader(new QPluginLoader); + pluginLoader->setFileName(absoluteFilePath); - bool ok = false; - int pluginLoaderVersion = iidParameters.at(1).toInt(&ok); + const QJsonObject jObj = pluginLoader->metaData(); + QJsonObject::const_iterator iid = jObj.find(QStringLiteral("IID")); - if (!ok || pluginLoaderVersion != PLUGIN_LOADER_VERSION) - { - WARNING_LOG(logger) << "Invalid plugin loader version" << pluginLoaderVersion << "for plugin:" << filename; - continue; - } - - PluginType pluginType = PluginType::UNKNOWN; - - const QString pluginName = iidParameters.at(2); - const QString pluginTypeString = iidParameters.at(0); - switch (pluginTypes.indexOf(pluginTypeString)) - { - case 0: - pluginType = PluginType::DATA; - break; - case 1: - pluginType = PluginType::GUI; - break; - case 2: - pluginType = PluginType::TOPIC_TYPE; - break; - case 3: - pluginType = PluginType::PROJECT; - break; - case 4: - pluginType = PluginType::STYLE; - break; - case 5: - pluginType = PluginType::SPECIAL; - break; - default: - break; - } - - if (pluginType != requestedPluginType) - { - DEBUG_LOG(logger) << "Plugin provides not the requested type " << (int)requestedPluginType << " is: " << (int)pluginType; - continue; - } - - if (pluginType == PluginType::SPECIAL && !specialTopicTypeFilter.isEmpty()) - { - if (!pluginName.startsWith(specialTopicTypeFilter)) - { - DEBUG_LOG(logger) << "Special plugin, but filter does not match: " << pluginName << " - " << specialTopicTypeFilter; - continue; - } - } - - if (checkPluginsLists) - { - bool found = false; - - { - QMutableListIterator i (requiredPluginsList); - - while (i.hasNext()) + if (iid == jObj.end()) { - const QString requiredPlugin = i.next().toLower(); - - if (pluginName == requiredPlugin) - { - found = true; - i.remove(); - break; - } + DEBUG_LOG(logger) << "Plugin '" << filename << "' has no IID !"; + continue; } - } + const QString jsonIid = iid.value().toString().toLower(); + const QStringList iidParameters = QString(jsonIid).split(QLatin1Char(':')); - if (!found) - { - for (auto i = optionalPluginsList.constBegin(); i != optionalPluginsList.constEnd(); i++) + DEBUG_LOG(logger) << "Plugin " << absoluteFilePath << " provides iid '" << jsonIid; + + if (iidParameters.count() != 3) { - const QString optionalPlugin = (*i).toLower(); - - if (pluginName == optionalPlugin) - { - found = true; - break; - } + WARNING_LOG(logger) << "Invalid iid " << jsonIid << " for plugin " << filename; + continue; } - } + bool ok = false; + int pluginLoaderVersion = iidParameters.at(1).toInt(&ok); - if (!found) - { - DEBUG_LOG(logger) << "Plugin " << pluginName << " was not requested"; - continue; - } + if (!ok || pluginLoaderVersion != PLUGIN_LOADER_VERSION) + { + WARNING_LOG(logger) << "Invalid plugin loader version" << pluginLoaderVersion << "for plugin:" << filename; + continue; + } + + PluginType pluginType = PluginType::UNKNOWN; + + const QString pluginName = iidParameters.at(2); + const QString pluginTypeString = iidParameters.at(0); + switch (pluginTypes.indexOf(pluginTypeString)) + { + case 0: + pluginType = PluginType::DATA; + break; + case 1: + pluginType = PluginType::GUI; + break; + case 2: + pluginType = PluginType::TOPIC_TYPE; + break; + case 3: + pluginType = PluginType::PROJECT; + break; + case 4: + pluginType = PluginType::STYLE; + break; + case 5: + pluginType = PluginType::SPECIAL; + break; + default: + break; + } + + if (pluginType != requestedPluginType) + { + DEBUG_LOG(logger) << "Plugin provides not the requested type " << (int)requestedPluginType + << " is: " << (int)pluginType; + continue; + } + + if (pluginType == PluginType::SPECIAL && !specialTopicTypeFilter.isEmpty()) + { + if (!pluginName.startsWith(specialTopicTypeFilter)) + { + DEBUG_LOG(logger) << "Special plugin, but filter does not match: " << pluginName << " - " + << specialTopicTypeFilter; + continue; + } + } + + if (checkPluginsLists) + { + bool found = false; + + { + QMutableListIterator i(requiredPluginsList); + + while (i.hasNext()) + { + const QString requiredPlugin = i.next().toLower(); + + if (pluginName == requiredPlugin) + { + found = true; + i.remove(); + break; + } + } + } + + if (!found) + { + for (auto i = optionalPluginsList.constBegin(); i != optionalPluginsList.constEnd(); i++) + { + const QString optionalPlugin = (*i).toLower(); + + if (pluginName == optionalPlugin) + { + found = true; + break; + } + } + } + + if (!found) + { + DEBUG_LOG(logger) << "Plugin " << pluginName << " was not requested"; + continue; + } + } + + if (loadPlugin && !m_loadedPlugins.isEmpty()) + { + QMap::iterator i = + m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); + + if (i != m_loadedPlugins.end()) + { + DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance (" + << i.value().plugin->metaObject()->className() << ")"; + + loadPlugin(i.value()); + continue; + } + } + + QObject* plugin = pluginLoader->instance(); + + if (!plugin) + { + ERROR_LOG(logger) << "Failed to load " << filename << " - " << pluginLoader->errorString(); + continue; + } + + PluginInstance pi; + pi.pluginName = pluginName; + pi.fileName = filename; + pi.fullFileName = absoluteFilePath; + pi.plugin = plugin; + pi.pluginLoader = pluginLoader.data(); + + if (loadPlugin && !loadPlugin(pi)) + { + DEBUG_LOG(logger) << "Plugin " << pluginName << " unloaded"; + delete pluginLoader->instance(); + pluginLoader->unload(); + continue; + } + pi.pluginLoader = pluginLoader.take(); + + m_loadedPlugins.insert(PluginKey(requestedPluginType, pluginName), pi); + + DEBUG_LOG(logger) << "Loaded " << jsonIid << " - File: " << filename; } - - - - if (loadPlugin && !m_loadedPlugins.isEmpty()) + if (checkPluginsLists && !requiredPluginsList.isEmpty()) { - QMap::iterator i = m_loadedPlugins.find(PluginKey(requestedPluginType, pluginName)); - - if (i != m_loadedPlugins.end()) - { - DEBUG_LOG(logger) << "Plugin " << pluginName << " already loaded, using that instance ("<metaObject()->className()<<")"; - - loadPlugin(i.value()); - continue; - } + WARNING_LOG(logger) << "These plugins could not be found for Plugin Type " << (int)requestedPluginType << ": " + << requiredPluginsList.join(QStringLiteral(", ")); + return false; } - - QObject *plugin = pluginLoader->instance(); - - if (!plugin) - { - ERROR_LOG(logger) << "Failed to load " << filename << " - " << pluginLoader->errorString(); - continue; - } - - PluginInstance pi; - pi.pluginName = pluginName; - pi.fileName = filename; - pi.fullFileName = absoluteFilePath; - pi.plugin = plugin; - pi.pluginLoader = pluginLoader.data(); - - if (loadPlugin && !loadPlugin(pi)) - { - DEBUG_LOG(logger) << "Plugin " << pluginName << " unloaded"; - delete pluginLoader->instance(); - pluginLoader->unload(); - continue; - } - pi.pluginLoader = pluginLoader.take(); - - - m_loadedPlugins.insert(PluginKey(requestedPluginType, pluginName), pi); - - - - - DEBUG_LOG(logger) << "Loaded " << jsonIid << " - File: " << filename; - } - - - if (checkPluginsLists && !requiredPluginsList.isEmpty()) - { - WARNING_LOG(logger) << "These plugins could not be found for Plugin Type " << (int)requestedPluginType << ": " << requiredPluginsList.join(QStringLiteral(", ")); - return false; - } - - return true; + return true; } -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.h old mode 100755 new mode 100644 index 9881bcefd..acb23157a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_loader.h @@ -1,25 +1,24 @@ - #pragma once #define PLUGIN_LOADER_VERSION 3 -#include -#include #include #include +#include +#include #ifndef LTSPLUGINLOADER_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSPLUGINLOADER_EXPORT -# else -# if defined(MAKE_LTSPLUGINLOADER_LIB) -# define LTSPLUGINLOADER_EXPORT Q_DECL_EXPORT -# else -# define LTSPLUGINLOADER_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSPLUGINLOADER_EXPORT +#else +#if defined(MAKE_LTSPLUGINLOADER_LIB) +#define LTSPLUGINLOADER_EXPORT Q_DECL_EXPORT +#else +#define LTSPLUGINLOADER_EXPORT Q_DECL_IMPORT +#endif +#endif #endif class QObject; @@ -33,53 +32,49 @@ struct AppDescription; namespace LtsPluginManager { -enum class PluginType -{ - UNKNOWN = 0, - DATA, - GUI, - TOPIC_TYPE, - PROJECT, - STYLE, - SPECIAL, +enum class PluginType { + UNKNOWN = 0, + DATA, + GUI, + TOPIC_TYPE, + PROJECT, + STYLE, + SPECIAL, }; - -struct PluginInstance +struct PluginInstance { - QString pluginName; - QString fullFileName; - QString fileName; - QObject *plugin = nullptr; - QPluginLoader *pluginLoader = nullptr; + QString pluginName; + QString fullFileName; + QString fileName; + QObject* plugin = nullptr; + QPluginLoader* pluginLoader = nullptr; }; - class LTSPLUGINLOADER_EXPORT LtsPluginLoader { -public: - static LtsPluginLoader *getInstance(); + public: + static LtsPluginLoader* getInstance(); - void unloadAllPlugins(); + void unloadAllPlugins(); - void checkPlugins(const QVector &appVector, - QStringList &errors ); + void checkPlugins(const QVector& appVector, QStringList& errors); - bool loadPlugins(PluginType requestedPluginType, - const std::function &loadPlugin, - const QStringList &requiredPlugins = QStringList(), - const QString &specialTopicTypeFilter = QString(), - const QStringList &optionalPlugins = QStringList()); + bool loadPlugins(PluginType requestedPluginType, + const std::function& loadPlugin, + const QStringList& requiredPlugins = QStringList(), + const QString& specialTopicTypeFilter = QString(), + const QStringList& optionalPlugins = QStringList()); - typedef QPair PluginKey; + typedef QPair PluginKey; -private: - friend struct LtsPluginLoaderHandler; + private: + friend struct LtsPluginLoaderHandler; - LtsPluginLoader() = default; - ~LtsPluginLoader(); + LtsPluginLoader() = default; + ~LtsPluginLoader(); - QMap m_loadedPlugins; + QMap m_loadedPlugins; }; -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.cpp old mode 100755 new mode 100644 index ba364cdf9..d8dd05505 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.cpp @@ -1,22 +1,20 @@ - #include "lts_plugin_manager.h" -#include + #include "Ui/lts_plugin_manager_dialog.h" -#include -#include -#include #include -#include #include +#include +#include +#include +#include #include #include - -#include #include - +#include +#include namespace LtsPluginManager { @@ -26,262 +24,168 @@ LtsPluginManager::LtsPluginManager() .getNGLLogger("LtsPluginManager")) , m_markedForDeletion(false) { - connect(m_sessionManager, &LtsSession::LtsSessionManager::signalQuit, - this, &LtsPluginManager::signalQuit); - connect(m_sessionManager, &LtsSession::LtsSessionManager::signalLogout, - this, &LtsPluginManager::signalLogout); - connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationFinished, - this, &LtsPluginManager::signalInitializationFinished); - connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationAborted, - this, &LtsPluginManager::signalInitializationAborted); - connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationFinished, - this, &LtsPluginManager::slotInitializationFinished); - connect(m_sessionManager, &LtsSession::LtsSessionManager::taskSwitch, - this, &LtsPluginManager::taskSwitch); - connect(m_sessionManager, &LtsSession::LtsSessionManager::hideAllOtherBLWs, - this, &LtsPluginManager::hideAllOtherBLWs); + connect(m_sessionManager, &LtsSession::LtsSessionManager::signalQuit, this, &LtsPluginManager::signalQuit); + connect(m_sessionManager, &LtsSession::LtsSessionManager::signalLogout, this, &LtsPluginManager::signalLogout); + connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationFinished, this, + &LtsPluginManager::signalInitializationFinished); + connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationAborted, this, + &LtsPluginManager::signalInitializationAborted); + connect(m_sessionManager, &LtsSession::LtsSessionManager::signalInitializationFinished, this, + &LtsPluginManager::slotInitializationFinished); + connect(m_sessionManager, &LtsSession::LtsSessionManager::taskSwitch, this, &LtsPluginManager::taskSwitch); + connect(m_sessionManager, &LtsSession::LtsSessionManager::hideAllOtherBLWs, this, + &LtsPluginManager::hideAllOtherBLWs); - QTimer *t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, - this, &LtsPluginManager::signalStillAlive); - t->start(); + QTimer* t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, this, &LtsPluginManager::signalStillAlive); + t->start(); } - LtsPluginManager::~LtsPluginManager() { - - delete m_sessionManager; + delete m_sessionManager; } - void LtsPluginManager::softQuit() { - emit signalSoftQuit(); + emit signalSoftQuit(); } - void LtsPluginManager::_softQuit() { - m_sessionManager->softQuit(); + m_sessionManager->softQuit(); } - -QVector LtsPluginManager::sessions() const +QVector LtsPluginManager::sessions() const { - return m_sessionManager->sessions(); + return m_sessionManager->sessions(); } -bool LtsPluginManager::hasSituationMapInstance(const LtsAppDescriptor::AppDescription &appDescription, bool alsoTestForScriptApp) +bool LtsPluginManager::hasSituationMapInstance(const LtsAppDescriptor::AppDescription& appDescription, + bool alsoTestForScriptApp) { - if (alsoTestForScriptApp && appDescription.id == LtsAppDescriptor::App::Scripts) - return true; + if (alsoTestForScriptApp && appDescription.id == LtsAppDescriptor::App::Scripts) + return true; - for (const LtsAppDescriptor::PluginInfo &pluginInfo : std::as_const(appDescription.pluginInfos)) - { - if (pluginInfo.flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS) && - (pluginInfo.iid == QStringLiteral("sitmap"))) - return true; - } - return false; + for (const LtsAppDescriptor::PluginInfo& pluginInfo : std::as_const(appDescription.pluginInfos)) + { + if (pluginInfo.flags.testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS) && + (pluginInfo.iid == QStringLiteral("sitmap"))) + return true; + } + return false; } bool LtsPluginManager::hasSituationMapInstance() const { - return hasSituationMapInstance(m_app); + return hasSituationMapInstance(m_app); } -LtsSession::LtsSession *LtsPluginManager::getSession(IDL::PartitionType partitionType, int partitionId) +LtsSession::LtsSession* LtsPluginManager::getSession(IDL::PartitionType partitionType, int partitionId) { - return m_sessionManager->getSession(partitionType, partitionId); + return m_sessionManager->getSession(partitionType, partitionId); } - -bool LtsPluginManager::startApp(const LtsAppDescriptor::AppDescription &app, bool headless, - const LtsSession::DdsConnectionParams &connParams, const QString &workspaceId, +bool LtsPluginManager::startApp(const LtsAppDescriptor::AppDescription& app, bool headless, + const LtsSession::DdsConnectionParams& connParams, const QString& workspaceId, bool hidden) { - - - LtsWidgets::LtsWaitDialogContainer wait; + LtsWidgets::LtsWaitDialogContainer wait; - m_app = app; - LtsPluginLoader *pluginLoader = LtsPluginLoader::getInstance(); + m_app = app; + LtsPluginLoader* pluginLoader = LtsPluginLoader::getInstance(); + QVector dataPlugins; + auto cb = [&](const PluginInstance& pi) { + dataPlugins.append(pi); + return true; + }; - - QVector dataPlugins; - auto cb = [&](const PluginInstance &pi) - { - dataPlugins.append(pi); - return true; - }; - - if (!pluginLoader->loadPlugins(PluginType::DATA, cb)) - { - WARNING_LOG(m_logger) << "PluginLoader failed to load data plugins - abort!"; - return false; - } - - - - QVector guiPlugins; - auto cbLoadPlugins = [&](const PluginInstance &pi) - { - guiPlugins.append(pi); - return true; - }; - - if (!pluginLoader->loadPlugins(PluginType::GUI, cbLoadPlugins)) - { - WARNING_LOG(m_logger) << "PluginLoader failed to load gui plugins - abort!"; - return false; - } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - QVector dataApiList; - for (auto i = dataPlugins.constBegin(); i != dataPlugins.constEnd(); ++i) - { - const PluginInstance &pi = *i; - - AppPluginInstance api; - api.pluginInstance = pi; - api.m_appName = m_app.appName; - api.m_appId = m_app.id; - - - dataApiList.append(api); - } - - - - - QVector guiApiList; - for (auto i = guiPlugins.constBegin(); i != guiPlugins.constEnd(); ++i) - { - const PluginInstance &pi = *i; - - AppPluginInstance api; - api.pluginInstance = pi; - api.m_appName = m_app.appName; - api.m_appId = m_app.id; - - - - for (auto i2 = app.pluginInfos.constBegin(); i2 != app.pluginInfos.constEnd(); ++i2) + if (!pluginLoader->loadPlugins(PluginType::DATA, cb)) { - const LtsAppDescriptor::PluginInfo &rp = *i2; - - - if (rp.type == LtsAppDescriptor::PluginInfo::PluginType::GUI - && rp.iid == pi.pluginName) - { - - api.m_flags = rp.flags; - api.m_options = rp.options; - - break; - } + WARNING_LOG(m_logger) << "PluginLoader failed to load data plugins - abort!"; + return false; } - - - - - + QVector guiPlugins; + auto cbLoadPlugins = [&](const PluginInstance& pi) { + guiPlugins.append(pi); + return true; + }; - guiApiList.append(api); - } + if (!pluginLoader->loadPlugins(PluginType::GUI, cbLoadPlugins)) + { + WARNING_LOG(m_logger) << "PluginLoader failed to load gui plugins - abort!"; + return false; + } + QVector dataApiList; + for (auto i = dataPlugins.constBegin(); i != dataPlugins.constEnd(); ++i) + { + const PluginInstance& pi = *i; - - - - - + AppPluginInstance api; + api.pluginInstance = pi; + api.m_appName = m_app.appName; + api.m_appId = m_app.id; + dataApiList.append(api); + } - LtsSession::DdsConnectionParams connParamsNew(connParams); - if (!connParamsNew.isValid()) - { - INFO_LOG(m_logger) << "Invalid connection params given - using default parameter"; - - connParamsNew.domainId = LtsSessionData::LtsSessionData::getInstance()->getDomainIdPreset(); - connParamsNew.partitionId = 0; - connParamsNew.exerciseId = 0; - connParamsNew.partitionType = IDL::PartitionType::Global; + QVector guiApiList; + for (auto i = guiPlugins.constBegin(); i != guiPlugins.constEnd(); ++i) + { + const PluginInstance& pi = *i; + AppPluginInstance api; + api.pluginInstance = pi; + api.m_appName = m_app.appName; + api.m_appId = m_app.id; - connParamsNew.tcpConnectionUrl = LtsSessionData::LtsSessionData::getInstance()->getTcpConnectionUrl(); - } - if (LtsSessionData::LtsSessionData::getInstance()->getQosFile().size() > 0 && LtsSessionData::LtsSessionData::getInstance()->getQosFile().at(0).size() > 0) - connParamsNew.qos_file = LtsSessionData::LtsSessionData::getInstance()->getQosFile(); - else - connParamsNew.qos_file = QStringList(); - if (!m_sessionManager->init(connParamsNew, - dataApiList, - guiApiList, - m_app.id, - workspaceId, - headless, - hidden)) - { - ERROR_LOG(m_logger) << "Could not create Global Session - abort."; - return false; - } + for (auto i2 = app.pluginInfos.constBegin(); i2 != app.pluginInfos.constEnd(); ++i2) + { + const LtsAppDescriptor::PluginInfo& rp = *i2; - return true; + if (rp.type == LtsAppDescriptor::PluginInfo::PluginType::GUI && rp.iid == pi.pluginName) + { + + api.m_flags = rp.flags; + api.m_options = rp.options; + + break; + } + } + + guiApiList.append(api); + } + + LtsSession::DdsConnectionParams connParamsNew(connParams); + if (!connParamsNew.isValid()) + { + INFO_LOG(m_logger) << "Invalid connection params given - using default parameter"; + + connParamsNew.domainId = LtsSessionData::LtsSessionData::getInstance()->getDomainIdPreset(); + connParamsNew.partitionId = 0; + connParamsNew.exerciseId = 0; + connParamsNew.partitionType = IDL::PartitionType::Global; + + connParamsNew.tcpConnectionUrl = LtsSessionData::LtsSessionData::getInstance()->getTcpConnectionUrl(); + } + if (LtsSessionData::LtsSessionData::getInstance()->getQosFile().size() > 0 && + LtsSessionData::LtsSessionData::getInstance()->getQosFile().at(0).size() > 0) + connParamsNew.qos_file = LtsSessionData::LtsSessionData::getInstance()->getQosFile(); + else + connParamsNew.qos_file = QStringList(); + if (!m_sessionManager->init(connParamsNew, dataApiList, guiApiList, m_app.id, workspaceId, headless, hidden)) + { + ERROR_LOG(m_logger) << "Could not create Global Session - abort."; + return false; + } + + return true; } -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.h old mode 100755 new mode 100644 index d831b9e3a..1608cc1dc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager.h @@ -1,110 +1,140 @@ - #pragma once #include "lts_plugin_manager_export.h" -#include #include +#include #include - +#include +#include #include #include -#include #include -#include - namespace NGL { class INGLLogger; } + namespace DataPluginBase { class Plugin; } + namespace GuiPluginBase { class Plugin; } + namespace ProjectPlugin { class Plugin; } + namespace LtsSession { class LtsSession; class LtsSessionManager; struct DdsConnectionParams; -} +} // namespace LtsSession + namespace DeveloperTools { class DevDialog; } - namespace LtsPluginManager { -struct AppPluginInstance +struct AppPluginInstance { - PluginInstance pluginInstance; + PluginInstance pluginInstance; - QFlags m_flags; - QStringList m_options; - QString m_appName; - LtsAppDescriptor::App m_appId = LtsAppDescriptor::App::Login; + QFlags m_flags; + QStringList m_options; + QString m_appName; + LtsAppDescriptor::App m_appId = LtsAppDescriptor::App::Login; }; class LTSPLUGINMANAGER_EXPORT LtsPluginManager : public QObject { - Q_OBJECT + Q_OBJECT -public: - LtsPluginManager(); - ~LtsPluginManager(); + public: + LtsPluginManager(); + ~LtsPluginManager(); - bool startApp(const LtsAppDescriptor::AppDescription &app, bool headless, - const LtsSession::DdsConnectionParams &connParams, - const QString &workspaceId = QString(), bool hidden = false); - LtsSession::LtsSession *getSession(IDL::PartitionType partitionType, int partitionId); - bool isInitialized() const { return m_initialized; } - const LtsAppDescriptor::AppDescription &appDescription() const { return m_app; } - QVector sessions() const; - Q_DECL_DEPRECATED void setMarkedForDeletion() { m_markedForDeletion = true; } - Q_DECL_DEPRECATED bool markedForDeletion() const { return m_markedForDeletion; } - const QString &description() const { return m_description; } - void setDescription(const QString &description) { m_description = description; } + bool startApp(const LtsAppDescriptor::AppDescription& app, bool headless, + const LtsSession::DdsConnectionParams& connParams, const QString& workspaceId = QString(), + bool hidden = false); + LtsSession::LtsSession* getSession(IDL::PartitionType partitionType, int partitionId); - static bool hasSituationMapInstance(const LtsAppDescriptor::AppDescription &appDescription, bool alsoTestFOrScriptApp = false); - bool hasSituationMapInstance() const; - void softQuit(); - void _softQuit(); + bool isInitialized() const + { + return m_initialized; + } + const LtsAppDescriptor::AppDescription& appDescription() const + { + return m_app; + } + QVector sessions() const; - LtsSession::LtsSessionManager *m_sessionManager; -private: - NGL::INGLLogger &m_logger; - friend class DeveloperTools::DevDialog; + Q_DECL_DEPRECATED void setMarkedForDeletion() + { + m_markedForDeletion = true; + } - LtsAppDescriptor::AppDescription m_app; - bool m_initialized = false; - bool m_markedForDeletion; - QString m_description; + Q_DECL_DEPRECATED bool markedForDeletion() const + { + return m_markedForDeletion; + } -private slots: - void slotInitializationFinished() { m_initialized = true; } + const QString& description() const + { + return m_description; + } -signals: - void signalQuit(); - void signalSoftQuit(); - void signalLogout(); - void signalInitializationFinished(); - void signalInitializationAborted(); - void signalStillAlive(); - void hideAllOtherBLWs(QObject *caller); - void taskSwitch(QObject *caller); + void setDescription(const QString& description) + { + m_description = description; + } + + static bool hasSituationMapInstance(const LtsAppDescriptor::AppDescription& appDescription, + bool alsoTestFOrScriptApp = false); + bool hasSituationMapInstance() const; + void softQuit(); + void _softQuit(); + + LtsSession::LtsSessionManager* m_sessionManager; + + private: + NGL::INGLLogger& m_logger; + friend class DeveloperTools::DevDialog; + + LtsAppDescriptor::AppDescription m_app; + bool m_initialized = false; + bool m_markedForDeletion; + QString m_description; + + private slots: + + void slotInitializationFinished() + { + m_initialized = true; + } + + signals: + void signalQuit(); + void signalSoftQuit(); + void signalLogout(); + void signalInitializationFinished(); + void signalInitializationAborted(); + void signalStillAlive(); + void hideAllOtherBLWs(QObject* caller); + void taskSwitch(QObject* caller); }; -} +} // namespace LtsPluginManager diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager_export.h old mode 100755 new mode 100644 index 5d563576f..c4a08b941 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPluginManager/lts_plugin_manager_export.h @@ -5,13 +5,13 @@ #include #ifndef LTSPLUGINMANAGER_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSPLUGINMANAGER_EXPORT -# else -# if defined(MAKE_LTSPLUGINMANAGER_LIB) -# define LTSPLUGINMANAGER_EXPORT Q_DECL_EXPORT -# else -# define LTSPLUGINMANAGER_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSPLUGINMANAGER_EXPORT +#else +#if defined(MAKE_LTSPLUGINMANAGER_LIB) +#define LTSPLUGINMANAGER_EXPORT Q_DECL_EXPORT +#else +#define LTSPLUGINMANAGER_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.cpp old mode 100755 new mode 100644 index fbb841b57..815b7cb16 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.cpp @@ -1,430 +1,386 @@ - #include "printing.h" + #include "printing_base.h" +#include #include #include #include - -#include -#include -#include -#include -#include #include +#include #include -#include -#include - -#include +#include +#include #include #include +#include +#include +#include #include -#include -#include -#include +#include +#include #include +#include +#include namespace LtsPrinting { - - - -bool itemsHaveNoChildren(const QTreeView *view) +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; + 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) +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") ); + 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()); + LtsSessionData::LtsSessionData* sessionData = LtsSessionData::LtsSessionData::getInstance(); + nglPrinter.setOperatorName(sessionData->getOperatorName()); } - -void printView(LtsSession::LtsSession *session, - QWidget *dialogParent, - const QAbstractItemView *view, +void printView(LtsSession::LtsSession* session, QWidget* dialogParent, const QAbstractItemView* view, const QString& headingHtml) { - const QTableView *tableView = dynamic_cast(view); - const QTreeView *treeView = dynamic_cast(view); - QSet hiddenCols; + const QTableView* tableView = dynamic_cast(view); + const QTreeView* treeView = dynamic_cast(view); + QSet 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(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(), - QPrinter::A4, QPrinter::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(view); - printView(session, dialogParent, itemView, headingHtml); -} - - -void printImage(LtsSession::LtsSession *session, QWidget *dialogParent, - const QImage &image, const QString &imageTitle, const QString &description, - const QPrinter::PageSize &pageSize, const QPrinter::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 &images, - QVector &imageTitles, QVector &descriptions, - const QPrinter::PageSize &pageSize, const QPrinter::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 &images) - -{ - QPrinter printer; - - printer.setColorMode(QPrinter::ColorMode::Color); - printer.setOrientation(QPrinter::Orientation::Portrait); - printer.setPageSize(QPrinter::PageSize::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(), - QPrinter::A3, QPrinter::Landscape); - if (!nglPrinter.printer()) - return; - - setNameOfExerciseAndOperator( session, nglPrinter ); - - cursor.movePosition(QTextCursor::End); - - report.setWidthForEndlessPrinter(0); - report.setPageSize(QPrinter::A3); - report.setOrientation(QPrinter::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, - QPrinter::A3, QPrinter::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, - QPrinter::A4, QPrinter::Portrait); - - QString str = QString(QStringLiteral("

%1 %2

")).arg(subject).arg(subjectContent); - str.append( QString(QStringLiteral("%1 %2
")).arg(time).arg(timeContent)); - str.append( QString(QStringLiteral("%1 %2
")).arg(from).arg(fromContent)); - str.append( QString(QStringLiteral("%1 %2
")).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, - QPrinter::A4, QPrinter::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("")); - 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("
")).size(); ++rowInCellCounter) + int switchNum = 0; + if (tableView != nullptr) { - htmlStr.append(QStringLiteral("")); - - if (rowInCellCounter < stringFirstColumn.split(QStringLiteral("
")).size()) - { - htmlStr.append(QStringLiteral("")); - } - else - { - htmlStr.append(QStringLiteral("")); - } - QString currentTextSecond = stringSecondColumn.split(QStringLiteral("
"))[rowInCellCounter]; - htmlStr.append(QStringLiteral("")); - - QString currentTextThird = stringThirdColumn.split(QStringLiteral("
"))[rowInCellCounter]; - htmlStr.append(QStringLiteral("")); - htmlStr.append(QStringLiteral("")); + switchNum = 1; + hiddenCols = LtsPrinting::Base::getHiddenCols(tableView); } - QTextDocument tempDoc; - tempDoc.setPageSize(doc.pageSize()); - tempDoc.setHtml(htmlStr); - currentHeight = doc.size().height() - previousPagesHeight; - - if (currentHeight + tempDoc.size().height() > nglPrinter.pageSizeInMM().height()) + else if (treeView != nullptr) { - tbfFormat.setPageBreakPolicy(QTextFormat::PageBreakFlag::PageBreak_AlwaysBefore); - cursor.insertBlock(tbfFormat); - previousPagesHeight = doc.size().height(); - currentHeight = doc.size().height() - previousPagesHeight; + switchNum = 2; + hiddenCols = LtsPrinting::Base::getHiddenCols(treeView); + if (itemsHaveNoChildren(treeView)) + switchNum = 1; } + else if (dynamic_cast(view) != nullptr) + switchNum = 3; else { - tbfFormat.setPageBreakPolicy(QTextFormat::PageBreakFlag::PageBreak_Auto); - currentHeight = doc.size().height() - previousPagesHeight; + 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(), QPrinter::A4, QPrinter::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); - htmlStr.clear(); - } - htmlStr.append(QStringLiteral("
")); - htmlStr.append(stringFirstColumn.split(QStringLiteral("
"))[rowInCellCounter]); - htmlStr.append(QStringLiteral("
")); - htmlStr.append(QStringLiteral("")); - htmlStr.append(currentTextSecond); - htmlStr.append(QStringLiteral("")); - htmlStr.append(currentTextThird); - htmlStr.append(QStringLiteral("
")); - cursor.insertHtml(htmlStr); - - cursor.movePosition(QTextCursor::End); - - setNameOfExerciseAndOperator(session, nglPrinter); - nglPrinter.print(&doc); + nglPrinter.print(&doc); } - +void printView(LtsSession::LtsSession* session, QWidget* dialogParent, QAbstractItemView* view, + const QString& headingHtml) +{ + const QAbstractItemView* itemView = static_cast(view); + printView(session, dialogParent, itemView, headingHtml); } + +void printImage(LtsSession::LtsSession* session, QWidget* dialogParent, const QImage& image, const QString& imageTitle, + const QString& description, const QPrinter::PageSize& pageSize, + const QPrinter::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& images, QVector& imageTitles, QVector& descriptions, + const QPrinter::PageSize& pageSize, const QPrinter::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& images) + +{ + QPrinter printer; + + printer.setColorMode(QPrinter::ColorMode::Color); + printer.setOrientation(QPrinter::Orientation::Portrait); + printer.setPageSize(QPrinter::PageSize::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(), QPrinter::A3, QPrinter::Landscape); + if (!nglPrinter.printer()) + return; + + setNameOfExerciseAndOperator(session, nglPrinter); + + cursor.movePosition(QTextCursor::End); + + report.setWidthForEndlessPrinter(0); + report.setPageSize(QPrinter::A3); + report.setOrientation(QPrinter::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, QPrinter::A3, + QPrinter::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, QPrinter::A4, + QPrinter::Portrait); + + QString str = QString(QStringLiteral("

%1 %2

")).arg(subject).arg(subjectContent); + str.append(QString(QStringLiteral("%1 %2
")).arg(time).arg(timeContent)); + str.append(QString(QStringLiteral("%1 %2
")).arg(from).arg(fromContent)); + str.append(QString(QStringLiteral("%1 %2
")).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(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, QPrinter::A4, + QPrinter::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("")); + 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("
")).size(); + ++rowInCellCounter) + { + htmlStr.append(QStringLiteral("")); + + if (rowInCellCounter < stringFirstColumn.split(QStringLiteral("
")).size()) + { + htmlStr.append(QStringLiteral("")); + } + else + { + htmlStr.append(QStringLiteral("")); + } + QString currentTextSecond = stringSecondColumn.split(QStringLiteral("
"))[rowInCellCounter]; + htmlStr.append(QStringLiteral("")); + + QString currentTextThird = stringThirdColumn.split(QStringLiteral("
"))[rowInCellCounter]; + htmlStr.append(QStringLiteral("")); + htmlStr.append(QStringLiteral("")); + } + 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("
")); + htmlStr.append(stringFirstColumn.split(QStringLiteral("
"))[rowInCellCounter]); + htmlStr.append(QStringLiteral("
")); + htmlStr.append(QStringLiteral("")); + htmlStr.append(currentTextSecond); + htmlStr.append(QStringLiteral("")); + htmlStr.append(currentTextThird); + htmlStr.append(QStringLiteral("
")); + cursor.insertHtml(htmlStr); + + cursor.movePosition(QTextCursor::End); + + setNameOfExerciseAndOperator(session, nglPrinter); + nglPrinter.print(&doc); +} + +} // namespace LtsPrinting diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.h old mode 100755 new mode 100644 index cfa985002..cfb841b7e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing.h @@ -1,94 +1,66 @@ - #pragma once #include #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 +#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 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 QPrinter::PageSize& pageSize = QPrinter::A3, + const QPrinter::Orientation& pageOrientation = QPrinter::Landscape); +LTSPRINTING_EXPORT void printImages(LtsSession::LtsSession* session, QWidget* dialogParent, const QString& docName, + QVector& images, QVector& imageTitles, + QVector& descriptions, const QPrinter::PageSize& pageSize = QPrinter::A3, + const QPrinter::Orientation& pageOrientation = QPrinter::Landscape); -LTSPRINTING_EXPORT void printImage(LtsSession::LtsSession *session, - QWidget *dialogParent, - const QImage &image, - const QString &imageTitle, - const QString &description, - const QPrinter::PageSize &pageSize = QPrinter::A3, - const QPrinter::Orientation &pageOrientation = QPrinter::Landscape); +LTSPRINTING_EXPORT void printPDFImages(QWidget* dialogParent, const QString& docName, const QString& printPath, + QVector& 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 printImages(LtsSession::LtsSession *session, - QWidget *dialogParent, - const QString &docName, - QVector < QImage> &images, - QVector < QString> &imageTitles, - QVector < QString> &descriptions, - const QPrinter::PageSize &pageSize = QPrinter::A3, - const QPrinter::Orientation &pageOrientation = QPrinter::Landscape); - - - -LTSPRINTING_EXPORT void printPDFImages(QWidget *dialogParent, - const QString &docName, - const QString &printPath, - QVector &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); - -} +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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.cpp old mode 100755 new mode 100644 index 1a3ef1a4f..d7dca62f3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.cpp @@ -1,59 +1,50 @@ - - - - - - #include "printing_base.h" -#include -#include +#include +#include +#include #include #include -#include -#include - -#include -#include -#include - -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include - -#include #include -#include - +#include #include #include - -#include -#include - +#include +#include namespace LtsPrinting { -static inline double mmToInches(double mm) { return mm * 0.039370147; } -static inline double inchesToMM(double inches) { return inches * 25.4; } +static inline double mmToInches(double mm) +{ + return mm * 0.039370147; +} + +static inline double inchesToMM(double inches) +{ + return inches * 25.4; +} bool LtsPrinting::Base::m_printToFile = false; -static int TitleDataHeight = 50; +static int TitleDataHeight = 50; static int DescriptionDataHeight = 50; -static void spanSizes(const QAbstractItemView *view, - const QModelIndex &ms, - int &rowSpanSize, - int &columnSpanSize, - QVector > &spannedL); - +static void spanSizes(const QAbstractItemView* view, const QModelIndex& ms, int& rowSpanSize, int& columnSpanSize, + QVector>& spannedL); Base::Base(QTextDocument &doc, QWidget *dialogParent, @@ -72,1233 +63,1064 @@ Base::Base(QTextDocument &doc, itemFontSize_(2), m_settings(new NGL::Settings(NGL::findProjectConfigFile())).getNGLLogger("NGLPrinting")), m_currentPage(1), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - QString fn = _fn; - fn = fn.remove(QLatin1Char(' ')); - fn = fn.remove(QLatin1String("..")); - fn = fn.remove(QLatin1Char('/')); - fn = m_settings->printPath() + fn; - if (!fn.endsWith(QLatin1String(".pdf"), Qt::CaseInsensitive)) - fn += QLatin1String(".pdf"); + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + QString fn = _fn; + fn = fn.remove(QLatin1Char(' ')); + fn = fn.remove(QLatin1String("..")); + fn = fn.remove(QLatin1Char('/')); + fn = m_settings->printPath() + fn; + if (!fn.endsWith(QLatin1String(".pdf"), Qt::CaseInsensitive)) + fn += QLatin1String(".pdf"); #ifndef WIN32 - m_printer->setOutputFileName(fn); + m_printer->setOutputFileName(fn); #endif - m_printer->setOutputFormat(QPrinter::NativeFormat); + m_printer->setOutputFormat(QPrinter::NativeFormat); - + m_printer->setPaperSize(_ps); + m_printer->setOrientation(_or); + m_printer->setColorMode(_cm); + m_printer->setFullPage(true); - m_printer->setPaperSize(_ps); - m_printer->setOrientation(_or); - m_printer->setColorMode(_cm); + QTextOption tOption = doc.defaultTextOption(); + tOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); - m_printer->setFullPage(true); + doc.setDefaultTextOption(tOption); - - - QTextOption tOption = doc.defaultTextOption(); - tOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); - - doc.setDefaultTextOption(tOption); - - - - doc.setPageSize(QSizeF(printerPageSize())); - doc.setDefaultStyleSheet(styleSheet()); - - if (m_printToFile) - return; - QPrintDialog *dialog = new QPrintDialog(m_printer, dialogParent); + doc.setPageSize(QSizeF(printerPageSize())); + doc.setDefaultStyleSheet(styleSheet()); - - QAbstractPrintDialog::PrintDialogOptions op = - QAbstractPrintDialog::PrintToFile | - QAbstractPrintDialog::PrintSelection | - QAbstractPrintDialog::PrintPageRange | - QAbstractPrintDialog::PrintShowPageSize | - QAbstractPrintDialog::PrintCollateCopies; - dialog->setOptions(op); - QString title = dialogTitle; - if (_ps == QPrinter::A2) title += QLatin1String(" (A2)"); - if (_ps == QPrinter::A3) title += QLatin1String(" (A3)"); - if (_ps == QPrinter::A4) title += QLatin1String(" (A4)"); - if (_ps == QPrinter::A5) title += QLatin1String(" (A5)"); - dialog->setWindowTitle(title); - if (dialog->exec() != QDialog::Accepted) - { - - - delete m_printer; - m_printer = nullptr; - return; - } + if (m_printToFile) + return; + QPrintDialog* dialog = new QPrintDialog(m_printer, dialogParent); - m_painter->begin(m_printer); + QAbstractPrintDialog::PrintDialogOptions op = + QAbstractPrintDialog::PrintToFile | QAbstractPrintDialog::PrintSelection | + QAbstractPrintDialog::PrintPageRange | QAbstractPrintDialog::PrintShowPageSize | + QAbstractPrintDialog::PrintCollateCopies; + dialog->setOptions(op); + QString title = dialogTitle; + if (_ps == QPrinter::A2) + title += QLatin1String(" (A2)"); + if (_ps == QPrinter::A3) + title += QLatin1String(" (A3)"); + if (_ps == QPrinter::A4) + title += QLatin1String(" (A4)"); + if (_ps == QPrinter::A5) + title += QLatin1String(" (A5)"); + dialog->setWindowTitle(title); + if (dialog->exec() != QDialog::Accepted) + { + + delete m_printer; + m_printer = nullptr; + return; + } + + m_painter->begin(m_printer); } - Base::~Base() { - delete m_printer; - delete m_painter; - delete m_tempdoc; - - for (int nr = 0; nr < m_iconFilenameNr; ++nr) - QFile::remove(iconFilename(nr)); - delete m_settings; -} + delete m_printer; + delete m_painter; + delete m_tempdoc; + for (int nr = 0; nr < m_iconFilenameNr; ++nr) + QFile::remove(iconFilename(nr)); + delete m_settings; +} void Base::setPrintToFile(bool printToFile) { - m_printToFile = printToFile; + m_printToFile = printToFile; } - -QPrinter *Base::printer() +QPrinter* Base::printer() { - DEBUG_LOG(m_logger) << "Base::printer" ; + DEBUG_LOG(m_logger) << "Base::printer"; - return m_printer; + return m_printer; } - QString Base::styleSheet() { - QString ret; - - return ret; -} + QString ret; + return ret; +} QSize Base::printerPageSize() const { - return QSize(m_printer->pageRect().width() - 2 * DOC_MARGIN, - m_printer->pageRect().height() - 2 * DOC_MARGIN); + return QSize(m_printer->pageRect().width() - 2 * DOC_MARGIN, m_printer->pageRect().height() - 2 * DOC_MARGIN); } bool Base::newPage() { - return m_printer->newPage(); + return m_printer->newPage(); } - QSize Base::contentPageSize() const { - QSize ps(printerPageSize()); - - ps.setHeight(ps.height() - 50 - 50); - return ps; + QSize ps(printerPageSize()); + + ps.setHeight(ps.height() - 50 - 50); + return ps; } - -void Base::printTitleData(QString &htmlStr, const QString &title, const QString &heading) +void Base::printTitleData(QString& htmlStr, const QString& title, const QString& heading) { - if (!title.isEmpty()) - { - htmlStr += QLatin1String("
") + - QLatin1Char('<') + heading + QLatin1Char('>') + title + QLatin1String("') + - QLatin1String("
"); - } + if (!title.isEmpty()) + { + htmlStr += QLatin1String("
") + QLatin1Char('<') + heading + + QLatin1Char('>') + title + QLatin1String("') + + QLatin1String("
"); + } } - -bool Base::printListData(QString &str, - const QAbstractItemView *view, - const QString &title, - bool asIcons, +bool Base::printListData(QString& str, const QAbstractItemView* view, const QString& title, bool asIcons, int iconExtent) { - if (!view) - return false; - printTitleData(str, title); - QAbstractItemModel *vm = view->model(); - if (!vm) - return false; - QItemSelectionModel *sm = view->selectionModel(); - QModelIndexList mil; - if (m_printer->printRange() == QPrinter::Selection) - mil = sm->selectedRows(); - else - { - int row = 0; - while (1) + if (!view) + return false; + printTitleData(str, title); + QAbstractItemModel* vm = view->model(); + if (!vm) + return false; + QItemSelectionModel* sm = view->selectionModel(); + QModelIndexList mil; + if (m_printer->printRange() == QPrinter::Selection) + mil = sm->selectedRows(); + else { - QModelIndex mi = vm->index(row, 0, QModelIndex()); - if (mi.isValid()) - { - mil.append(mi); - row++; - continue; - } - break; + int row = 0; + while (1) + { + QModelIndex mi = vm->index(row, 0, QModelIndex()); + if (mi.isValid()) + { + mil.append(mi); + row++; + continue; + } + break; + } } - } - if (mil.count() == 0) - return false; - if (asIcons) - { - - int elemWidth = iconExtent + 40; - int tableWidth = contentPageSize().width(); - int nColums = tableWidth / elemWidth; - str += QLatin1String("") + - QLatin1String("") + - QLatin1String("") + - QLatin1String("") + - QLatin1String(""); - - int columIdx = 0; - for (const QModelIndex &mi :std::as_const(mil)) + if (mil.count() == 0) + return false; + if (asIcons) { - - if (columIdx >= nColums) - { - - columIdx = 0; - str += QLatin1String(""); - } - - str += QLatin1String(""); - ++columIdx; - - } - str += QLatin1String("
"); - printDecorationData(str, vm, mi, iconExtent / 2); - - QVariant vdata = vm->data(mi, Qt::DisplayRole); - str += QLatin1String("
"); - QString displayText; - if (vdata.isValid()) - displayText = vdata.toString(); - else - displayText = QLatin1Char(' '); - str += QLatin1String("") + displayText + QLatin1String("") + - QLatin1String("
"); - } - else - { - - for (const QModelIndex &mi :std::as_const(mil)) - { - if (printItemData(str, vm, mi, iconExtent)) - str += QLatin1String("
"); - } - } - return true; -} -static QModelIndexList getItemChildren(const QAbstractItemModel *model, - const QTreeView *tv, - const QModelIndex &root) -{ - QModelIndexList ret; - const int rc = model->rowCount(root); - ret.reserve(rc); + int elemWidth = iconExtent + 40; + int tableWidth = contentPageSize().width(); + int nColums = tableWidth / elemWidth; + str += QLatin1String("") + QLatin1String("") + QLatin1String("") + QLatin1String("") + QLatin1String(""); - for (int row = 0; row < rc; ++row) - { - const QModelIndex mi = model->index(row, 0, root); - ret += mi; - if (tv->isExpanded(mi)) - ret += getItemChildren(model, tv, mi); - } + int columIdx = 0; + for (const QModelIndex& mi : std::as_const(mil)) + { - return ret; -} + if (columIdx >= nColums) + { + columIdx = 0; + str += QLatin1String(""); + } -bool Base::printTableData(QString &str, - const QAbstractItemView *view, - const QString &title_, - const QSet &suppressCols, - int iconExtent) -{ - if (!view) - return false; - QString title = title_; - printTitleData(str, title.remove(QLatin1String("[*]"))); - const QAbstractItemModel *imodel = view->model(); - QModelIndexList mil; - if (m_printer->printRange() == QPrinter::Selection) - { - const QItemSelectionModel *sm = view->selectionModel(); - mil += sm->selectedRows(); - } - else - { - const QTreeView *tv = qobject_cast(view); - if (tv) - { - const int rc = imodel->rowCount(); - mil.reserve(rc); - for (int row = 0; row < rc; ++row) - { - QModelIndex mi = imodel->index(row, 0); - mil += mi; - if (tv->isExpanded(mi)) - mil += getItemChildren(imodel, tv, mi); - } + str += QLatin1String(""); + ++columIdx; + } + str += QLatin1String("
"); + printDecorationData(str, vm, mi, iconExtent / 2); + + QVariant vdata = vm->data(mi, Qt::DisplayRole); + str += QLatin1String("
"); + QString displayText; + if (vdata.isValid()) + displayText = vdata.toString(); + else + displayText = QLatin1Char(' '); + str += QLatin1String("") + displayText + QLatin1String("") + QLatin1String("
"); } else { - const int rc = imodel->rowCount(); - mil.reserve(rc); - for (int row = 0; row < rc; ++row) - mil.append(imodel->index(row, 0)); - } - } - int colCount = imodel->columnCount(); - QStringList tableHeader; - for (int i = 0; i < colCount; i++) - { - if (suppressCols.contains(i)) - continue; - QVariant v = imodel->headerData(i, Qt::Horizontal); - if (v.isValid()) - tableHeader.append(v.toString()); - } - str += QLatin1String("") + - QLatin1String("") + - QLatin1String(""); - for (const QString &s : std::as_const(tableHeader)) - str += QLatin1String(""); - str += QLatin1String(""); - - - - QVector > spannedL; - for (const QModelIndex &mi :std::as_const(mil)) - { - str += QLatin1String(""); - for (int ii = 0; ii < colCount; ii++) + for (const QModelIndex& mi : std::as_const(mil)) + { + if (printItemData(str, vm, mi, iconExtent)) + str += QLatin1String("
"); + } + } + return true; +} + +static QModelIndexList getItemChildren(const QAbstractItemModel* model, const QTreeView* tv, const QModelIndex& root) +{ + QModelIndexList ret; + const int rc = model->rowCount(root); + ret.reserve(rc); + + for (int row = 0; row < rc; ++row) { - if (suppressCols.contains(ii)) - continue; - const QModelIndex ms = mi.sibling(mi.row(), ii); - if (spannedL.contains(qMakePair(ms.row(), ms.column()))) - continue; - int rowSpanSize; - int columnSpanSize; - spanSizes(view, ms, rowSpanSize, columnSpanSize, spannedL); - printTableItemData(str, imodel, ms, rowSpanSize, columnSpanSize, - iconExtent); + const QModelIndex mi = model->index(row, 0, root); + ret += mi; + if (tv->isExpanded(mi)) + ret += getItemChildren(model, tv, mi); + } + + return ret; +} + +bool Base::printTableData(QString& str, const QAbstractItemView* view, const QString& title_, + const QSet& suppressCols, int iconExtent) +{ + if (!view) + return false; + QString title = title_; + printTitleData(str, title.remove(QLatin1String("[*]"))); + const QAbstractItemModel* imodel = view->model(); + QModelIndexList mil; + if (m_printer->printRange() == QPrinter::Selection) + { + const QItemSelectionModel* sm = view->selectionModel(); + mil += sm->selectedRows(); + } + else + { + const QTreeView* tv = qobject_cast(view); + if (tv) + { + const int rc = imodel->rowCount(); + mil.reserve(rc); + for (int row = 0; row < rc; ++row) + { + QModelIndex mi = imodel->index(row, 0); + mil += mi; + if (tv->isExpanded(mi)) + mil += getItemChildren(imodel, tv, mi); + } + } + else + { + const int rc = imodel->rowCount(); + mil.reserve(rc); + for (int row = 0; row < rc; ++row) + mil.append(imodel->index(row, 0)); + } + } + int colCount = imodel->columnCount(); + QStringList tableHeader; + for (int i = 0; i < colCount; i++) + { + if (suppressCols.contains(i)) + continue; + QVariant v = imodel->headerData(i, Qt::Horizontal); + if (v.isValid()) + tableHeader.append(v.toString()); + } + str += + QLatin1String("
") + s + QLatin1String("
") + + QLatin1String("") + QLatin1String(""); + for (const QString& s : std::as_const(tableHeader)) + str += QLatin1String(""); + str += QLatin1String(""); + + QVector> spannedL; + for (const QModelIndex& mi : std::as_const(mil)) + { + str += QLatin1String(""); + for (int ii = 0; ii < colCount; ii++) + { + if (suppressCols.contains(ii)) + continue; + const QModelIndex ms = mi.sibling(mi.row(), ii); + if (spannedL.contains(qMakePair(ms.row(), ms.column()))) + continue; + int rowSpanSize; + int columnSpanSize; + spanSizes(view, ms, rowSpanSize, columnSpanSize, spannedL); + printTableItemData(str, imodel, ms, rowSpanSize, columnSpanSize, iconExtent); + } + str += QLatin1String(""); + } + str += QLatin1String("
") + s + QLatin1String("
"); + + DEBUG_LOG(m_logger) << qPrintable(str); + return true; +} + +void spanSizes(const QAbstractItemView* view, const QModelIndex& ms, int& rowSpanSize, int& columnSpanSize, + QVector>& spannedL) +{ + rowSpanSize = 1; + columnSpanSize = 1; + const QTableView* tview = qobject_cast(view); + if (tview) + { + rowSpanSize = tview->rowSpan(ms.row(), ms.column()); + columnSpanSize = tview->columnSpan(ms.row(), ms.column()); + for (int row = ms.row(); row < ms.row() + rowSpanSize; ++row) + spannedL << qMakePair(row, ms.column()); + for (int column = ms.column(); column < ms.column() + columnSpanSize; ++column) + spannedL << qMakePair(ms.row(), column); + } +} + +bool Base::printTableItemData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi, int rowSpanSize, + int columnSpanSize, int iconExtent) +{ + QVariant vdata; + QString htmlString; + + vdata = model->data(mi, Qt::BackgroundRole); + if (vdata.isValid()) + { + QString bgColorString = vdata.value().color().name(); + htmlString += QLatin1String(" 1) + htmlString += QLatin1String(" rowspan=\"") + QString::number(rowSpanSize) + QLatin1Char('\"'); + if (columnSpanSize > 1) + htmlString += QLatin1String(" colspan=\"") + QString::number(columnSpanSize) + QLatin1Char('\"'); + + htmlString += QLatin1Char('>'); + + printItemData(htmlString, model, mi, iconExtent); + htmlString += QLatin1String(""); + str += htmlString; + return true; +} + +bool Base::printTreeData(QString& str, const QAbstractItemView* view, const QString& title, + const QSet& suppressCols, int iconExtent, const QList& tabtexts) +{ + if (!view) + return false; + printTitleData(str, title); + QAbstractItemModel* vm = view->model(); + if (!vm) + return false; + QItemSelectionModel* sm = view->selectionModel(); + QModelIndexList milColumn0; + if (m_printer->printRange() == QPrinter::Selection) + milColumn0 = sm->selectedRows(); + else + { + int row = 0; + while (1) + { + QModelIndex mi = vm->index(row, 0); + if (mi.isValid()) + { + milColumn0.append(mi); + row++; + continue; + } + break; + } + } + if (milColumn0.count() == 0) + return false; + + str += QLatin1String("") + QLatin1String(""); + + QStringList tableHeader; + if (tabtexts.size() > 0) + tableHeader = tabtexts; + else + { + for (int i = 0; i < vm->columnCount(); i++) + { + if (suppressCols.contains(i)) + continue; + QVariant v = vm->headerData(i, Qt::Horizontal); + if (v.isValid()) + tableHeader.append(v.toString()); + else + tableHeader.append(QString()); + } + } + + for (const QString& s : std::as_const(tableHeader)) + str += QLatin1String(""); + str += QLatin1String(""); + for (const QModelIndex& miColumn0 : std::as_const(milColumn0)) + printListPoint(str, view, vm, miColumn0, suppressCols, iconExtent); + + str += QLatin1String("

") + s + QLatin1String("



"); + + return true; +} + +void Base::printListPoint(QString& str, const QAbstractItemView* view, const QAbstractItemModel* vm, + const QModelIndex& miColumn0, const QSet& suppressCols, int iconExtent) +{ + if (!miColumn0.isValid()) + return; + + str += QLatin1String(""); + for (int column = 0; column < vm->columnCount(); column++) + { + if (suppressCols.contains(column)) + continue; + QModelIndex ms = miColumn0.sibling(miColumn0.row(), column); + if (!ms.isValid()) + continue; + str += QLatin1String("
"); + if (column == 0) + { + + int hierCount = hierarchyCount(ms); + for (int genIdx = 0; genIdx < hierCount; ++genIdx) + str += QLatin1String("
"); + str += QLatin1String("
"); + printItemData(str, vm, ms, iconExtent); + str += QLatin1String("
"); + for (int genIdx = 0; genIdx < hierCount; ++genIdx) + str += QLatin1String("
"); + } + else + { + str += QLatin1String("
"); + printItemData(str, vm, ms, iconExtent); + str += QLatin1String("
"); + } + str += QLatin1String("
"); } str += QLatin1String(""); - } - str += QLatin1String(""); - DEBUG_LOG(m_logger) << qPrintable(str) ; - return true; -} - - -void spanSizes(const QAbstractItemView *view, - const QModelIndex &ms, - int &rowSpanSize, - int &columnSpanSize, - QVector > &spannedL) -{ - rowSpanSize = 1; - columnSpanSize = 1; - const QTableView *tview = qobject_cast(view); - if (tview) - { - rowSpanSize = tview->rowSpan(ms.row(), ms.column()); - columnSpanSize = tview->columnSpan(ms.row(), ms.column()); - for (int row = ms.row(); row < ms.row() + rowSpanSize; ++row) - spannedL << qMakePair(row, ms.column()); - for (int column = ms.column(); column < ms.column() + columnSpanSize; ++column) - spannedL << qMakePair(ms.row(), column); - } -} - - -bool Base::printTableItemData(QString &str, - const QAbstractItemModel *model, - const QModelIndex &mi, - int rowSpanSize, - int columnSpanSize, - int iconExtent) -{ - QVariant vdata; - QString htmlString; - - - vdata = model->data(mi, Qt::BackgroundRole); - if (vdata.isValid()) - { - QString bgColorString = vdata.value().color().name(); - htmlString += QLatin1String(" 1) - htmlString += QLatin1String(" rowspan=\"") + QString::number(rowSpanSize) + QLatin1Char('\"'); - if (columnSpanSize > 1) - htmlString += QLatin1String(" colspan=\"") + QString::number(columnSpanSize) + QLatin1Char('\"'); - - htmlString += QLatin1Char('>'); - - printItemData(htmlString, model, mi, iconExtent); - htmlString += QLatin1String(""); - str += htmlString; - return true; -} - - - - -bool Base::printTreeData(QString &str, - const QAbstractItemView *view, - const QString &title, - const QSet &suppressCols, - int iconExtent, - const QList &tabtexts) -{ - if (!view) - return false; - printTitleData(str, title); - QAbstractItemModel *vm = view->model(); - if (!vm) - return false; - QItemSelectionModel *sm = view->selectionModel(); - QModelIndexList milColumn0; - if (m_printer->printRange() == QPrinter::Selection) - milColumn0 = sm->selectedRows(); - else - { - int row = 0; - while (1) + const QTreeView* tv = qobject_cast(view); + const bool expanded = tv ? tv->isExpanded(miColumn0) : true; + if (expanded) { - QModelIndex mi = vm->index(row, 0); - if (mi.isValid()) - { - milColumn0.append(mi); - row++; - continue; - } - break; + const int rc = vm->rowCount(miColumn0); + for (int row = 0; row < rc; row++) + { + QModelIndex cmi = vm->index(row, 0, miColumn0); + if (cmi.isValid()) + printListPoint(str, view, vm, cmi, suppressCols, iconExtent); + } } - } - if (milColumn0.count() == 0) - return false; - - str += QLatin1String("") + - QLatin1String(""); - - QStringList tableHeader; - if (tabtexts.size() > 0) - tableHeader = tabtexts; - else - { - for (int i = 0; i < vm->columnCount(); i++) - { - if (suppressCols.contains(i)) - continue; - QVariant v = vm->headerData(i, Qt::Horizontal); - if (v.isValid()) - tableHeader.append(v.toString()); - else - tableHeader.append(QString()); - } - } - - for (const QString &s : std::as_const(tableHeader)) - str += QLatin1String(""); - str += QLatin1String(""); - for (const QModelIndex &miColumn0 : std::as_const(milColumn0)) - printListPoint(str, view, vm, miColumn0, suppressCols, iconExtent); - - str += QLatin1String("

") + s + QLatin1String("



"); - - - - - - return true; } - -void Base::printListPoint(QString &str, - const QAbstractItemView *view, - const QAbstractItemModel *vm, - const QModelIndex &miColumn0, - const QSet &suppressCols, - int iconExtent) +int Base::hierarchyCount(const QModelIndex& child) { - if (!miColumn0.isValid()) - return; - - str += QLatin1String(""); - for (int column = 0; column < vm->columnCount(); column++) - { - if (suppressCols.contains(column)) - continue; - QModelIndex ms = miColumn0.sibling(miColumn0.row(), column); - if (!ms.isValid()) - continue; - str += QLatin1String("
"); - if (column == 0) - { - - int hierCount = hierarchyCount(ms); - for (int genIdx = 0; genIdx < hierCount; ++genIdx) - str += QLatin1String("
"); - str += QLatin1String("
"); - printItemData(str, vm, ms, iconExtent); - str += QLatin1String("
"); - for (int genIdx = 0; genIdx < hierCount; ++genIdx) - str += QLatin1String("
"); - } - else - { - str += QLatin1String("
"); - printItemData(str, vm, ms, iconExtent); - str += QLatin1String("
"); - } - str += QLatin1String("
"); - } - str += QLatin1String(""); - - - const QTreeView *tv = qobject_cast(view); - const bool expanded = tv ? tv->isExpanded(miColumn0) : true; - if (expanded) - { - const int rc = vm->rowCount(miColumn0); - for (int row = 0; row < rc; row++) - { - QModelIndex cmi = vm->index(row, 0, miColumn0); - if (cmi.isValid()) - printListPoint(str, view, vm, cmi, suppressCols, iconExtent); - } - } + int count = 0; + const auto parent = child.parent(); + if (parent.isValid()) + count = hierarchyCount(parent) + 1; + return count; } - -int Base::hierarchyCount(const QModelIndex &child) +bool Base::printItemData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi, int iconExtent) { - int count = 0; - const auto parent = child.parent(); - if (parent.isValid()) - count = hierarchyCount(parent) + 1; - return count; + QVariant vdata; + QString displayString; + QString htmlString; + + vdata = model->data(mi, Qt::CheckStateRole); + if (vdata.isValid()) + { + displayString += QLatin1String(""); + if (static_cast(vdata.toInt())) + displayString += QLatin1String("⊗ "); + else + displayString += QLatin1String("ο "); + displayString += QLatin1String(""); + } + + printDecorationData(displayString, model, mi, iconExtent / 2); + + displayString += QLatin1Char(' '); + vdata = model->data(mi, Qt::DisplayRole); + if (vdata.isValid()) + displayString += vdata.toString(); + + QString fgColorString; + vdata = model->data(mi, Qt::TextColorRole); + if (vdata.isValid()) + fgColorString = vdata.value().name(); + + vdata = model->data(mi, Qt::ForegroundRole); + if (vdata.isValid()) + fgColorString = vdata.value().color().name(); + + htmlString += QLatin1String("') + displayString + QLatin1String(""); + + str += htmlString; + return true; } - -bool Base::printItemData(QString &str, - const QAbstractItemModel *model, - const QModelIndex &mi, - int iconExtent) +void Base::printDecorationData(QString& str, const QAbstractItemModel* model, const QModelIndex& mi, int iconExtent) { - QVariant vdata; - QString displayString; - QString htmlString; + QVariant vdata = model->data(mi, Qt::DecorationRole); + if (vdata.isNull() || !vdata.isValid()) + return; + QIcon icon = vdata.value(); + if (icon.isNull()) + return; - - vdata = model->data(mi, Qt::CheckStateRole); - if (vdata.isValid()) - { - displayString += QLatin1String(""); - if (static_cast(vdata.toInt())) - displayString += QLatin1String("⊗ "); - else - displayString += QLatin1String("ο "); - displayString += QLatin1String(""); - } - - printDecorationData(displayString, model, mi, iconExtent / 2); - - displayString += QLatin1Char(' '); - vdata = model->data(mi, Qt::DisplayRole); - if (vdata.isValid()) - displayString += vdata.toString(); - - QString fgColorString; - vdata = model->data(mi, Qt::TextColorRole); - if (vdata.isValid()) - fgColorString = vdata.value().name(); - - vdata = model->data(mi, Qt::ForegroundRole); - if (vdata.isValid()) - fgColorString = vdata.value().color().name(); - - htmlString += QLatin1String("') + displayString + QLatin1String(""); + QString fn = iconFilename(m_iconFilenameNr++); + QPixmap pm = icon.pixmap(1000); + pm.save(fn); - str += htmlString; - return true; + str += QLatin1String("\"icon\""); } - -void Base::printDecorationData(QString &str, - const QAbstractItemModel *model, - const QModelIndex &mi, - int iconExtent) -{ - QVariant vdata = model->data(mi, Qt::DecorationRole); - if (vdata.isNull() || !vdata.isValid()) - return; - QIcon icon = vdata.value(); - if (icon.isNull()) - return; - - QString fn = iconFilename(m_iconFilenameNr++); - QPixmap pm = icon.pixmap(1000); - pm.save(fn); - - str += QLatin1String("\"icon\""); -} - - QString Base::iconFilename(int nr) const { - return m_settings->printPath() + QLatin1String("icon_") + QString::number(nr) + QLatin1String(".png"); + return m_settings->printPath() + QLatin1String("icon_") + QString::number(nr) + QLatin1String(".png"); } - -bool Base::printDocTextBlock(QTextDocument &doc, - const QString &text, - const QString &title) +bool Base::printDocTextBlock(QTextDocument& doc, const QString& text, const QString& title) { - QTextCursor cursor(&doc); - cursor.movePosition(QTextCursor::End); + QTextCursor cursor(&doc); + cursor.movePosition(QTextCursor::End); + + if (!title.isEmpty()) + { + QString htmlStr; + printTitleData(htmlStr, title); + cursor.insertHtml(htmlStr); + } + cursor.insertBlock(); + + QTextBlockFormat bf = cursor.blockFormat(); + bf.setNonBreakableLines(false); + cursor.setBlockFormat(bf); + + QTextCharFormat cf = cursor.blockCharFormat(); + cf.setFontWeight(QFont::Normal); + cursor.setBlockCharFormat(cf); + + cursor.insertText(text); + return true; +} + +bool Base::printDocImage(QTextDocument& doc, const QImage& image, const QString& title, const QString& description, + const qreal alreadyUsedHeight) const +{ + if (image.isNull()) + return false; + QTextCursor cursor(&doc); + + static int iImageCounter = 0; + QString name = QStringLiteral("printing://image_%1.png").arg(iImageCounter++); + doc.addResource(QTextDocument::ImageResource, QUrl(name), QVariant(image)); - if (!title.isEmpty()) - { QString htmlStr; - printTitleData(htmlStr, title); + if (!title.isEmpty()) + printTitleData(htmlStr, title); + if (!description.isEmpty()) + printTitleData(htmlStr, description, QLatin1String("h4")); + double rel = (double)image.height() / (double)image.width(); + + double dwMax = contentPageSize().width(); + double dhMax = contentPageSize().height() - alreadyUsedHeight; + if (!title.isEmpty()) + dhMax -= TitleDataHeight; + if (!description.isEmpty()) + dhMax -= DescriptionDataHeight; + double dh = dhMax; + double dw = dwMax; + + if (rel >= 1) + { + + double new_dw = dhMax / rel; + if (new_dw > dwMax) + { + + dh = dwMax * rel; + } + else + dw = new_dw; + } + else + { + + double new_dh = dw * rel; + if (new_dh > dhMax) + { + + dw = dhMax / rel; + } + else + dh = new_dh; + } + + QTextImageFormat tif; + tif.setName(name); + tif.setHeight(dh); + tif.setWidth(dw); + cursor.insertHtml(htmlStr); - } - cursor.insertBlock(); - - QTextBlockFormat bf = cursor.blockFormat(); - bf.setNonBreakableLines(false); - cursor.setBlockFormat(bf); - - QTextCharFormat cf = cursor.blockCharFormat(); - cf.setFontWeight(QFont::Normal); - cursor.setBlockCharFormat(cf); - - cursor.insertText(text); - return true; + cursor.insertImage(tif); + return true; } - -bool Base::printDocImage(QTextDocument &doc, const QImage &image, - const QString &title, const QString &description, const qreal alreadyUsedHeight) const +bool Base::printReportData(QTextDocument& doc, KDReports::Report& report) { - if (image.isNull()) - return false; - QTextCursor cursor(&doc); + QTextCursor cursor(&doc); + cursor.movePosition(QTextCursor::End); - static int iImageCounter = 0; - QString name = QStringLiteral("printing://image_%1.png").arg(iImageCounter++); - doc.addResource(QTextDocument::ImageResource, - QUrl(name), - QVariant(image)); - - QString htmlStr; - if (!title.isEmpty()) - printTitleData(htmlStr, title); - if (!description.isEmpty()) - printTitleData(htmlStr, description, QLatin1String("h4")); - double rel = (double)image.height() / (double)image.width(); - - double dwMax = contentPageSize().width(); - double dhMax = contentPageSize().height() - alreadyUsedHeight; - if (!title.isEmpty()) - dhMax -= TitleDataHeight; - if (!description.isEmpty()) - dhMax -= DescriptionDataHeight; - double dh = dhMax; - double dw = dwMax; - - if (rel >= 1) - { - - - double new_dw = dhMax / rel; - if (new_dw > dwMax) - { - - dh = dwMax * rel; - } - else - dw = new_dw; - } - else - { - - - double new_dh = dw * rel; - if (new_dh > dhMax) - { - - dw = dhMax / rel; - } - else - dh = new_dh; - } - - QTextImageFormat tif; - tif.setName(name); - tif.setHeight(dh); - tif.setWidth(dw); - - cursor.insertHtml(htmlStr); - cursor.insertImage(tif); - return true; + QTemporaryFile tempFile; + if (!tempFile.open()) + return false; + if (!report.exportToHtml(tempFile.fileName())) + return false; + cursor.insertHtml(QString::fromUtf8(tempFile.readAll())); + return true; } - -bool Base::printReportData(QTextDocument &doc, KDReports::Report &report ) -{ - QTextCursor cursor(&doc); - cursor.movePosition(QTextCursor::End); - - QTemporaryFile tempFile; - if (!tempFile.open()) - return false; - if (!report.exportToHtml(tempFile.fileName())) - return false; - cursor.insertHtml(QString::fromUtf8(tempFile.readAll())); - return true; -} - - QPrinter::PageSize Base::pageSize() const { - return m_printer->pageSize(); + return m_printer->pageSize(); } - void Base::setPageSize(QPrinter::PageSize size) { - m_printer->setPageSize(size); + m_printer->setPageSize(size); } - QPrinter::Orientation Base::orientation() const { - return m_printer->orientation(); + return m_printer->orientation(); } - void Base::setOrientation(QPrinter::Orientation orientation) { - m_printer->setOrientation(orientation); + m_printer->setOrientation(orientation); } - double Base::leftMargin() const { - return leftmargin_; + return leftmargin_; } - void Base::setLeftMargin(double margin) { - if ((margin > 0) && (margin < m_printer->paperRect().width() / 2)) - leftmargin_ = margin; - else - leftmargin_ = 0; + if ((margin > 0) && (margin < m_printer->paperRect().width() / 2)) + leftmargin_ = margin; + else + leftmargin_ = 0; } - double Base::rightMargin() const { - return rightmargin_; + return rightmargin_; } - void Base::setRightMargin(double margin) { - if ((margin > 0) && (margin < m_printer->paperRect().width() / 2)) - rightmargin_ = margin; - else - rightmargin_ = 0; + if ((margin > 0) && (margin < m_printer->paperRect().width() / 2)) + rightmargin_ = margin; + else + rightmargin_ = 0; } - double Base::topMargin() const { - return topmargin_; + return topmargin_; } - void Base::setTopMargin(double margin) { - if ((margin > 0) && (margin < m_printer->paperRect().height() / 4)) - topmargin_ = margin; - else - topmargin_ = 0; + if ((margin > 0) && (margin < m_printer->paperRect().height() / 4)) + topmargin_ = margin; + else + topmargin_ = 0; } - double Base::bottomMargin() const { - return bottommargin_; + return bottommargin_; } - void Base::setBottomMargin(double margin) { - if ((margin > 0) && (margin < m_printer->paperRect().height() / 4)) - bottommargin_ = margin; - else - bottommargin_ = 0; + if ((margin > 0) && (margin < m_printer->paperRect().height() / 4)) + bottommargin_ = margin; + else + bottommargin_ = 0; } - void Base::setMargins(double margin) { - if ((margin > 0) - && (margin < m_printer->paperRect().height() / 2) - && (margin < m_printer->paperRect().width() / 2)) - leftmargin_ = rightmargin_ = topmargin_ = bottommargin_ = margin; - else - leftmargin_ = rightmargin_ = topmargin_ = bottommargin_ = 0; + if ((margin > 0) && (margin < m_printer->paperRect().height() / 2) && (margin < m_printer->paperRect().width() / 2)) + leftmargin_ = rightmargin_ = topmargin_ = bottommargin_ = margin; + else + leftmargin_ = rightmargin_ = topmargin_ = bottommargin_ = 0; } - double Base::spacing() const { - return spacing_; + return spacing_; } - void Base::setSpacing(double spacing) { - if ((spacing > 0) && (spacing <= m_printer->paperRect().height() / 8)) - spacing_ = spacing; - else - spacing_ = 0; + if ((spacing > 0) && (spacing <= m_printer->paperRect().height() / 8)) + spacing_ = spacing; + else + spacing_ = 0; } - double Base::headerSize() const { - return headersize_; + return headersize_; } - void Base::setHeaderSize(double size) { - if ((size > 0) && (size <= m_printer->paperRect().height() / 8)) - headersize_ = size; - else - headersize_ = 0; + if ((size > 0) && (size <= m_printer->paperRect().height() / 8)) + headersize_ = size; + else + headersize_ = 0; } - double Base::headerRule() const { - return headerrule_; + return headerrule_; } - void Base::setHeaderRule(double pointsize) { - headerrule_ = qMax(0.0, pointsize); + headerrule_ = qMax(0.0, pointsize); } - -const QString &Base::headerText() const +const QString& Base::headerText() const { - return headertext_; + return headertext_; } - - - - - - - - - -void Base::setHeaderText(const QString &text) +void Base::setHeaderText(const QString& text) { - headertext_ = text; + headertext_ = text; } - double Base::footerSize() const { - return footersize_; + return footersize_; } - void Base::setFooterSize(double size) { - if ((size > 0) && (size <= m_printer->paperRect().height() / 8)) - footersize_ = size; - else - footersize_ = 0; + if ((size > 0) && (size <= m_printer->paperRect().height() / 8)) + footersize_ = size; + else + footersize_ = 0; } - double Base::footerRule() const { - return footerrule_; + return footerrule_; } - - void Base::setFooterRule(double pointsize) { - footerrule_ = qMax(0.0, pointsize); + footerrule_ = qMax(0.0, pointsize); } - -const QString &Base::footerText() const +const QString& Base::footerText() const { - return footertext_; + return footertext_; } - - - - - - - - -void Base::setFooterText(const QString &text) +void Base::setFooterText(const QString& text) { - footertext_ = text; + footertext_ = text; } - -void Base:: setItemFontSize(int itemFontSize) +void Base::setItemFontSize(int itemFontSize) { - itemFontSize_ = itemFontSize; + itemFontSize_ = itemFontSize; } - -QRectF Base::paperRect(QPaintDevice *device) +QRectF Base::paperRect(QPaintDevice* device) { - - QRectF rect = m_printer->paperRect(); - - rect.setWidth(rect.width() * - device->logicalDpiX() / m_printer->logicalDpiX()); - rect.setHeight(rect.height() * - device->logicalDpiY() / m_printer->logicalDpiY()); - return rect; + QRectF rect = m_printer->paperRect(); + + rect.setWidth(rect.width() * device->logicalDpiX() / m_printer->logicalDpiX()); + rect.setHeight(rect.height() * device->logicalDpiY() / m_printer->logicalDpiY()); + + return rect; } - -QRectF Base::contentRect(QPaintDevice *device) +QRectF Base::contentRect(QPaintDevice* device) { - - QRectF rect = paperRect(device); - rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), - mmToInches(topmargin_) * device->logicalDpiY(), - -mmToInches(rightmargin_) * device->logicalDpiX(), - -mmToInches(bottommargin_) * device->logicalDpiY()); + QRectF rect = paperRect(device); - - if (headersize_ > 0) - { - rect.adjust(0, mmToInches(headersize_) * device->logicalDpiY(), 0, 0); - rect.adjust(0, mmToInches(spacing_) * device->logicalDpiY(), 0, 0); - } - - if (footersize_ > 0) - { - rect.adjust(0, 0, 0, -mmToInches(footersize_) * device->logicalDpiY()); - rect.adjust(0, 0, 0, -mmToInches(spacing_) * device->logicalDpiY()); - } + rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), mmToInches(topmargin_) * device->logicalDpiY(), + -mmToInches(rightmargin_) * device->logicalDpiX(), -mmToInches(bottommargin_) * device->logicalDpiY()); - return rect; + if (headersize_ > 0) + { + rect.adjust(0, mmToInches(headersize_) * device->logicalDpiY(), 0, 0); + rect.adjust(0, mmToInches(spacing_) * device->logicalDpiY(), 0, 0); + } + + if (footersize_ > 0) + { + rect.adjust(0, 0, 0, -mmToInches(footersize_) * device->logicalDpiY()); + rect.adjust(0, 0, 0, -mmToInches(spacing_) * device->logicalDpiY()); + } + + return rect; } - -QRectF Base::headerRect(QPaintDevice *device) +QRectF Base::headerRect(QPaintDevice* device) { - QRectF rect = paperRect(device); - rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), - mmToInches(topmargin_) * device->logicalDpiY(), - -mmToInches(rightmargin_) * device->logicalDpiX(), 0); + QRectF rect = paperRect(device); + rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), mmToInches(topmargin_) * device->logicalDpiY(), + -mmToInches(rightmargin_) * device->logicalDpiX(), 0); - rect.setBottom(rect.top() + - mmToInches(headersize_) * device->logicalDpiY()); + rect.setBottom(rect.top() + mmToInches(headersize_) * device->logicalDpiY()); - return rect; + return rect; } - -QRectF Base::footerRect(QPaintDevice *device) +QRectF Base::footerRect(QPaintDevice* device) { - QRectF rect = paperRect(device); - rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), 0, - -mmToInches(rightmargin_) * device->logicalDpiX(), - -mmToInches(bottommargin_) * device->logicalDpiY()); + QRectF rect = paperRect(device); + rect.adjust(mmToInches(leftmargin_) * device->logicalDpiX(), 0, -mmToInches(rightmargin_) * device->logicalDpiX(), + -mmToInches(bottommargin_) * device->logicalDpiY()); - rect.setTop(rect.bottom() - - mmToInches(footersize_) * device->logicalDpiY()); + rect.setTop(rect.bottom() - mmToInches(footersize_) * device->logicalDpiY()); - return rect; + return rect; } - -void Base::print(QTextDocument *doc) +void Base::print(QTextDocument* doc) { - m_tempdoc = doc->clone(); - print(); - delete m_tempdoc; - m_tempdoc = nullptr; + m_tempdoc = doc->clone(); + print(); + delete m_tempdoc; + m_tempdoc = nullptr; } - - -void Base::printSinglePage(QTextDocument *doc) +void Base::printSinglePage(QTextDocument* doc) { - m_tempdoc = doc->clone(); - printSinglePage(); - delete m_tempdoc; - m_tempdoc = nullptr; + m_tempdoc = doc->clone(); + printSinglePage(); + delete m_tempdoc; + m_tempdoc = nullptr; } - void Base::printSinglePage() { - if (!m_printer || !m_tempdoc) return; + if (!m_printer || !m_tempdoc) + return; - m_tempdoc->setUseDesignMetrics(true); - m_tempdoc->documentLayout()->setPaintDevice(m_printer); - m_tempdoc->setPageSize(contentRect(m_printer).size()); - - QTextFrameFormat fmt = m_tempdoc->rootFrame()->frameFormat(); - fmt.setMargin(0); - m_tempdoc->rootFrame()->setFrameFormat(fmt); + m_tempdoc->setUseDesignMetrics(true); + m_tempdoc->documentLayout()->setPaintDevice(m_printer); + m_tempdoc->setPageSize(contentRect(m_printer).size()); - - + QTextFrameFormat fmt = m_tempdoc->rootFrame()->frameFormat(); + fmt.setMargin(0); + m_tempdoc->rootFrame()->setFrameFormat(fmt); - - int doccopies; - int pagecopies; - if (m_printer->collateCopies()) - { - doccopies = 1; - pagecopies = m_printer->numCopies(); - } - else - { - doccopies = m_printer->numCopies(); - pagecopies = 1; - } - - - int firstpage = m_printer->fromPage(); - int lastpage = m_printer->toPage(); - if (firstpage == 0 && lastpage == 0) - { - firstpage = 1; - lastpage = m_tempdoc->pageCount(); - } - - - bool ascending = true; - if (m_printer->pageOrder() == QPrinter::LastPageFirst) - { - int tmp = firstpage; - firstpage = lastpage; - lastpage = tmp; - ascending = false; - } - - - m_painter->setRenderHints(QPainter::Antialiasing | - QPainter::TextAntialiasing | - QPainter::SmoothPixmapTransform, true); - for (int dc = 0; dc < doccopies; dc++) - { - int pagenum = firstpage; - - while (true) + int doccopies; + int pagecopies; + if (m_printer->collateCopies()) { - for (int pc = 0; pc < pagecopies; pc++) - { - if (m_printer->printerState() == QPrinter::Aborted || - m_printer->printerState() == QPrinter::Error) - return; - - paintPage( m_tempdoc, pagenum); - if (pc < pagecopies - 1) - m_printer->newPage(); - } - if (pagenum == lastpage) - break; - if (ascending) - pagenum++; - else - pagenum--; - - { - m_printer->newPage(); - } + doccopies = 1; + pagecopies = m_printer->numCopies(); + } + else + { + doccopies = m_printer->numCopies(); + pagecopies = 1; } - if (dc < doccopies - 1) + int firstpage = m_printer->fromPage(); + int lastpage = m_printer->toPage(); + if (firstpage == 0 && lastpage == 0) { - m_printer->newPage(); + firstpage = 1; + lastpage = m_tempdoc->pageCount(); + } + + bool ascending = true; + if (m_printer->pageOrder() == QPrinter::LastPageFirst) + { + int tmp = firstpage; + firstpage = lastpage; + lastpage = tmp; + ascending = false; + } + + m_painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform, + true); + for (int dc = 0; dc < doccopies; dc++) + { + int pagenum = firstpage; + + while (true) + { + for (int pc = 0; pc < pagecopies; pc++) + { + if (m_printer->printerState() == QPrinter::Aborted || m_printer->printerState() == QPrinter::Error) + return; + + paintPage(m_tempdoc, pagenum); + if (pc < pagecopies - 1) + m_printer->newPage(); + } + if (pagenum == lastpage) + break; + if (ascending) + pagenum++; + else + pagenum--; + + { + m_printer->newPage(); + } + } + + if (dc < doccopies - 1) + { + m_printer->newPage(); + } } - } } - void Base::printDone() { - m_painter->end(); - m_currentPage = 1; + m_painter->end(); + m_currentPage = 1; } - - void Base::print() { - m_currentPage = 1; - printSinglePage(); - m_painter->end(); - m_currentPage = 1; + m_currentPage = 1; + printSinglePage(); + m_painter->end(); + m_currentPage = 1; } - - -void Base::paintPage(QTextDocument *document, - int pagenum) +void Base::paintPage(QTextDocument* document, int pagenum) { - QRectF rect; - double onepoint = m_painter->device()->logicalDpiY() / 72.0; + QRectF rect; + double onepoint = m_painter->device()->logicalDpiY() / 72.0; - - if (headersize_ > 0) - { - rect = headerRect(m_painter->device()); - if (headerrule_ > 0.0) + if (headersize_ > 0) { - m_painter->save(); - - m_painter->translate(0, onepoint + (headerrule_ * onepoint / 2.0)); - m_painter->setPen(QPen(Qt::black, headerrule_ * onepoint)); - m_painter->drawLine(rect.bottomLeft(), rect.bottomRight()); - m_painter->restore(); + rect = headerRect(m_painter->device()); + if (headerrule_ > 0.0) + { + m_painter->save(); + + m_painter->translate(0, onepoint + (headerrule_ * onepoint / 2.0)); + m_painter->setPen(QPen(Qt::black, headerrule_ * onepoint)); + m_painter->drawLine(rect.bottomLeft(), rect.bottomRight()); + m_painter->restore(); + } + + QString header = headertext_; + QString title = document->metaInformation(QTextDocument::DocumentTitle).remove(QLatin1String("[*]")); + header.replace(QLatin1String("&exercise;"), currentExerciseName()); + header.replace(QLatin1String("&title;"), title); + header.replace(QLatin1String("&logo;"), m_settings->logoProject()); + header.replace(QLatin1String("&logoHeight;"), QString::number(ProjectIconHeight)); + + m_painter->save(); + m_painter->translate(rect.left(), rect.top()); + QRectF clip(0, 0, rect.width(), rect.height()); + QTextDocument doc; + doc.setUseDesignMetrics(true); + doc.setHtml(header); + doc.documentLayout()->setPaintDevice(m_painter->device()); + doc.setPageSize(rect.size()); + + double newtop = clip.bottom() - doc.size().height(); + clip.setHeight(doc.size().height()); + m_painter->translate(0, newtop); + + doc.drawContents(m_painter, clip); + m_painter->restore(); } - - QString header = headertext_; - QString title = document->metaInformation(QTextDocument::DocumentTitle).remove(QLatin1String("[*]")); - header.replace(QLatin1String("&exercise;"), currentExerciseName()); - header.replace(QLatin1String("&title;"), title); - header.replace(QLatin1String("&logo;"), m_settings->logoProject()); - header.replace(QLatin1String("&logoHeight;"), QString::number(ProjectIconHeight)); - - - m_painter->save(); - m_painter->translate(rect.left(), rect.top()); - QRectF clip(0, 0, rect.width(), rect.height()); - QTextDocument doc; - doc.setUseDesignMetrics(true); - doc.setHtml(header); - doc.documentLayout()->setPaintDevice(m_painter->device()); - doc.setPageSize(rect.size()); - - - double newtop = clip.bottom() - doc.size().height(); - clip.setHeight(doc.size().height()); - m_painter->translate(0, newtop); - - doc.drawContents(m_painter, clip); - m_painter->restore(); - } - - - if (footersize_ > 0) - { - rect = footerRect(m_painter->device()); - if (footerrule_ > 0.0) + if (footersize_ > 0) { - m_painter->save(); - - m_painter->translate(0, -onepoint + (-footerrule_ * onepoint / 2.0)); - m_painter->setPen(QPen(Qt::black, footerrule_ * onepoint)); - m_painter->drawLine(rect.topLeft(), rect.topRight()); - m_painter->restore(); + rect = footerRect(m_painter->device()); + if (footerrule_ > 0.0) + { + m_painter->save(); + + m_painter->translate(0, -onepoint + (-footerrule_ * onepoint / 2.0)); + m_painter->setPen(QPen(Qt::black, footerrule_ * onepoint)); + m_painter->drawLine(rect.topLeft(), rect.topRight()); + m_painter->restore(); + } + + QString footer = footertext_; + footer.replace(QLatin1String("&date;"), + QObject::tr("Printed on: ") + DTG::toString(QDateTime::currentDateTime())); + footer.replace(QLatin1String("&user;"), operatorName()); + footer.replace(QLatin1String("&footertitle;"), footertitle_); + footer.replace(QLatin1String("&page;"), QString::number(m_currentPage++)); + + m_painter->save(); + m_painter->translate(rect.left(), rect.top()); + QRectF clip(0, 0, rect.width(), rect.height()); + QTextDocument doc; + doc.setUseDesignMetrics(true); + doc.setHtml(footer); + doc.documentLayout()->setPaintDevice(m_painter->device()); + doc.setPageSize(rect.size()); + doc.drawContents(m_painter, clip); + m_painter->restore(); } - - QString footer = footertext_; - footer.replace(QLatin1String("&date;"), QObject::tr("Printed on: ") + DTG::toString(QDateTime::currentDateTime()) ); - footer.replace(QLatin1String("&user;"), operatorName()); - footer.replace(QLatin1String("&footertitle;"), footertitle_); - footer.replace(QLatin1String("&page;"), QString::number(m_currentPage++)); - m_painter->save(); - m_painter->translate(rect.left(), rect.top()); - QRectF clip(0, 0, rect.width(), rect.height()); - QTextDocument doc; - doc.setUseDesignMetrics(true); - doc.setHtml(footer); - doc.documentLayout()->setPaintDevice(m_painter->device()); - doc.setPageSize(rect.size()); - doc.drawContents(m_painter, clip); + + rect = contentRect(m_painter->device()); + m_painter->translate(rect.left(), rect.top() - (pagenum - 1) * rect.height()); + QRectF clip(0, (pagenum - 1) * rect.height(), rect.width(), rect.height()); + + document->drawContents(m_painter, clip); + m_painter->restore(); - } - - - m_painter->save(); - - rect = contentRect(m_painter->device()); - m_painter->translate(rect.left(), rect.top() - (pagenum - 1) * rect.height()); - QRectF clip(0, (pagenum - 1) * rect.height(), rect.width(), rect.height()); - - document->drawContents(m_painter, clip); - - m_painter->restore(); } -void Base::setCurrentExerciseName( const QString& exerciseName ) +void Base::setCurrentExerciseName(const QString& exerciseName) { - m_exerciseName = exerciseName; + m_exerciseName = exerciseName; } - QString Base::currentExerciseName() const { - return m_exerciseName; + return m_exerciseName; } -void Base::setOperatorName( const QString& operatorName ) +void Base::setOperatorName(const QString& operatorName) { - m_operatorName = operatorName; + m_operatorName = operatorName; } - QString Base::operatorName() const { - return m_operatorName; + return m_operatorName; } - - QSize Base::pageSizeInMM() { - QRectF rect = contentRect(m_printer); - return rect.size().toSize(); + QRectF rect = contentRect(m_printer); + return rect.size().toSize(); } -} +} // namespace LtsPrinting diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.h old mode 100755 new mode 100644 index b7e05ccbf..ae079a054 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsPrinting/printing_base.h @@ -9,7 +9,8 @@ namespace NGL { class INGLLogger; class Settings; -} +} // namespace NGL + namespace KDReports { class Report; @@ -28,273 +29,201 @@ static constexpr int DECORATION_EXTENT = 50; static constexpr int DOC_MARGIN = 60; static constexpr int ProjectIconHeight = 40; +static const QLatin1String + HeaderText("" + " " + " " + " " + " " + " " + "
&exercise;&title;\"Logo\"
"); -static const QLatin1String HeaderText( - "" - " " - " " - " " - " " - " " - "
&exercise;&title;\"Logo\"
"); - -static const QLatin1String FooterText( - "" - " " - " " - " " - " " - " " - "
&date; -- &user;&footertitle;&page;
"); - +static const QLatin1String FooterText("" + " " + " " + " " + " " + " " + "
&date; -- &user;&footertitle;&page;
"); class Base { -public: - + public: + Base(QTextDocument& doc, QWidget* dialogParent, const QString& dialogTitle, const QString& _fn, + QPrinter::PaperSize _ps = QPrinter::A4, QPrinter::Orientation _or = QPrinter::Portrait, + QPrinter::ColorMode _cm = QPrinter::Color); - Base(QTextDocument &doc, - QWidget *dialogParent, - const QString &dialogTitle, - const QString &_fn, - QPrinter::PaperSize _ps = QPrinter::A4, - QPrinter::Orientation _or = QPrinter::Portrait, - QPrinter::ColorMode _cm = QPrinter::Color); + virtual ~Base(); - + QPrinter* printer(); - virtual ~Base(); + static void setPrintToFile(bool printToFile); - + static QString styleSheet(); - QPrinter *printer(); + QPrinter::PageSize pageSize() const; - + void setPageSize(QPrinter::PageSize size); - static void setPrintToFile(bool printToFile); + QPrinter::Orientation orientation() const; - + void setOrientation(QPrinter::Orientation orientation); - static QString styleSheet(); + bool newPage(); - - QPrinter::PageSize pageSize() const; - - void setPageSize(QPrinter::PageSize size); - - QPrinter::Orientation orientation() const; - - void setOrientation(QPrinter::Orientation orientation); + double leftMargin() const; - bool newPage(); + void setLeftMargin(double margin); - - 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 rightMargin() const; - - double spacing() const; - - void setSpacing(double spacing); + void setRightMargin(double margin); - - double headerSize() const; - - void setHeaderSize(double size); - - double headerRule() const; - - void setHeaderRule(double pointsize); - - const QString &headerText() const; - - void setHeaderText(const QString &text); + double topMargin() const; - - 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); + void setTopMargin(double margin); - + double bottomMargin() const; - static void printTitleData(QString &htmlStr, const QString &title, const QString &heading = QStringLiteral("h3")); + void setBottomMargin(double margin); - + void setMargins(double margin); - bool printListData(QString &str, - const QAbstractItemView *view, - const QString &title, - bool asIcons = false, - int iconExtent = DECORATION_EXTENT); - + double spacing() const; - bool printTableData(QString &str, - const QAbstractItemView *view, - const QString &title = QString(), - const QSet &suppressCols = QSet(), - int iconExtent = DECORATION_EXTENT); - + void setSpacing(double spacing); - bool printTreeData(QString &str, - const QAbstractItemView *view, - const QString &title = QString(), - const QSet &suppressCols = QSet(), - int iconExtent = DECORATION_EXTENT, - const QList &tabtexts = QList()); + double headerSize() const; - + void setHeaderSize(double size); - static bool printDocTextBlock(QTextDocument &doc, - const QString &text, - const QString &title = QString()); + double headerRule() const; - + void setHeaderRule(double pointsize); - bool printDocImage(QTextDocument &doc, const QImage &image, - const QString &title = QString(), const QString &description = QString(), const qreal alreadyUsedHeight = 0) const; + const QString& headerText() const; - + void setHeaderText(const QString& text); - static bool printReportData(QTextDocument &doc, KDReports::Report &report); + double footerSize() const; - + void setFooterSize(double size); - virtual void print(QTextDocument *doc); + double footerRule() const; + void setFooterRule(double pointsize); - virtual void printSinglePage(QTextDocument *doc); + const QString& footerText() const; + void setFooterText(const QString& text); - virtual void printDone(); - - - - - template - static QSet getHiddenCols(T *view) - { - QSet hiddenCols; - int colCount = view->model()->columnCount(); - for (int i = 0; i < colCount; ++i) + void setFooterTitle(const QString& footertitle) { - if (view->isColumnHidden(i)) - hiddenCols += i; + footertitle_ = footertitle; } - return hiddenCols; - } - + void setItemFontSize(int itemFontSize); - void setCurrentExerciseName( const QString& exerciseName ); + 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); - void setOperatorName( const QString& operatorName ); + bool printTableData(QString& str, const QAbstractItemView* view, const QString& title = QString(), + const QSet& suppressCols = QSet(), int iconExtent = DECORATION_EXTENT); - - void paintPage(QTextDocument *document, - int pagenum); + bool printTreeData(QString& str, const QAbstractItemView* view, const QString& title = QString(), + const QSet& suppressCols = QSet(), int iconExtent = DECORATION_EXTENT, + const QList& tabtexts = QList()); - QSize pageSizeInMM(); + static bool printDocTextBlock(QTextDocument& doc, const QString& text, const QString& title = QString()); -protected: + bool printDocImage(QTextDocument& doc, const QImage& image, const QString& title = QString(), + const QString& description = QString(), const qreal alreadyUsedHeight = 0) const; -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 &suppressCols = QSet(), - int iconExtent = DECORATION_EXTENT); - static int hierarchyCount(const QModelIndex &child); - QString iconFilename(int nr) const; - QSize printerPageSize() const; - QSize contentPageSize() const; + static bool printReportData(QTextDocument& doc, KDReports::Report& report); - QString currentExerciseName() const; - QString operatorName() const; + virtual void print(QTextDocument* doc); - - QRectF paperRect(QPaintDevice *device); - - QRectF contentRect(QPaintDevice *device); - QRectF headerRect(QPaintDevice *device); - QRectF footerRect(QPaintDevice *device); + virtual void printSinglePage(QTextDocument* doc); + virtual void printDone(); - - void printSinglePage(); - void print(); + template static QSet getHiddenCols(T* view) + { + QSet hiddenCols; + int colCount = view->model()->columnCount(); + for (int i = 0; i < colCount; ++i) + { + if (view->isColumnHidden(i)) + hiddenCols += i; + } + return hiddenCols; + } -private: - QPrinter *m_printer; - QPainter *m_painter; - static bool m_printToFile; - int m_iconFilenameNr; + void setCurrentExerciseName(const QString& exerciseName); - QTextDocument *m_tempdoc; + void setOperatorName(const QString& operatorName); - double leftmargin_; - double rightmargin_; - double topmargin_; - double bottommargin_; - double spacing_; + void paintPage(QTextDocument* document, int pagenum); - double headersize_; - double headerrule_; - QString headertext_; - double footersize_; - double footerrule_; - QString footertext_; - QString footertitle_; - int itemFontSize_; + QSize pageSizeInMM(); -private: - NGL::Settings *m_settings; - QString m_exerciseName; - QString m_operatorName; - int m_currentPage; + 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& suppressCols = QSet(), + 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.cpp old mode 100755 new mode 100644 index 7678fdc5a..a3b60419d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.cpp @@ -1,63 +1,56 @@ - #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* ClientMessageFactory::createMessage(LtsWebSocket::ReplyHandler* client, + const QString& message) { - LtsWebSocket::AbstractClientMessage *result = checkAttributes(client, message); + LtsWebSocket::AbstractClientMessage* result = checkAttributes(client, message); - if (result) - return result; + 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::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); + if (m_type == JsonKeys::LOGOUT_REQUEST()) + result = new LoginRequest(m_messageHandler, client, m_type, m_uuid, m_data); - return checkResult(client, message, result); + 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)); - } + 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; + 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()); + m_client->addReply(m_messageHandler->handleLogoutRequest()); } bool LogoutRequest::hasValidData() const { - return true; + return true; } - -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.h old mode 100755 new mode 100644 index 1ab4fe499..1a6a4aacb --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/client_message.h @@ -1,12 +1,10 @@ - #pragma once -#include - #include "logger.h" +#include namespace LtsProjectionWorkstation { @@ -14,52 +12,57 @@ class MessageHandler; class ClientMessageFactory : public LtsWebSocket::AbstractClientMessageFactory { -public: - explicit ClientMessageFactory(MessageHandler *messageHandler) - : LtsWebSocket::AbstractClientMessageFactory(getLogger("ClientMessageFactory")) - , m_messageHandler(messageHandler) - {} + public: + explicit ClientMessageFactory(MessageHandler* messageHandler) + : LtsWebSocket::AbstractClientMessageFactory(getLogger("ClientMessageFactory")), + m_messageHandler(messageHandler) + { + } - - LtsWebSocket::AbstractClientMessage *createMessage(LtsWebSocket::ReplyHandler *client, const QString &message) override final; + LtsWebSocket::AbstractClientMessage* createMessage(LtsWebSocket::ReplyHandler* client, + const QString& message) override final; -private: - MessageHandler *m_messageHandler; -}; + 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) - {} + 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; - -}; + 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) - {} + 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; -}; + 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) - {} + 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; -}; + void process(); + bool hasValidData() const; +}; -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/json_keys.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/json_keys.h index d301f1a80..12da29188 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/json_keys.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/json_keys.h @@ -4,32 +4,97 @@ #include -namespace LtsProjectionWorkstation::JsonKeys { +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 ERROR_MESSAGE() +{ + return QStringLiteral("errorMessage"); } -inline QString LOGIN_REPLY() { return QStringLiteral("loginReply"); } -inline QString LOGOUT_REPLY() { return QStringLiteral("logoutReply"); } -inline QString DEDICAED_DISCONNECT() { - return QStringLiteral("dedicatedDisconnect"); +inline QString LOGIN_REQUEST() +{ + return QStringLiteral("loginRequest"); } -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"); } +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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.cpp old mode 100755 new mode 100644 index e89573346..e24ffc172 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.cpp @@ -1,53 +1,53 @@ #include "message_factory.h" -#include "messages.h" + #include "json_keys.h" +#include "messages.h" #include #include - #include namespace LtsProjectionWorkstation { -LtsWebSocket::AbstractClientMessage *MessageFactory::createMessage(LtsWebSocket::ReplyHandler *client, const QString &message) +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 (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")); + } - if (result) - return result; + LtsWebSocket::AbstractClientMessage* result = checkAttributes(client, message); - if (m_type == JsonKeys::DEDICAED_DISCONNECT()) - result = new STC::DedicatedDisconnect(m_handler, client, m_type, m_uuid, m_data); + if (result) + return result; - if (m_type == JsonKeys::LOGIN_REPLY()) - result = new STC::LoginRequestReply(m_handler, client, m_type, m_uuid, m_data); + if (m_type == JsonKeys::DEDICAED_DISCONNECT()) + result = new STC::DedicatedDisconnect(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_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_REPLY()) + result = new STC::LoginRequestReply(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::LOGIN_REQUEST()) + result = new CTS::LoginRequest(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 == JsonKeys::LOGOUT_REQUEST()) + result = new CTS::LogoutRequest(m_handler, client, m_type, m_uuid, m_data); - if (m_type == LtsWebSocket::JsonKeys::ERROR_()) - return nullptr; + if (m_type == JsonKeys::DISCONNECT_REQUEST()) + result = new CTS::DisconnectRequest(m_handler, client, m_type, m_uuid, m_data); - return checkResult(client, message, result); + if (m_type == LtsWebSocket::JsonKeys::ERROR_()) + return nullptr; + + return checkResult(client, message, result); } -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.h old mode 100755 new mode 100644 index 635487422..9444c285c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/message_factory.h @@ -1,30 +1,29 @@ #pragma once -#include -#include - #include "ltsprojectionworkstation_export.h" +#include +#include + namespace LtsProjectionWorkstation { class AbstractMessageHandler; -class LTSPROJECTIONWORKSTATION_EXPORT MessageFactory - : public LtsWebSocket::AbstractClientMessageFactory +class LTSPROJECTIONWORKSTATION_EXPORT MessageFactory : public LtsWebSocket::AbstractClientMessageFactory { -public: - MessageFactory(AbstractMessageHandler *handler, LOGGER_T &logger) - : LtsWebSocket::AbstractClientMessageFactory(logger) - , m_handler(handler) - {} + public: + MessageFactory(AbstractMessageHandler* handler, LOGGER_T& logger) + : LtsWebSocket::AbstractClientMessageFactory(logger), m_handler(handler) + { + } - - LtsWebSocket::AbstractClientMessage *createMessage(LtsWebSocket::ReplyHandler *client, const QString &message) override final; + LtsWebSocket::AbstractClientMessage* createMessage(LtsWebSocket::ReplyHandler* client, + const QString& message) override final; -private: - AbstractMessageHandler *m_handler; + private: + AbstractMessageHandler* m_handler; }; -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.cpp old mode 100755 new mode 100644 index 01d47524a..1f7e3d4ba --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.cpp @@ -1,210 +1,205 @@ - #include "messages.h" -#include #include +#include namespace LtsProjectionWorkstation { - -STC::LoginRequestReply::LoginRequestReply(const QString &uuid, Reason reason, int reasonUserId, const QVector &screens) - : Message(nullptr, nullptr, JsonKeys::LOGIN_REPLY(), uuid, QJsonValue()) - , m_screens(screens) - , m_reasonUserId(reasonUserId) - , m_reason(reason) +STC::LoginRequestReply::LoginRequestReply(const QString& uuid, Reason reason, int reasonUserId, + const QVector& 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); + 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); + 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; + 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) +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; + 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); + 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; + 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) +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; + 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); + 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; + 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); + if (!m_handler || !m_client) + return; + m_handler->handleMessage(this); } - bool CTS::LogoutRequest::hasValidData() const { - if (!m_handler || !m_client) return false; - return true; + 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) +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; + 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); + 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; + if (!m_handler || !m_client) + return false; + QJsonObject obj = m_data.toObject(); + if (obj.value(JsonKeys::USER_ID()).isUndefined()) + return false; + return true; } - - -ErrorMessage::ErrorMessage(const QString &uuid, const QString &reason) - : Message(nullptr, nullptr, JsonKeys::ERROR_MESSAGE(), uuid, QJsonValue()) - , m_reason(reason) +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; + 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); + 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; + if (!m_handler || !m_client) + return false; + QJsonObject obj = m_data.toObject(); + if (obj.value(JsonKeys::REASON()).isUndefined()) + return false; + return true; } - -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.h old mode 100755 new mode 100644 index 5c0b0e860..15f39aa98 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/messages.h @@ -1,192 +1,209 @@ - #pragma once #include "json_keys.h" - -#include -#include - #include "ltsprojectionworkstation_export.h" -#include +#include +#include +#include #include -namespace LtsWebSocket { class ReplyHandler; } +namespace LtsWebSocket +{ +class ReplyHandler; +} namespace LtsProjectionWorkstation { class AbstractMessageHandler { -public: - virtual ~AbstractMessageHandler() = default; - virtual void handleMessage(LtsWebSocket::AbstractClientMessage *message) = 0; + 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); - } + 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) - {} + 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; - } + 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; - -}; + 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); + public: + using Message::Message; + ErrorMessage(const QString& uuid, const QString& reason); - - void process() override final; - bool hasValidData() const override final; + void process() override final; + bool hasValidData() const override final; -private: - QString m_reason; + private: + QString m_reason; }; -namespace STC +namespace STC { class LTSPROJECTIONWORKSTATION_EXPORT LoginRequestReply : public Message { -public: - enum Reason - { - LoginSuccessful, - OtherUser, - }; + public: + enum Reason { + LoginSuccessful, + OtherUser, + }; - using Message::Message; - LoginRequestReply(const QString &uuid, Reason reason, int reasonUserId, const QVector &screens); + using Message::Message; + LoginRequestReply(const QString& uuid, Reason reason, int reasonUserId, const QVector& screens); - - void process() override final; - bool hasValidData() const override final; + void process() override final; + bool hasValidData() const override final; - int reasonUserId() const { return m_reasonUserId; } - Reason reason() const { return m_reason; } - const QVector &screens() const { return m_screens; } + int reasonUserId() const + { + return m_reasonUserId; + } -private: - QVector m_screens; - int m_reasonUserId = -1; - Reason m_reason = LoginSuccessful; -}; + Reason reason() const + { + return m_reason; + } + + const QVector& screens() const + { + return m_screens; + } + + private: + QVector 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); + public: + using Message::Message; + DedicatedDisconnect(const QString& uuid, int userId); - - void process() override final; - bool hasValidData() const override final; + void process() override final; + bool hasValidData() const override final; - int userid() const { return m_userId; } + int userid() const + { + return m_userId; + } -private: - int m_userId = -1; + private: + int m_userId = -1; +}; -}; +} // namespace STC - -} - - -namespace CTS +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); + 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; + 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; } + int userId() const + { + return m_userId; + } -private: - QByteArray m_settingsData; - int m_userId = 0; - int m_priority = 0; - int m_exerciseId = 0; + 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()) - {} + public: + using Message::Message; - - void process() override final; - bool hasValidData() const override final; - -}; + 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); + public: + using Message::Message; + explicit DisconnectRequest(const QString& uuid, int userId); - - void process() override final; - bool hasValidData() const override final; + void process() override final; + bool hasValidData() const override final; - int userId() const { return m_userId; } -private: - int m_userId{0}; + int userId() const + { + return m_userId; + } -}; + private: + int m_userId{0}; +}; -} +} // namespace CTS -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.cpp old mode 100755 new mode 100644 index 6ca832899..83b1d4f60 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.cpp @@ -1,21 +1,20 @@ - #include "reply_message.h" namespace LtsProjectionWorkstation { -LoginReply::LoginReply(const QJsonObject &data, const QString &uuid) - : LtsWebSocket::ReplyMessage(JsonKeys::LOGIN_REPLY(), uuid) +LoginReply::LoginReply(const QJsonObject& data, const QString& uuid) + : LtsWebSocket::ReplyMessage(JsonKeys::LOGIN_REPLY(), uuid) { - m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data); + m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data); } -LogoutReply::LogoutReply(const QJsonObject &data, const QString &uuid) - : LtsWebSocket::ReplyMessage(JsonKeys::LOGOUT_REPLY(), uuid) +LogoutReply::LogoutReply(const QJsonObject& data, const QString& uuid) + : LtsWebSocket::ReplyMessage(JsonKeys::LOGOUT_REPLY(), uuid) { - m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data); + m_jsonRepresentation.insert(LtsWebSocket::JsonKeys::DATA(), data); } -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.h old mode 100755 new mode 100644 index e3f4235e7..65747f167 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/WebSocket/reply_message.h @@ -1,24 +1,23 @@ - #include "json_keys.h" -#include #include +#include namespace LtsProjectionWorkstation { class LoginReply : public LtsWebSocket::ReplyMessage { -public: - explicit LoginReply(const QJsonObject &data, const QString &uuid); -}; + public: + explicit LoginReply(const QJsonObject& data, const QString& uuid); +}; class LogoutReply : public LtsWebSocket::ReplyMessage { -public: - explicit LogoutReply(const QJsonObject &data, const QString &uuid); -}; + public: + explicit LogoutReply(const QJsonObject& data, const QString& uuid); +}; -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.cpp old mode 100755 new mode 100644 index 07b63f904..171c856e3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.cpp @@ -1,6 +1,5 @@ - #include "logger.h" #include @@ -8,25 +7,24 @@ namespace LtsProjectionWorkstation { -LOGGER_T getLogger(const char *name) +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); + 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(); - } + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception& ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.h old mode 100755 new mode 100644 index d5021abd1..9987a8b39 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/logger.h @@ -1,18 +1,19 @@ - #pragma once -#include #include "ltsprojectionworkstation_export.h" +#include + namespace LtsProjectionWorkstation { using LOGGER_T = NGL::INGLLogger&; -LTSPROJECTIONWORKSTATION_EXPORT LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) +LTSPROJECTIONWORKSTATION_EXPORT LOGGER_T getLogger(const char* name); + +inline LOGGER_T getLogger(const QString& loggerName) { - return getLogger(loggerName.toUtf8().constData()); + return getLogger(loggerName.toUtf8().constData()); } -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.cpp old mode 100755 new mode 100644 index 72e6a8dfc..efc51699e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.cpp @@ -1,247 +1,225 @@ - #include "lts_projection_workstation.h" -#include -#include "WebSocket/message_factory.h" + #include "WebSocket/json_keys.h" +#include "WebSocket/message_factory.h" -#include #include - -#include - +#include #include +#include #include #include -#include +#include +#include namespace LtsProjectionWorkstation { -static LtsProjectionWorkstation *s_ltsProjectionWorkstation = nullptr; +static LtsProjectionWorkstation* s_ltsProjectionWorkstation = nullptr; -LtsProjectionWorkstation *LtsProjectionWorkstation::getInstance() +LtsProjectionWorkstation* LtsProjectionWorkstation::getInstance() { - if (!s_ltsProjectionWorkstation) - { - s_ltsProjectionWorkstation = new LtsProjectionWorkstation; - qAddPostRoutine(&cleanupLtsProjectionWorkstation); - } - return s_ltsProjectionWorkstation; + if (!s_ltsProjectionWorkstation) + { + s_ltsProjectionWorkstation = new LtsProjectionWorkstation; + qAddPostRoutine(&cleanupLtsProjectionWorkstation); + } + return s_ltsProjectionWorkstation; } void LtsProjectionWorkstation::cleanupLtsProjectionWorkstation() { - delete s_ltsProjectionWorkstation; - s_ltsProjectionWorkstation = nullptr; + delete s_ltsProjectionWorkstation; + s_ltsProjectionWorkstation = nullptr; } bool LtsProjectionWorkstation::hasInstance() { - return !!s_ltsProjectionWorkstation; + return !!s_ltsProjectionWorkstation; } -LtsProjectionWorkstation::LtsProjectionWorkstation(QObject *parent) - : QObject(parent) - , 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)) +LtsProjectionWorkstation::LtsProjectionWorkstation(QObject* parent) + : QObject(parent), 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); + 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); + 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(); - } + 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; + delete m_vncManager; + delete m_messageFactory; + delete m_webSocketServer; } LoginInformation LtsProjectionWorkstation::pendingLoginRequest() { - if (!m_pendingLoginRequest) - return {}; + if (!m_pendingLoginRequest) + return {}; - LoginInformation result = *m_pendingLoginRequest; + LoginInformation result = *m_pendingLoginRequest; - INFO_LOG(m_logger) << " reset pendingLoginRequest.."; + INFO_LOG(m_logger) << " reset pendingLoginRequest.."; - delete m_pendingLoginRequest; - m_pendingLoginRequest = nullptr; + delete m_pendingLoginRequest; + m_pendingLoginRequest = nullptr; - return result; + return result; } -void LtsProjectionWorkstation::handleMessage(LtsWebSocket::AbstractClientMessage *message) +void LtsProjectionWorkstation::handleMessage(LtsWebSocket::AbstractClientMessage* message) { - CTS::LoginRequest *login = dynamic_cast(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) + CTS::LoginRequest* login = dynamic_cast(message); + if (login) { - - 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() ); + 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; - - - DEBUG_LOG(m_logger) << "Login request received and DedicatedDisconnect distributed, wait some seconds..."; - int i=0; - while(i<20) + if (login->userId() > 0 && login->priority() > 0 && login->exerciseId() > 0) { - DEBUG_LOG(m_logger) << "Login request received and DedicatedDisconnect distributed, wait some seconds...i=" << i; - qApp->processEvents(QEventLoop::AllEvents, 50); - QThread::msleep(50); - ++i; + + 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())) + ->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; + } } - INFO_LOG(m_logger) << "Login request received and DedicatedDisconnect distributed, wait some seconds... done"; + else + ERROR_LOG(m_logger) << "invalid login request received -> userId: " << login->userId() + << " priority: " << login->priority() << " exerciseId: " << login->exerciseId(); - - 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()) - )->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; - } + return; } - else - ERROR_LOG(m_logger) << "invalid login request received -> userId: " << login->userId() - << " priority: " << login->priority() - << " exerciseId: " << login->exerciseId(); - return; - } + CTS::LogoutRequest* logout = dynamic_cast(message); + if (logout) + { + DEBUG_LOG(m_logger) << "Logging out now!"; + slotLogoutRequestReceived(); + return; + } - CTS::LogoutRequest *logout = dynamic_cast(message); - if (logout) - { - DEBUG_LOG(m_logger) << "Logging out now!"; - slotLogoutRequestReceived(); - return; - } + CTS::DisconnectRequest* discon = dynamic_cast(message); + if (discon) + { - CTS::DisconnectRequest *discon = dynamic_cast(message); - if (discon) - { - - - - - - - - - int disconnectingUserId = discon->userId(); - INFO_LOG(m_logger) << "Disconnecting now! " - << ", disconnectingUserId=" << disconnectingUserId - << ", m_pendingLoginRequest=" << m_pendingLoginRequest; - m_lastLoginRequest = LoginInformation(); - return; - } + 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); + 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(); + emit signalLogoutRequestReceived(); } - void LtsProjectionWorkstation::slotLogoffDone() { - if (hasPendingLoginRequest()) - return; - for (LtsWebSocket::ClientConnection *con : std::as_const(m_connections)) - con->webSocket()->close(); + if (hasPendingLoginRequest()) + return; + for (LtsWebSocket::ClientConnection* con : std::as_const(m_connections)) + con->webSocket()->close(); } - -void LtsProjectionWorkstation::clientDisconnected(LtsWebSocket::ClientConnection *client) +void LtsProjectionWorkstation::clientDisconnected(LtsWebSocket::ClientConnection* client) { - INFO_LOG(m_logger) << Q_FUNC_INFO << " START" - << ", m_connections.size = " << m_connections.size(); + 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(); + 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) +void LtsProjectionWorkstation::clientConnected(LtsWebSocket::ClientConnection* client) { - m_connections.append(client); + m_connections.append(client); } -void LtsProjectionWorkstation::setProjectionOperatorPreset(const QString &operatorName, const QString &operatorPassword) +void LtsProjectionWorkstation::setProjectionOperatorPreset(const QString& operatorName, const QString& operatorPassword) { - m_projectionOperatorPreset.first = operatorName; - m_projectionOperatorPreset.second = operatorPassword; + m_projectionOperatorPreset.first = operatorName; + m_projectionOperatorPreset.second = operatorPassword; } -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.h old mode 100755 new mode 100644 index d5cfe7a48..42ca9c152 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation.h @@ -1,84 +1,101 @@ - #pragma once -#include "ltsprojectionworkstation_export.h" -#include "vnc_server_manager.h" #include "WebSocket/messages.h" #include "logger.h" +#include "ltsprojectionworkstation_export.h" +#include "vnc_server_manager.h" #include - #include #include -namespace LtsWebSocket { class LtsWebSocketServer; } +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) {} + LoginInformation() = default; - QByteArray m_settingsData; - int m_userId = 0; - int m_priority = 0; - int m_exerciseId = 0; + 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 + Q_OBJECT -public: - static LtsProjectionWorkstation *getInstance(); - static bool hasInstance(); + 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 &projectionOperatorPreset() const { return m_projectionOperatorPreset; } + const LoginInformation& lastLoginRequest() const + { + return m_lastLoginRequest; + } - - void handleMessage(LtsWebSocket::AbstractClientMessage *message) override final; + LoginInformation pendingLoginRequest(); -public slots: - void slotLoginRequestReceived(int userId, int exerciseId); - void slotLogoutRequestReceived(); + bool hasPendingLoginRequest() const + { + return !!m_pendingLoginRequest; + } - void slotLogoffDone(); + void setProjectionOperatorPreset(const QString& operatorName, const QString& operatorPassword); -signals: - void signalLoginRequestReceived(int userId, int exerciseId); - void signalLogoutRequestReceived(); + const QPair& projectionOperatorPreset() const + { + return m_projectionOperatorPreset; + } -private slots: - void clientDisconnected(LtsWebSocket::ClientConnection* client); - void clientConnected(LtsWebSocket::ClientConnection* client); + void handleMessage(LtsWebSocket::AbstractClientMessage* message) override final; -private: - explicit LtsProjectionWorkstation(QObject *parent = nullptr); - ~LtsProjectionWorkstation(); - static void cleanupLtsProjectionWorkstation(); + public slots: + void slotLoginRequestReceived(int userId, int exerciseId); + void slotLogoutRequestReceived(); - LOGGER_T m_logger; - MessageFactory *m_messageFactory; - LtsWebSocket::LtsWebSocketServer *m_webSocketServer; + void slotLogoffDone(); + signals: + void signalLoginRequestReceived(int userId, int exerciseId); + void signalLogoutRequestReceived(); - LoginInformation m_lastLoginRequest; + private slots: + void clientDisconnected(LtsWebSocket::ClientConnection* client); + void clientConnected(LtsWebSocket::ClientConnection* client); - LoginInformation *m_pendingLoginRequest; - QPair m_projectionOperatorPreset; + private: + explicit LtsProjectionWorkstation(QObject* parent = nullptr); + ~LtsProjectionWorkstation(); + static void cleanupLtsProjectionWorkstation(); - QVector m_connections; + LOGGER_T m_logger; + MessageFactory* m_messageFactory; + LtsWebSocket::LtsWebSocketServer* m_webSocketServer; - VncServerManager *m_vncManager; -}; + LoginInformation m_lastLoginRequest; -} + LoginInformation* m_pendingLoginRequest; + QPair m_projectionOperatorPreset; + + QVector m_connections; + + VncServerManager* m_vncManager; +}; + +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation_export.h old mode 100755 new mode 100644 index a65af195b..133e5df14 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/lts_projection_workstation_export.h @@ -5,13 +5,13 @@ #include #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 +#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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.cpp old mode 100755 new mode 100644 index 50dfa8724..aad8444e4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.cpp @@ -1,195 +1,179 @@ - #include "vnc_server_manager.h" -#include +#include #include #include -#include +#include namespace LtsProjectionWorkstation { -VncServerManager::VncServerManager(LOGGER_T &logger, QObject *parent) - : QObject(parent) - , m_logger(logger) -{ -} - +VncServerManager::VncServerManager(LOGGER_T& logger, QObject* parent) : QObject(parent), m_logger(logger) {} VncServerManager::~VncServerManager() { - stopScreens(); + stopScreens(); } -QList sortScreen(const QList &screens) +QList sortScreen(const QList& 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; + 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 &screens) +bool VncServerManager::init(const QList& screens) { - killScreens(); - createPwdFile(); + killScreens(); + createPwdFile(); - const auto sortedScreens = sortScreen(screens); + const auto sortedScreens = sortScreen(screens); - DEBUG_LOG(m_logger) << "Setup VNCScreens with " << screens.size() << " screens"; + DEBUG_LOG(m_logger) << "Setup VNCScreens with " << screens.size() << " screens"; - int count = 1; + int count = 1; - static constexpr char VNC_START_ARGS[] = "-rfbauth,%1/.vnc/passwd,-clip,%2x%3+%4+%5,-loop100,-forever,-display,:0,-threads,-noxdamage"; + 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()); + for (QScreen* screen : sortedScreens) + { + VncScreen vncScreen; - vncScreen.proc->setProgram(QStringLiteral("x11vnc")); - vncScreen.proc->setArguments(startArgs.split(QLatin1Char(','))); + 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()); - NOTICE_LOG(m_logger) << "Started VNC for Screen " << count << " with geometry " - << screen->geometry().width() << "," << screen->geometry().height() << "+" - << screen->geometry().x() << "+" << screen->geometry().y(); + vncScreen.proc->setProgram(QStringLiteral("x11vnc")); + vncScreen.proc->setArguments(startArgs.split(QLatin1Char(','))); - m_vncScreens.push_back(vncScreen); - count++; - } + NOTICE_LOG(m_logger) << "Started VNC for Screen " << count << " with geometry " << screen->geometry().width() + << "," << screen->geometry().height() << "+" << screen->geometry().x() << "+" + << screen->geometry().y(); - DEBUG_LOG(m_logger) << m_vncScreens.size() << " VNCScreen(s) created - Setup completed."; - return true; + 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"; + 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) ..."; + 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"; + 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"; -} + 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"; -} + 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(QObject::sender()); - if (!p) - return; + QProcess* p = qobject_cast(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.capturedRef(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; - } + 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.capturedRef(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(QObject::sender()); - if (p) - ERROR_LOG(m_logger) << p->errorString(); + QProcess* p = qobject_cast(QObject::sender()); + if (p) + ERROR_LOG(m_logger) << p->errorString(); } - - - -SingleShotProcess::SingleShotProcess(const QString &cmd, bool startImmediatly) - : m_cmd(cmd) +SingleShotProcess::SingleShotProcess(const QString& cmd, bool startImmediatly) : m_cmd(cmd) { - if (startImmediatly) execute(); + if (startImmediatly) + execute(); } bool SingleShotProcess::execute() { - m_process.start(m_cmd); - return m_process.waitForFinished(); + m_process.start(m_cmd); + return m_process.waitForFinished(); } - - -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.h old mode 100755 new mode 100644 index 3e1f01441..5b45b7581 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsProjectionWorkstation/vnc_server_manager.h @@ -1,16 +1,15 @@ - #pragma once +#include "logger.h" + #include #include #include #include #include -#include "logger.h" - class QScreen; namespace LtsProjectionWorkstation @@ -18,52 +17,51 @@ namespace LtsProjectionWorkstation class SingleShotProcess { -public: - explicit SingleShotProcess(const QString &cmd, bool startImmediatly = false); + public: + explicit SingleShotProcess(const QString& cmd, bool startImmediatly = false); - bool execute(); + bool execute(); -private: - QProcess m_process; - QString m_cmd; + private: + QProcess m_process; + QString m_cmd; }; - struct VncScreen { - QString name; - QProcess *proc = nullptr; - QRect geometry; - quint16 port = 0; + 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); + Q_OBJECT + public: + explicit VncServerManager(LOGGER_T& logger, QObject* parent = nullptr); - ~VncServerManager(); + ~VncServerManager(); - bool init(const QList &screens); + bool init(const QList& screens); - const QVector &screens() const { return m_vncScreens; } + const QVector& screens() const + { + return m_vncScreens; + } - + void startScreens(); + void stopScreens(); + void killScreens(); + void createPwdFile(); - void startScreens(); - void stopScreens(); - void killScreens(); - void createPwdFile(); + private slots: + void slotReadStandardOutput(); + void slotErrorOccured(); -private slots: - void slotReadStandardOutput(); - void slotErrorOccured(); - -private: - QVector m_vncScreens; - LOGGER_T &m_logger; + private: + QVector m_vncScreens; + LOGGER_T& m_logger; }; -} +} // namespace LtsProjectionWorkstation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/main.cpp old mode 100755 new mode 100644 index 30c682cea..b3ae2de25 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/main.cpp @@ -1,12 +1,12 @@ #include "mainwindow.h" + #include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - QApplication a(argc, argv); - MainWindow w; - w.show(); - - return a.exec(); + QApplication a(argc, argv); + MainWindow w; + w.show(); + + return a.exec(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.cpp old mode 100755 new mode 100644 index f5acea730..3f3a25b9f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.cpp @@ -1,104 +1,86 @@ #include "mainwindow.h" + #include "ui_mainwindow.h" #include - -#include #include +#include - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent) - , ui(new Ui::MainWindow) - , m_selectedTe(nullptr) - , m_currentNewTopicEditor(nullptr) - , m_currentEditTopicEditor(nullptr) +MainWindow::MainWindow(QWidget* parent) + : QMainWindow(parent), ui(new Ui::MainWindow), m_selectedTe(nullptr), m_currentNewTopicEditor(nullptr), + m_currentEditTopicEditor(nullptr) { - ui->setupUi(this); + ui->setupUi(this); - ui->masterSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->masterSplitter), 20); - ui->masterSplitter->setStretchFactor(ui->masterSplitter->indexOf(ui->toolBox), 0); + 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); + 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->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; - 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; - 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!"; - + 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; + if (!m_selectedTe) + return; - m_selectedTe = nullptr; + m_selectedTe = nullptr; + + if (m_currentEditTopicEditor) + { + + delete m_currentEditTopicEditor; + m_currentEditTopicEditor = nullptr; + ui->lblNoTopicSelected->setVisible(true); + } - if (m_currentEditTopicEditor) - { - - delete m_currentEditTopicEditor; - m_currentEditTopicEditor = nullptr; ui->lblNoTopicSelected->setVisible(true); - } - - ui->lblNoTopicSelected->setVisible(true); } - -void MainWindow::slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry *te) +void MainWindow::slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry* te) { - qDeleteAll(ui->topicEditorTab->layout()->children()); - disconnectTrackEntry(); + qDeleteAll(ui->topicEditorTab->layout()->children()); + disconnectTrackEntry(); - if (!te) - return; + if (!te) + return; - ui->lblNoTopicSelected->setVisible(false); + ui->lblNoTopicSelected->setVisible(false); - m_selectedTe = te; + 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); + 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; + delete ui; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.h old mode 100755 new mode 100644 index e24da1631..b5f8facf7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/Test/mainwindow.h @@ -1,7 +1,6 @@ #pragma once -#include - #include +#include namespace Ui { @@ -13,23 +12,22 @@ namespace LtsScriptTimeline class TrackEntry; } - class MainWindow : public QMainWindow { - Q_OBJECT - -public: - explicit MainWindow(QWidget *parent = 0); - ~MainWindow(); + Q_OBJECT -private: - Ui::MainWindow *ui; - LtsScriptTimeline::TrackEntry *m_selectedTe; - QWidget *m_currentNewTopicEditor; - QWidget *m_currentEditTopicEditor; + public: + explicit MainWindow(QWidget* parent = 0); + ~MainWindow(); - void disconnectTrackEntry(); + private: + Ui::MainWindow* ui; + LtsScriptTimeline::TrackEntry* m_selectedTe; + QWidget* m_currentNewTopicEditor; + QWidget* m_currentEditTopicEditor; -private slots: - void slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry *te); + void disconnectTrackEntry(); + + private slots: + void slotTrackEntrySelectionChanged(LtsScriptTimeline::TrackEntry* te); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.cpp old mode 100755 new mode 100644 index 988a14c3e..7dec09903 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.cpp @@ -1,190 +1,163 @@ #include "filter_background_widget.h" -#include "track_content_widget.h" -#include "tools.h" -#include "track_entry.h" + #include "script_timeline.h" +#include "tools.h" +#include "track_content_widget.h" +#include "track_entry.h" #include - namespace LtsScriptTimeline { -FilterBackgroundWidget::FilterBackgroundWidget(QWidget *parent) - : QWidget(parent) - , m_readonly(false) - , m_scriptTimeline(nullptr) - , m_tools(nullptr) - , m_trackWidget(nullptr) +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; + m_readonly = readonly; - for (auto i = m_filterContentWidgets.begin(); i != m_filterContentWidgets.end(); ++i) - { - TrackContentWidget *tcw = *i; - tcw->setReadonly(readonly); - } + for (auto i = m_filterContentWidgets.begin(); i != m_filterContentWidgets.end(); ++i) + { + TrackContentWidget* tcw = *i; + tcw->setReadonly(readonly); + } } - -void FilterBackgroundWidget::paintEvent(QPaintEvent *event) +void FilterBackgroundWidget::paintEvent(QPaintEvent* event) { - (void)event; + (void)event; - QPainter painter(this); + QPainter painter(this); - painter.save(); + painter.save(); - painter.setBrush(QColor("lightgray")); - painter.drawRect(rect()); + painter.setBrush(QColor("lightgray")); + painter.drawRect(rect()); - painter.restore(); + painter.restore(); } - -void FilterBackgroundWidget::setTools(Tools *tools) +void FilterBackgroundWidget::setTools(Tools* tools) { - m_tools = tools; + m_tools = tools; } - -void FilterBackgroundWidget::adjustFilterContentWidgets(const TrackEntry *te) +void FilterBackgroundWidget::adjustFilterContentWidgets(const TrackEntry* te) { - TrackContentWidget *tcw = m_filterContentWidgets.value(te->m_topicId, nullptr); + TrackContentWidget* tcw = m_filterContentWidgets.value(te->m_topicId, nullptr); - if (tcw == nullptr) - { - trackEntryAdded(te); - return; - } + if (tcw == nullptr) + { + trackEntryAdded(te); + return; + } - QRect currentGeo = tcw->geometry(); - int currentX = currentGeo.x(); - int currentWidth = currentGeo.width(); + 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); - int x = m_tools->getPos(te->m_startTime); - int width = m_tools->getLength(te->m_startTime, te->m_length); + if (currentX != x || currentWidth != width) + { - if (currentX != x || currentWidth != width) - { - - tcw->setGeometry(x, currentGeo.y(), width, currentGeo.height()); - - } - else - { - - } + tcw->setGeometry(x, currentGeo.y(), width, currentGeo.height()); + } + else + { + } } - void FilterBackgroundWidget::slotChangesMade() { - QObject *tcwObj = sender(); - TrackContentWidget *tcw = qobject_cast(tcwObj); + QObject* tcwObj = sender(); + TrackContentWidget* tcw = qobject_cast(tcwObj); - if (tcw == nullptr) - { - return; - } + if (tcw == nullptr) + { + return; + } - int topicId = m_filterContentWidgets.key(tcw, -1); + int topicId = m_filterContentWidgets.key(tcw, -1); - if (topicId == -1) - { - return; - } + if (topicId == -1) + { + return; + } - emit signalChangesMade(topicId); + emit signalChangesMade(topicId); } - void FilterBackgroundWidget::trackEntryDeleted(const int topicId) { - auto fcwI = m_filterContentWidgets.find(topicId); + auto fcwI = m_filterContentWidgets.find(topicId); - if (fcwI != m_filterContentWidgets.end()) - { - TrackContentWidget *tcw = *fcwI; - m_filterContentWidgets.erase(fcwI); - tcw->deleteLater(); - } + if (fcwI != m_filterContentWidgets.end()) + { + TrackContentWidget* tcw = *fcwI; + m_filterContentWidgets.erase(fcwI); + tcw->deleteLater(); + } } - -void FilterBackgroundWidget::addFilterEntry(TrackEntry *main, TrackEntry *filter) +void FilterBackgroundWidget::addFilterEntry(TrackEntry* main, TrackEntry* filter) { - auto fcwI = m_filterContentWidgets.find(main->m_topicId); + auto fcwI = m_filterContentWidgets.find(main->m_topicId); - if (fcwI != m_filterContentWidgets.end()) - { - TrackContentWidget *tcw = *fcwI; - tcw->addTrackEntry(filter, false); - emit tcw->signalChangesMade(); - } + if (fcwI != m_filterContentWidgets.end()) + { + TrackContentWidget* tcw = *fcwI; + tcw->addTrackEntry(filter, false); + emit tcw->signalChangesMade(); + } } - -void FilterBackgroundWidget::trackEntryAdded(const TrackEntry *te) +void FilterBackgroundWidget::trackEntryAdded(const TrackEntry* te) { - auto fcwI = m_filterContentWidgets.find(te->m_topicId); + auto fcwI = m_filterContentWidgets.find(te->m_topicId); - if (fcwI == m_filterContentWidgets.end()) - { - TrackContentWidget *tcw = new TrackContentWidget(this, true, m_tools, 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(); + 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::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); + 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); - } + m_filterContentWidgets.insert(te->m_topicId, tcw); + } - adjustFilterContentWidgets(te); + adjustFilterContentWidgets(te); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.h old mode 100755 new mode 100644 index 49f08a4bf..437802726 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_background_widget.h @@ -1,11 +1,9 @@ #pragma once -#include - #include "track_content_widget.h" -#include #include - +#include +#include namespace LtsScriptTimeline { @@ -13,42 +11,55 @@ class TrackEntry; class ScriptTimeline; class Tools; - class FilterBackgroundWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit FilterBackgroundWidget(QWidget *parent = nullptr); - const QMap &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; } + public: + explicit FilterBackgroundWidget(QWidget* parent = nullptr); -signals: - void signalChangesMade(int topicId); - void signalUnselectAll(); - void signalTrackEntrySelectionChanged(TrackEntry *te); - void signalTrackEntryDeleted(const int topicId); - void signalEditEntry(const int topicId); + const QMap& filterContentWidgets() const + { + return m_filterContentWidgets; + } -private slots: - void slotChangesMade(); + 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); -private: - QMap m_filterContentWidgets; - bool m_readonly; - ScriptTimeline *m_scriptTimeline; - Tools *m_tools; - TrackWidget *m_trackWidget; + void setScriptTimeline(ScriptTimeline* scriptTimeline) + { + m_scriptTimeline = scriptTimeline; + } -protected: - void paintEvent(QPaintEvent *event); + 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 m_filterContentWidgets; + bool m_readonly; + ScriptTimeline* m_scriptTimeline; + Tools* m_tools; + TrackWidget* m_trackWidget; + + protected: + void paintEvent(QPaintEvent* event); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.cpp old mode 100755 new mode 100644 index df74bf358..b46230842 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.cpp @@ -1,155 +1,107 @@ #include "filter_track_widget.h" -#include "ui_filter_track_widget.h" -#include "track_entry.h" -#include "script_timeline.h" -#include +#include "script_timeline.h" +#include "track_entry.h" +#include "ui_filter_track_widget.h" + #include #include +#include #include - 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) +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(); + ui->setupUi(this); + ui->cbSelect->hide(); - setReadonly(readonly); - setBaseWidth(baseWidth); + setReadonly(readonly); + setBaseWidth(baseWidth); - connect(ui->pbDelete, &QPushButton::clicked, - this, &FilterTrackWidget::signalDeleteMe); + 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); + 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; - + + delete ui; } - -void FilterTrackWidget::setTrackWidget(TrackWidget *trackWidget) +void FilterTrackWidget::setTrackWidget(TrackWidget* trackWidget) { - m_trackWidget = trackWidget; - ui->fbw->setTrackWidget(trackWidget); + m_trackWidget = trackWidget; + ui->fbw->setTrackWidget(trackWidget); } - void FilterTrackWidget::setReadonly(bool readonly) { - m_readonly = readonly; - ui->pbDelete->setVisible(!readonly); - ui->fbw->setReadonly(readonly); + m_readonly = readonly; + ui->pbDelete->setVisible(!readonly); + ui->fbw->setReadonly(readonly); } - -void FilterTrackWidget::setTools(Tools *tools) +void FilterTrackWidget::setTools(Tools* tools) { - m_tools = tools; - ui->fbw->setTools(tools); + m_tools = tools; + ui->fbw->setTools(tools); } - -void FilterTrackWidget::setScriptTimeline(ScriptTimeline *scriptTimeline) +void FilterTrackWidget::setScriptTimeline(ScriptTimeline* scriptTimeline) { - m_scriptTimeline = scriptTimeline; - ui->fbw->setScriptTimeline(m_scriptTimeline); + m_scriptTimeline = scriptTimeline; + ui->fbw->setScriptTimeline(m_scriptTimeline); } - -FilterBackgroundWidget *FilterTrackWidget::fbw() +FilterBackgroundWidget* FilterTrackWidget::fbw() { - return ui->fbw; + return ui->fbw; } -const FilterBackgroundWidget *FilterTrackWidget::fbw() const +const FilterBackgroundWidget* FilterTrackWidget::fbw() const { - return ui->fbw; + return ui->fbw; } - - - - - - - void FilterTrackWidget::setBaseWidth(int width) { - ui->left->setMinimumWidth(width); - ui->left->setMaximumWidth(width); + ui->left->setMinimumWidth(width); + ui->left->setMaximumWidth(width); } - -void FilterTrackWidget::addFilterEntry(TrackEntry *main, TrackEntry *filter) +void FilterTrackWidget::addFilterEntry(TrackEntry* main, TrackEntry* filter) { - filter->m_topicId = m_scriptTimeline->nextUniqueId(); - ui->fbw->addFilterEntry(main, 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() -{ - + return (ui->cbSelect->checkState() == Qt::CheckState::Checked); } +void FilterTrackWidget::unselectAll() {} void FilterTrackWidget::updateMe() { - update(); - + update(); } - - - - - - - -void FilterTrackWidget::paintEvent(QPaintEvent *event) +void FilterTrackWidget::paintEvent(QPaintEvent* event) { - - - - - - - - - - - - QWidget::paintEvent(event); + QWidget::paintEvent(event); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.h old mode 100755 new mode 100644 index f4224d71c..960c7fd7e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/filter_track_widget.h @@ -1,18 +1,15 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" #include "track_entry_painters.h" +#include #include - namespace Ui { class FilterTrackWidget; } - namespace LtsScriptTimeline { class TrackEntry; @@ -22,53 +19,50 @@ class ScriptTimeline; class Tools; class TrackWidget; - class LTSSCRIPTTIMELINE_EXPORT FilterTrackWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit FilterTrackWidget(int baseWidth, bool readonly = false, QWidget *parent = nullptr); - ~FilterTrackWidget(); + public: + explicit FilterTrackWidget(int baseWidth, bool readonly = false, QWidget* parent = nullptr); + ~FilterTrackWidget(); - FilterBackgroundWidget *fbw(); - const FilterBackgroundWidget *fbw() const; + 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); + 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); -private: - Ui::FilterTrackWidget *ui; - int m_baseWidth; - bool m_readonly; - ScriptTimeline *m_scriptTimeline; - Tools *m_tools; - TrackWidget *m_trackWidget; + void setBaseWidth(int width); -protected: - void paintEvent(QPaintEvent *event); + void setScriptTimeline(ScriptTimeline* scriptTimeline); + void setTools(Tools* tools); + void setTrackWidget(TrackWidget* trackWidget); -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); + 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.cpp old mode 100755 new mode 100644 index cb4e42ff6..35ac5afdc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.cpp @@ -1,82 +1,73 @@ #include "indicator.h" + #include "ui_indicator.h" + #include namespace LtsScriptTimeline { -Indicator::Indicator(QWidget *parent) - : QWidget(parent) - , ui(new Ui::Indicator) +Indicator::Indicator(QWidget* parent) : QWidget(parent), ui(new Ui::Indicator) { - ui->setupUi(this); + ui->setupUi(this); - connect(ui->splitter, &QSplitter::splitterMoved, - this, &Indicator::slotSplitterMoved); + 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); + connect(ui->m_widgetTrackHeader, &TrackHeader::signalHeaderIndicatorTimeChanged, this, + &Indicator::signalHeaderIndicatorTimeChanged); + connect(ui->m_widgetTrackHeader, &TrackHeader::signalHeaderIndicatorTimeUserChanged, this, + &Indicator::signalHeaderIndicatorTimeUserChanged); - QList sizes; - sizes << 100 << 900; - ui->splitter->setSizes(sizes); + QList sizes; + sizes << 100 << 900; + ui->splitter->setSizes(sizes); - QTimer::singleShot(500, this, [this]() - { - slotSplitterMoved(); - emit signalHeaderIndicatorTimeUserChanged(ui->m_widgetTrackHeader->indicatorTime()); - ui->m_widgetTrackHeader->recreatePositionLabels(); - }); + QTimer::singleShot(500, this, [this]() { + slotSplitterMoved(); + emit signalHeaderIndicatorTimeUserChanged(ui->m_widgetTrackHeader->indicatorTime()); + ui->m_widgetTrackHeader->recreatePositionLabels(); + }); } - Indicator::~Indicator() { - delete ui; + delete ui; } - -void Indicator::setTools(Tools *tools) +void Indicator::setTools(Tools* tools) { - ui->m_widgetTrackHeader->setTools(tools); + ui->m_widgetTrackHeader->setTools(tools); } - void Indicator::lockIndicator(bool lock) { - ui->m_widgetTrackHeader->lockIndicator(lock); + ui->m_widgetTrackHeader->lockIndicator(lock); } - void Indicator::setIndicatorTime(int time) { - ui->m_widgetTrackHeader->setIndicatorTime(time); + ui->m_widgetTrackHeader->setIndicatorTime(time); } - void Indicator::updateMe() { - ui->m_widgetTrackHeader->updateMe(); - update(); + ui->m_widgetTrackHeader->updateMe(); + update(); } - -void Indicator::resizeEvent(QResizeEvent *) +void Indicator::resizeEvent(QResizeEvent*) { - slotSplitterMoved(); + slotSplitterMoved(); } - void Indicator::slotSplitterMoved() { - int newSize = ui->m_widgetTrackLabel->width() + ui->splitter->handleWidth(); + int newSize = ui->m_widgetTrackLabel->width() + ui->splitter->handleWidth(); - if (newSize < 0) - newSize = 0; + if (newSize < 0) + newSize = 0; - emit signalHandleResized(newSize); + emit signalHandleResized(newSize); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.h old mode 100755 new mode 100644 index a9ffa5542..fa3e61da1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/indicator.h @@ -1,6 +1,5 @@ #pragma once #include - #include namespace Ui @@ -14,29 +13,29 @@ class Tools; class Indicator : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit Indicator(QWidget *parent = nullptr); - ~Indicator(); + public: + explicit Indicator(QWidget* parent = nullptr); + ~Indicator(); - void updateMe(); - void setIndicatorTime(int time); - void lockIndicator(bool lock = true); - void setTools(Tools *tools); + void updateMe(); + void setIndicatorTime(int time); + void lockIndicator(bool lock = true); + void setTools(Tools* tools); -private: - void resizeEvent(QResizeEvent *event); + private: + void resizeEvent(QResizeEvent* event); - Ui::Indicator *ui; + Ui::Indicator* ui; -signals: - void signalHandleResized(int width); - void signalHeaderIndicatorTimeChanged(int time); - void signalHeaderIndicatorTimeUserChanged(int time); + signals: + void signalHandleResized(int width); + void signalHeaderIndicatorTimeChanged(int time); + void signalHeaderIndicatorTimeUserChanged(int time); -private slots: - void slotSplitterMoved(); + private slots: + void slotSplitterMoved(); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.cpp old mode 100755 new mode 100644 index fa34be3af..9f64a29e9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.cpp @@ -1,1203 +1,1050 @@ #include "script_timeline.h" -#include -#include "ui_script_timeline.h" -#include "track_widget.h" -#include "tools.h" -#include "track_entry.h" -#include "track_content_widget.h" -#include "filter_track_widget.h" + #include "filter_background_widget.h" +#include "filter_track_widget.h" #include "temporary_pointer_vector.h" +#include "tools.h" +#include "track_content_widget.h" +#include "track_entry.h" +#include "track_widget.h" +#include "ui_script_timeline.h" #include - +#include +#include #include #include -#include -#include #include -#include - -#include - +#include +#include +#include namespace LtsScriptTimeline { -ScriptTimeline::ScriptTimeline(QWidget *parent) - : QWidget(parent) - , ui(new Ui::ScriptTimeline) - , m_uniqueId(0) - , m_scriptId(-1) - , m_baseTrackWidgetWidth(150) - , m_readonly(false) - , m_time(0) - , m_tools(new Tools(this)) - , m_mlmsMaster(nullptr) - , m_ignoreChanges(false) +ScriptTimeline::ScriptTimeline(QWidget* parent) + : QWidget(parent), ui(new Ui::ScriptTimeline), m_uniqueId(0), m_scriptId(-1), m_baseTrackWidgetWidth(150), + m_readonly(false), m_time(0), m_tools(new Tools(this)), m_mlmsMaster(nullptr), m_ignoreChanges(false) { - ui->setupUi(this); + ui->setupUi(this); - this->setFocusPolicy(Qt::StrongFocus); + this->setFocusPolicy(Qt::StrongFocus); - ui->indicator->setTools(m_tools); + ui->indicator->setTools(m_tools); - - ui->trackScrollBar->setMinimum(0); - ui->trackScrollBar->setMaximum(5 * 60); + ui->trackScrollBar->setMinimum(0); + ui->trackScrollBar->setMaximum(5 * 60); - connect(ui->zoomSlider, &QSlider::valueChanged, this, &ScriptTimeline::slotZoomValueChanged); + connect(ui->zoomSlider, &QSlider::valueChanged, this, &ScriptTimeline::slotZoomValueChanged); - connect(ui->trackScrollBar, &QScrollBar::sliderReleased, this, &ScriptTimeline::slotScrollbarValueChanged); - connect(ui->trackScrollBar, &QScrollBar::actionTriggered, this, &ScriptTimeline::slotScrollbarValueChanged); + connect(ui->trackScrollBar, &QScrollBar::sliderReleased, this, &ScriptTimeline::slotScrollbarValueChanged); + connect(ui->trackScrollBar, &QScrollBar::actionTriggered, this, &ScriptTimeline::slotScrollbarValueChanged); - connect(ui->indicator, &Indicator::signalHandleResized, - this, &ScriptTimeline::slotHeaderHandleResized); - connect(ui->indicator, &Indicator::signalHeaderIndicatorTimeChanged, - this, &ScriptTimeline::slotHeaderIndicatorTimeChanged); - connect(ui->indicator, &Indicator::signalHeaderIndicatorTimeUserChanged, - this, &ScriptTimeline::signalHeaderIndicatorTimeUserChanged); + connect(ui->indicator, &Indicator::signalHandleResized, this, &ScriptTimeline::slotHeaderHandleResized); + connect(ui->indicator, &Indicator::signalHeaderIndicatorTimeChanged, this, + &ScriptTimeline::slotHeaderIndicatorTimeChanged); + connect(ui->indicator, &Indicator::signalHeaderIndicatorTimeUserChanged, this, + &ScriptTimeline::signalHeaderIndicatorTimeUserChanged); - - QTimer *t = new QTimer(this); - t->setInterval(1500); - connect(t, &QTimer::timeout, - this, &ScriptTimeline::slotSetNewScrollBarMaximum); - t->start(); + QTimer* t = new QTimer(this); + t->setInterval(1500); + connect(t, &QTimer::timeout, this, &ScriptTimeline::slotSetNewScrollBarMaximum); + t->start(); - - - - slotZoomValueChanged(ui->zoomSlider->value()); + slotZoomValueChanged(ui->zoomSlider->value()); } - ScriptTimeline::~ScriptTimeline() { - m_copyTopics.clear(); - m_ignoreChanges = true; - qDeleteAll(m_clipboard); - delete ui; + m_copyTopics.clear(); + m_ignoreChanges = true; + qDeleteAll(m_clipboard); + delete ui; } - void ScriptTimeline::selectAll() { - const QList vecTrackWidgets = getTrackWidgets(); - for (TrackWidget *tw : vecTrackWidgets) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - tcw->selectAll(); - } -} - - -bool ScriptTimeline::checkNewLength(TrackEntry *te, int newLength) -{ - const QList tws = getTrackWidgets(); - TrackContentWidget *tesTcw = nullptr; - - - for (TrackWidget *tw : tws) - { - const QVector &tes = tw->getTrackContentWidget()->getTrackEntries(); - - auto it = std::find_if(tes.begin(), tes.end(), [te](const TrackEntry * a) + const QList vecTrackWidgets = getTrackWidgets(); + for (TrackWidget* tw : vecTrackWidgets) { - return (a->m_topicId == te->m_topicId); - }); - - if (it == tes.end()) - continue; - - tesTcw = tw->getTrackContentWidget(); - break; - } - - if (tesTcw == nullptr) - return false; - - - TrackEntry newTe(te); - newTe.m_length = newLength; - return tesTcw->checkForCollisionsSimple(newTe); + TrackContentWidget* tcw = tw->getTrackContentWidget(); + tcw->selectAll(); + } } +bool ScriptTimeline::checkNewLength(TrackEntry* te, int newLength) +{ + const QList tws = getTrackWidgets(); + TrackContentWidget* tesTcw = nullptr; + + for (TrackWidget* tw : tws) + { + const QVector& tes = tw->getTrackContentWidget()->getTrackEntries(); + + auto it = + std::find_if(tes.begin(), tes.end(), [te](const TrackEntry* a) { return (a->m_topicId == te->m_topicId); }); + + if (it == tes.end()) + continue; + + tesTcw = tw->getTrackContentWidget(); + break; + } + + if (tesTcw == nullptr) + return false; + + TrackEntry newTe(te); + newTe.m_length = newLength; + return tesTcw->checkForCollisionsSimple(newTe); +} void ScriptTimeline::lockIndicator(bool lock) { - ui->indicator->lockIndicator(lock); + ui->indicator->lockIndicator(lock); } - -void ScriptTimeline::keyPressEvent(QKeyEvent *event) +void ScriptTimeline::keyPressEvent(QKeyEvent* event) { - if (event->key() == Qt::Key_Delete) - { - slotDeleteSelectedTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_C) - { - slotCopyTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_V) - { - slotPasteTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_X) - { - slotCutTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_A) - { - selectAll(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_S) - { - emit signalSave(); - } - else - { - const QList vecTrackWidgets = getTrackWidgets(); + if (event->key() == Qt::Key_Delete) + { + slotDeleteSelectedTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_C) + { + slotCopyTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_V) + { + slotPasteTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_X) + { + slotCutTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_A) + { + selectAll(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_S) + { + emit signalSave(); + } + else + { + const QList vecTrackWidgets = getTrackWidgets(); + for (auto w : vecTrackWidgets) + w->keyPressEvent(event); + } +} + +void ScriptTimeline::mousePressEvent(QMouseEvent* event) +{ + if (event->buttons() != Qt::LeftButton) + return; + slotStartRubberband(event->pos()); +} + +void ScriptTimeline::mouseMoveEvent(QMouseEvent*) +{ + slotModifyRubberband(); +} + +void ScriptTimeline::mouseReleaseEvent(QMouseEvent*) +{ + const QList vecTrackWidgets = getTrackWidgets(); for (auto w : vecTrackWidgets) - w->keyPressEvent(event); - } + w->unselectAll(); + + slotStopRubberband(); } - -void ScriptTimeline::mousePressEvent(QMouseEvent *event) -{ - if (event->buttons() != Qt::LeftButton) - return; - slotStartRubberband(event->pos()); -} - - -void ScriptTimeline::mouseMoveEvent(QMouseEvent *) -{ - slotModifyRubberband(); -} - - -void ScriptTimeline::mouseReleaseEvent(QMouseEvent *) -{ - const QList vecTrackWidgets = getTrackWidgets(); - for (auto w : vecTrackWidgets) - w->unselectAll(); - - slotStopRubberband(); -} - - void ScriptTimeline::slotScroll(int incr) { - int oldValue = ui->trackScrollBar->value(); - ui->trackScrollBar->setValue(oldValue + incr); - slotScrollbarValueChanged(); + int oldValue = ui->trackScrollBar->value(); + ui->trackScrollBar->setValue(oldValue + incr); + slotScrollbarValueChanged(); } - void ScriptTimeline::setReadonly(bool readonly) { - m_readonly = readonly; + m_readonly = readonly; - const QList vecTrackWidgets = getTrackWidgets(); - for (TrackWidget *tw : vecTrackWidgets) - tw->setReadonly(readonly); + const QList vecTrackWidgets = getTrackWidgets(); + for (TrackWidget* tw : vecTrackWidgets) + tw->setReadonly(readonly); } - void ScriptTimeline::clear() { - m_copyTopics.clear(); + m_copyTopics.clear(); - const QList trackWidgetList = getTrackWidgets(); + const QList trackWidgetList = getTrackWidgets(); - - for (TrackWidget *tw : trackWidgetList) - delete tw; + for (TrackWidget* tw : trackWidgetList) + delete tw; - qDeleteAll(m_clipboard); - m_clipboard.clear(); + qDeleteAll(m_clipboard); + m_clipboard.clear(); - m_uniqueId = 0; + m_uniqueId = 0; - updateEverything(); + updateEverything(); } - void ScriptTimeline::slotSetNewScrollBarMaximum() { - int max = 5 * 60; + int max = 5 * 60; - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - const QVector &trackEntries = tw->getTrackContentWidget()->getTrackEntries(); - - for (const TrackEntry *te : trackEntries) + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) { - int maxTeTime = te->m_startTime + te->m_length; - + const QVector& trackEntries = tw->getTrackContentWidget()->getTrackEntries(); - if (maxTeTime > max) - { - max = maxTeTime + 5 * 60; - } + for (const TrackEntry* te : trackEntries) + { + int maxTeTime = te->m_startTime + te->m_length; + + if (maxTeTime > max) + { + max = maxTeTime + 5 * 60; + } + } } - } - - ui->trackScrollBar->setMaximum(max); - ui->trackScrollBar->setPageStep(60); - m_tools->m_timelineLength = max; + ui->trackScrollBar->setMaximum(max); + ui->trackScrollBar->setPageStep(60); + m_tools->m_timelineLength = max; - updateEverything(); + updateEverything(); } - void ScriptTimeline::setIndicatorTime(int time) { - ui->indicator->setIndicatorTime(time); + ui->indicator->setIndicatorTime(time); } - int ScriptTimeline::getCurrentScriptEndTime() { - int currEndTime = 0; - const QList listTrackWidgets = getTrackWidgets(); - for (const auto ltw : listTrackWidgets) - { - const auto cont = ltw->getTrackEntries(); - for (const auto pTE : cont) + int currEndTime = 0; + const QList listTrackWidgets = getTrackWidgets(); + for (const auto ltw : listTrackWidgets) { - int endTime = pTE->m_startTime + pTE->m_length; - currEndTime = qMax(currEndTime, endTime); + const auto cont = ltw->getTrackEntries(); + for (const auto pTE : cont) + { + int endTime = pTE->m_startTime + pTE->m_length; + currEndTime = qMax(currEndTime, endTime); + } } - } - return currEndTime; + return currEndTime; } - void ScriptTimeline::slotHeaderIndicatorTimeChanged(int time) { - m_time = time; + m_time = time; + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) + tw->setIndicatorTime(time); - - - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - tw->setIndicatorTime(time); - - emit signalHeaderIndicatorTimeChanged(time); + emit signalHeaderIndicatorTimeChanged(time); } - void ScriptTimeline::slotHeaderHandleResized(int newSize) { - m_baseTrackWidgetWidth = newSize; + m_baseTrackWidgetWidth = newSize; - updateEverything(); + updateEverything(); - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - tw->setBaseWidth(newSize); + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) + tw->setBaseWidth(newSize); } - void ScriptTimeline::slotDeleteTracks() { - int count = 0; + int count = 0; - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - if (tw->isSelected()) - count++; - } + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) + { + if (tw->isSelected()) + count++; + } - if (count < 1) - { - QApplication::beep(); - return; - } + if (count < 1) + { + QApplication::beep(); + return; + } - if (QMessageBox::question(this, tr("Delete selected tracks"), tr("Are you sure you want to delete all %1 tracks?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) - return; + if (QMessageBox::question(this, tr("Delete selected tracks"), + tr("Are you sure you want to delete all %1 tracks?").arg(count), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) + return; - for (TrackWidget *tw : trackWidgetList) - { - if (tw->isSelected()) - tw->deleteLater(); - } - - + for (TrackWidget* tw : trackWidgetList) + { + if (tw->isSelected()) + tw->deleteLater(); + } } - void ScriptTimeline::slotZoomValueChanged(int value) { - if (value < 1) - value = 1; + if (value < 1) + value = 1; - m_tools->m_zoomFactor = value; + m_tools->m_zoomFactor = value; - - - updateEverything(); + updateEverything(); } - - -void ScriptTimeline::resizeEvent(QResizeEvent *event) +void ScriptTimeline::resizeEvent(QResizeEvent* event) { - QWidget::resizeEvent(event); + QWidget::resizeEvent(event); - { - QPixmap p(QStringLiteral(":/style/portrait-mode.svg")); - int h = ui->trackScrollBar->height(); - QSize s(h, h); - ui->lbPortrait->setPixmap(p.scaled(s, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - ui->lbPortrait->setFixedSize(s); - } - { - QPixmap p(QStringLiteral(":/style/landscape-mode.svg")); - int h = ui->trackScrollBar->height(); - QSize s(h, h); - ui->lbLandscape->setPixmap(p.scaled(s, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - ui->lbLandscape->setFixedSize(s); - } + { + QPixmap p(QStringLiteral(":/style/portrait-mode.svg")); + int h = ui->trackScrollBar->height(); + QSize s(h, h); + ui->lbPortrait->setPixmap(p.scaled(s, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + ui->lbPortrait->setFixedSize(s); + } + { + QPixmap p(QStringLiteral(":/style/landscape-mode.svg")); + int h = ui->trackScrollBar->height(); + QSize s(h, h); + ui->lbLandscape->setPixmap(p.scaled(s, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + ui->lbLandscape->setFixedSize(s); + } - updateEverything(); + updateEverything(); } - void ScriptTimeline::slotUnselectAll() { - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - tw->unselectAll(); + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) + tw->unselectAll(); } - -int ScriptTimeline::getFilterTrackEntryRealTime(TrackEntry *te) +int ScriptTimeline::getFilterTrackEntryRealTime(TrackEntry* te) { - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - { - for (FilterTrackWidget *ftw : tw->filterLines()) + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) { - const QMap &filterContentWidgets = ftw->fbw()->filterContentWidgets(); - - int foundMainTrackEntryId = -1; - for (auto itFcw = filterContentWidgets.begin(); itFcw != filterContentWidgets.end(); ++itFcw) - { - const TrackContentWidget *tcw = itFcw.value(); - const QVector &trackEntries = tcw->getTrackEntries(); - - for (const TrackEntry *tempFilterTe : trackEntries) + for (FilterTrackWidget* ftw : tw->filterLines()) { - if (tempFilterTe->m_topicId == te->m_topicId) - { - foundMainTrackEntryId = itFcw.key(); - break; - } - } - if (foundMainTrackEntryId != -1) - break; - } + const QMap& filterContentWidgets = ftw->fbw()->filterContentWidgets(); - if (foundMainTrackEntryId != -1) - { - const QVector &trackEntries = tw->getTrackContentWidget()->getTrackEntries(); - for (const TrackEntry *mainTe : trackEntries) + int foundMainTrackEntryId = -1; + for (auto itFcw = filterContentWidgets.begin(); itFcw != filterContentWidgets.end(); ++itFcw) + { + const TrackContentWidget* tcw = itFcw.value(); + const QVector& trackEntries = tcw->getTrackEntries(); + + for (const TrackEntry* tempFilterTe : trackEntries) + { + if (tempFilterTe->m_topicId == te->m_topicId) + { + foundMainTrackEntryId = itFcw.key(); + break; + } + } + if (foundMainTrackEntryId != -1) + break; + } + + if (foundMainTrackEntryId != -1) + { + const QVector& trackEntries = tw->getTrackContentWidget()->getTrackEntries(); + for (const TrackEntry* mainTe : trackEntries) + { + if (mainTe->m_topicId == foundMainTrackEntryId) + return mainTe->m_startTime + te->m_startTime; + } + } + } + } + + return -1; +} + +QList ScriptTimeline::getTrackWidgets() const +{ + return ui->trackScrollArea->findChildren(); +} + +TrackEntry* ScriptTimeline::getTrackEntryWithFiltersAsEntries(int topicId) +{ + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) + { + const QVector trackEntries = tw->getTrackEntriesFiltersAsEntries(); + for (TrackEntry* te : std::as_const(trackEntries)) { - if (mainTe->m_topicId == foundMainTrackEntryId) - return mainTe->m_startTime + te->m_startTime; + if (te->m_topicId == topicId) + return te; } - } } - } - return -1; + return nullptr; } - -QList ScriptTimeline::getTrackWidgets() const +TrackEntry* ScriptTimeline::getTrackEntry(int topicId) { - return ui->trackScrollArea->findChildren(); -} - - -TrackEntry *ScriptTimeline::getTrackEntryWithFiltersAsEntries(int topicId) -{ - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - const QVector trackEntries = tw->getTrackEntriesFiltersAsEntries(); - for (TrackEntry *te : std::as_const(trackEntries)) + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) { - if (te->m_topicId == topicId) - return te; + const QVector trackEntries = tw->getTrackEntries(); + for (TrackEntry* te : trackEntries) + { + if (te->m_topicId == topicId) + return te; + } } - } - return nullptr; + return nullptr; } - -TrackEntry *ScriptTimeline::getTrackEntry(int topicId) +QVector ScriptTimeline::getTrackEntriesWithFiltersAsEntries(bool selectedEntriesOnly) const { - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - const QVector trackEntries = tw->getTrackEntries(); - for (TrackEntry *te : trackEntries) + QVector tes; + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) + tes += tw->getTrackEntriesFiltersAsEntries(selectedEntriesOnly); + + return tes; +} + +QMap> ScriptTimeline::getTrackEntriesWithFilters(bool selectedEntriesOnly) const +{ + QMap> trackList; + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) { - if (te->m_topicId == topicId) - return te; + QString trackName(tw->trackName()); + const QVector trackEntries = tw->getTrackEntriesWithFilters(selectedEntriesOnly); + + trackList.insert(trackName, trackEntries); } - } - return nullptr; + return trackList; } - -QVector ScriptTimeline::getTrackEntriesWithFiltersAsEntries(bool selectedEntriesOnly) const +QVector ScriptTimeline::getTrackEntries(bool selectedEntriesOnly) const { - QVector tes; - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - tes += tw->getTrackEntriesFiltersAsEntries(selectedEntriesOnly); + QVector tes; + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) + tes += tw->getTrackEntries(selectedEntriesOnly); - return tes; + return tes; } - -QMap > ScriptTimeline::getTrackEntriesWithFilters(bool selectedEntriesOnly) const +bool ScriptTimeline::importTrackEntries(const QVector& importTes) { - QMap > trackList; - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - QString trackName(tw->trackName()); - const QVector trackEntries = tw->getTrackEntriesWithFilters(selectedEntriesOnly); - trackList.insert(trackName, trackEntries); - } - - return trackList; -} - - -QVector ScriptTimeline::getTrackEntries(bool selectedEntriesOnly) const -{ - QVector tes; - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - tes += tw->getTrackEntries(selectedEntriesOnly); - - return tes; -} - - -bool ScriptTimeline::importTrackEntries(const QVector &importTes) -{ - - int importLength = 0; - for (TrackEntry *te : std::as_const(importTes)) - { - int teLen = te->m_startTime + te->m_length; - if (teLen > importLength) - importLength = teLen; - } - - - - const QVector tes = getTrackEntries(); - int pasteTime = m_time; - - for (TrackEntry *te : std::as_const(tes)) - { - int start = te->m_startTime; - int sum = start + te->m_length; - - if (start < m_time - && sum > m_time - && pasteTime < sum) + int importLength = 0; + for (TrackEntry* te : std::as_const(importTes)) { - pasteTime = sum; + int teLen = te->m_startTime + te->m_length; + if (teLen > importLength) + importLength = teLen; } - } - int diff = pasteTime - m_time; + const QVector tes = getTrackEntries(); + int pasteTime = m_time; - - - for (TrackEntry *te : std::as_const(tes)) - { - if (te->m_startTime >= m_time) - te->m_startTime += importLength + diff; - } - - - - QVector finalImportTes(importTes); - - for (TrackEntry *te : finalImportTes) - { - - te->m_startTime += pasteTime; - - - if (!addTopic(te)) + for (TrackEntry* te : std::as_const(tes)) { - qCritical() << "could not add te #" << te->m_topicId; - delete te; + int start = te->m_startTime; + int sum = start + te->m_length; + + if (start < m_time && sum > m_time && pasteTime < sum) + { + pasteTime = sum; + } } - } + int diff = pasteTime - m_time; - - m_time = pasteTime; - setIndicatorTime(m_time); - - - return true; -} - - -bool ScriptTimeline::addTopic(TrackEntry *te) -{ - if (te->m_topicId == 0) - te->m_topicId = nextUniqueId(); - - if (te->m_channelName.isEmpty()) - te->m_channelName = tr("Unnamed Track"); - - te->isSet = true; - - - const QList trackWidgetList = getTrackWidgets(); - for (TrackWidget *tw : trackWidgetList) - { - if (tw->trackName() == te->m_channelName) + for (TrackEntry* te : std::as_const(tes)) { - m_ignoreChanges = true; - bool result = tw->addTrackEntry(te, false); - m_ignoreChanges = false; - - if (!result) - return false; - - tw->updateMe(); - return true; + if (te->m_startTime >= m_time) + te->m_startTime += importLength + diff; } - } - - return false; + QVector finalImportTes(importTes); + + for (TrackEntry* te : finalImportTes) + { + + te->m_startTime += pasteTime; + + if (!addTopic(te)) + { + qCritical() << "could not add te #" << te->m_topicId; + delete te; + } + } + + m_time = pasteTime; + setIndicatorTime(m_time); + + return true; } - -QVector ScriptTimeline::getSelectedEntriesWithFilterEntries() const +bool ScriptTimeline::addTopic(TrackEntry* te) { - QVector tes; + if (te->m_topicId == 0) + te->m_topicId = nextUniqueId(); - const QList tws = getTrackWidgets(); + if (te->m_channelName.isEmpty()) + te->m_channelName = tr("Unnamed Track"); - for (const TrackWidget *tw : std::as_const(tws)) - tes += tw->getTrackEntriesFiltersAsEntries(true); + te->isSet = true; - return tes; + const QList trackWidgetList = getTrackWidgets(); + for (TrackWidget* tw : trackWidgetList) + { + if (tw->trackName() == te->m_channelName) + { + m_ignoreChanges = true; + bool result = tw->addTrackEntry(te, false); + m_ignoreChanges = false; + + if (!result) + return false; + + tw->updateMe(); + return true; + } + } + + return false; } +QVector ScriptTimeline::getSelectedEntriesWithFilterEntries() const +{ + QVector tes; + + const QList tws = getTrackWidgets(); + + for (const TrackWidget* tw : std::as_const(tws)) + tes += tw->getTrackEntriesFiltersAsEntries(true); + + return tes; +} QString ScriptTimeline::newTrackName() const { - QString newTrackName; - int add = 1; - const QList trackWidgetList = getTrackWidgets(); - bool newTrackNameFound = false; - while (!newTrackNameFound) - { - newTrackNameFound = true; - newTrackName = tr("New Track %1").arg(add); - for (const TrackWidget *tw : trackWidgetList) + QString newTrackName; + int add = 1; + const QList trackWidgetList = getTrackWidgets(); + bool newTrackNameFound = false; + while (!newTrackNameFound) { - if (tw->trackName() == newTrackName) - { - - add++; - newTrackNameFound = false; - break; - } + newTrackNameFound = true; + newTrackName = tr("New Track %1").arg(add); + for (const TrackWidget* tw : trackWidgetList) + { + if (tw->trackName() == newTrackName) + { + + add++; + newTrackNameFound = false; + break; + } + } } - } - return newTrackName; + return newTrackName; } - void ScriptTimeline::updateAllTracks() { - const QList tws = getTrackWidgets(); + const QList tws = getTrackWidgets(); - for (TrackWidget *tw : tws) - tw->updateMe(); + for (TrackWidget* tw : tws) + tw->updateMe(); } - -QVector ScriptTimeline::getSelectedFilterEntries() const +QVector ScriptTimeline::getSelectedFilterEntries() const { - QVector result; + QVector result; - const QList tws = getTrackWidgets(); - for (const TrackWidget *tw : std::as_const(tws)) - { - result += tw->getSelectedFilterEntries(); - } + const QList tws = getTrackWidgets(); + for (const TrackWidget* tw : std::as_const(tws)) + { + result += tw->getSelectedFilterEntries(); + } - return result; + return result; } - void ScriptTimeline::slotDeleteSelectedTopics() { - int topicCount = 0; + int topicCount = 0; - const QList tws = getTrackWidgets(); - for (const TrackWidget *tw : std::as_const(tws)) - { - topicCount += tw->getSelectedFilterEntries().count(); - - TrackContentWidget *tcw = tw->getTrackContentWidget(); - topicCount += tcw->getSelectedEntries().count(); - } - - if (!topicCount) - { - QApplication::beep(); - return; - } - - connect(new LtsWidgets::LtsMessageDialogNew(this, tr("Are you sure that you want to delete %1 topics?").arg(topicCount), - QString(), LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No), - &LtsWidgets::LtsMessageDialogNew::yes, - this, [this]() - { - const QList tws = getTrackWidgets(); - for (const TrackWidget *tw : std::as_const(tws)) + const QList tws = getTrackWidgets(); + for (const TrackWidget* tw : std::as_const(tws)) { - - const QVector &ftws = tw->filterLines(); + topicCount += tw->getSelectedFilterEntries().count(); - for (const FilterTrackWidget *ftw : std::as_const(ftws)) - { - const FilterBackgroundWidget *fbw = ftw->fbw(); - const QMap &fcws = fbw->filterContentWidgets(); - - for (TrackContentWidget *tcw: fcws) - tcw->deleteSelectedTopics(); - } - - TrackContentWidget *tcw = tw->getTrackContentWidget(); - tcw->deleteSelectedTopics(); + TrackContentWidget* tcw = tw->getTrackContentWidget(); + topicCount += tcw->getSelectedEntries().count(); } - }); -} + if (!topicCount) + { + QApplication::beep(); + return; + } + + connect(new LtsWidgets::LtsMessageDialogNew( + this, tr("Are you sure that you want to delete %1 topics?").arg(topicCount), QString(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No), + &LtsWidgets::LtsMessageDialogNew::yes, this, [this]() { + const QList tws = getTrackWidgets(); + for (const TrackWidget* tw : std::as_const(tws)) + { + + const QVector& ftws = tw->filterLines(); + + for (const FilterTrackWidget* ftw : std::as_const(ftws)) + { + const FilterBackgroundWidget* fbw = ftw->fbw(); + const QMap& fcws = fbw->filterContentWidgets(); + + for (TrackContentWidget* tcw : fcws) + tcw->deleteSelectedTopics(); + } + + TrackContentWidget* tcw = tw->getTrackContentWidget(); + tcw->deleteSelectedTopics(); + } + }); +} void ScriptTimeline::slotCutTopics() { - slotCopyTopics(); + slotCopyTopics(); - const QList tws = getTrackWidgets(); - for (const TrackWidget *tw : std::as_const(tws)) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - tcw->deleteSelectedTopics(); - } + const QList tws = getTrackWidgets(); + for (const TrackWidget* tw : std::as_const(tws)) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); + tcw->deleteSelectedTopics(); + } } - void ScriptTimeline::slotCopyTopics() { - const QList tws = getTrackWidgets(); - int firstTeTime = -1; + const QList tws = getTrackWidgets(); + int firstTeTime = -1; - - - for (const TrackWidget *tw : std::as_const(tws)) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - - const QVector &selected = tcw->getSelectedEntries(); - - if (tcw->getSelectedEntries().isEmpty()) - continue; - - for (const TrackEntry *te : std::as_const(selected)) + for (const TrackWidget* tw : std::as_const(tws)) { - if (firstTeTime > te->m_startTime || firstTeTime == -1) - firstTeTime = te->m_startTime; + TrackContentWidget* tcw = tw->getTrackContentWidget(); + + const QVector& selected = tcw->getSelectedEntries(); + + if (tcw->getSelectedEntries().isEmpty()) + continue; + + for (const TrackEntry* te : std::as_const(selected)) + { + if (firstTeTime > te->m_startTime || firstTeTime == -1) + firstTeTime = te->m_startTime; + } } - } - if (firstTeTime == -1) - { - QApplication::beep(); - return; - } - - - m_copyTopics.clear(); - - - - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - - if (tcw->getSelectedEntries().isEmpty()) - continue; - - - connect(tw, &QObject::destroyed, - this, [this](QObject *obj) + if (firstTeTime == -1) { - m_copyTopics.remove(static_cast(obj)); - }); + QApplication::beep(); + return; + } - m_copyTopics.insert(tw, TrackContentWidget::itemsToData(tw->getTrackEntriesWithFilters(true), firstTeTime, false)); - } + m_copyTopics.clear(); + + for (TrackWidget* tw : tws) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); + + if (tcw->getSelectedEntries().isEmpty()) + continue; + + connect(tw, &QObject::destroyed, this, + [this](QObject* obj) { m_copyTopics.remove(static_cast(obj)); }); + + m_copyTopics.insert(tw, + TrackContentWidget::itemsToData(tw->getTrackEntriesWithFilters(true), firstTeTime, false)); + } } - void ScriptTimeline::slotPasteTopics() { - if (m_copyTopics.isEmpty() || m_time < 0) - { - QApplication::beep(); - return; - } - - - for (auto i = m_copyTopics.constBegin(); i != m_copyTopics.constEnd(); ++i) - { - const TrackWidget *tw = i.key(); - const QByteArray &data = i.value(); - - TrackContentWidget *tcw = tw->getTrackContentWidget(); - int dummy = 0; - const TemporaryPointerVector tempTes(TrackContentWidget::dataToItems(data, dummy)); - if (!tcw->canPasteTopics(tempTes, 0, m_time)) + if (m_copyTopics.isEmpty() || m_time < 0) { - new LtsWidgets::LtsMessageDialogNew(this, tr("Topics can't be pasted here as one or more topics intersects with another existing topic.")); - return; + QApplication::beep(); + return; } - } - - for (auto i = m_copyTopics.constBegin(); i != m_copyTopics.constEnd(); ++i) - { - TrackWidget *tw = i.key(); - TrackContentWidget *tcw = tw->getTrackContentWidget(); - const QByteArray &data = i.value(); + for (auto i = m_copyTopics.constBegin(); i != m_copyTopics.constEnd(); ++i) + { + const TrackWidget* tw = i.key(); + const QByteArray& data = i.value(); - int dummy = 0; - const TemporaryPointerVector tempTes(TrackContentWidget::dataToItems(data, dummy)); - tcw->forcePasteTopics(tempTes, 0, m_time); - } + TrackContentWidget* tcw = tw->getTrackContentWidget(); + int dummy = 0; + const TemporaryPointerVector tempTes(TrackContentWidget::dataToItems(data, dummy)); + if (!tcw->canPasteTopics(tempTes, 0, m_time)) + { + new LtsWidgets::LtsMessageDialogNew( + this, tr("Topics can't be pasted here as one or more topics intersects with another existing topic.")); + return; + } + } + + for (auto i = m_copyTopics.constBegin(); i != m_copyTopics.constEnd(); ++i) + { + TrackWidget* tw = i.key(); + TrackContentWidget* tcw = tw->getTrackContentWidget(); + const QByteArray& data = i.value(); + + int dummy = 0; + const TemporaryPointerVector tempTes(TrackContentWidget::dataToItems(data, dummy)); + tcw->forcePasteTopics(tempTes, 0, m_time); + } } - void ScriptTimeline::slotMoveAll(int direction) { - int factor = 1; + int factor = 1; - if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - factor = 10; + if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + factor = 10; - QList tws = getTrackWidgets(); + QList tws = getTrackWidgets(); - - for (TrackWidget *tw : std::as_const(tws)) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - if (!tcw->canMoveAll(direction * factor)) + for (TrackWidget* tw : std::as_const(tws)) { - QApplication::beep(); - qWarning() << "cols and/or parls @" << tcw; - return; + TrackContentWidget* tcw = tw->getTrackContentWidget(); + if (!tcw->canMoveAll(direction * factor)) + { + QApplication::beep(); + qWarning() << "cols and/or parls @" << tcw; + return; + } } - } - - for (TrackWidget *tw : std::as_const(tws)) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - tcw->forceMoveAll(direction * factor); - } + for (TrackWidget* tw : std::as_const(tws)) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); + tcw->forceMoveAll(direction * factor); + } } - -static inline bool containsFailedTrackContentWidget(const QHash &mlmsTCWStates) +static inline bool containsFailedTrackContentWidget(const QHash& mlmsTCWStates) { - auto end = mlmsTCWStates.end(); - for (auto it = mlmsTCWStates.begin(); it != end; ++it) - { - if (it.value() == false) - return true; - } - return false; + auto end = mlmsTCWStates.end(); + for (auto it = mlmsTCWStates.begin(); it != end; ++it) + { + if (it.value() == false) + return true; + } + return false; } -TrackWidget *ScriptTimeline::addTrack(const QString &name, bool filtersAllowed) +TrackWidget* ScriptTimeline::addTrack(const QString& name, bool filtersAllowed) { - TrackWidget *tw = new TrackWidget(m_baseTrackWidgetWidth, m_readonly, m_tools, filtersAllowed); - tw->setScriptTimeline(this); - tw->setTrackName(name); + TrackWidget* tw = new TrackWidget(m_baseTrackWidgetWidth, m_readonly, m_tools, filtersAllowed); + tw->setScriptTimeline(this); + tw->setTrackName(name); - ui->trackLayout->insertWidget(1, tw); + ui->trackLayout->insertWidget(1, tw); - connect(tw, &TrackWidget::signalTrackEntrySelectionChanged, - this, &ScriptTimeline::slotTrackEntrySelectionChanged); - connect(tw, &TrackWidget::signalTrackEntryDeleted, - this, &ScriptTimeline::signalTrackEntryDeleted); - connect(tw, &TrackWidget::signalUnselectAll, - this, &ScriptTimeline::slotUnselectAll); - connect(tw, &TrackWidget::signalSelectTrack, - this, &ScriptTimeline::slotSelectTrack); - connect(tw, &TrackWidget::signalChangesMade, - this, &ScriptTimeline::signalChangesMade); - connect(tw, &TrackWidget::signalEditEntry, - this, &ScriptTimeline::signalEditEntry); + connect(tw, &TrackWidget::signalTrackEntrySelectionChanged, this, &ScriptTimeline::slotTrackEntrySelectionChanged); + connect(tw, &TrackWidget::signalTrackEntryDeleted, this, &ScriptTimeline::signalTrackEntryDeleted); + connect(tw, &TrackWidget::signalUnselectAll, this, &ScriptTimeline::slotUnselectAll); + connect(tw, &TrackWidget::signalSelectTrack, this, &ScriptTimeline::slotSelectTrack); + connect(tw, &TrackWidget::signalChangesMade, this, &ScriptTimeline::signalChangesMade); + connect(tw, &TrackWidget::signalEditEntry, this, &ScriptTimeline::signalEditEntry); - TrackContentWidget *tcw = tw->getTrackContentWidget(); + TrackContentWidget* tcw = tw->getTrackContentWidget(); - connect(tcw, &TrackContentWidget::signalStartRubberband, - this, &ScriptTimeline::slotStartRubberband); - connect(tcw, &TrackContentWidget::signalStopRubberband, - this, &ScriptTimeline::slotStopRubberband); - connect(tcw, &TrackContentWidget::signalEscapeRubberband, - this, &ScriptTimeline::slotEscapeRubberband); - connect(tcw, &TrackContentWidget::signalModifyRubberband, - this, &ScriptTimeline::slotModifyRubberband); - connect(tcw, &TrackContentWidget::signalSelectAllGlobal, - this, &ScriptTimeline::selectAll); - connect(tcw, &TrackContentWidget::signalCopyTopics, - this, &ScriptTimeline::slotCopyTopics); - connect(tcw, &TrackContentWidget::signalPasteTopics, - this, &ScriptTimeline::slotPasteTopics); - connect(tcw, &TrackContentWidget::signalCutTopics, - this, &ScriptTimeline::slotCutTopics); - connect(tcw, &TrackContentWidget::signalDeleteSelectedTopics, - this, &ScriptTimeline::slotDeleteSelectedTopics); - connect(tcw, &TrackContentWidget::signalSave, - this, &ScriptTimeline::signalSave); - connect(tcw, &TrackContentWidget::signalMoveAll, - this, &ScriptTimeline::slotMoveAll); - connect(tcw, &TrackContentWidget::signalScroll, - this, &ScriptTimeline::slotScroll); + connect(tcw, &TrackContentWidget::signalStartRubberband, this, &ScriptTimeline::slotStartRubberband); + connect(tcw, &TrackContentWidget::signalStopRubberband, this, &ScriptTimeline::slotStopRubberband); + connect(tcw, &TrackContentWidget::signalEscapeRubberband, this, &ScriptTimeline::slotEscapeRubberband); + connect(tcw, &TrackContentWidget::signalModifyRubberband, this, &ScriptTimeline::slotModifyRubberband); + connect(tcw, &TrackContentWidget::signalSelectAllGlobal, this, &ScriptTimeline::selectAll); + connect(tcw, &TrackContentWidget::signalCopyTopics, this, &ScriptTimeline::slotCopyTopics); + connect(tcw, &TrackContentWidget::signalPasteTopics, this, &ScriptTimeline::slotPasteTopics); + connect(tcw, &TrackContentWidget::signalCutTopics, this, &ScriptTimeline::slotCutTopics); + connect(tcw, &TrackContentWidget::signalDeleteSelectedTopics, this, &ScriptTimeline::slotDeleteSelectedTopics); + connect(tcw, &TrackContentWidget::signalSave, this, &ScriptTimeline::signalSave); + connect(tcw, &TrackContentWidget::signalMoveAll, this, &ScriptTimeline::slotMoveAll); + connect(tcw, &TrackContentWidget::signalScroll, this, &ScriptTimeline::slotScroll); + connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionFailed, this, [this]() { + TrackContentWidget* senderTcw = qobject_cast(sender()); + if (senderTcw == nullptr) + return; - connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionFailed, - this, [this]() - { - TrackContentWidget *senderTcw = qobject_cast(sender()); + m_mlmsTCWStates.insert(senderTcw, false); - if (senderTcw == nullptr) - return; + const QList tws = getTrackWidgets(); - m_mlmsTCWStates.insert(senderTcw, false); + for (TrackWidget* tw : tws) + { - const QList tws = getTrackWidgets(); + TrackContentWidget* tcw = tw->getTrackContentWidget(); + tcw->setDragPossible(false); + } + }); - for (TrackWidget *tw : tws) - { - - TrackContentWidget *tcw = tw->getTrackContentWidget(); - tcw->setDragPossible(false); - } - }); + connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionOkay, this, [this]() { + TrackContentWidget* senderTcw = qobject_cast(sender()); + if (senderTcw == nullptr) + return; - connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionOkay, - this, [this]() - { - - + m_mlmsTCWStates.insert(senderTcw, true); - TrackContentWidget *senderTcw = qobject_cast(sender()); + if (containsFailedTrackContentWidget(m_mlmsTCWStates)) + return; - if (senderTcw == nullptr) - return; + const QList tws = getTrackWidgets(); - m_mlmsTCWStates.insert(senderTcw, true); + for (TrackWidget* tw : tws) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); - if (containsFailedTrackContentWidget(m_mlmsTCWStates)) - return; + if (tcw == senderTcw) + continue; - + tcw->setDragPossible(true); + } + }); - const QList tws = getTrackWidgets(); + connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionDone, this, [this](int dropPos) { + TrackContentWidget* senderTcw = qobject_cast(sender()); - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); + if (senderTcw == nullptr) + return; - if (tcw == senderTcw) - continue; + const QList tws = getTrackWidgets(); - tcw->setDragPossible(true); - } - }); + for (TrackWidget* tw : tws) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); + if (tcw == senderTcw) + continue; - connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionDone, - this, [this](int dropPos) - { - TrackContentWidget *senderTcw = qobject_cast(sender()); + if (containsFailedTrackContentWidget(m_mlmsTCWStates) || dropPos == -1) + { + QApplication::beep(); + tcw->dragEnd(); + } + else + tcw->dragDrop(dropPos); + } - if (senderTcw == nullptr) - return; + m_mlmsMaster = nullptr; + m_mlmsTCWStates.clear(); + m_ignoreChanges = false; + updateAllTracks(); + }); + connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionMove, this, [this](int x) { + TrackContentWidget* senderTcw = qobject_cast(sender()); + if (senderTcw == nullptr) + return; - const QList tws = getTrackWidgets(); + if (senderTcw != m_mlmsMaster) + return; - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); + const QList tws = getTrackWidgets(); - if (tcw == senderTcw) - continue; + for (TrackWidget* tw : tws) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); - if (containsFailedTrackContentWidget(m_mlmsTCWStates) || dropPos == -1) - { - QApplication::beep(); - tcw->dragEnd(); - } - else - tcw->dragDrop(dropPos); - } + if (tcw == senderTcw) + continue; - m_mlmsMaster = nullptr; - m_mlmsTCWStates.clear(); - m_ignoreChanges = false; + tcw->dragMove(x); + } + }); - updateAllTracks(); - }); + connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionStart, this, [this](int dragPosTime) { + if (m_mlmsMaster != nullptr) + return; + TrackContentWidget* senderTcw = qobject_cast(sender()); - connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionMove, - this, [this](int x) - { - TrackContentWidget *senderTcw = qobject_cast(sender()); + if (senderTcw == nullptr) + return; - if (senderTcw == nullptr) - return; + m_mlmsMaster = senderTcw; + m_ignoreChanges = true; - - if (senderTcw != m_mlmsMaster) - return; + const QList tws = getTrackWidgets(); - const QList tws = getTrackWidgets(); + for (TrackWidget* tw : tws) + { + TrackContentWidget* tcw = tw->getTrackContentWidget(); - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); + if (tcw == senderTcw) + continue; - if (tcw == senderTcw) - continue; + tcw->dragEnter(tcw->selectedItemsToData(dragPosTime)); + } + }); - tcw->dragMove(x); - } - }); - - - connect(tcw, &TrackContentWidget::signalMultiLineMultiSelectionStart, - this, [this](int dragPosTime) - { - if (m_mlmsMaster != nullptr) - return; - - TrackContentWidget *senderTcw = qobject_cast(sender()); - - if (senderTcw == nullptr) - return; - - m_mlmsMaster = senderTcw; - m_ignoreChanges = true; - - const QList tws = getTrackWidgets(); - - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - - if (tcw == senderTcw) - continue; - - tcw->dragEnter(tcw->selectedItemsToData(dragPosTime)); - } - }); - - - return tw; + return tw; } - void ScriptTimeline::slotEscapeRubberband() { - if (m_rubberbandAction.rubberBand == nullptr) - return; + if (m_rubberbandAction.rubberBand == nullptr) + return; - m_rubberbandAction.rubberBand->deleteLater(); + m_rubberbandAction.rubberBand->deleteLater(); } - void ScriptTimeline::slotStopRubberband() { - if (m_rubberbandAction.rubberBand == nullptr) - return; + if (m_rubberbandAction.rubberBand == nullptr) + return; - QRect geo(m_rubberbandAction.rubberBand->geometry()); + QRect geo(m_rubberbandAction.rubberBand->geometry()); - m_rubberbandAction.rubberBand->deleteLater(); + m_rubberbandAction.rubberBand->deleteLater(); - if (m_readonly) - return; + if (m_readonly) + return; - QPoint rubberbandLength = geo.topLeft() - geo.bottomRight(); - if (rubberbandLength.manhattanLength() <= 6) - return; + QPoint rubberbandLength = geo.topLeft() - geo.bottomRight(); + if (rubberbandLength.manhattanLength() <= 6) + return; - - const QList tws = getTrackWidgets(); - for (TrackWidget *tw : tws) - { - TrackContentWidget *tcw = tw->getTrackContentWidget(); - - QRect tcwGeo(tcw->geometry()); - QPoint topLeft(tcw->mapTo(this, tcwGeo.topLeft())); - QPoint bottomRight(tcw->mapTo(this, tcwGeo.bottomRight())); - - if (QRect(topLeft, bottomRight).intersects(geo)) + const QList tws = getTrackWidgets(); + for (TrackWidget* tw : tws) { - QPoint tcwTL(tcw->mapFrom(this, geo.topLeft())); - QPoint tcwBR(tcw->mapFrom(this, geo.bottomRight())); + TrackContentWidget* tcw = tw->getTrackContentWidget(); - int fromPos = tcwTL.x(); - int toPos = tcwBR.x(); + QRect tcwGeo(tcw->geometry()); + QPoint topLeft(tcw->mapTo(this, tcwGeo.topLeft())); + QPoint bottomRight(tcw->mapTo(this, tcwGeo.bottomRight())); - tcw->selectEntriesAtPositions(fromPos, toPos); + if (QRect(topLeft, bottomRight).intersects(geo)) + { + QPoint tcwTL(tcw->mapFrom(this, geo.topLeft())); + QPoint tcwBR(tcw->mapFrom(this, geo.bottomRight())); + + int fromPos = tcwTL.x(); + int toPos = tcwBR.x(); + + tcw->selectEntriesAtPositions(fromPos, toPos); + } } - } } - -void ScriptTimeline::slotStartRubberband(const QPoint &) +void ScriptTimeline::slotStartRubberband(const QPoint&) { - if (m_readonly) - return; + if (m_readonly) + return; - if (m_rubberbandAction.rubberBand == nullptr) - { - QPoint cursorPos(mapFromGlobal(QCursor::pos())); - m_rubberbandAction.origin = cursorPos; - m_rubberbandAction.rubberBand = new QRubberBand(QRubberBand::Rectangle, this); + if (m_rubberbandAction.rubberBand == nullptr) + { + QPoint cursorPos(mapFromGlobal(QCursor::pos())); + m_rubberbandAction.origin = cursorPos; + m_rubberbandAction.rubberBand = new QRubberBand(QRubberBand::Rectangle, this); - m_rubberbandAction.rubberBand->setGeometry(QRect(cursorPos, QSize())); - m_rubberbandAction.rubberBand->show(); - } + m_rubberbandAction.rubberBand->setGeometry(QRect(cursorPos, QSize())); + m_rubberbandAction.rubberBand->show(); + } } void ScriptTimeline::slotModifyRubberband() { - if (!m_rubberbandAction.rubberBand) - return; + if (!m_rubberbandAction.rubberBand) + return; - m_rubberbandAction.rubberBand->setGeometry(QRect(m_rubberbandAction.origin, mapFromGlobal(QCursor::pos())).normalized()); + m_rubberbandAction.rubberBand->setGeometry( + QRect(m_rubberbandAction.origin, mapFromGlobal(QCursor::pos())).normalized()); } - -void ScriptTimeline::slotTrackEntrySelectionChanged(TrackEntry *) +void ScriptTimeline::slotTrackEntrySelectionChanged(TrackEntry*) { - if (m_ignoreChanges) - return; + if (m_ignoreChanges) + return; - const QList tws = getTrackWidgets(); + const QList tws = getTrackWidgets(); - - bool hasSelections = false; - bool activateMultiLineMultiSelectionMode = false; - for (const TrackWidget *tw : tws) - { - if (!hasSelections) + bool hasSelections = false; + bool activateMultiLineMultiSelectionMode = false; + for (const TrackWidget* tw : tws) { - if (!tw->getSelectedEntries().isEmpty() || !tw->getSelectedFilterEntries().isEmpty()) - hasSelections = true; - } - else if (!tw->getSelectedEntries().isEmpty()) - { - - activateMultiLineMultiSelectionMode = true; - break; - } - } + if (!hasSelections) + { + if (!tw->getSelectedEntries().isEmpty() || !tw->getSelectedFilterEntries().isEmpty()) + hasSelections = true; + } + else if (!tw->getSelectedEntries().isEmpty()) + { - - for (TrackWidget *tw : std::as_const(tws)) - tw->getTrackContentWidget()->setMultiLineMultiSelectionMode(activateMultiLineMultiSelectionMode); + activateMultiLineMultiSelectionMode = true; + break; + } + } - emit signalTrackEntrySelectionChanged(nullptr); + for (TrackWidget* tw : std::as_const(tws)) + tw->getTrackContentWidget()->setMultiLineMultiSelectionMode(activateMultiLineMultiSelectionMode); + + emit signalTrackEntrySelectionChanged(nullptr); } - void ScriptTimeline::slotSelectTrack() { - const QList trackWidgetList = getTrackWidgets(); - for (const TrackWidget *tw : trackWidgetList) - { - if (tw->isSelected()) + const QList trackWidgetList = getTrackWidgets(); + for (const TrackWidget* tw : trackWidgetList) { - - return; + if (tw->isSelected()) + { + + return; + } } - } - - } - void ScriptTimeline::updateEverything() { - - - TrackWidget *tw = ui->trackScrollArea->findChild(); + TrackWidget* tw = ui->trackScrollArea->findChild(); - if (tw != nullptr) - m_tools->m_paintWidth = tw->width(); + if (tw != nullptr) + m_tools->m_paintWidth = tw->width(); - ui->indicator->updateMe(); + ui->indicator->updateMe(); - updateAllTracks(); - update(); + updateAllTracks(); + update(); } - void ScriptTimeline::slotScrollbarValueChanged() { - m_tools->m_scrollPos = ui->trackScrollBar->value(); + m_tools->m_scrollPos = ui->trackScrollBar->value(); - updateEverything(); + updateEverything(); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.h old mode 100755 new mode 100644 index 376fcc88f..56f9b9ef2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/script_timeline.h @@ -1,23 +1,19 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" #include "track_entry_painters.h" -#include #include +#include #include - +#include namespace Ui { class ScriptTimeline; } - class QRubberBand; - namespace LtsScriptTimeline { class TrackContentWidget; @@ -27,100 +23,114 @@ class Tools; class LTSSCRIPTTIMELINE_EXPORT ScriptTimeline : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit ScriptTimeline(QWidget *parent = nullptr); - ~ScriptTimeline(); + 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 getTrackEntriesWithFiltersAsEntries(bool selectedEntriesOnly = false) const; - QMap > getTrackEntriesWithFilters(bool selectedEntriesOnly = false) const; - QVector getTrackEntries(bool selectedEntriesOnly = false) const; - QVector getSelectedEntriesWithFilterEntries() const; - QVector 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 getTrackWidgets() const; - void lockIndicator(bool lock = true); - int getFilterTrackEntryRealTime(TrackEntry *te); - bool checkNewLength(TrackEntry *te, int newLength); - bool importTrackEntries(const QVector &importTes); + TrackWidget* addTrack(const QString& name, bool filtersAllowed = true); -protected: - void keyPressEvent(QKeyEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *) override; - void mouseReleaseEvent(QMouseEvent *) override; + void setScriptId(int scriptId) + { + m_scriptId = scriptId; + } -private: - Ui::ScriptTimeline *ui; - int m_uniqueId; - int m_scriptId; - int m_baseTrackWidgetWidth; - QVector m_clipboard; - - bool m_readonly; - int m_time; - Tools *m_tools; - TrackContentWidget *m_mlmsMaster; - QHash m_mlmsTCWStates; - bool m_ignoreChanges; - QHash m_copyTopics; + bool addTopic(TrackEntry* te); + QString newTrackName() const; - struct RubberbandAction - { - QPoint origin; - QPointer rubberBand; - } m_rubberbandAction; + int nextUniqueId() + { + return ++m_uniqueId; + } - void resizeEvent(QResizeEvent *event) override; - void updateAllTracks(); + void setUniqueIdCounter(int uniqueId) + { + m_uniqueId = uniqueId; + } -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(); + QVector getTrackEntriesWithFiltersAsEntries(bool selectedEntriesOnly = false) const; + QMap> getTrackEntriesWithFilters(bool selectedEntriesOnly = false) const; + QVector getTrackEntries(bool selectedEntriesOnly = false) const; + QVector getSelectedEntriesWithFilterEntries() const; + QVector getSelectedFilterEntries() const; + TrackEntry* getTrackEntry(int topicId); + TrackEntry* getTrackEntryWithFiltersAsEntries(int topicId); + void setIndicatorTime(int time); + int getCurrentScriptEndTime(); -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); + void updateEverything(); + void clear(); + void setReadonly(bool readonly); + QList getTrackWidgets() const; + void lockIndicator(bool lock = true); + int getFilterTrackEntryRealTime(TrackEntry* te); + bool checkNewLength(TrackEntry* te, int newLength); + bool importTrackEntries(const QVector& importTes); -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(); + 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 m_clipboard; + + bool m_readonly; + int m_time; + Tools* m_tools; + TrackContentWidget* m_mlmsMaster; + QHash m_mlmsTCWStates; + bool m_ignoreChanges; + QHash m_copyTopics; + + struct RubberbandAction + { + QPoint origin; + QPointer 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/temporary_pointer_vector.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/temporary_pointer_vector.h old mode 100755 new mode 100644 index f07401d23..bdcc88429 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/temporary_pointer_vector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/temporary_pointer_vector.h @@ -1,50 +1,43 @@ #pragma once -#include #include - +#include namespace LtsScriptTimeline { -template -class TemporaryPointerVector : public QVector +template class TemporaryPointerVector : public QVector { - static_assert(std::is_pointer::value, "Type must be of pointer type"); + static_assert(std::is_pointer::value, "Type must be of pointer type"); -public: - TemporaryPointerVector() = default; + public: + TemporaryPointerVector() = default; - explicit TemporaryPointerVector(const QVector &other) - { - discard(); - this->append(other); - } + explicit TemporaryPointerVector(const QVector& other) + { + discard(); + this->append(other); + } + ~TemporaryPointerVector() + { + discard(); + } - ~TemporaryPointerVector() - { - discard(); - } + void setDiscardable(bool discardable) + { + m_discard = discardable; + } + private: + bool m_discard = true; - void setDiscardable(bool discardable) - { - m_discard = discardable; - } - - -private: - bool m_discard = true; - - - void discard() - { - if (m_discard) - qDeleteAll(this->begin(), this->end()); - this->clear(); - } - + void discard() + { + if (m_discard) + qDeleteAll(this->begin(), this->end()); + this->clear(); + } }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.cpp old mode 100755 new mode 100644 index 71cba4058..3edbb0372 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.cpp @@ -2,83 +2,74 @@ #include - namespace LtsScriptTimeline { - - - - - int Tools::getLength(int startTime, int duration) { - return (getPos(startTime + duration) - getPos(startTime)); + return (getPos(startTime + duration) - getPos(startTime)); } - -int Tools::getDuration(int duration) +int Tools::getDuration(int duration) { - double max = Tools::m_timelineLength; - max /= Tools::m_zoomFactor; + double max = Tools::m_timelineLength; + max /= Tools::m_zoomFactor; - int paintWidth = m_paintWidth; + int paintWidth = m_paintWidth; - double x = duration; - x /= paintWidth; - x *= max; + double x = duration; + x /= paintWidth; + x *= max; - return lrint(x); + return lrint(x); } - -int Tools::getTime(int pos, bool neutral) +int Tools::getTime(int pos, bool neutral) { - double visibleMax = Tools::m_timelineLength; - visibleMax /= Tools::m_zoomFactor; + double visibleMax = Tools::m_timelineLength; + visibleMax /= Tools::m_zoomFactor; - if (!neutral) - visibleMax += Tools::m_scrollPos; + if (!neutral) + visibleMax += Tools::m_scrollPos; - int visibleMin = 0; + int visibleMin = 0; - if (!neutral) - visibleMin = Tools::m_scrollPos; + if (!neutral) + visibleMin = Tools::m_scrollPos; - double diff = visibleMax - visibleMin; - int paintWidth = m_paintWidth; + double diff = visibleMax - visibleMin; + int paintWidth = m_paintWidth; - double x = pos; - x /= paintWidth; - x *= diff; - x += visibleMin; + double x = pos; + x /= paintWidth; + x *= diff; + x += visibleMin; - return lrint(x); + return lrint(x); } - -int Tools::getPos(int time, bool neutral) +int Tools::getPos(int time, bool neutral) { - double visibleMax = Tools::m_timelineLength; - visibleMax /= Tools::m_zoomFactor; + double visibleMax = Tools::m_timelineLength; + visibleMax /= Tools::m_zoomFactor; - if (!neutral) - visibleMax += Tools::m_scrollPos; + if (!neutral) + visibleMax += Tools::m_scrollPos; - int visibleMin = 0; + int visibleMin = 0; - if (!neutral) - visibleMin = Tools::m_scrollPos; + if (!neutral) + visibleMin = Tools::m_scrollPos; - double diff = visibleMax - visibleMin; - int paintWidth = m_paintWidth; + double diff = visibleMax - visibleMin; + int paintWidth = m_paintWidth; - double x = time; - x -= visibleMin; - x /= diff; - x *= paintWidth; + double x = time; + x -= visibleMin; + x /= diff; + x *= paintWidth; - return lrint(x); + return lrint(x); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.h old mode 100755 new mode 100644 index a100012cd..77c07062b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/tools.h @@ -2,32 +2,28 @@ #include - namespace LtsScriptTimeline { class Tools : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit Tools(QObject *parent) - : QObject(parent) - , m_timelineLength(5 * 60) - , m_zoomFactor(1) - , m_scrollPos(0) - , m_paintWidth(1) - {} + 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 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); + 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.cpp old mode 100755 new mode 100644 index a5b6dfa32..2e7bc1fd7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.cpp @@ -1,1653 +1,1430 @@ #include "track_content_widget.h" -#include -#include "track_entry.h" -#include "tools.h" -#include "track_entry_painters.h" -#include "track_widget.h" -#include "script_timeline.h" + #include "filter_background_widget.h" -#include "track_drag_handler.h" -#include "track_select_handler.h" -#include "track_resize_handler.h" +#include "script_timeline.h" #include "temporary_pointer_vector.h" +#include "tools.h" +#include "track_drag_handler.h" +#include "track_entry.h" +#include "track_entry_painters.h" +#include "track_resize_handler.h" +#include "track_select_handler.h" +#include "track_widget.h" #include - -#include +#include #include -#include #include +#include #include -#include -#include +#include #include +#include #include #include #include -#include -#include - -#include - - +#include +#include #include - +#include +#include namespace LtsScriptTimeline { -QDataStream &operator<<(QDataStream &ds, const TrackEntry &te) +QDataStream& operator<<(QDataStream& ds, const TrackEntry& te) { - const QByteArray jsonContent = QJsonDocument(te.m_detailData).toBinaryData(); - ds << te.m_topicId - << te.m_startTime - << te.m_length - << static_cast(te.m_type) - << te.isSet - << te.index - << jsonContent - << te.x << te.y << te.h << te.w - << te.m_channelName - << te.m_description; - return ds; + const QByteArray jsonContent = QJsonDocument(te.m_detailData).toBinaryData(); + ds << te.m_topicId << te.m_startTime << te.m_length << static_cast(te.m_type) << te.isSet << te.index + << jsonContent << te.x << te.y << te.h << te.w << te.m_channelName << te.m_description; + return ds; } - -QDataStream &operator>>(QDataStream &ds, TrackEntry &te) +QDataStream& operator>>(QDataStream& ds, TrackEntry& te) { - QByteArray jsonContent; - quint8 type; - ds >> te.m_topicId - >> te.m_startTime - >> te.m_length - >> type - >> te.isSet - >> te.index - >> jsonContent - >> te.x >> te.y >> te.h >> te.w - >> te.m_channelName - >> te.m_description; + QByteArray jsonContent; + quint8 type; + ds >> te.m_topicId >> te.m_startTime >> te.m_length >> type >> te.isSet >> te.index >> jsonContent >> te.x >> + te.y >> te.h >> te.w >> te.m_channelName >> te.m_description; - te.m_type = static_cast(type); - te.m_detailData = QJsonDocument::fromBinaryData(jsonContent).object(); - return ds; + te.m_type = static_cast(type); + te.m_detailData = QJsonDocument::fromBinaryData(jsonContent).object(); + return ds; } - bool isCollision(int start_s, int end_s, int toCompare_start_s, int toCompare_end_s) { - - + if (start_s >= toCompare_start_s && - - + start_s < toCompare_end_s) + { + return true; + } + if (start_s < toCompare_start_s && + end_s > toCompare_start_s) + { + return true; + } - - - - - - - - - - if (start_s >= toCompare_start_s && - - start_s < toCompare_end_s) - { - - return true; - } - - - if (start_s < toCompare_start_s && - - end_s > toCompare_start_s) - { - - return true; - } - - return false; -} - - -bool isCollision2(int startPreview_s, int endPreview_s, const TrackEntry *pTrackEntry) -{ - return isCollision(startPreview_s, endPreview_s, pTrackEntry->m_startTime, pTrackEntry->m_startTime + pTrackEntry->m_length); -} - - - - -void sortTrackEntriesChronologically(QVector &vecTrackEntries) -{ - std::sort(vecTrackEntries.begin(), vecTrackEntries.end(), - [](const TrackEntry *a, const TrackEntry *b) -> bool - { - return a->m_startTime < b->m_startTime; - }); -} - - -bool TrackContentWidget::checkForCollisionsSimple(const TrackEntry &previewEntry) const -{ - - const int startPreview = previewEntry.m_startTime; - if (startPreview < 0) return false; - const int endPreview = startPreview + previewEntry.m_length; - - const QVector trackEntries = getTrackEntries(); - for (const TrackEntry *checkTe : trackEntries) - { - if (checkTe->m_topicId == previewEntry.m_topicId) - continue; - - if (LtsScriptTimeline::isCollision2(startPreview, endPreview, checkTe)) - return false; - } - - return true; } - -bool TrackContentWidget::checkForCollisions(const TrackContentWidget *tcw, const QVector &preview, int dropTime_s, QVector &vecCollisions, bool ignoreSelected, bool ignoreSelfCheck) +bool isCollision2(int startPreview_s, int endPreview_s, const TrackEntry* pTrackEntry) { - QVector _preview = preview; - sortTrackEntriesChronologically(_preview); - - vecCollisions.clear(); - - QVector vecEntriesToCheck; - const QVector &trackEntries = tcw->getTrackEntries(); - - if (ignoreSelected) - { - - const QVector &selectedEntries = tcw->getSelectedEntries(); - for (TrackEntry *te : std::as_const(trackEntries)) - { - if (!selectedEntries.contains(te)) - vecEntriesToCheck.append(te); - } - } - else - vecEntriesToCheck = trackEntries; - - - auto leftMostI = std::min_element(_preview.constBegin(), _preview.constEnd(), [](const TrackEntry * a, const TrackEntry * b) - { - return a->m_startTime < b->m_startTime; - }); - - if (leftMostI == _preview.constEnd()) - return false; - - int startTimeMostLeft_s = (*leftMostI)->m_startTime; - int startOffset_s = dropTime_s - startTimeMostLeft_s; - - - for (TrackEntry *previewEntry : std::as_const(_preview)) - { - int startPreview_s = previewEntry->m_startTime + startOffset_s; - - if (startPreview_s < 0) - { - vecCollisions.append(previewEntry); - continue; - } - - int endPreview_s = startPreview_s + previewEntry->m_length; - - for (const TrackEntry *checkTe : std::as_const(vecEntriesToCheck)) - { - if (checkTe->m_topicId == previewEntry->m_topicId && !ignoreSelfCheck) - { - continue; - } - - if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, checkTe)) - { - vecCollisions.append(previewEntry); - break; - } - } - } - - return !vecCollisions.isEmpty(); + return isCollision(startPreview_s, endPreview_s, pTrackEntry->m_startTime, + pTrackEntry->m_startTime + pTrackEntry->m_length); } - -bool TrackContentWidget::checkForCollisions(const TrackContentWidget *pTCW, const QVector &vecPreviewTrackEntries, int dropTime_s) +void sortTrackEntriesChronologically(QVector& vecTrackEntries) { - QVector dummy_vecCollidingTopics; - return TrackContentWidget::checkForCollisions(pTCW, vecPreviewTrackEntries, dropTime_s, dummy_vecCollidingTopics, true); + std::sort(vecTrackEntries.begin(), vecTrackEntries.end(), + [](const TrackEntry* a, const TrackEntry* b) -> bool { return a->m_startTime < b->m_startTime; }); } +bool TrackContentWidget::checkForCollisionsSimple(const TrackEntry& previewEntry) const +{ + + const int startPreview = previewEntry.m_startTime; + if (startPreview < 0) + return false; + const int endPreview = startPreview + previewEntry.m_length; + + const QVector trackEntries = getTrackEntries(); + for (const TrackEntry* checkTe : trackEntries) + { + if (checkTe->m_topicId == previewEntry.m_topicId) + continue; + + if (LtsScriptTimeline::isCollision2(startPreview, endPreview, checkTe)) + return false; + } + + return true; +} + +bool TrackContentWidget::checkForCollisions(const TrackContentWidget* tcw, const QVector& preview, + int dropTime_s, QVector& vecCollisions, bool ignoreSelected, + bool ignoreSelfCheck) +{ + QVector _preview = preview; + sortTrackEntriesChronologically(_preview); + + vecCollisions.clear(); + + QVector vecEntriesToCheck; + const QVector& trackEntries = tcw->getTrackEntries(); + + if (ignoreSelected) + { + + const QVector& selectedEntries = tcw->getSelectedEntries(); + for (TrackEntry* te : std::as_const(trackEntries)) + { + if (!selectedEntries.contains(te)) + vecEntriesToCheck.append(te); + } + } + else + vecEntriesToCheck = trackEntries; + + auto leftMostI = + std::min_element(_preview.constBegin(), _preview.constEnd(), + [](const TrackEntry* a, const TrackEntry* b) { return a->m_startTime < b->m_startTime; }); + + if (leftMostI == _preview.constEnd()) + return false; + + int startTimeMostLeft_s = (*leftMostI)->m_startTime; + int startOffset_s = dropTime_s - startTimeMostLeft_s; + + for (TrackEntry* previewEntry : std::as_const(_preview)) + { + int startPreview_s = previewEntry->m_startTime + startOffset_s; + + if (startPreview_s < 0) + { + vecCollisions.append(previewEntry); + continue; + } + + int endPreview_s = startPreview_s + previewEntry->m_length; + + for (const TrackEntry* checkTe : std::as_const(vecEntriesToCheck)) + { + if (checkTe->m_topicId == previewEntry->m_topicId && !ignoreSelfCheck) + { + continue; + } + + if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, checkTe)) + { + vecCollisions.append(previewEntry); + break; + } + } + } + + return !vecCollisions.isEmpty(); +} + +bool TrackContentWidget::checkForCollisions(const TrackContentWidget* pTCW, + const QVector& vecPreviewTrackEntries, int dropTime_s) +{ + QVector dummy_vecCollidingTopics; + return TrackContentWidget::checkForCollisions(pTCW, vecPreviewTrackEntries, dropTime_s, dummy_vecCollidingTopics, + true); +} QString TrackContentWidget::parallelError() { - return tr("At least one topic of type Situation, Building, Audio or Video has been selected\nwhich can not be played parallel on both screens. Placement not possible."); + return tr("At least one topic of type Situation, Building, Audio or Video has been selected\nwhich can not be " + "played parallel on both screens. Placement not possible."); } - - -bool TrackContentWidget::checkForParallelTopics(const TrackContentWidget *tcw, const QVector &preview, int dropTime_s, QVector &vecParallelTopics, bool ignoreSelectedTopics, bool hack) +bool TrackContentWidget::checkForParallelTopics(const TrackContentWidget* tcw, const QVector& preview, + int dropTime_s, QVector& vecParallelTopics, + bool ignoreSelectedTopics, bool hack) { - - { - QVector vecParallelForbiddenFilter = { TrackEntryType::Building, TrackEntryType::Audio, TrackEntryType::Video, TrackEntryType::SituationMap, TrackEntryType::Situation }; - QVector previewCopy(preview); - sortTrackEntriesChronologically(previewCopy); - QVector vecTrackEntries(tcw->getTrackEntries()); - - auto itE = std::remove_if(previewCopy.begin(), previewCopy.end(), - [vecParallelForbiddenFilter](TrackEntry *pTE) { - return !vecParallelForbiddenFilter.contains(pTE->m_type); - }); - previewCopy.erase(itE, previewCopy.end()); + QVector vecParallelForbiddenFilter = {TrackEntryType::Building, TrackEntryType::Audio, + TrackEntryType::Video, TrackEntryType::SituationMap, + TrackEntryType::Situation}; + QVector previewCopy(preview); + sortTrackEntriesChronologically(previewCopy); + QVector vecTrackEntries(tcw->getTrackEntries()); + auto itE = + std::remove_if(previewCopy.begin(), previewCopy.end(), [vecParallelForbiddenFilter](TrackEntry* pTE) { + return !vecParallelForbiddenFilter.contains(pTE->m_type); + }); + previewCopy.erase(itE, previewCopy.end()); - if (ignoreSelectedTopics) - { - - itE = std::remove_if(previewCopy.begin(), previewCopy.end(), - [tcw](TrackEntry *pTE) - { - return tcw->getSelectedEntries().contains(pTE); - }); - previewCopy.erase(itE, previewCopy.end()); + if (ignoreSelectedTopics) + { + + itE = std::remove_if(previewCopy.begin(), previewCopy.end(), + [tcw](TrackEntry* pTE) { return tcw->getSelectedEntries().contains(pTE); }); + previewCopy.erase(itE, previewCopy.end()); + } + + itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), + [vecParallelForbiddenFilter](TrackEntry* pTE) { + return !vecParallelForbiddenFilter.contains(pTE->m_type); + }); + vecTrackEntries.erase(itE, vecTrackEntries.end()); + + itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), + [tcw](TrackEntry* pTE) { return tcw->getSelectedEntries().contains(pTE); }); + vecTrackEntries.erase(itE, vecTrackEntries.end()); + + if (!previewCopy.isEmpty() && !vecTrackEntries.isEmpty()) + { + auto leftMostI = std::min_element( + previewCopy.constBegin(), previewCopy.constEnd(), + [](const TrackEntry* a, const TrackEntry* b) { return a->m_startTime < b->m_startTime; }); + + if (leftMostI != previewCopy.constEnd()) + { + int startTimeMostLeft_s = (*leftMostI)->m_startTime; + + for (TrackEntry* previewEntry : std::as_const(previewCopy)) + { + + int startOffset_s = previewEntry->m_startTime; + + if (!hack) + startOffset_s -= startTimeMostLeft_s; + + for (TrackEntry* pTrackEntry : std::as_const(vecTrackEntries)) + { + + if (previewEntry->m_type != pTrackEntry->m_type) + { + + continue; + } + + if (previewEntry->m_topicId == pTrackEntry->m_topicId) + { + + continue; + } + + int startPreview_s = startOffset_s; + + if (!hack) + startPreview_s += dropTime_s; + + int endPreview_s = startPreview_s + previewEntry->m_length; + + if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, pTrackEntry)) + { + + vecParallelTopics.append(previewEntry); + break; + } + } + } + } + } + else + { + } } - - - itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), - [vecParallelForbiddenFilter](TrackEntry *pTE) { - return !vecParallelForbiddenFilter.contains(pTE->m_type); - }); - vecTrackEntries.erase(itE, vecTrackEntries.end()); + QVector previewCopy(preview); + sortTrackEntriesChronologically(previewCopy); + QVector> differentParallelForbidden = { + {TrackEntryType::Situation, TrackEntryType::Snapshot}, + {TrackEntryType::Situation, TrackEntryType::SituationReplay}, + {TrackEntryType::Situation, TrackEntryType::SituationMap}, + }; + QVector vecTrackEntries(tcw->getTrackEntries()); - - itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), - [tcw](TrackEntry *pTE) - { - return tcw->getSelectedEntries().contains(pTE); - }); - vecTrackEntries.erase(itE, vecTrackEntries.end()); + int step = 1; + auto findUnusedType = [differentParallelForbidden, &step](const TrackEntry* pTE) { + auto x = std::find_if(differentParallelForbidden.constBegin(), differentParallelForbidden.constEnd(), + [pTE, step](const QPair& pair) { + bool x = (pair.first == pTE->m_type || pair.second == pTE->m_type); + if (x) + qDebug() << ">>" << step << ".1 type" << (int)pTE->m_type + << "in type list - not removing"; + return x; + }); + if (x == differentParallelForbidden.constEnd()) + qDebug() << ">>" << step << ".2 type" << (int)pTE->m_type << "not found in type list - removing!"; - - if (!previewCopy.isEmpty() && !vecTrackEntries.isEmpty()) - { - auto leftMostI = std::min_element(previewCopy.constBegin(), previewCopy.constEnd(), [](const TrackEntry *a, const TrackEntry *b) - { - return a->m_startTime < b->m_startTime; - }); + return (x == differentParallelForbidden.constEnd()); + }; - if (leftMostI != previewCopy.constEnd()) - { - int startTimeMostLeft_s = (*leftMostI)->m_startTime; - + auto itE = std::remove_if(previewCopy.begin(), previewCopy.end(), findUnusedType); + previewCopy.erase(itE, previewCopy.end()); + step = 2; - - for (TrackEntry *previewEntry : std::as_const(previewCopy)) + itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), findUnusedType); + vecTrackEntries.erase(itE, vecTrackEntries.end()); + + if (ignoreSelectedTopics) { - - int startOffset_s = previewEntry->m_startTime; + itE = std::remove_if(previewCopy.begin(), previewCopy.end(), + [tcw](TrackEntry* pTE) { return tcw->getSelectedEntries().contains(pTE); }); + previewCopy.erase(itE, previewCopy.end()); + } - if (!hack) - startOffset_s -= startTimeMostLeft_s; + itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), [tcw](TrackEntry* pTE) { + bool x = tcw->getSelectedEntries().contains(pTE); - + return x; + }); + vecTrackEntries.erase(itE, vecTrackEntries.end()); - for (TrackEntry *pTrackEntry : std::as_const(vecTrackEntries)) - { - - - if (previewEntry->m_type != pTrackEntry->m_type) - { - - continue; - } + if (!previewCopy.size() || !vecTrackEntries.size()) + { - - if (previewEntry->m_topicId == pTrackEntry->m_topicId) - { - - continue; - } + return !vecParallelTopics.isEmpty(); + } - int startPreview_s = startOffset_s; + auto leftMostI = + std::min_element(previewCopy.constBegin(), previewCopy.constEnd(), + [](const TrackEntry* a, const TrackEntry* b) { return a->m_startTime < b->m_startTime; }); + + if (leftMostI == previewCopy.constEnd()) + return !vecParallelTopics.isEmpty(); + + int startTimeMostLeft_s = (*leftMostI)->m_startTime; + + QVector correspondingDifferentTopicTypes; + + for (TrackEntry* previewEntry : std::as_const(previewCopy)) + { + correspondingDifferentTopicTypes.clear(); + + int startOffset_s = previewEntry->m_startTime; if (!hack) - startPreview_s += dropTime_s; + startOffset_s -= startTimeMostLeft_s; - int endPreview_s = startPreview_s + previewEntry->m_length; - - if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, pTrackEntry)) + for (const QPair& pair : std::as_const(differentParallelForbidden)) { - - vecParallelTopics.append(previewEntry); - break; + if (pair.first == previewEntry->m_type) + correspondingDifferentTopicTypes += pair.second; + + if (pair.second == previewEntry->m_type) + correspondingDifferentTopicTypes += pair.first; } - - } + Q_ASSERT(!correspondingDifferentTopicTypes.isEmpty()); + + if (correspondingDifferentTopicTypes.isEmpty()) + continue; + + for (const TrackEntryType correspondingDifferentTopicType : std::as_const(correspondingDifferentTopicTypes)) + { + + for (TrackEntry* pTrackEntry : std::as_const(vecTrackEntries)) + { + + if (pTrackEntry->m_type != correspondingDifferentTopicType) + { + + continue; + } + + if (previewEntry->m_topicId == pTrackEntry->m_topicId) + { + + continue; + } + + int startPreview_s = startOffset_s; + + if (!hack) + startPreview_s += dropTime_s; + + int endPreview_s = startPreview_s + previewEntry->m_length; + + if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, pTrackEntry)) + { + + vecParallelTopics.append(previewEntry); + break; + } + } + } } - } - } - else - { - - } - } - - - - - { - - QVector previewCopy(preview); - sortTrackEntriesChronologically(previewCopy); - QVector > differentParallelForbidden = - { - { TrackEntryType::Situation, TrackEntryType::Snapshot }, - { TrackEntryType::Situation, TrackEntryType::SituationReplay }, - { TrackEntryType::Situation, TrackEntryType::SituationMap }, - }; - QVector vecTrackEntries(tcw->getTrackEntries()); - - - int step = 1; - auto findUnusedType = [differentParallelForbidden, &step](const TrackEntry *pTE) - { - auto x = std::find_if(differentParallelForbidden.constBegin(), differentParallelForbidden.constEnd(), [pTE, step](const QPair &pair) - { - bool x = (pair.first == pTE->m_type || pair.second == pTE->m_type); - if (x) - qDebug() << ">>"<m_type << "in type list - not removing"; - return x; - }); - - if (x == differentParallelForbidden.constEnd()) - qDebug() << ">>"<m_type << "not found in type list - removing!"; - - return (x == differentParallelForbidden.constEnd()); - }; - - - - auto itE = std::remove_if(previewCopy.begin(), previewCopy.end(), findUnusedType); - previewCopy.erase(itE, previewCopy.end()); - - - step = 2; - - itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), findUnusedType); - vecTrackEntries.erase(itE, vecTrackEntries.end()); - - - if (ignoreSelectedTopics) - { - - itE = std::remove_if(previewCopy.begin(), previewCopy.end(), - [tcw](TrackEntry *pTE) - { - return tcw->getSelectedEntries().contains(pTE); - }); - previewCopy.erase(itE, previewCopy.end()); } - - - itE = std::remove_if(vecTrackEntries.begin(), vecTrackEntries.end(), - [tcw](TrackEntry *pTE) - { - bool x = tcw->getSelectedEntries().contains(pTE); - - return x; - }); - vecTrackEntries.erase(itE, vecTrackEntries.end()); - - - - if (!previewCopy.size() || !vecTrackEntries.size()) - { - - return !vecParallelTopics.isEmpty(); - } - - - auto leftMostI = std::min_element(previewCopy.constBegin(), previewCopy.constEnd(), [](const TrackEntry * a, const TrackEntry * b) - { - return a->m_startTime < b->m_startTime; - }); - - if (leftMostI == previewCopy.constEnd()) - return !vecParallelTopics.isEmpty(); - - int startTimeMostLeft_s = (*leftMostI)->m_startTime; - - - - QVector correspondingDifferentTopicTypes; - - for (TrackEntry *previewEntry : std::as_const(previewCopy)) - { - correspondingDifferentTopicTypes.clear(); - - - int startOffset_s = previewEntry->m_startTime; - - if (!hack) - startOffset_s -= startTimeMostLeft_s; - - - for (const QPair &pair : std::as_const(differentParallelForbidden)) - { - if (pair.first == previewEntry->m_type) - correspondingDifferentTopicTypes += pair.second; - - if (pair.second == previewEntry->m_type) - correspondingDifferentTopicTypes += pair.first; - } - - Q_ASSERT(!correspondingDifferentTopicTypes.isEmpty()); - - if (correspondingDifferentTopicTypes.isEmpty()) - continue; - - for (const TrackEntryType correspondingDifferentTopicType : std::as_const(correspondingDifferentTopicTypes)) - { - - - for (TrackEntry *pTrackEntry : std::as_const(vecTrackEntries)) - { - - - if (pTrackEntry->m_type != correspondingDifferentTopicType) - { - - continue; - } - - - if (previewEntry->m_topicId == pTrackEntry->m_topicId) - { - - continue; - } - - int startPreview_s = startOffset_s; - - if (!hack) - startPreview_s += dropTime_s; - - int endPreview_s = startPreview_s + previewEntry->m_length; - - if (LtsScriptTimeline::isCollision2(startPreview_s, endPreview_s, pTrackEntry)) - { - - vecParallelTopics.append(previewEntry); - break; - } - - - } - } - } - } - - return !vecParallelTopics.isEmpty(); + return !vecParallelTopics.isEmpty(); } - -bool TrackContentWidget::checkForParallelTopics(const TrackContentWidget *pTCW, const QVector &vecPreviewTrackEntries, int dropTime_s, bool hack) +bool TrackContentWidget::checkForParallelTopics(const TrackContentWidget* pTCW, + const QVector& vecPreviewTrackEntries, int dropTime_s, + bool hack) { - QVector dummy_vecParallelTopics; - return checkForParallelTopics(pTCW, vecPreviewTrackEntries, dropTime_s, dummy_vecParallelTopics, false, hack); + QVector dummy_vecParallelTopics; + return checkForParallelTopics(pTCW, vecPreviewTrackEntries, dropTime_s, dummy_vecParallelTopics, false, hack); } - QString TrackContentWidget::mime = QStringLiteral("application/rheinmetall.script.topic"); - -TrackContentWidget::TrackContentWidget(QWidget *parent, bool isFilter, Tools *tools, int mainTopicId) - : QWidget(parent) - , m_selectHandler(new SelectHandler(this)) - , m_resizeHandler(new ResizeHandler(this)) - , m_dragHandler(new DragHandler(this)) - , m_dragOffsetTime(-1) - , m_dragPos(-1) - , m_mainSelected(nullptr) - , m_width(0) - , m_cursorSet(false) - , m_oldEntryLength(-1) - , m_unselectAllImmune(false) - , m_indicatorTime(-1) - , m_isFilter(isFilter) - , m_readonly(false) - , m_trackWidget(nullptr) - , m_scriptTimeline(nullptr) - , m_tools(tools) - , m_isMultiLineMultiSelectionMode(false) - , m_multiLineMultiSelectionOkay(false) - , m_dragPossible(false) - , m_moveValid(false) - , m_mainTopicId(mainTopicId) +TrackContentWidget::TrackContentWidget(QWidget* parent, bool isFilter, Tools* tools, int mainTopicId) + : QWidget(parent), m_selectHandler(new SelectHandler(this)), m_resizeHandler(new ResizeHandler(this)), + m_dragHandler(new DragHandler(this)), m_dragOffsetTime(-1), m_dragPos(-1), m_mainSelected(nullptr), m_width(0), + m_cursorSet(false), m_oldEntryLength(-1), m_unselectAllImmune(false), m_indicatorTime(-1), m_isFilter(isFilter), + m_readonly(false), m_trackWidget(nullptr), m_scriptTimeline(nullptr), m_tools(tools), + m_isMultiLineMultiSelectionMode(false), m_multiLineMultiSelectionOkay(false), m_dragPossible(false), + m_moveValid(false), m_mainTopicId(mainTopicId) { - setAcceptDrops(true); - setFocusPolicy(Qt::StrongFocus); - setMouseTracking(true); + setAcceptDrops(true); + setFocusPolicy(Qt::StrongFocus); + setMouseTracking(true); - addFilterType(TrackEntryType::TacticalPlan); - addFilterType(TrackEntryType::SituationMapFilter); + addFilterType(TrackEntryType::TacticalPlan); + addFilterType(TrackEntryType::SituationMapFilter); - - if (m_isFilter) - { - addAllowedType(TrackEntryType::Text); - addAllowedType(TrackEntryType::Pdf); - addAllowedType(TrackEntryType::Image); - } + if (m_isFilter) + { + addAllowedType(TrackEntryType::Text); + addAllowedType(TrackEntryType::Pdf); + addAllowedType(TrackEntryType::Image); + } } - TrackContentWidget::~TrackContentWidget() { - delete m_selectHandler; - delete m_resizeHandler; - delete m_dragHandler; + delete m_selectHandler; + delete m_resizeHandler; + delete m_dragHandler; - QVector entryList = m_entryList; + QVector entryList = m_entryList; - - for (TrackEntry *te : entryList) - { - disconnect(te, &TrackEntry::destroyed, - this, nullptr); - } + for (TrackEntry* te : entryList) + { + disconnect(te, &TrackEntry::destroyed, this, nullptr); + } - qDeleteAll(entryList); + qDeleteAll(entryList); } - bool TrackContentWidget::setDescriptionForSelected() { - if (getSelectedEntries().count() > 1) - { - QApplication::beep(); - return false; - } + if (getSelectedEntries().count() > 1) + { + QApplication::beep(); + return false; + } - m_selectHandler->slotSetDescription(); - return true; + m_selectHandler->slotSetDescription(); + return true; } - -void TrackContentWidget::addCorrespondingTrackWidget(TrackContentWidget *pCorrespondingTrackWidget) +void TrackContentWidget::addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget) { - m_tcwCorresponding += pCorrespondingTrackWidget; - m_dragHandler->m_tcwCorresponding += pCorrespondingTrackWidget; - m_resizeHandler->m_tcwCorresponding += pCorrespondingTrackWidget; + m_tcwCorresponding += pCorrespondingTrackWidget; + m_dragHandler->m_tcwCorresponding += pCorrespondingTrackWidget; + m_resizeHandler->m_tcwCorresponding += pCorrespondingTrackWidget; } - -void TrackContentWidget::setTools(Tools *tools) +void TrackContentWidget::setTools(Tools* tools) { - m_tools = tools; + m_tools = tools; } - -void TrackContentWidget::setTrackWidget(TrackWidget *trackWidget) +void TrackContentWidget::setTrackWidget(TrackWidget* trackWidget) { - m_trackWidget = trackWidget; + m_trackWidget = trackWidget; } - void TrackContentWidget::setReadonly(bool readonly) { - m_readonly = readonly; + m_readonly = readonly; } - -void TrackContentWidget::addFilterType(const TrackEntryType &tet) +void TrackContentWidget::addFilterType(const TrackEntryType& tet) { - if (m_isFilter) - addAllowedType(tet); - else - addDisallowedType(tet); + if (m_isFilter) + addAllowedType(tet); + else + addDisallowedType(tet); } - void TrackContentWidget::setIndicatorTime(int time) { - m_indicatorTime = time; - update(); + m_indicatorTime = time; + update(); } - -void TrackContentWidget::mouseMoveEvent(QMouseEvent *event) +void TrackContentWidget::mouseMoveEvent(QMouseEvent* event) { - if (!m_resizeHandler->mouseMoveEvent(event)) - m_dragHandler->mouseMoveEvent(event); + if (!m_resizeHandler->mouseMoveEvent(event)) + m_dragHandler->mouseMoveEvent(event); - emit signalModifyRubberband(); + emit signalModifyRubberband(); } - -TrackEntry *TrackContentWidget::getTrackEntryAt(int clickedTime) +TrackEntry* TrackContentWidget::getTrackEntryAt(int clickedTime) { - for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) - { - TrackEntry *te = *i; + for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) + { + TrackEntry* te = *i; - if (te->m_startTime <= clickedTime - && (te->m_startTime + te->m_length) >= clickedTime) - return te; - } + if (te->m_startTime <= clickedTime && (te->m_startTime + te->m_length) >= clickedTime) + return te; + } - return nullptr; + return nullptr; } - -void TrackContentWidget::mousePressEvent(QMouseEvent *event) +void TrackContentWidget::mousePressEvent(QMouseEvent* event) { - if (m_readonly) - return; + if (m_readonly) + return; - m_selectHandler->mousePressEvent(event); - m_resizeHandler->mousePressEvent(event); - m_dragHandler->mousePressEvent(event); + m_selectHandler->mousePressEvent(event); + m_resizeHandler->mousePressEvent(event); + m_dragHandler->mousePressEvent(event); - if (!m_selected.isEmpty()) - return; + if (!m_selected.isEmpty()) + return; - if (event->buttons() != Qt::LeftButton) - return; - emit signalStartRubberband(event->pos()); + if (event->buttons() != Qt::LeftButton) + return; + emit signalStartRubberband(event->pos()); } - -void TrackContentWidget::resizeEvent(QResizeEvent *event) +void TrackContentWidget::resizeEvent(QResizeEvent* event) { - QWidget::resizeEvent(event); - m_width = event->size().width(); + QWidget::resizeEvent(event); + m_width = event->size().width(); } - -void TrackContentWidget::mouseReleaseEvent(QMouseEvent *event) +void TrackContentWidget::mouseReleaseEvent(QMouseEvent* event) { - if (m_readonly) - return; + if (m_readonly) + return; - if (!m_resizeHandler->m_resizing) - m_selectHandler->mouseReleaseEvent(event); + if (!m_resizeHandler->m_resizing) + m_selectHandler->mouseReleaseEvent(event); - m_resizeHandler->mouseReleaseEvent(event); + m_resizeHandler->mouseReleaseEvent(event); - emit signalStopRubberband(); + emit signalStopRubberband(); } - -void TrackContentWidget::paintEvent(QPaintEvent *event) +void TrackContentWidget::paintEvent(QPaintEvent* event) { - Q_UNUSED(event); + Q_UNUSED(event); - QPainter painter(this); - - painter.save(); - - - - if (m_isFilter) - { - painter.setBrush(QGuiApplication::palette().window().color()); - painter.drawRect(rect()); - } - - - - painter.setPen(QColor(36, 36, 36)); - painter.drawLine(QPoint(0, 0), QPoint(0, height())); - - if (m_isFilter) - painter.drawLine(QPoint(width() - 1, 0), QPoint(width() - 1, height())); - - - - painter.setClipping(true); - painter.setClipRect(1, 1, width() - 1, height() - 1); - - - - for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) - { - TrackEntry *te = *i; - - int startPx = m_tools->getPos(te->m_startTime, m_isFilter); - int endPx = m_tools->getPos(te->m_startTime + te->m_length, m_isFilter); - - if (endPx < 0 || startPx > width()) - continue; - - int heightPx = height() - 2; - int lengthPx = endPx - startPx; - + QPainter painter(this); painter.save(); - painter.translate(startPx, 1); - bool isSelected = m_selected.contains(te); - QRect trackRect(0, 0, lengthPx, heightPx); - drawTrackEntry(te, painter, trackRect, isSelected); - - if (isSelected) + if (m_isFilter) { - - + painter.setBrush(QGuiApplication::palette().window().color()); + painter.drawRect(rect()); + } + painter.setPen(QColor(36, 36, 36)); + painter.drawLine(QPoint(0, 0), QPoint(0, height())); + + if (m_isFilter) + painter.drawLine(QPoint(width() - 1, 0), QPoint(width() - 1, height())); + + painter.setClipping(true); + painter.setClipRect(1, 1, width() - 1, height() - 1); + + for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) + { + TrackEntry* te = *i; + + int startPx = m_tools->getPos(te->m_startTime, m_isFilter); + int endPx = m_tools->getPos(te->m_startTime + te->m_length, m_isFilter); + + if (endPx < 0 || startPx > width()) + continue; + + int heightPx = height() - 2; + int lengthPx = endPx - startPx; + + painter.save(); + painter.translate(startPx, 1); + + bool isSelected = m_selected.contains(te); + QRect trackRect(0, 0, lengthPx, heightPx); + drawTrackEntry(te, painter, trackRect, isSelected); + + if (isSelected) + { + } + + painter.restore(); + } + + if (m_dragPos > -1 && !m_preview.isEmpty()) + { + int firstTeTime = -1; + + for (const TrackEntry* te : std::as_const(m_preview)) + { + if (firstTeTime > te->m_startTime || firstTeTime == -1) + firstTeTime = te->m_startTime; + } + + int drop = m_tools->getTime(m_dragPos, m_isFilter); + int finalDrop = drop - m_dragOffsetTime; + int diff = finalDrop - firstTeTime; + int heightPx = height() - 2; + + for (auto i = m_preview.constBegin(); i != m_preview.constEnd(); ++i) + { + const TrackEntry* te = *i; + + if (m_dragHandler->m_vecCollisions.contains(*i) || m_dragHandler->m_vecParallel.contains(*i) || + !isDragPossible() || !m_moveValid) + painter.setBrush(QColor("red")); + else + painter.setBrush(QColor("lightgreen")); + + int time = te->m_startTime + diff; + + int startPx = m_tools->getPos(time, m_isFilter); + int endPx = m_tools->getPos(time + te->m_length, m_isFilter); + + if (endPx < 0 || startPx > width()) + continue; + + int lengthPx = endPx - startPx; + painter.drawRect(startPx, 1, lengthPx, heightPx); + } + } + + if (m_indicatorTime > -1) + { + int pos = m_tools->getPos(m_indicatorTime, m_isFilter); + + if (pos > 0 && pos <= m_tools->m_paintWidth) + { + painter.setPen(QColor("cyan")); + painter.drawLine(pos, 0, pos, height()); + } } painter.restore(); - } - - - - if (m_dragPos > -1 && !m_preview.isEmpty()) - { - int firstTeTime = -1; - - for (const TrackEntry *te : std::as_const(m_preview)) - { - if (firstTeTime > te->m_startTime || firstTeTime == -1) - firstTeTime = te->m_startTime; - } - - int drop = m_tools->getTime(m_dragPos, m_isFilter); - int finalDrop = drop - m_dragOffsetTime; - int diff = finalDrop - firstTeTime; - int heightPx = height() - 2; - - for (auto i = m_preview.constBegin(); i != m_preview.constEnd(); ++i) - { - const TrackEntry *te = *i; - - if (m_dragHandler->m_vecCollisions.contains(*i) || m_dragHandler->m_vecParallel.contains(*i) || !isDragPossible() || !m_moveValid) - painter.setBrush(QColor("red")); - else - painter.setBrush(QColor("lightgreen")); - - int time = te->m_startTime + diff; - - int startPx = m_tools->getPos(time, m_isFilter); - int endPx = m_tools->getPos(time + te->m_length, m_isFilter); - - if (endPx < 0 || startPx > width()) - continue; - - int lengthPx = endPx - startPx; - painter.drawRect(startPx, 1, lengthPx, heightPx); - } - } - - - - if (m_indicatorTime > -1) - { - int pos = m_tools->getPos(m_indicatorTime, m_isFilter); - - if (pos > 0 && pos <= m_tools->m_paintWidth) - { - painter.setPen(QColor("cyan")); - painter.drawLine(pos, 0, pos, height()); - } - } - - - painter.restore(); } - -void TrackContentWidget::dragEnterEvent(QDragEnterEvent *event) +void TrackContentWidget::dragEnterEvent(QDragEnterEvent* event) { - if (m_readonly) - return; + if (m_readonly) + return; - m_dragHandler->dragEnterEvent(event); + m_dragHandler->dragEnterEvent(event); } +void TrackContentWidget::dragLeave() {} -void TrackContentWidget::dragLeave() +void TrackContentWidget::dragLeaveEvent(QDragLeaveEvent* event) { + if (m_readonly) + return; + m_dragHandler->dragLeaveEvent(event); } - -void TrackContentWidget::dragLeaveEvent(QDragLeaveEvent *event) -{ - if (m_readonly) - return; - - m_dragHandler->dragLeaveEvent(event); -} - - void TrackContentWidget::unselect() { - m_unselectAllImmune = true; - emit signalUnselectAll(); - m_unselectAllImmune = false; + m_unselectAllImmune = true; + emit signalUnselectAll(); + m_unselectAllImmune = false; } - void TrackContentWidget::forceLocalUnselect() { - m_mainSelected = nullptr; - m_selected.clear(); + m_mainSelected = nullptr; + m_selected.clear(); } - void TrackContentWidget::selectAll() { - m_selected.clear(); + m_selected.clear(); - for (TrackEntry *te : std::as_const(m_entryList)) - { - m_selected.append(te); - m_mainSelected = te; - } + for (TrackEntry* te : std::as_const(m_entryList)) + { + m_selected.append(te); + m_mainSelected = te; + } - emit signalTrackEntrySelectionChanged(nullptr); - update(); + emit signalTrackEntrySelectionChanged(nullptr); + update(); } - void TrackContentWidget::unselectAll() { - if (!m_unselectAllImmune) - forceLocalUnselect(); - else - { - if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + if (!m_unselectAllImmune) + forceLocalUnselect(); + else { - forceLocalUnselect(); - emit signalTrackEntrySelectionChanged(nullptr); - } - } - - update(); -} - - -TrackEntry *TrackContentWidget::getParentTopicOfFilter(TrackEntry *filterTe) const -{ - - if (m_isFilter && m_trackWidget != nullptr) - { - - int mainTopicId = m_trackWidget->getParentTopicIdOfFilter(filterTe); - TrackContentWidget *mainTcw = m_trackWidget->getTrackContentWidget(); - const QVector &teList = mainTcw->getTrackEntries(); - - for (auto i = teList.constBegin(); i != teList.constEnd(); ++i) - { - TrackEntry *mainTe = *i; - - if (mainTe->m_topicId != mainTopicId) - continue; - - return mainTe; - } - } - - return nullptr; -} - - -bool TrackContentWidget::addTrackEntry(TrackEntry *te, bool selectTrackEntry) -{ - if (!allowedByType(te)) - { - qWarning() << "TrackContentWidget::addTrackEntry: topic #" << te->m_topicId << "type" << (int)te->m_type << "not allowed"; - return false; - } - - connect(te, &TrackEntry::destroyed, - this, [this]() - { - TrackEntry *o = static_cast(sender()); - m_entryList.removeAll(o); - m_selected.removeAll(o); - - if (m_mainSelected == o) - { - m_mainSelected = nullptr; - emit signalTrackEntrySelectionChanged(nullptr); - } - }); - - te->m_channelName = m_trackName; - m_entryList.append(te); - - - TrackEntry *mainTe = getParentTopicOfFilter(te); - - if (mainTe != nullptr) - { - - if ((te->m_startTime + te->m_length) > mainTe->m_length) - te->m_length = mainTe->m_length - te->m_startTime; - - te->m_filterParentChannel = mainTe->m_channelName; - } - - - if (selectTrackEntry && !m_readonly) - selectEntry(te); - - emit signalTrackEntryAdded(te); - - update(); - return true; -} - - -void TrackContentWidget::removeTrackEntryByTopicId(TrackEntry *te) -{ - auto itE = std::remove_if(m_entryList.begin(), m_entryList.end(), - [te](TrackEntry * pTE) - { - if (pTE->m_topicId == te->m_topicId) - { - pTE->deleteLater(); - return true; + if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + { + forceLocalUnselect(); + emit signalTrackEntrySelectionChanged(nullptr); + } } - return false; - }); - m_entryList.erase(itE, m_entryList.end()); + update(); +} +TrackEntry* TrackContentWidget::getParentTopicOfFilter(TrackEntry* filterTe) const +{ - itE = std::remove_if(m_selected.begin(), m_selected.end(), - [te](TrackEntry * pTE) - { - if (pTE->m_topicId == te->m_topicId) + if (m_isFilter && m_trackWidget != nullptr) { - pTE->deleteLater(); - return true; + + int mainTopicId = m_trackWidget->getParentTopicIdOfFilter(filterTe); + TrackContentWidget* mainTcw = m_trackWidget->getTrackContentWidget(); + const QVector& teList = mainTcw->getTrackEntries(); + + for (auto i = teList.constBegin(); i != teList.constEnd(); ++i) + { + TrackEntry* mainTe = *i; + + if (mainTe->m_topicId != mainTopicId) + continue; + + return mainTe; + } } - return false; - }); - m_selected.erase(itE, m_selected.end()); + return nullptr; } - -void TrackContentWidget::dropEvent(QDropEvent *event) +bool TrackContentWidget::addTrackEntry(TrackEntry* te, bool selectTrackEntry) { - if (m_readonly) - return; + if (!allowedByType(te)) + { + qWarning() << "TrackContentWidget::addTrackEntry: topic #" << te->m_topicId << "type" << (int)te->m_type + << "not allowed"; + return false; + } - m_dragHandler->dropEvent(event); + connect(te, &TrackEntry::destroyed, this, [this]() { + TrackEntry* o = static_cast(sender()); + m_entryList.removeAll(o); + m_selected.removeAll(o); + + if (m_mainSelected == o) + { + m_mainSelected = nullptr; + emit signalTrackEntrySelectionChanged(nullptr); + } + }); + + te->m_channelName = m_trackName; + m_entryList.append(te); + + TrackEntry* mainTe = getParentTopicOfFilter(te); + + if (mainTe != nullptr) + { + + if ((te->m_startTime + te->m_length) > mainTe->m_length) + te->m_length = mainTe->m_length - te->m_startTime; + + te->m_filterParentChannel = mainTe->m_channelName; + } + + if (selectTrackEntry && !m_readonly) + selectEntry(te); + + emit signalTrackEntryAdded(te); + + update(); + return true; } - -void TrackContentWidget::dragMoveEvent(QDragMoveEvent *event) +void TrackContentWidget::removeTrackEntryByTopicId(TrackEntry* te) { - if (m_readonly) - return; + auto itE = std::remove_if(m_entryList.begin(), m_entryList.end(), [te](TrackEntry* pTE) { + if (pTE->m_topicId == te->m_topicId) + { + pTE->deleteLater(); + return true; + } - m_dragHandler->dragMoveEvent(event); + return false; + }); + m_entryList.erase(itE, m_entryList.end()); + + itE = std::remove_if(m_selected.begin(), m_selected.end(), [te](TrackEntry* pTE) { + if (pTE->m_topicId == te->m_topicId) + { + pTE->deleteLater(); + return true; + } + + return false; + }); + m_selected.erase(itE, m_selected.end()); } +void TrackContentWidget::dropEvent(QDropEvent* event) +{ + if (m_readonly) + return; + + m_dragHandler->dropEvent(event); +} + +void TrackContentWidget::dragMoveEvent(QDragMoveEvent* event) +{ + if (m_readonly) + return; + + m_dragHandler->dragMoveEvent(event); +} bool TrackContentWidget::canMoveAll(int offset) const { - if (m_selected.isEmpty()) - return true; + if (m_selected.isEmpty()) + return true; - auto leftMostI = std::min_element(m_selected.constBegin(), m_selected.constEnd(), [](const TrackEntry * a, const TrackEntry * b) - { - return a->m_startTime < b->m_startTime; - }); + auto leftMostI = + std::min_element(m_selected.constBegin(), m_selected.constEnd(), + [](const TrackEntry* a, const TrackEntry* b) { return a->m_startTime < b->m_startTime; }); - if (leftMostI == m_selected.constEnd()) - return false; + if (leftMostI == m_selected.constEnd()) + return false; - int startTimeMostLeft = (*leftMostI)->m_startTime; + int startTimeMostLeft = (*leftMostI)->m_startTime; - - QVector cols; + QVector cols; - int newTime = startTimeMostLeft + offset; - checkForCollisions(this, m_selected, newTime, cols, true); + int newTime = startTimeMostLeft + offset; + checkForCollisions(this, m_selected, newTime, cols, true); - QVector parls; - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - checkForParallelTopics(tcw, m_selected, newTime, parls); + QVector parls; + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + checkForParallelTopics(tcw, m_selected, newTime, parls); - if (!cols.isEmpty() || !parls.isEmpty()) - return false; + if (!cols.isEmpty() || !parls.isEmpty()) + return false; - return true; + return true; } - void TrackContentWidget::forceMoveAll(int offset) { - for (auto i = m_selected.begin(); i != m_selected.end(); ++i) - { - TrackEntry *te = *i; + for (auto i = m_selected.begin(); i != m_selected.end(); ++i) + { + TrackEntry* te = *i; - - int newTime = te->m_startTime + offset; + int newTime = te->m_startTime + offset; - if (newTime < 0) - newTime = 0; + if (newTime < 0) + newTime = 0; - + te->m_startTime = newTime; + } - - te->m_startTime = newTime; - } - - update(); - emit signalChangesMade(); + update(); + emit signalChangesMade(); } - void TrackContentWidget::deleteSelectedTopics() { - m_mainSelected = nullptr; - m_selectHandler->m_pressedEntry = nullptr; + m_mainSelected = nullptr; + m_selectHandler->m_pressedEntry = nullptr; - bool somethingSeleted = false; - for (auto &pTopic : m_selected) - { - m_preview.removeAll(pTopic); - m_entryList.removeAll(pTopic); - emit signalTrackEntryDeleted(pTopic->m_topicId); - pTopic->deleteLater(); - somethingSeleted = true; - } - - if (somethingSeleted) - emit signalTrackEntrySelectionChanged(nullptr); - - m_selected.clear(); - emit signalChangesMade(); - update(); -} - - -void TrackContentWidget::mouseDoubleClickEvent(QMouseEvent *event) -{ - if (m_readonly) - return; - - m_selectHandler->mouseDoubleClick(event); -} - - -void TrackContentWidget::keyPressEvent(QKeyEvent *event) -{ - if (m_readonly) - return; - - if (event->key() == Qt::Key_Delete) - { - emit signalDeleteSelectedTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_C) - { - emit signalCopyTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_V) - { - emit signalPasteTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_X) - { - emit signalCutTopics(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_A) - { - emit signalSelectAllGlobal(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_S) - { - emit signalSave(); - } - else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_D) - { - setDescriptionForSelected(); - } - else - { - m_resizeHandler->keyPressEvent(event); - m_selectHandler->keyPressEvent(event); - m_dragHandler->keyPressEvent(event); - } - - if (event->key() == Qt::Key_Escape) - { - emit signalEscapeRubberband(); - emit signalMultiLineMultiSelectionDone(-1); - } -} - - -void TrackContentWidget::selectEntry(int topicId) -{ - for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) - { - TrackEntry *te = *i; - - if (te->m_topicId == topicId) + bool somethingSeleted = false; + for (auto& pTopic : m_selected) { - selectEntry((te)); - return; + m_preview.removeAll(pTopic); + m_entryList.removeAll(pTopic); + emit signalTrackEntryDeleted(pTopic->m_topicId); + pTopic->deleteLater(); + somethingSeleted = true; } - } + + if (somethingSeleted) + emit signalTrackEntrySelectionChanged(nullptr); + + m_selected.clear(); + emit signalChangesMade(); + update(); } +void TrackContentWidget::mouseDoubleClickEvent(QMouseEvent* event) +{ + if (m_readonly) + return; + + m_selectHandler->mouseDoubleClick(event); +} + +void TrackContentWidget::keyPressEvent(QKeyEvent* event) +{ + if (m_readonly) + return; + + if (event->key() == Qt::Key_Delete) + { + emit signalDeleteSelectedTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_C) + { + emit signalCopyTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_V) + { + emit signalPasteTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_X) + { + emit signalCutTopics(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_A) + { + emit signalSelectAllGlobal(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_S) + { + emit signalSave(); + } + else if (QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && event->key() == Qt::Key_D) + { + setDescriptionForSelected(); + } + else + { + m_resizeHandler->keyPressEvent(event); + m_selectHandler->keyPressEvent(event); + m_dragHandler->keyPressEvent(event); + } + + if (event->key() == Qt::Key_Escape) + { + emit signalEscapeRubberband(); + emit signalMultiLineMultiSelectionDone(-1); + } +} + +void TrackContentWidget::selectEntry(int topicId) +{ + for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) + { + TrackEntry* te = *i; + + if (te->m_topicId == topicId) + { + selectEntry((te)); + return; + } + } +} void TrackContentWidget::selectEntriesAtPositions(int fromPos, int toPos) { - m_unselectAllImmune = true; - - for (TrackEntry *te : std::as_const(m_entryList)) - { - int start = m_tools->getPos(te->m_startTime); - int end = m_tools->getPos(te->m_startTime + te->m_length); - if (end >= fromPos && start <= toPos) - selectEntry(te); - } - - m_unselectAllImmune = false; -} - - -void TrackContentWidget::selectEntry(TrackEntry *te) -{ - bool ctrl = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier); - - if (!m_unselectAllImmune && !ctrl) - unselect(); - - if (te == nullptr) - return; - - if (!m_selected.contains(te)) - { - m_selected.append(te); - m_mainSelected = te; - - emit signalTrackEntrySelectionChanged(nullptr); - } - else - { - m_selected.removeAll(te); - if (m_mainSelected == te) - m_mainSelected = nullptr; - - emit signalTrackEntrySelectionChanged(nullptr); - } - - update(); -} - - -bool TrackContentWidget::canPasteTopics(const QVector &topics, int offsetTime, int pasteTime) const -{ - TemporaryPointerVector newTes; - - newTes.reserve(topics.size()); - for (TrackEntry *te : std::as_const(topics)) - { - TrackEntry *newTe = new TrackEntry(te); - newTe->m_startTime = (newTe->m_startTime - offsetTime + pasteTime); - newTes += newTe; - } - - - - QVector dummy_vecCollidingTopics; - - bool parl = false; - - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - { - parl = checkForParallelTopics(tcw, newTes, pasteTime, true ); - if (parl) - break; - } - - if (checkForCollisions(this, newTes, pasteTime, dummy_vecCollidingTopics, false, true) || parl) - return false; - - return true; - - - -} - - -void TrackContentWidget::forcePasteTopics(const QVector &topics, int offsetTime, int pasteTime) -{ - - - m_selected.clear(); - - - for (TrackEntry *te : std::as_const(topics)) - { - TrackEntry *newTe = new TrackEntry(te); - newTe->m_topicId = m_scriptTimeline->nextUniqueId(); - newTe->m_startTime = (newTe->m_startTime - offsetTime + pasteTime); - newTe->isSet = true; - m_unselectAllImmune = true; - if (!m_trackWidget->addTrackEntry(newTe, false)) + + for (TrackEntry* te : std::as_const(m_entryList)) { - qWarning() << "TrackContentWidget::forcePasteTopics: topic #" << te->m_topicId << "type" << (int)te->m_type << "not allowed"; - delete newTe; - delete te; - continue; + int start = m_tools->getPos(te->m_startTime); + int end = m_tools->getPos(te->m_startTime + te->m_length); + if (end >= fromPos && start <= toPos) + selectEntry(te); } + m_unselectAllImmune = false; - } } - -bool TrackContentWidget::allowedByType(const TrackEntry *te) const +void TrackContentWidget::selectEntry(TrackEntry* te) { - if (m_disallowedTypes.contains(te->m_type)) - return false; + bool ctrl = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier); - if (m_allowedTypes.isEmpty()) - return true; + if (!m_unselectAllImmune && !ctrl) + unselect(); - return (m_allowedTypes.contains(te->m_type)); -} + if (te == nullptr) + return; - -void TrackContentWidget::setTrackName(const QString &trackName) -{ - m_trackName = trackName; - - for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) - { - TrackEntry *te = *i; - te->m_channelName = m_trackName; - } -} - - -TrackEntry *TrackContentWidget::getTrackEntryOnPos(QPoint globalPos) -{ - QPoint clickedPos = mapFromGlobal(globalPos); - int clickedPosY = clickedPos.y(); - int clickedPosX = clickedPos.x(); - - if (clickedPosY < 0 || clickedPosY > height()) - return nullptr; - - int clickedTime = m_tools->getTime(clickedPosX, m_isFilter); - - return getTrackEntryAt(clickedTime); -} - - -QVector TrackContentWidget::dataToItems(const QByteArray &data, int &offset) -{ - if (data.isEmpty()) - return {}; - - QDataStream dataStream(data); - - int count; - dataStream >> count; - dataStream >> offset; - - QVector tes; - tes.reserve(count); - for (int i = 0; i < count; i++) - { - TrackEntry *te = new TrackEntry; - dataStream >> *te; - te->m_startTime -= offset; - tes += te; - } - - return tes; -} - - -bool TrackContentWidget::dragEnter(const QByteArray &itemData) -{ - dragEnd(); - - TemporaryPointerVector tes(dataToItems(itemData, m_dragOffsetTime)); - - if (tes.isEmpty()) - return false; - - for (TrackEntry *te : std::as_const(tes)) - { - if (!allowedByType(te)) + if (!m_selected.contains(te)) { - qWarning() << "TrackContentWidget::dragEnter: topic #" << te->m_topicId << "type" << (int)te->m_type << "not allowed"; - return false; + m_selected.append(te); + m_mainSelected = te; + + emit signalTrackEntrySelectionChanged(nullptr); } - } - - if (m_isFilter && m_mainTopicId != -1) - { - auto it = std::find_if(tes.begin(), tes.end(), [this](const TrackEntry * a) + else { - return (a->m_topicId == m_mainTopicId); - }); + m_selected.removeAll(te); + if (m_mainSelected == te) + m_mainSelected = nullptr; - if (it != tes.end()) - return false; - } + emit signalTrackEntrySelectionChanged(nullptr); + } - const QVector &thisTes = getTrackEntries(); + update(); +} - - if (m_isMultiLineMultiSelectionMode) - { - for (TrackEntry *te : std::as_const(tes)) +bool TrackContentWidget::canPasteTopics(const QVector& topics, int offsetTime, int pasteTime) const +{ + TemporaryPointerVector newTes; + + newTes.reserve(topics.size()); + for (TrackEntry* te : std::as_const(topics)) { - bool found = false; + TrackEntry* newTe = new TrackEntry(te); + newTe->m_startTime = (newTe->m_startTime - offsetTime + pasteTime); + newTes += newTe; + } - for (TrackEntry *thisTe : std::as_const(thisTes)) - { - if (thisTe->m_topicId == te->m_topicId) - { - found = true; - break; - } - } + QVector dummy_vecCollidingTopics; - if (!found) + bool parl = false; + + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + { + parl = checkForParallelTopics(tcw, newTes, pasteTime, true); + if (parl) + break; + } + + if (checkForCollisions(this, newTes, pasteTime, dummy_vecCollidingTopics, false, true) || parl) return false; - } - } - sortTrackEntriesChronologically(tes); + return true; +} - +void TrackContentWidget::forcePasteTopics(const QVector& topics, int offsetTime, int pasteTime) +{ - if (!m_isFilter && tes.size() == 1) - { - TrackEntry *pPreview = tes.front(); - bool hasJustBeenAddedByUser = true; + m_selected.clear(); - for (auto pTE : std::as_const(m_entryList)) + for (TrackEntry* te : std::as_const(topics)) { - if (pPreview->m_topicId == pTE->m_topicId) - { - hasJustBeenAddedByUser = false; - break; - } - } + TrackEntry* newTe = new TrackEntry(te); + newTe->m_topicId = m_scriptTimeline->nextUniqueId(); + newTe->m_startTime = (newTe->m_startTime - offsetTime + pasteTime); + newTe->isSet = true; - - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - { - for (auto pTE : std::as_const(tcw->m_entryList)) - { - if (pPreview->m_topicId == pTE->m_topicId) + m_unselectAllImmune = true; + if (!m_trackWidget->addTrackEntry(newTe, false)) { - hasJustBeenAddedByUser = false; - break; + qWarning() << "TrackContentWidget::forcePasteTopics: topic #" << te->m_topicId << "type" << (int)te->m_type + << "not allowed"; + delete newTe; + delete te; + continue; } - } + m_unselectAllImmune = false; } +} - if (hasJustBeenAddedByUser) +bool TrackContentWidget::allowedByType(const TrackEntry* te) const +{ + if (m_disallowedTypes.contains(te->m_type)) + return false; + + if (m_allowedTypes.isEmpty()) + return true; + + return (m_allowedTypes.contains(te->m_type)); +} + +void TrackContentWidget::setTrackName(const QString& trackName) +{ + m_trackName = trackName; + + for (auto i = m_entryList.begin(); i != m_entryList.end(); ++i) { - - m_selected.clear(); - - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - tcw->m_selected.clear(); + TrackEntry* te = *i; + te->m_channelName = m_trackName; } - } +} - tes.setDiscardable(false); - m_preview = tes; - return true; +TrackEntry* TrackContentWidget::getTrackEntryOnPos(QPoint globalPos) +{ + QPoint clickedPos = mapFromGlobal(globalPos); + int clickedPosY = clickedPos.y(); + int clickedPosX = clickedPos.x(); + + if (clickedPosY < 0 || clickedPosY > height()) + return nullptr; + + int clickedTime = m_tools->getTime(clickedPosX, m_isFilter); + + return getTrackEntryAt(clickedTime); +} + +QVector TrackContentWidget::dataToItems(const QByteArray& data, int& offset) +{ + if (data.isEmpty()) + return {}; + + QDataStream dataStream(data); + + int count; + dataStream >> count; + dataStream >> offset; + + QVector tes; + tes.reserve(count); + for (int i = 0; i < count; i++) + { + TrackEntry* te = new TrackEntry; + dataStream >> *te; + te->m_startTime -= offset; + tes += te; + } + + return tes; +} + +bool TrackContentWidget::dragEnter(const QByteArray& itemData) +{ + dragEnd(); + + TemporaryPointerVector tes(dataToItems(itemData, m_dragOffsetTime)); + + if (tes.isEmpty()) + return false; + + for (TrackEntry* te : std::as_const(tes)) + { + if (!allowedByType(te)) + { + qWarning() << "TrackContentWidget::dragEnter: topic #" << te->m_topicId << "type" << (int)te->m_type + << "not allowed"; + return false; + } + } + + if (m_isFilter && m_mainTopicId != -1) + { + auto it = std::find_if(tes.begin(), tes.end(), + [this](const TrackEntry* a) { return (a->m_topicId == m_mainTopicId); }); + + if (it != tes.end()) + return false; + } + + const QVector& thisTes = getTrackEntries(); + + if (m_isMultiLineMultiSelectionMode) + { + for (TrackEntry* te : std::as_const(tes)) + { + bool found = false; + + for (TrackEntry* thisTe : std::as_const(thisTes)) + { + if (thisTe->m_topicId == te->m_topicId) + { + found = true; + break; + } + } + + if (!found) + return false; + } + } + + sortTrackEntriesChronologically(tes); + + if (!m_isFilter && tes.size() == 1) + { + TrackEntry* pPreview = tes.front(); + bool hasJustBeenAddedByUser = true; + + for (auto pTE : std::as_const(m_entryList)) + { + if (pPreview->m_topicId == pTE->m_topicId) + { + hasJustBeenAddedByUser = false; + break; + } + } + + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + { + for (auto pTE : std::as_const(tcw->m_entryList)) + { + if (pPreview->m_topicId == pTE->m_topicId) + { + hasJustBeenAddedByUser = false; + break; + } + } + } + + if (hasJustBeenAddedByUser) + { + + m_selected.clear(); + + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + tcw->m_selected.clear(); + } + } + + tes.setDiscardable(false); + m_preview = tes; + return true; } void TrackContentWidget::clearDrag() { - qDeleteAll(m_preview); - m_preview.clear(); - m_dragOffsetTime = -1; - m_dragPos = -1; - m_dragPossible = false; - m_moveValid = false; - update(); + qDeleteAll(m_preview); + m_preview.clear(); + m_dragOffsetTime = -1; + m_dragPos = -1; + m_dragPossible = false; + m_moveValid = false; + update(); } int TrackContentWidget::getDropPos() const { - return (m_dragHandler == nullptr) ? -1 : m_dragHandler->m_dropPos; + return (m_dragHandler == nullptr) ? -1 : m_dragHandler->m_dropPos; } - void TrackContentWidget::dragEnd() { - clearDrag(); + clearDrag(); } bool TrackContentWidget::dragDrop(int pos) { - if (!isDragPossible() || !m_moveValid) - { - dragEnd(); - return false; - } - - int dropTime = m_tools->getTime(pos, m_isFilter) - m_dragOffsetTime; - QVector selectedOld = m_selected; - - if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && !m_isMultiLineMultiSelectionMode) - unselect(); - - int firstTeTime = -1; - - for (const TrackEntry *te : std::as_const(m_preview)) - { - if (firstTeTime > te->m_startTime || firstTeTime == -1) - firstTeTime = te->m_startTime; - } - - int selected = firstTeTime; - int diff = dropTime - selected; - - - for (auto i = m_preview.constBegin(); i != m_preview.constEnd(); ++i) - { - TrackEntry *prevTe = *i; - TrackEntry *newTe = new TrackEntry(prevTe); - newTe->m_topicId = m_scriptTimeline->nextUniqueId(); - newTe->m_startTime = prevTe->m_startTime + diff; - newTe->isSet = true; - - - - m_unselectAllImmune = true; - if (m_isFilter) + if (!isDragPossible() || !m_moveValid) { - addTrackEntry(newTe, true); - } - else - { - if (m_trackWidget == nullptr || !m_trackWidget->addTrackEntry(newTe, true)) - { - delete newTe; + dragEnd(); return false; - } } - update(); + int dropTime = m_tools->getTime(pos, m_isFilter) - m_dragOffsetTime; + QVector selectedOld = m_selected; - - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - tcw->removeTrackEntryByTopicId(prevTe); + if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && !m_isMultiLineMultiSelectionMode) + unselect(); - m_unselectAllImmune = false; - } + int firstTeTime = -1; - dragEnd(); + for (const TrackEntry* te : std::as_const(m_preview)) + { + if (firstTeTime > te->m_startTime || firstTeTime == -1) + firstTeTime = te->m_startTime; + } - if (m_isMultiLineMultiSelectionMode) - { - - for (TrackEntry *oldSel : std::as_const(selectedOld)) - emit signalTrackEntryDeleted(oldSel->m_topicId); - qDeleteAll(selectedOld); + int selected = firstTeTime; + int diff = dropTime - selected; - emit signalMultiLineMultiSelectionDone(pos); - } + for (auto i = m_preview.constBegin(); i != m_preview.constEnd(); ++i) + { + TrackEntry* prevTe = *i; + TrackEntry* newTe = new TrackEntry(prevTe); + newTe->m_topicId = m_scriptTimeline->nextUniqueId(); + newTe->m_startTime = prevTe->m_startTime + diff; + newTe->isSet = true; - emit signalChangesMade(); - return true; + m_unselectAllImmune = true; + if (m_isFilter) + { + addTrackEntry(newTe, true); + } + else + { + if (m_trackWidget == nullptr || !m_trackWidget->addTrackEntry(newTe, true)) + { + delete newTe; + return false; + } + } + + update(); + + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + tcw->removeTrackEntryByTopicId(prevTe); + + m_unselectAllImmune = false; + } + + dragEnd(); + + if (m_isMultiLineMultiSelectionMode) + { + + for (TrackEntry* oldSel : std::as_const(selectedOld)) + emit signalTrackEntryDeleted(oldSel->m_topicId); + qDeleteAll(selectedOld); + + emit signalMultiLineMultiSelectionDone(pos); + } + + emit signalChangesMade(); + return true; } bool TrackContentWidget::dragMove(int pos) { - m_dragPos = pos; + m_dragPos = pos; - - int dropTime_s = m_tools->getTime(m_dragPos, m_isFilter) - m_dragOffsetTime; - checkForCollisions(this, m_preview, dropTime_s, m_dragHandler->m_vecCollisions, true); + int dropTime_s = m_tools->getTime(m_dragPos, m_isFilter) - m_dragOffsetTime; + checkForCollisions(this, m_preview, dropTime_s, m_dragHandler->m_vecCollisions, true); - m_dragHandler->m_vecParallel.clear(); - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - checkForParallelTopics(tcw, m_preview, dropTime_s, m_dragHandler->m_vecParallel); + m_dragHandler->m_vecParallel.clear(); + for (const auto& tcw : std::as_const(m_tcwCorresponding)) + checkForParallelTopics(tcw, m_preview, dropTime_s, m_dragHandler->m_vecParallel); - m_moveValid = m_dragHandler->m_vecCollisions.isEmpty() && m_dragHandler->m_vecParallel.isEmpty(); + m_moveValid = m_dragHandler->m_vecCollisions.isEmpty() && m_dragHandler->m_vecParallel.isEmpty(); - if (!m_moveValid || !isDragPossible()) - { - - setCursor(Qt::ForbiddenCursor); - } - else - { - setCursor(Qt::DragMoveCursor); - } - - update(); - - if (m_isMultiLineMultiSelectionMode) - { - if (m_moveValid) - emit signalMultiLineMultiSelectionOkay(); - else - emit signalMultiLineMultiSelectionFailed(); - } - - - - static int scrollByPixels = 1; - - if (pos >= (m_width - 60)) - emit signalScroll(scrollByPixels); - else if (pos < 60) - emit signalScroll(-scrollByPixels); - - return m_moveValid; -} - - -TrackEntry *TrackContentWidget::trackEntryAtPos(int x) const -{ - int time = m_tools->getTime(x); - const QVector tes = getTrackEntries(); - - for (TrackEntry *te : tes) - { - int start = te->m_startTime; - if (time >= start && time <= (start + te->m_length)) - return te; - } - - return nullptr; -} - - -QByteArray TrackContentWidget::itemsToData(const QVector &items, int dragPosTime, bool calculateFirstTeTime) -{ - int count = items.count(); - if (!count) - return {}; - - QByteArray itemData; - QDataStream dataStream(&itemData, QIODevice::WriteOnly); - - dataStream << count; - - if (dragPosTime != -1) - { - int firstTeTime = -1; - - if (calculateFirstTeTime) + if (!m_moveValid || !isDragPossible()) { - for (TrackEntry *te : items) - { - if (firstTeTime > te->m_startTime || firstTeTime == -1) - firstTeTime = te->m_startTime; - } + + setCursor(Qt::ForbiddenCursor); } else - firstTeTime = 0; + { + setCursor(Qt::DragMoveCursor); + } - int finalOffsetTime = dragPosTime - firstTeTime; - dataStream << finalOffsetTime; - } - else - dataStream << 0; + update(); - - for (auto i = items.constBegin(); i != items.constEnd(); ++i) - { - TrackEntry *te = *i; - dataStream << *te; - } + if (m_isMultiLineMultiSelectionMode) + { + if (m_moveValid) + emit signalMultiLineMultiSelectionOkay(); + else + emit signalMultiLineMultiSelectionFailed(); + } - return itemData; + static int scrollByPixels = 1; + + if (pos >= (m_width - 60)) + emit signalScroll(scrollByPixels); + else if (pos < 60) + emit signalScroll(-scrollByPixels); + + return m_moveValid; } +TrackEntry* TrackContentWidget::trackEntryAtPos(int x) const +{ + int time = m_tools->getTime(x); + const QVector tes = getTrackEntries(); + + for (TrackEntry* te : tes) + { + int start = te->m_startTime; + if (time >= start && time <= (start + te->m_length)) + return te; + } + + return nullptr; +} + +QByteArray TrackContentWidget::itemsToData(const QVector& items, int dragPosTime, + bool calculateFirstTeTime) +{ + int count = items.count(); + if (!count) + return {}; + + QByteArray itemData; + QDataStream dataStream(&itemData, QIODevice::WriteOnly); + + dataStream << count; + + if (dragPosTime != -1) + { + int firstTeTime = -1; + + if (calculateFirstTeTime) + { + for (TrackEntry* te : items) + { + if (firstTeTime > te->m_startTime || firstTeTime == -1) + firstTeTime = te->m_startTime; + } + } + else + firstTeTime = 0; + + int finalOffsetTime = dragPosTime - firstTeTime; + dataStream << finalOffsetTime; + } + else + dataStream << 0; + + for (auto i = items.constBegin(); i != items.constEnd(); ++i) + { + TrackEntry* te = *i; + dataStream << *te; + } + + return itemData; +} QByteArray TrackContentWidget::selectedItemsToData(int dragPosTime, bool calculateFirstTeTime) { - return itemsToData(m_selected, dragPosTime, calculateFirstTeTime); + return itemsToData(m_selected, dragPosTime, calculateFirstTeTime); } - void TrackContentWidget::setDragPossible(bool possible) { - m_dragPossible = possible; - update(); + m_dragPossible = possible; + update(); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.h old mode 100755 new mode 100644 index f5791db67..d2363e214 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_content_widget.h @@ -1,11 +1,9 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" +#include #include - namespace LtsScriptTimeline { class TrackEntry; @@ -17,171 +15,229 @@ 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 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); +LTSSCRIPTTIMELINE_EXPORT bool isCollision2(int startPreview_s, int endPreview_s, const TrackEntry* pTrackEntry); class LTSSCRIPTTIMELINE_EXPORT TrackContentWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TrackContentWidget(QWidget *parent = nullptr, bool isFilter = false, Tools *tools = nullptr, int mainTopicId = -1); - ~TrackContentWidget() override; + 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); + bool addTrackEntry(TrackEntry* te, bool selectTrackEntry); + void removeTrackEntryByTopicId(TrackEntry* te); - void selectAll(); - void unselectAll(); - const QVector &getTrackEntries() const { return m_entryList; } - const QVector &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(); + void selectAll(); + void unselectAll(); - static bool checkForParallelTopics(const TrackContentWidget *pTCW, const QVector &vecPreviewTrackEntries, int dropTime_s, bool hack = false); - static bool checkForParallelTopics(const TrackContentWidget *tcw, const QVector &preview, int dropTime_s, QVector &vecParallelTopics, bool ignoreSelectedTopics = false, bool hack = false); - static bool checkForCollisions(const TrackContentWidget *tcw, const QVector &preview, int dropTime_s, - QVector &vecCollisions, bool ignoreSelected = false, bool ignoreSelfCheck = false); - static bool checkForCollisions(const TrackContentWidget *pTCW, const QVector &vecPreviewTrackEntries, int dropTime_s); - bool checkForCollisionsSimple(const TrackEntry &previewEntry) const; + const QVector& getTrackEntries() const + { + return m_entryList; + } - QByteArray selectedItemsToData(int dragPosTime = 0, bool calculateFirstTeTime = true); - static QByteArray itemsToData(const QVector &items, int dragPosTime = 0, bool calculateFirstTeTime = true); - static QVector dataToItems(const QByteArray &data, int &offset); - bool canPasteTopics(const QVector &topics, int offsetTime, int pasteTime) const; - void forcePasteTopics(const QVector &topics, int offsetTime, int pasteTime); - bool canMoveAll(int offset) const; - void forceMoveAll(int offset); - bool setDescriptionForSelected(); + const QVector& getSelectedEntries() const + { + return m_selected; + } - static QString mime; + void setIndicatorTime(int time); + void setTrackName(const QString& trackName); + void deleteSelectedTopics(); + void selectEntry(int topicId); - 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; + void setTopicFilterId(int id) + { + m_topicFilterId = id; + } - TrackWidget *trackWidget() { return m_trackWidget; } - TrackEntry *trackEntryAtPos(int x) const; + int topicFilterId() const + { + return m_topicFilterId; + } - void keyPressEvent(QKeyEvent *event) override; + void setReadonly(bool readonly); -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; + void addAllowedType(const TrackEntryType& tet) + { + m_allowedTypes.append(tet); + } -private: - TrackEntry *getTrackEntryOnPos(QPoint globalPos); - bool allowedByType(const TrackEntry *te) const; - TrackEntry *getParentTopicOfFilter(TrackEntry *filterTe) const; + void addDisallowedType(const TrackEntryType& tet) + { + m_disallowedTypes.append(tet); + } - int m_topicFilterId = -1; + void setTrackWidget(TrackWidget* trackWidget); - friend class SelectHandler; - SelectHandler *m_selectHandler; + void setScriptTimeline(ScriptTimeline* scriptTimeline) + { + m_scriptTimeline = scriptTimeline; + } - friend class ResizeHandler; - ResizeHandler *m_resizeHandler; + void setTools(Tools* tools); + void addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget); + static QString parallelError(); - friend class DragHandler; - DragHandler *m_dragHandler; + bool isMultiLineMultiSelectionMode() const + { + return m_isMultiLineMultiSelectionMode; + } - - 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; } - + void setMultiLineMultiSelectionMode(bool active) + { + m_isMultiLineMultiSelectionMode = active; + } + bool isDragPossible() const + { + return (!m_isMultiLineMultiSelectionMode || m_dragPossible); + } - int m_dragOffsetTime; - int m_dragPos; - QVector m_entryList; - QVector m_selected; - - TrackEntry *m_mainSelected; - QVector m_preview; - int m_width; - bool m_cursorSet; - int m_oldEntryLength; - bool m_unselectAllImmune; - int m_indicatorTime; - QString m_trackName; - QVector m_allowedTypes; - QVector m_disallowedTypes; - bool m_isFilter; - bool m_readonly; - TrackWidget *m_trackWidget; - ScriptTimeline *m_scriptTimeline; - Tools *m_tools; - QVector m_tcwCorresponding; - bool m_isMultiLineMultiSelectionMode; - bool m_multiLineMultiSelectionOkay; - bool m_dragPossible; - bool m_moveValid; - int m_mainTopicId; + void selectEntriesAtPositions(int fromPos, int toPos); + void forceLocalUnselect(); -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); + static bool checkForParallelTopics(const TrackContentWidget* pTCW, + const QVector& vecPreviewTrackEntries, int dropTime_s, + bool hack = false); + static bool checkForParallelTopics(const TrackContentWidget* tcw, const QVector& preview, + int dropTime_s, QVector& vecParallelTopics, + bool ignoreSelectedTopics = false, bool hack = false); + static bool checkForCollisions(const TrackContentWidget* tcw, const QVector& preview, int dropTime_s, + QVector& vecCollisions, bool ignoreSelected = false, + bool ignoreSelfCheck = false); + static bool checkForCollisions(const TrackContentWidget* pTCW, const QVector& vecPreviewTrackEntries, + int dropTime_s); + bool checkForCollisionsSimple(const TrackEntry& previewEntry) const; + + QByteArray selectedItemsToData(int dragPosTime = 0, bool calculateFirstTeTime = true); + static QByteArray itemsToData(const QVector& items, int dragPosTime = 0, + bool calculateFirstTeTime = true); + static QVector dataToItems(const QByteArray& data, int& offset); + bool canPasteTopics(const QVector& topics, int offsetTime, int pasteTime) const; + void forcePasteTopics(const QVector& 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 m_entryList; + QVector m_selected; + + TrackEntry* m_mainSelected; + QVector m_preview; + int m_width; + bool m_cursorSet; + int m_oldEntryLength; + bool m_unselectAllImmune; + int m_indicatorTime; + QString m_trackName; + QVector m_allowedTypes; + QVector m_disallowedTypes; + bool m_isFilter; + bool m_readonly; + TrackWidget* m_trackWidget; + ScriptTimeline* m_scriptTimeline; + Tools* m_tools; + QVector 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.cpp old mode 100755 new mode 100644 index 609d1047f..31af881d0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.cpp @@ -1,182 +1,164 @@ #include "track_drag_handler.h" -#include +#include "script_timeline.h" +#include "tools.h" #include "track_content_widget.h" #include "track_entry.h" -#include "tools.h" - #include "track_widget.h" -#include "script_timeline.h" #include - +#include +#include +#include #include #include -#include -#include #include -#include - -#include - +#include +#include namespace LtsScriptTimeline { -void DragHandler::dragEnterEvent(QDragEnterEvent *event) +void DragHandler::dragEnterEvent(QDragEnterEvent* event) { - if (m_tcw->isMultiLineMultiSelectionMode()) - { - if (event->source() != m_tcw) + if (m_tcw->isMultiLineMultiSelectionMode()) { - event->ignore(); - return; + 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->pos().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->pos().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->globalPos()); + + if (!m_tcw->m_mainSelected || ((cursorPos - m_dragStartPos).manhattanLength() < QApplication::startDragDistance() && + (m_dragStartPos - cursorPos).manhattanLength() < QApplication::startDragDistance())) + return; + + QVector 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 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 { - for (const auto &tcw : std::as_const(m_tcwCorresponding)) - tcw->dragEnter(tcw->selectedItemsToData(tcw->m_tools->getTime(m_dragStartPos.x()))); + emit m_tcw->signalMultiLineMultiSelectionDone(-1); } - } - - 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) +void DragHandler::keyPressEvent(QKeyEvent* 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->pos().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) + switch (event->key()) { - new LtsWidgets::LtsMessageDialogNew(m_tcw, TrackContentWidget::parallelError(), QObject::tr("Error")); - break; - } - } + case Qt::Key_Left: { + emit m_tcw->signalMoveAll(-1); + break; + } - if (m_tcw->dragDrop(dropPos)) - event->acceptProposedAction(); - else - emit m_tcw->signalMultiLineMultiSelectionDone(0); + case Qt::Key_Right: { + emit m_tcw->signalMoveAll(1); + break; + } + + default: { + break; + } + } } - -void DragHandler::dragMoveEvent(QDragMoveEvent *event) -{ - int pos = event->pos().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->globalPos()); - - - if (!m_tcw->m_mainSelected - || ((cursorPos - m_dragStartPos).manhattanLength() < QApplication::startDragDistance() - && (m_dragStartPos - cursorPos).manhattanLength() < QApplication::startDragDistance())) - return; - - QVector 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 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.h old mode 100755 new mode 100644 index 968e08b5b..c077b22bf --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_drag_handler.h @@ -11,25 +11,22 @@ class TrackEntry; class LTSSCRIPTTIMELINE_EXPORT DragHandler { -public: - explicit DragHandler(TrackContentWidget *_tcw) - : m_tcw(_tcw) - , m_dropPos(-1) - {} + 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); + 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 m_tcwCorresponding; + TrackContentWidget* m_tcw; + QVector m_tcwCorresponding; - QPoint m_dragStartPos; - QVector m_vecCollisions, m_vecParallel; - int m_dropPos; + QPoint m_dragStartPos; + QVector m_vecCollisions, m_vecParallel; + int m_dropPos; }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry.h old mode 100755 new mode 100644 index 1d45b4fc5..475fd5ed3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry.h @@ -11,177 +11,121 @@ namespace LtsScriptTimeline class LTSSCRIPTTIMELINE_EXPORT TrackEntry : public QObject { - Q_OBJECT + 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) - {} + 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(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(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) - {} + 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(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() {} - 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; + 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; - } + return *this; + } - int m_topicId; - int m_startTime; - int m_length; - TrackEntryType m_type; - bool isSet; - int index; + int m_topicId; + int m_startTime; + int m_length; + TrackEntryType m_type; + bool isSet; + int index; - - double x; - double y; - double h; - double w; + double x; + double y; + double h; + double w; - QJsonObject m_detailData; - QString m_channelName; - QString m_description; - QString m_filterParentChannel; + 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(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(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(); - } + QJsonObject toJson() const + { + return QJsonObject({{QStringLiteral("topicId"), m_topicId}, + {QStringLiteral("startTime"), m_startTime}, + {QStringLiteral("length"), m_length}, + {QStringLiteral("type"), static_cast(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(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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.cpp old mode 100755 new mode 100644 index 4d01a6b47..f425e1d08 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.cpp @@ -1,321 +1,328 @@ - #include "track_entry_painters.h" + #include "track_entry.h" -#include #include - - - +#include namespace LtsScriptTimeline { -QString translateTrackEntryType(const TrackEntryType &tet) +QString translateTrackEntryType(const TrackEntryType& tet) { - switch (tet) - { - case TrackEntryType::INVALID: return QObject::tr(""); - 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"); + switch (tet) + { + case TrackEntryType::INVALID: + return QObject::tr(""); + 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"); - } + case TrackEntryType::TacticalPlan: + return QObject::tr("Tactical Plan Map Filter"); + case TrackEntryType::SituationMapFilter: + return QObject::tr("Map Filter"); + } - return QString(); + return QString(); } - -QString trackEntryTypeName(const TrackEntryType &tet) +QString trackEntryTypeName(const TrackEntryType& tet) { - switch (tet) - { - case TrackEntryType::INVALID: return QStringLiteral(""); - 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"); - } + switch (tet) + { + case TrackEntryType::INVALID: + return QStringLiteral(""); + 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(); + 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")); - } + 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(); + return QIcon(); } - -TrackEntryPainter *getTrackEntryPainter(const TrackEntryType &type) +TrackEntryPainter* getTrackEntryPainter(const TrackEntryType& type) { - TrackEntryPainter *trackEntryPainter = nullptr; - static TrackEntryPainter painter; + TrackEntryPainter* trackEntryPainter = nullptr; + static TrackEntryPainter painter; - switch (type) - { - case TrackEntryType::SituationMap: + switch (type) { - painter = TrackEntryPainter(QColor(QStringLiteral("#b1cbbb")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; + case TrackEntryType::SituationMap: { + painter = TrackEntryPainter(QColor(QStringLiteral("#b1cbbb")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Situation: { + painter = TrackEntryPainter(QColor(QStringLiteral("#b1c1cb")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::SituationReplay: { + painter = TrackEntryPainter(QColor(QStringLiteral("#c94c4c")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Audio: { + painter = TrackEntryPainter(QColor(QStringLiteral("#034f84")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Video: { + painter = TrackEntryPainter(QColor(QStringLiteral("#618685")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Image: { + painter = TrackEntryPainter(QColor(QStringLiteral("#fefbd8")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Evaluation: { + painter = TrackEntryPainter(QColor(QStringLiteral("#d6cbd3")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Pdf: { + painter = TrackEntryPainter(QColor(QStringLiteral("#80ced6")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Text: { + painter = TrackEntryPainter(QColor(QStringLiteral("#92a8d1")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Xml: { + painter = TrackEntryPainter(QColor(QStringLiteral("#eea29a")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::TacticalPlan: { + painter = TrackEntryPainter(QColor(QStringLiteral("#dac292")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::MSOffice: { + painter = TrackEntryPainter(QColor(QStringLiteral("#f7cac9")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::OpenOffice: { + painter = TrackEntryPainter(QColor(QStringLiteral("#b2b2b2")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Building: { + painter = TrackEntryPainter(QColor(QStringLiteral("#c6bcb6")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::SituationMapFilter: { + painter = TrackEntryPainter(QColor(QStringLiteral("#36486b")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Snapshot: { + painter = TrackEntryPainter(QColor(QStringLiteral("#f18973")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + case TrackEntryType::Report: { + painter = TrackEntryPainter(QColor(QStringLiteral("#feb236")), translateTrackEntryType(type)); + trackEntryPainter = static_cast(&painter); + break; + } + + default: { + qWarning() << "no painter found for type" << (int)type; + trackEntryPainter = nullptr; + break; + } } - case TrackEntryType::Situation: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#b1c1cb")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::SituationReplay: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#c94c4c")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Audio: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#034f84")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Video: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#618685")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Image: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#fefbd8")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Evaluation: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#d6cbd3")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Pdf: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#80ced6")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Text: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#92a8d1")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Xml: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#eea29a")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::TacticalPlan: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#dac292")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::MSOffice: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#f7cac9")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::OpenOffice: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#b2b2b2")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Building: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#c6bcb6")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::SituationMapFilter: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#36486b")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Snapshot: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#f18973")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - case TrackEntryType::Report: - { - painter = TrackEntryPainter(QColor(QStringLiteral("#feb236")), translateTrackEntryType(type)); - trackEntryPainter = static_cast(&painter); - break; - } - - default: - { - qWarning() << "no painter found for type" << (int)type; - trackEntryPainter = nullptr; - break; - } - } - - return trackEntryPainter; + return trackEntryPainter; } - - -void drawTrackEntry(TrackEntry *te, QPainter &painter, const QRect &trackRect, bool isSelected, bool isEnabled) +void drawTrackEntry(TrackEntry* te, QPainter& painter, const QRect& trackRect, bool isSelected, bool isEnabled) { - TrackEntryPainter *trackEntryPainter = getTrackEntryPainter(te->m_type); + TrackEntryPainter* trackEntryPainter = getTrackEntryPainter(te->m_type); - if (!trackEntryPainter) - - return; + if (!trackEntryPainter) - QColor trackEntryBgColor = trackEntryPainter->bgColor(); + 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()); - 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); + gradient.setColorAt(0, QColor(r, g, b, 255)); + gradient.setColorAt(1, QColor(r, g, b, 0)); + painter.fillRect(gradientRect, gradient); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.h old mode 100755 new mode 100644 index 3d3ef5afc..537ce03aa --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_painters.h @@ -1,90 +1,89 @@ - #pragma once #include "ltsscripttimeline_export.h" #include -#include -#include -#include #include +#include +#include +#include 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 +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 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) + +inline std::ostream& operator<<(std::ostream& stream, const TrackEntryType tet) { - return stream << trackEntryTypeName(tet).toStdString(); + 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) - { - } + 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); - } + 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; - } + QColor bgColor() const + { + return m_bgColor; + } - void setBgColor(const QColor &bgColor) - { - m_bgColor = bgColor; - } + void setBgColor(const QColor& bgColor) + { + m_bgColor = bgColor; + } - const QString &trackEntryType() const - { - return m_trackEntryType; - } + const QString& trackEntryType() const + { + return m_trackEntryType; + } - void setTrackEntryType(const QString &trackEntryType) - { - m_trackEntryType = trackEntryType; - } + void setTrackEntryType(const QString& trackEntryType) + { + m_trackEntryType = trackEntryType; + } -protected: - QColor m_bgColor; - QString m_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); +void drawTrackEntry(TrackEntry* te, QPainter& painter, const QRect& trackRect, bool isSelected, bool isEnabled = true); +TrackEntryPainter* getTrackEntryPainter(const TrackEntryType& type); -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.cpp old mode 100755 new mode 100644 index 4643569a2..a6719e48f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.cpp @@ -1,105 +1,89 @@ #include "track_entry_preview_widget.h" -#include "ui_track_entry_preview_widget.h" + #include "track_entry.h" +#include "ui_track_entry_preview_widget.h" #include #include - -#include #include #include +#include #include - namespace LtsScriptTimeline { -TrackEntryPreviewWidget::TrackEntryPreviewWidget(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::TrackEntryPreviewWidget) +TrackEntryPreviewWidget::TrackEntryPreviewWidget(QWidget* parent) + : QWidget(parent), m_ui(new Ui::TrackEntryPreviewWidget) { - m_ui->setupUi(this); + m_ui->setupUi(this); #ifndef LTS_DEBUG - m_ui->lbTopicId->hide(); - m_ui->lblTopicId->hide(); + m_ui->lbTopicId->hide(); + m_ui->lblTopicId->hide(); - m_ui->lbLen->hide(); - m_ui->lblLen->hide(); + m_ui->lbLen->hide(); + m_ui->lblLen->hide(); #endif - connect(m_ui->widget, &TrackEntryPreviewer::signalDelete, - this, &TrackEntryPreviewWidget::signalDelete); + 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); + connect(m_ui->widget, &TrackEntryPreviewer::signalStartDrag, this, &TrackEntryPreviewWidget::signalStartDrag); + connect(m_ui->widget, &TrackEntryPreviewer::signalStopDrag, this, &TrackEntryPreviewWidget::signalStopDrag); } - TrackEntryPreviewWidget::~TrackEntryPreviewWidget() { - delete m_ui; + delete m_ui; } - -void TrackEntryPreviewWidget::contextMenuEvent(QContextMenuEvent *event) +void TrackEntryPreviewWidget::contextMenuEvent(QContextMenuEvent* event) { #ifndef LTS_DEBUG - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("TrackEntryPreviewWidget.DebugMenu")) == QVariant(true)) + 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); - }); + QMenu* m = new QMenu(this); + m->setAttribute(Qt::WA_DeleteOnClose); - m->addAction(QStringLiteral("disable"), this, [this]() - { - setTopicEnabled(false); - }); + QPoint p = mapToGlobal(m->pos()); + m->setGeometry(QRect(p, QPoint(event->x(), event->y()))); - m->addAction(QStringLiteral("show detail data"), this, [this]() - { - TrackEntry *te = m_ui->widget->trackEntry(); + m->addAction(QStringLiteral("enable"), this, [this]() { setTopicEnabled(true); }); - if (te == nullptr) - { - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("no te was set")); - return; - } + m->addAction(QStringLiteral("disable"), this, [this]() { setTopicEnabled(false); }); - 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->addAction(QStringLiteral("show detail data"), this, [this]() { + TrackEntry* te = m_ui->widget->trackEntry(); - m->show(); - } + 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); + m_ui->widget->setEnabled(enabled); } - -void TrackEntryPreviewWidget::setTrackEntry(TrackEntry *te) +void TrackEntryPreviewWidget::setTrackEntry(TrackEntry* te) { - m_ui->lblDnD->setVisible(!te->isSet); - m_ui->widget->setVisible(!te->isSet); + 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); + 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.h old mode 100755 new mode 100644 index 3e7c5d6fd..9a5c35efc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_preview_widget.h @@ -1,11 +1,9 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" +#include #include - namespace Ui { class TrackEntryPreviewWidget; @@ -15,30 +13,27 @@ namespace LtsScriptTimeline { class TrackEntry; - class LTSSCRIPTTIMELINE_EXPORT TrackEntryPreviewWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TrackEntryPreviewWidget(QWidget *parent = nullptr); - ~TrackEntryPreviewWidget(); + public: + explicit TrackEntryPreviewWidget(QWidget* parent = nullptr); + ~TrackEntryPreviewWidget(); - + void setTrackEntry(TrackEntry* te); - void setTrackEntry(TrackEntry *te); + void setTopicEnabled(bool enabled); - void setTopicEnabled(bool enabled); + private: + Ui::TrackEntryPreviewWidget* m_ui; -private: - Ui::TrackEntryPreviewWidget *m_ui; + void contextMenuEvent(QContextMenuEvent* event); - void contextMenuEvent(QContextMenuEvent *event); - -signals: - void signalStartDrag(); - void signalStopDrag(); - void signalDelete(); + signals: + void signalStartDrag(); + void signalStopDrag(); + void signalDelete(); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.cpp old mode 100755 new mode 100644 index c2c67489a..ecd9fbbba --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.cpp @@ -1,86 +1,76 @@ #include "track_entry_previewer.h" + +#include "track_content_widget.h" #include "track_entry.h" #include "track_entry_painters.h" -#include "track_content_widget.h" -#include #include #include #include - +#include namespace LtsScriptTimeline { -QDataStream &operator<<(QDataStream &ds, const TrackEntry &te); -QDataStream &operator>>(QDataStream &ds, TrackEntry &te); +QDataStream& operator<<(QDataStream& ds, const TrackEntry& te); +QDataStream& operator>>(QDataStream& ds, TrackEntry& te); -TrackEntryPreviewer::TrackEntryPreviewer(QWidget *parent) - : QWidget(parent) - , m_te(nullptr) +TrackEntryPreviewer::TrackEntryPreviewer(QWidget* parent) : QWidget(parent), m_te(nullptr) { - - setVisible(false); + setVisible(false); } +TrackEntryPreviewer::~TrackEntryPreviewer() {} -TrackEntryPreviewer::~TrackEntryPreviewer() -{} - - -void TrackEntryPreviewer::setTrackEntry(TrackEntry *te) +void TrackEntryPreviewer::setTrackEntry(TrackEntry* te) { - m_te = te; + m_te = te; - if (m_te->isSet) - return; + if (m_te->isSet) + return; - connect(m_te, &TrackEntry::destroyed, - this, [this]() - { - m_te = nullptr; - emit signalDelete(); - }); + connect(m_te, &TrackEntry::destroyed, this, [this]() { + m_te = nullptr; + emit signalDelete(); + }); } - -void TrackEntryPreviewer::mousePressEvent(QMouseEvent *event) +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; + if (!m_te || event->buttons() != Qt::LeftButton) + return; - QMimeData *mimeData = new QMimeData; - mimeData->setData(TrackContentWidget::mime, itemData); + m_te->isSet = true; + QByteArray itemData(TrackContentWidget::itemsToData({m_te}, 0)); + m_te->isSet = false; - QDrag *drag = new QDrag(this); - drag->setDragCursor(QPixmap(), Qt::CopyAction); - drag->setMimeData(mimeData); + QMimeData* mimeData = new QMimeData; + mimeData->setData(TrackContentWidget::mime, itemData); - emit signalStartDrag(); + QDrag* drag = new QDrag(this); + drag->setDragCursor(QPixmap(), Qt::CopyAction); + drag->setMimeData(mimeData); - if (drag->exec(Qt::CopyAction) == Qt::CopyAction) - emit signalDelete(); + emit signalStartDrag(); - emit signalStopDrag(); + if (drag->exec(Qt::CopyAction) == Qt::CopyAction) + emit signalDelete(); + + emit signalStopDrag(); } - -void TrackEntryPreviewer::paintEvent(QPaintEvent *event) +void TrackEntryPreviewer::paintEvent(QPaintEvent* event) { - QWidget::paintEvent(event); + QWidget::paintEvent(event); - QPainter painter(this); + QPainter painter(this); - if (!m_te) - return; + if (!m_te) + return; - drawTrackEntry(m_te, painter, rect().adjusted(0, 0, -1, -1), false, isEnabled()); + drawTrackEntry(m_te, painter, rect().adjusted(0, 0, -1, -1), false, isEnabled()); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.h old mode 100755 new mode 100644 index a83a7992a..3835c3eab --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_entry_previewer.h @@ -1,39 +1,37 @@ #pragma once #include - #include - namespace LtsScriptTimeline { class TrackEntry; - class TrackEntryPreviewer : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TrackEntryPreviewer(QWidget *parent = nullptr); - ~TrackEntryPreviewer(); + public: + explicit TrackEntryPreviewer(QWidget* parent = nullptr); + ~TrackEntryPreviewer(); - + void setTrackEntry(TrackEntry* te); - void setTrackEntry(TrackEntry *te); - TrackEntry *trackEntry() const { return m_te; } + TrackEntry* trackEntry() const + { + return m_te; + } -protected: - void paintEvent(QPaintEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; + protected: + void paintEvent(QPaintEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; -private: - TrackEntry *m_te; - -signals: - void signalDelete(); - void signalStartDrag(); - void signalStopDrag(); + private: + TrackEntry* m_te; + signals: + void signalDelete(); + void signalStartDrag(); + void signalStopDrag(); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.cpp old mode 100755 new mode 100644 index cf24ea392..f9c46f1b5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.cpp @@ -1,191 +1,158 @@ #include "track_header.h" + #include "tools.h" -#include +#include #include -#include #include #include -#include -#include -#include -#include -#include - #include - +#include +#include +#include +#include +#include +#include namespace LtsScriptTimeline { -TrackHeader::TrackHeader(QWidget *parent) - : QWidget(parent) - , m_indicatorTime(-1) - , m_textMargin(12) - , m_textSpacing(10) - , m_indicatorLock(false) - , m_tools(nullptr) +TrackHeader::TrackHeader(QWidget* parent) + : QWidget(parent), m_indicatorTime(-1), m_textMargin(12), m_textSpacing(10), m_indicatorLock(false), + m_tools(nullptr) { - setCursor(Qt::IBeamCursor); + setCursor(Qt::IBeamCursor); - m_timeFormat = QStringLiteral("HH:mm:ss"); + m_timeFormat = QStringLiteral("HH:mm:ss"); } - -void TrackHeader::setTools(Tools *tools) +void TrackHeader::setTools(Tools* tools) { - m_tools = tools; + m_tools = tools; } - -void TrackHeader::mousePressEvent(QMouseEvent *event) +void TrackHeader::mousePressEvent(QMouseEvent* event) { - if (event->buttons() != Qt::LeftButton) - return; - if (!m_indicatorLock) - { - setIndicatorTime(m_tools->getTime(event->localPos().x())); - emit signalHeaderIndicatorTimeUserChanged(m_indicatorTime); - } + if (event->buttons() != Qt::LeftButton) + return; + if (!m_indicatorLock) + { + setIndicatorTime(m_tools->getTime(event->localPos().x())); + emit signalHeaderIndicatorTimeUserChanged(m_indicatorTime); + } } - void TrackHeader::setIndicatorTime(int time) { - m_indicatorTime = time; - emit signalHeaderIndicatorTimeChanged(m_indicatorTime); - update(); + m_indicatorTime = time; + emit signalHeaderIndicatorTimeChanged(m_indicatorTime); + update(); } - void TrackHeader::recreatePositionLabels() { - - QTime t; - t.setHMS(23, 59, 59); - QFontMetrics fm(QApplication::font()); - + 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()); + int currentTextWidth = fm.width(t.toString()); #else - int currentTextWidth = fm.horizontalAdvance(t.toString()); + 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) + if (currentTextWidth < 1) { - - m_positionMarkers.append(m_tools->getPos(time)); + qCritical() << "TrackHeader::recreatePositionLabels: invalid text size"; + return; } - time += currentTextWidthTime + textSpacingTime; - count++; - } + int currentTextWidthTime = m_tools->getDuration(currentTextWidth); - + int time = m_tools->getDuration(m_textMargin); + int end = (m_tools->m_timelineLength * 2) + currentTextWidthTime; - update(); + 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) +void TrackHeader::resizeEvent(QResizeEvent* event) { - recreatePositionLabels(); + recreatePositionLabels(); - QWidget::resizeEvent(event); + QWidget::resizeEvent(event); } - void TrackHeader::updateMe() { - recreatePositionLabels(); - update(); + recreatePositionLabels(); + update(); } - -void TrackHeader::paintEvent(QPaintEvent *event) +void TrackHeader::paintEvent(QPaintEvent* event) { - QPainter painter(this); + 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); + QWidget::paintEvent(event); painter.save(); - painter.setPen(QGuiApplication::palette().link().color()); - painter.drawLine(pos, (h / 2) + 2, pos, h); + + 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(); - - - } - - - painter.restore(); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.h old mode 100755 new mode 100644 index 309abd150..a1133e99a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_header.h @@ -1,44 +1,50 @@ #pragma once #include - #include - namespace LtsScriptTimeline { class Tools; class TrackHeader : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TrackHeader(QWidget *parent = nullptr); - + 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; } + void recreatePositionLabels(); + void updateMe(); + void setIndicatorTime(int time); -private: - void resizeEvent(QResizeEvent *event) override; - void paintEvent(QPaintEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; + void lockIndicator(bool lock = true) + { + m_indicatorLock = lock; + } - int m_indicatorTime; - int m_textMargin; - int m_textSpacing; - QString m_timeFormat; - QVector m_positionMarkers; - bool m_indicatorLock; - Tools *m_tools; + void setTools(Tools* tools); -signals: - void signalHeaderIndicatorTimeChanged(int time); - void signalHeaderIndicatorTimeUserChanged(qint64 time); + 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 m_positionMarkers; + bool m_indicatorLock; + Tools* m_tools; + + signals: + void signalHeaderIndicatorTimeChanged(int time); + void signalHeaderIndicatorTimeUserChanged(qint64 time); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.cpp old mode 100755 new mode 100644 index 9b615d65a..cc3231a06 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.cpp @@ -1,183 +1,183 @@ #include "track_resize_handler.h" -#include + +#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 "track_content_widget.h" -#include "filter_track_widget.h" -#include "filter_background_widget.h" - -#include "tools.h" #include - -#include #include - +#include +#include namespace LtsScriptTimeline { -void ResizeHandler::mousePressEvent(QMouseEvent *event) +void ResizeHandler::mousePressEvent(QMouseEvent* event) { - if (event->buttons() != Qt::LeftButton || !m_possible) - return; + if (event->buttons() != Qt::LeftButton || !m_possible) + return; - TrackEntry *te = m_trackContentWidget->getTrackEntryOnPos(event->globalPos()); + TrackEntry* te = m_trackContentWidget->getTrackEntryOnPos(event->globalPos()); - if (te == nullptr) - return; + if (te == nullptr) + return; - m_oldLength = te->m_length; - m_resizing = true; + m_oldLength = te->m_length; + m_resizing = true; } - -void ResizeHandler::mouseReleaseEvent(QMouseEvent *) +void ResizeHandler::mouseReleaseEvent(QMouseEvent*) { - m_resizing = false; + m_resizing = false; - if (!m_trackContentWidget->m_mainSelected) - return; + if (!m_trackContentWidget->m_mainSelected) + return; - QVector vecPreviewTrackEntries = {m_trackContentWidget->m_mainSelected}; + QVector 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)) + bool msg = true; + for (TrackContentWidget* tcw : std::as_const(m_tcwCorresponding)) { - if (msg) - { - LtsWidgets::LtsMessageDialog::showMessage(m_trackContentWidget, TrackContentWidget::parallelError(), QObject::tr("Error")); - msg = false; - } - m_trackContentWidget->m_mainSelected->m_length = m_oldLength; + 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; + 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 &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) + for (auto i = m_trackContentWidget->m_entryList.constBegin(); i != m_trackContentWidget->m_entryList.constEnd(); + ++i) { - int filterContentWidgetTopicId = iFilterContentWidget.key(); - if (m_trackContentWidget->m_mainSelected->m_topicId != filterContentWidgetTopicId) - continue; + const TrackEntry* trackEntry = *i; - 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 (!trackEntry || trackEntry == m_trackContentWidget->m_mainSelected) - continue; - - if (endTime < startTime + trackEntry->m_startTime + trackEntry->m_length) - return true; - } + if (LtsScriptTimeline::isCollision2(startTime, endTime, trackEntry)) + return true; } - } - return false; + const QVector& 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) +bool ResizeHandler::mouseMoveEvent(QMouseEvent* event) { - QPoint pos = m_trackContentWidget->mapFromGlobal(event->globalPos()); - int posX = pos.x(); - int cursorTime = m_trackContentWidget->m_tools->getTime(posX, m_trackContentWidget->m_isFilter); + QPoint pos = m_trackContentWidget->mapFromGlobal(event->globalPos()); + 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)) + if (m_resizing && m_trackContentWidget->m_mainSelected) { - newLength = m_oldLength; - m_trackContentWidget->setCursor(Qt::ForbiddenCursor); + 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 { - m_trackContentWidget->setCursor(m_cursor); + TrackEntry* te = m_trackContentWidget->getTrackEntryOnPos(event->globalPos()); + + 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(); + } } - m_trackContentWidget->m_mainSelected->m_length = newLength; - m_trackContentWidget->update(); - emit m_trackContentWidget->signalChangesMade(); - return true; - } - else - { - TrackEntry *te = m_trackContentWidget->getTrackEntryOnPos(event->globalPos()); - - 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; + return false; } - -void ResizeHandler::keyPressEvent(QKeyEvent *event) +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(); - } + 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 diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.h old mode 100755 new mode 100644 index 570044775..b5aa15f7d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_resize_handler.h @@ -1,6 +1,7 @@ #pragma once #include "ltsscripttimeline_export.h" + #include #include @@ -11,30 +12,27 @@ 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) - {} + 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); + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + bool mouseMoveEvent(QMouseEvent* event); + void keyPressEvent(QKeyEvent* event); - TrackContentWidget *m_trackContentWidget; - QVector m_tcwCorresponding; + TrackContentWidget* m_trackContentWidget; + QVector m_tcwCorresponding; - bool m_resizing; - bool m_possible; - int m_oldLength; - int m_mainTeLength; - Qt::CursorShape m_cursor; + bool m_resizing; + bool m_possible; + int m_oldLength; + int m_mainTeLength; + Qt::CursorShape m_cursor; -private: - bool isCollision(int newLength) const; + private: + bool isCollision(int newLength) const; }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.cpp old mode 100755 new mode 100644 index cfa5aaa2d..dfd4ac07e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.cpp @@ -1,182 +1,169 @@ #include "track_select_handler.h" + +#include "tools.h" #include "track_content_widget.h" #include "track_entry.h" -#include "tools.h" - +#include +#include +#include +#include #include #include -#include -#include -#include #include -#include - - namespace LtsScriptTimeline { void SelectHandler::slotSetDescription() { - if (m_pressedEntry == nullptr) - return; + 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(); - } + 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) +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); + 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) +void SelectHandler::mousePressEvent(QMouseEvent* event) { - if (event->buttons() == Qt::LeftButton) - { - m_pressedEntry = nullptr; + if (event->buttons() == Qt::LeftButton) + { + m_pressedEntry = nullptr; + QPoint clickedPos = tcw->mapFromGlobal(event->globalPos()); + 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->globalPos()); + } +} + +void SelectHandler::mouseReleaseEvent(QMouseEvent* event) +{ QPoint clickedPos = tcw->mapFromGlobal(event->globalPos()); - 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); + TrackEntry* releasedEntry = tcw->getTrackEntryAt(clickedTime); - contextMenu->addSection(tr("All tracks")); + if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier) && (!m_pressedEntry || !releasedEntry)) { - 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); + emit tcw->signalUnselectAll(); + emit tcw->signalTrackEntrySelectionChanged(nullptr); } - + else { - 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); + if (m_pressedEntry == releasedEntry) + tcw->selectEntry(releasedEntry); } - - - 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->globalPos()); - } } - - -void SelectHandler::mouseReleaseEvent(QMouseEvent *event) +void SelectHandler::keyPressEvent(QKeyEvent* event) { - QPoint clickedPos = tcw->mapFromGlobal(event->globalPos()); - 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); - } + if (event->key() == Qt::Key_Escape) + { + m_pressedEntry = nullptr; + emit tcw->signalUnselectAll(); + emit tcw->signalTrackEntrySelectionChanged(nullptr); + } } - - -void SelectHandler::keyPressEvent(QKeyEvent *event) -{ - if (event->key() == Qt::Key_Escape) - { - m_pressedEntry = nullptr; - emit tcw->signalUnselectAll(); - emit tcw->signalTrackEntrySelectionChanged(nullptr); - } -} -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.h old mode 100755 new mode 100644 index 589ebf2be..31c904e32 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_select_handler.h @@ -1,14 +1,12 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" +#include class QMouseEvent; class QKeyEvent; - namespace LtsScriptTimeline { class TrackContentWidget; @@ -16,24 +14,20 @@ class TrackEntry; class LTSSCRIPTTIMELINE_EXPORT SelectHandler : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit SelectHandler(TrackContentWidget *_tcw) - : QObject(nullptr) - , tcw(_tcw) - , m_pressedEntry(nullptr) - {} + 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); + void mouseDoubleClick(QMouseEvent* event); + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + void keyPressEvent(QKeyEvent* event); - TrackContentWidget *tcw; - TrackEntry *m_pressedEntry; + TrackContentWidget* tcw; + TrackEntry* m_pressedEntry; -public slots: - void slotSetDescription(); + public slots: + void slotSetDescription(); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.cpp old mode 100755 new mode 100644 index 292692f6e..a878ba650 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.cpp @@ -1,560 +1,476 @@ #include "track_widget.h" -#include -#include "ui_track_widget.h" -#include "track_entry.h" -#include "filter_track_widget.h" -#include "filter_background_widget.h" -#include "track_content_widget.h" -#include "tools.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 +#include #include #include #include #include #include -#include -#include #include - +#include 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) +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); + Q_ASSERT(m_tools != nullptr); - ui->setupUi(this); - ui->mainTrack->setTrackWidget(this); - ui->mainTrack->setTools(tools); + ui->setupUi(this); + ui->mainTrack->setTrackWidget(this); + ui->mainTrack->setTools(tools); - ui->chkSelect->hide(); + ui->chkSelect->hide(); - ui->filtersWidget->hide(); - ui->leName->hide(); - ui->pbApply->hide(); - ui->pbCancel->hide(); + ui->filtersWidget->hide(); + ui->leName->hide(); + ui->pbApply->hide(); + ui->pbCancel->hide(); - ui->pbEditName->hide(); + ui->pbEditName->hide(); - if (!filtersAllowed) - ui->pbExpand->hide(); + if (!filtersAllowed) + ui->pbExpand->hide(); - ui->pbAddFilter->hide(); + ui->pbAddFilter->hide(); - setBaseWidth(baseWidth); - setReadonly(readonly); + 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->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::stateChanged, - this, &TrackWidget::signalSelectTrack); - connect(ui->pbExpand, &QPushButton::clicked, - this, &TrackWidget::slotExpand); - connect(ui->pbAddFilter, &QPushButton::clicked, - this, &TrackWidget::slotAddFilter); + connect(ui->chkSelect, &QCheckBox::stateChanged, 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; + m_filterLines.clear(); + delete ui; } - void TrackWidget::setReadonly(bool readonly) { - m_readonly = readonly; - ui->mainTrack->setReadonly(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 TrackWidget::getSelectedFilterEntries() const -{ - QVector result; - const QVector &ftws = filterLines(); - - for (const FilterTrackWidget *ftw : std::as_const(ftws)) - { - const FilterBackgroundWidget *fbw = ftw->fbw(); - const QMap &fcws = fbw->filterContentWidgets(); - - for (auto i = fcws.constBegin(); i != fcws.constEnd(); ++i) - { - TrackContentWidget *tcw = i.value(); - result += tcw->getSelectedEntries(); - } - } - - return result; -} - - -const QVector &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(sender())); - sender()->deleteLater(); - emit signalChangesMade(); - }); - - emit signalChangesMade(); - slotMainChangesMade(); -} - - -void TrackWidget::slotMainChangesMade() -{ - const QVector trackEntries = ui->mainTrack->getTrackEntries(); - - for (auto i1 = trackEntries.constBegin(); i1 != trackEntries.constEnd(); ++i1) - { - const TrackEntry *te = *i1; + 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->fbw()->adjustFilterContentWidgets(te); + FilterTrackWidget* ftw = *i3; + ftw->setReadonly(readonly); } - } - - } - -void TrackWidget::slotTrackEntryAdded(TrackEntry *te) +void TrackWidget::setScriptTimeline(ScriptTimeline* scriptTimeline) { - - - for (FilterTrackWidget *ftw : std::as_const(m_filterLines)) - ftw->fbw()->trackEntryAdded(te); - - emit signalTrackEntryAdded(te); + m_scriptTimeline = scriptTimeline; + ui->mainTrack->setScriptTimeline(m_scriptTimeline); } +void TrackWidget::keyPressEvent(QKeyEvent* event) +{ + getTrackContentWidget()->keyPressEvent(event); +} + +QVector TrackWidget::getSelectedFilterEntries() const +{ + QVector result; + const QVector& ftws = filterLines(); + + for (const FilterTrackWidget* ftw : std::as_const(ftws)) + { + const FilterBackgroundWidget* fbw = ftw->fbw(); + const QMap& fcws = fbw->filterContentWidgets(); + + for (auto i = fcws.constBegin(); i != fcws.constEnd(); ++i) + { + TrackContentWidget* tcw = i.value(); + result += tcw->getSelectedEntries(); + } + } + + return result; +} + +const QVector& 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(sender())); + sender()->deleteLater(); + emit signalChangesMade(); + }); + + emit signalChangesMade(); + slotMainChangesMade(); +} + +void TrackWidget::slotMainChangesMade() +{ + const QVector 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); + for (FilterTrackWidget* ftw : std::as_const(m_filterLines)) + ftw->fbw()->trackEntryDeleted(topicId); - emit signalTrackEntryDeleted(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 (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(); + if (!m_readonly) + ui->pbAddFilter->show(); - ui->filtersWidget->show(); - slotMainChangesMade(); - } + ui->filtersWidget->show(); + slotMainChangesMade(); + } } - void TrackWidget::selectEntry(int topicId) { - ui->mainTrack->selectEntry(topicId); + ui->mainTrack->selectEntry(topicId); } - -int TrackWidget::getParentTopicIdOfFilter(const TrackEntry *te) const +int TrackWidget::getParentTopicIdOfFilter(const TrackEntry* te) const { - - for (const FilterTrackWidget *ftw : m_filterLines) - { - const FilterBackgroundWidget *fbw = ftw->fbw(); - const QMap &filterContentWidgets = fbw->filterContentWidgets(); - - for (auto i = filterContentWidgets.constBegin(); i != filterContentWidgets.constEnd(); ++i) + for (const FilterTrackWidget* ftw : m_filterLines) { - int parentTopicId = i.key(); - const TrackContentWidget *datWidget = i.value(); - const QVector &filterEntries = datWidget->getTrackEntries(); + const FilterBackgroundWidget* fbw = ftw->fbw(); + const QMap& filterContentWidgets = fbw->filterContentWidgets(); - for (const TrackEntry *filterTE : filterEntries) - { - if (filterTE == te) - return parentTopicId; - } - } - } + for (auto i = filterContentWidgets.constBegin(); i != filterContentWidgets.constEnd(); ++i) + { + int parentTopicId = i.key(); + const TrackContentWidget* datWidget = i.value(); + const QVector& filterEntries = datWidget->getTrackEntries(); - return -1; -} - - -QVector TrackWidget::getTrackEntriesWithFilters(bool selectedEntriesOnly) const -{ - QVector result; - const QVector 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 &filterContentWidgets = fbw->filterContentWidgets(); - - - const TrackContentWidget *datWidget = filterContentWidgets.value(te->m_topicId); - - if (datWidget == nullptr) - continue; - - const QVector &filterEntries = datWidget->getTrackEntries(); - - if (filterEntries.isEmpty()) - continue; - - QJsonArray jsonFilterLine; - for (const TrackEntry *fte : filterEntries) - jsonFilterLine.append(fte->toJson()); - - jsonFilterLines.append(jsonFilterLine); + for (const TrackEntry* filterTE : filterEntries) + { + if (filterTE == te) + return parentTopicId; + } + } } - te->m_detailData[QStringLiteral("Filters")] = jsonFilterLines; - } - - return result; + return -1; } - -QVector TrackWidget::getTrackEntriesFiltersAsEntries(bool selectedEntriesOnly) const +QVector TrackWidget::getTrackEntriesWithFilters(bool selectedEntriesOnly) const { - QVector result; - const QVector trackEntryList = ui->mainTrack->getTrackEntries(); + QVector result; + const QVector trackEntryList = ui->mainTrack->getTrackEntries(); - for (TrackEntry *te : trackEntryList) - { - if (selectedEntriesOnly && !ui->mainTrack->getSelectedEntries().contains(te)) - continue; - - result += te; - - - for (FilterTrackWidget *ftw : m_filterLines) + for (TrackEntry* te : trackEntryList) { - const QMap &filterContentWidgets = ftw->fbw()->filterContentWidgets(); + if (selectedEntriesOnly && !ui->mainTrack->getSelectedEntries().contains(te)) + continue; - for (auto i1 = filterContentWidgets.constBegin(); i1 != filterContentWidgets.constEnd(); ++i1) - { - TrackContentWidget *tcw = i1.value(); - result += tcw->getTrackEntries(); - } + result += te; + + QJsonArray jsonFilterLines; + + for (const FilterTrackWidget* ftw : std::as_const(m_filterLines)) + { + const FilterBackgroundWidget* fbw = ftw->fbw(); + const QMap& filterContentWidgets = fbw->filterContentWidgets(); + + const TrackContentWidget* datWidget = filterContentWidgets.value(te->m_topicId); + + if (datWidget == nullptr) + continue; + + const QVector& 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; + return result; } - -QVector TrackWidget::getTrackEntries(bool selectedEntriesOnly) const +QVector TrackWidget::getTrackEntriesFiltersAsEntries(bool selectedEntriesOnly) const { - QVector result; - const QVector trackEntryList = ui->mainTrack->getTrackEntries(); + QVector result; + const QVector trackEntryList = ui->mainTrack->getTrackEntries(); - if (selectedEntriesOnly) - { - for (TrackEntry *te : trackEntryList) + for (TrackEntry* te : trackEntryList) { - if (!ui->mainTrack->getSelectedEntries().contains(te)) - continue; + if (selectedEntriesOnly && !ui->mainTrack->getSelectedEntries().contains(te)) + continue; - result += te; + result += te; + + for (FilterTrackWidget* ftw : m_filterLines) + { + const QMap& filterContentWidgets = ftw->fbw()->filterContentWidgets(); + + for (auto i1 = filterContentWidgets.constBegin(); i1 != filterContentWidgets.constEnd(); ++i1) + { + TrackContentWidget* tcw = i1.value(); + result += tcw->getTrackEntries(); + } + } } - } - else - { - return trackEntryList; - } - return result; + return result; } +QVector TrackWidget::getTrackEntries(bool selectedEntriesOnly) const +{ + QVector result; + const QVector 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; + m_baseWidth = width; - ui->mainLeft->setMinimumWidth(width); - ui->mainLeft->setMaximumWidth(width); + ui->mainLeft->setMinimumWidth(width); + ui->mainLeft->setMaximumWidth(width); - for (FilterTrackWidget *ftw : std::as_const(m_filterLines)) - ftw->setBaseWidth(m_baseWidth); + for (FilterTrackWidget* ftw : std::as_const(m_filterLines)) + ftw->setBaseWidth(m_baseWidth); } - -void TrackWidget::addCorrespondingTrackWidget(TrackContentWidget *pCorrespondingTrackWidget) +void TrackWidget::addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget) { - ui->mainTrack->addCorrespondingTrackWidget(pCorrespondingTrackWidget); + ui->mainTrack->addCorrespondingTrackWidget(pCorrespondingTrackWidget); } - -TrackContentWidget *TrackWidget::getTrackContentWidget() const +TrackContentWidget* TrackWidget::getTrackContentWidget() const { - return ui->mainTrack; + return ui->mainTrack; } - -void TrackWidget::setInternalName(const QString &name) +void TrackWidget::setInternalName(const QString& name) { - m_internalName = name; - ui->mainTrack->setTrackName(name); + m_internalName = name; + ui->mainTrack->setTrackName(name); } - -void TrackWidget::setTrackName(const QString &name) +void TrackWidget::setTrackName(const QString& name) { - ui->lblTrackName->setText(name); + ui->lblTrackName->setText(name); } - -bool TrackWidget::addTrackEntry(TrackEntry *te, bool selectTrackEntry) +bool TrackWidget::addTrackEntry(TrackEntry* te, bool selectTrackEntry) { - if (!ui->mainTrack->addTrackEntry(te, selectTrackEntry)) - return false; + if (!ui->mainTrack->addTrackEntry(te, selectTrackEntry)) + return false; - const QJsonObject detailData = te->m_detailData; + 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) + if (detailData.isEmpty()) { - TrackEntry *filterTe = new TrackEntry; - filterTe->fromJson(filter.toObject()); - - m_filterLines.at(i1)->addFilterEntry(te , filterTe); - - + return true; } - } - emit signalChangesMade(); + const QJsonArray filterLines = detailData[QStringLiteral("Filters")].toArray(); - return true; + 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; + return m_internalName; } - bool TrackWidget::isSelected() const { - return (ui->chkSelect->checkState() == Qt::CheckState::Checked); + return (ui->chkSelect->checkState() == Qt::CheckState::Checked); } - void TrackWidget::unselectAll() { - ui->mainTrack->unselectAll(); + ui->mainTrack->unselectAll(); - for (FilterTrackWidget *ftw : std::as_const(m_filterLines)) - { - const auto fcw = ftw->fbw()->filterContentWidgets(); - for (TrackContentWidget *tcw : fcw) - tcw->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(); + update(); + ui->mainTrack->update(); + slotMainChangesMade(); } - void TrackWidget::setIndicatorTime(int time) { - ui->mainTrack->setIndicatorTime(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) + for (FilterTrackWidget* ftw : std::as_const(m_filterLines)) { - int mainTeId = i1.key(); - int mainTeStart = 0; + const auto filterContentWidgets = ftw->fbw()->filterContentWidgets(); - const QVector &tes = ui->mainTrack->getTrackEntries(); - for (const TrackEntry *te : tes) - { - if (te->m_topicId == mainTeId) + for (auto i1 = filterContentWidgets.begin(); i1 != filterContentWidgets.end(); ++i1) { - mainTeStart = te->m_startTime; - break; + int mainTeId = i1.key(); + int mainTeStart = 0; + + const QVector& 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); } - } - - TrackContentWidget *filterTcw = i1.value(); - filterTcw->setIndicatorTime(time - mainTeStart); } - } } - -void TrackWidget::paintEvent(QPaintEvent *event) +void TrackWidget::paintEvent(QPaintEvent* event) { - Q_UNUSED(event); + Q_UNUSED(event); - QPainter painter(this); + QPainter painter(this); - painter.save(); + painter.save(); - painter.setPen(QGuiApplication::palette().windowText().color()); - painter.setBrush(QGuiApplication::palette().window().color()); - painter.drawRect(rect()); + painter.setPen(QGuiApplication::palette().windowText().color()); + painter.setBrush(QGuiApplication::palette().window().color()); + painter.drawRect(rect()); - painter.restore(); + painter.restore(); } -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.h old mode 100755 new mode 100644 index 91c367329..f3ad49204 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsScriptTimeline/track_widget.h @@ -1,20 +1,17 @@ #pragma once -#include - #include "ltsscripttimeline_export.h" #include "track_entry_painters.h" -#include #include +#include +#include #include - namespace Ui { class TrackWidget; } - namespace LtsScriptTimeline { class TrackEntry; @@ -24,67 +21,70 @@ class FilterBackgroundWidget; class ScriptTimeline; class Tools; - class LTSSCRIPTTIMELINE_EXPORT TrackWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TrackWidget(int baseWidth, bool readonly, Tools *tools, bool filtersAllowed, QWidget *parent = nullptr); - ~TrackWidget(); + public: + explicit TrackWidget(int baseWidth, bool readonly, Tools* tools, bool filtersAllowed, QWidget* parent = nullptr); + ~TrackWidget(); - void setReadonly(bool readonly); - void updateMe(); - void unselectAll(); - bool isSelected() const; - QString trackName() const; - bool addTrackEntry(TrackEntry *te, bool selectTrackEntry); - void setTrackName(const QString &name); - void addCorrespondingTrackWidget(TrackContentWidget *pCorrespondingTrackWidget); - TrackContentWidget *getTrackContentWidget() const; - void setBaseWidth(int width); - void setIndicatorTime(int time); - void selectEntry(int topicId); - - void setInternalName(const QString &name); - QVector getTrackEntriesFiltersAsEntries(bool selectedEntriesOnly = false) const; - QVector getTrackEntriesWithFilters(bool selectedEntriesOnly = false) const; - QVector getTrackEntries(bool selectedEntriesOnly = false) const; - QVector getSelectedFilterEntries() const; - const QVector &getSelectedEntries() const; - int getParentTopicIdOfFilter(const TrackEntry *te) const; - void setScriptTimeline(ScriptTimeline *scriptTimeline); - const QVector &filterLines() const { return m_filterLines; } + void setReadonly(bool readonly); + void updateMe(); + void unselectAll(); + bool isSelected() const; + QString trackName() const; + bool addTrackEntry(TrackEntry* te, bool selectTrackEntry); + void setTrackName(const QString& name); + void addCorrespondingTrackWidget(TrackContentWidget* pCorrespondingTrackWidget); + TrackContentWidget* getTrackContentWidget() const; + void setBaseWidth(int width); + void setIndicatorTime(int time); + void selectEntry(int topicId); - void keyPressEvent(QKeyEvent *event) override; + void setInternalName(const QString& name); + QVector getTrackEntriesFiltersAsEntries(bool selectedEntriesOnly = false) const; + QVector getTrackEntriesWithFilters(bool selectedEntriesOnly = false) const; + QVector getTrackEntries(bool selectedEntriesOnly = false) const; + QVector getSelectedFilterEntries() const; + const QVector& getSelectedEntries() const; + int getParentTopicIdOfFilter(const TrackEntry* te) const; + void setScriptTimeline(ScriptTimeline* scriptTimeline); -private: - QVector m_filterLines; - Ui::TrackWidget *ui; - int m_baseWidth; - QString m_internalName; - bool m_readonly; - ScriptTimeline *m_scriptTimeline; - Tools *m_tools; + const QVector& filterLines() const + { + return m_filterLines; + } -protected: - void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; -private slots: - void slotExpand(); - void slotTrackEntryAdded(TrackEntry *te); - void slotTrackEntryDeleted(const int topicId); - void slotMainChangesMade(); - void slotAddFilter(); + private: + QVector m_filterLines; + Ui::TrackWidget* ui; + int m_baseWidth; + QString m_internalName; + bool m_readonly; + ScriptTimeline* m_scriptTimeline; + Tools* m_tools; -signals: - void signalUnselectAll(); - void signalSelectTrack(); - void signalTrackEntrySelectionChanged(TrackEntry *te); - void signalChangesMade(); - void signalEditEntry(const int topicId); - void signalTrackEntryDeleted(const int topicId); - void signalTrackEntryAdded(TrackEntry *te); + protected: + void paintEvent(QPaintEvent* event) override; + + private slots: + void slotExpand(); + void slotTrackEntryAdded(TrackEntry* te); + void slotTrackEntryDeleted(const int topicId); + void slotMainChangesMade(); + void slotAddFilter(); + + signals: + void signalUnselectAll(); + void signalSelectTrack(); + void signalTrackEntrySelectionChanged(TrackEntry* te); + void signalChangesMade(); + void signalEditEntry(const int topicId); + void signalTrackEntryDeleted(const int topicId); + void signalTrackEntryAdded(TrackEntry* te); }; -} +} // namespace LtsScriptTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp old mode 100755 new mode 100644 index c75d4f318..36061e248 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.cpp @@ -1,6 +1,5 @@ - #include "logger.h" #include @@ -8,25 +7,24 @@ namespace LtsSerialPortQuerry { -LOGGER_T getLogger(const char *name) +LOGGER_T getLogger(const char* name) { - static const char ns[] = "SPQ."; - std::string loggerName; - const size_t len = strlen(name); - loggerName.reserve(sizeof(ns) + len); - loggerName.append(ns, sizeof(ns) - 1); - loggerName.append(name, len); + static const char ns[] = "SPQ."; + 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(); - } + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception& ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } -} +} // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h old mode 100755 new mode 100644 index 75fc2cdc4..c3e498bbc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/logger.h @@ -1,18 +1,17 @@ - #pragma once #include namespace LtsSerialPortQuerry { -typedef NGL::INGLLogger &LOGGER_T; +typedef NGL::INGLLogger& LOGGER_T; -LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) +LOGGER_T getLogger(const char* name); + +inline LOGGER_T getLogger(const QString& loggerName) { - return getLogger(loggerName.toUtf8().constData()); + return getLogger(loggerName.toUtf8().constData()); } -} - +} // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h old mode 100755 new mode 100644 index 6dd71ca0b..e31057379 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_comport_querry.h @@ -1,52 +1,47 @@ #pragma once -#include "ltsserialportquerry_export.h" #include "lts_seri" +#include "ltsserialportquerry_export.h" + #include -#include #include - - - +#include namespace LtsSerialPortQuerry { class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject { - Q_OBJECT -public: - explicit LtsSerialPortQuerry(QObject *parent = nullptr); + Q_OBJECT + public: + explicit LtsSerialPortQuerry(QObject* parent = nullptr); - void setSerialPortSettings(const QSerialPort::BaudRate &baudRate, - const QSerialPort::OpenModeFlag &openModeFlag, - const QSerialPort::DataBits &dataBits, - const QSerialPort::FlowControl &flowControll, - const QSerialPort::Parity &parity, - const QSerialPort::StopBits &stopBits); - void continueQuerry(); - void restartQuerry(); - QSerialPort *currentSerialPort(); + void setSerialPortSettings(const QSerialPort::BaudRate& baudRate, const QSerialPort::OpenModeFlag& openModeFlag, + const QSerialPort::DataBits& dataBits, const QSerialPort::FlowControl& flowControll, + const QSerialPort::Parity& parity, const QSerialPort::StopBits& stopBits); + void continueQuerry(); + void restartQuerry(); + QSerialPort* currentSerialPort(); -signals: - void connectionEstablished(); + signals: + void connectionEstablished(); -private: - void querrySerialPort(const QSerialPortInfo &info); - void closeAndDeleteCurrentPort(); + private: + void querrySerialPort(const QSerialPortInfo& info); + void closeAndDeleteCurrentPort(); -private: - void onSerialPortError(QSerialPort::SerialPortError serialPortError); + private: + void onSerialPortError(QSerialPort::SerialPortError serialPortError); -private: - QList m_serialPortInfos; - int m_currentQuerry; - QSerialPort::BaudRate m_baudRate; - QSerialPort::OpenModeFlag m_openModeFlag; - QSerialPort::DataBits m_dataBits; - QSerialPort::FlowControl m_flowControll; - QSerialPort::Parity m_parity; - QSerialPort::StopBits m_stopBits; - QSerialPort *m_currentSerialPort; + private: + QList m_serialPortInfos; + int m_currentQuerry; + QSerialPort::BaudRate m_baudRate; + QSerialPort::OpenModeFlag m_openModeFlag; + QSerialPort::DataBits m_dataBits; + QSerialPort::FlowControl m_flowControll; + QSerialPort::Parity m_parity; + QSerialPort::StopBits m_stopBits; + QSerialPort* m_currentSerialPort; }; -} +} // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp old mode 100755 new mode 100644 index 52cc57d6f..965d2dfec --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.cpp @@ -5,148 +5,136 @@ namespace LtsSerialPortQuerry { -LtsSerialPortQuerry::LtsSerialPortQuerry(QObject *parent) - : QObject(parent) - , m_currentQuerry(0) - , m_baudRate(QSerialPort::Baud115200) - , m_openModeFlag(QSerialPort::ReadWrite) - , m_dataBits(QSerialPort::Data8) - , m_flowControll(QSerialPort::NoFlowControl) - , m_parity(QSerialPort::NoParity) - , m_stopBits(QSerialPort::OneStop) - , m_currentSerialPort(nullptr) +LtsSerialPortQuerry::LtsSerialPortQuerry(QObject* parent) + : QObject(parent), m_currentQuerry(0), m_baudRate(QSerialPort::Baud115200), m_openModeFlag(QSerialPort::ReadWrite), + m_dataBits(QSerialPort::Data8), m_flowControll(QSerialPort::NoFlowControl), m_parity(QSerialPort::NoParity), + m_stopBits(QSerialPort::OneStop), m_currentSerialPort(nullptr) { - } -void LtsSerialPortQuerry::setSerialPortSettings(const QSerialPort::BaudRate &baudRate, - const QIODevice::OpenModeFlag &openModeFlag, - const QSerialPort::DataBits &dataBits, - const QSerialPort::FlowControl &flowControll, - const QSerialPort::Parity &parity, - const QSerialPort::StopBits &stopBits) +void LtsSerialPortQuerry::setSerialPortSettings(const QSerialPort::BaudRate& baudRate, + const QIODevice::OpenModeFlag& openModeFlag, + const QSerialPort::DataBits& dataBits, + const QSerialPort::FlowControl& flowControll, + const QSerialPort::Parity& parity, + const QSerialPort::StopBits& stopBits) { - m_baudRate = baudRate; - m_openModeFlag = openModeFlag; - m_dataBits = dataBits; - m_flowControll = flowControll; - m_parity = parity; - m_stopBits = stopBits; + m_baudRate = baudRate; + m_openModeFlag = openModeFlag; + m_dataBits = dataBits; + m_flowControll = flowControll; + m_parity = parity; + m_stopBits = stopBits; } void LtsSerialPortQuerry::continueQuerry() { - m_currentQuerry++; - if (m_currentQuerry>= m_serialPortInfos.size()) - { - - restartQuerry(); - return; - } - querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); + m_currentQuerry++; + if (m_currentQuerry >= m_serialPortInfos.size()) + { + + restartQuerry(); + return; + } + querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); } void LtsSerialPortQuerry::restartQuerry() { - DEBUG_LOG(m_logger) << "restart querry "; - m_serialPortInfos = QSerialPortInfo::availablePorts(); - m_currentQuerry = 0; - if (m_serialPortInfos.size()) - querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); - else - QTimer::singleShot(1000, this, &LtsSerialPortQuerry::restartQuerry); + DEBUG_LOG(m_logger) << "restart querry "; + m_serialPortInfos = QSerialPortInfo::availablePorts(); + m_currentQuerry = 0; + if (m_serialPortInfos.size()) + querrySerialPort(m_serialPortInfos.at(m_currentQuerry)); + else + QTimer::singleShot(1000, this, &LtsSerialPortQuerry::restartQuerry); } -QSerialPort *LtsSerialPortQuerry::currentSerialPort() +QSerialPort* LtsSerialPortQuerry::currentSerialPort() { - return m_currentSerialPort; + return m_currentSerialPort; } -void LtsSerialPortQuerry::querrySerialPort(const QSerialPortInfo &info) +void LtsSerialPortQuerry::querrySerialPort(const QSerialPortInfo& info) { - closeAndDeleteCurrentPort(); - m_currentSerialPort = new QSerialPort(info, this); - m_currentSerialPort->setBaudRate(m_baudRate); - m_currentSerialPort->setDataBits(m_dataBits); - m_currentSerialPort->setParity(m_parity); - m_currentSerialPort->setStopBits(m_stopBits); - m_currentSerialPort->setFlowControl(m_flowControll); - - DEBUG_LOG(m_logger) << "Try opening Comport:" << m_currentSerialPort->portName() << " index is: " << m_currentQuerry; - + closeAndDeleteCurrentPort(); + m_currentSerialPort = new QSerialPort(info, this); + m_currentSerialPort->setBaudRate(m_baudRate); + m_currentSerialPort->setDataBits(m_dataBits); + m_currentSerialPort->setParity(m_parity); + m_currentSerialPort->setStopBits(m_stopBits); + m_currentSerialPort->setFlowControl(m_flowControll); - if (!m_currentSerialPort->open(QSerialPort::ReadWrite)) - { - - DEBUG_LOG(m_logger) << "Oppening failed query next"; + DEBUG_LOG(m_logger) << "Try opening Comport:" << m_currentSerialPort->portName() + << " index is: " << m_currentQuerry; - continueQuerry(); - }else - { - connect(m_currentSerialPort, &QSerialPort::errorOccurred, - this, &LtsSerialPortQuerry::onSerialPortError, Qt::UniqueConnection); - DEBUG_LOG(m_logger) << "Oppened comport" << m_currentSerialPort->portName(); - emit connectionEstablished(); - } + if (!m_currentSerialPort->open(QSerialPort::ReadWrite)) + { + + DEBUG_LOG(m_logger) << "Oppening failed query next"; + + continueQuerry(); + } + else + { + connect(m_currentSerialPort, &QSerialPort::errorOccurred, this, &LtsSerialPortQuerry::onSerialPortError, + Qt::UniqueConnection); + DEBUG_LOG(m_logger) << "Oppened comport" << m_currentSerialPort->portName(); + emit connectionEstablished(); + } } void LtsSerialPortQuerry::closeAndDeleteCurrentPort() { - if (m_currentSerialPort) - { - m_currentSerialPort->disconnect(); - if (m_currentSerialPort->isOpen()) - m_currentSerialPort->close(); - m_currentSerialPort->deleteLater(); - - m_currentSerialPort = nullptr; - } -} + if (m_currentSerialPort) + { + m_currentSerialPort->disconnect(); + if (m_currentSerialPort->isOpen()) + m_currentSerialPort->close(); + m_currentSerialPort->deleteLater(); + m_currentSerialPort = nullptr; + } +} void LtsSerialPortQuerry::onSerialPortError(QSerialPort::SerialPortError serialPortError) { - if (!m_currentSerialPort) - return; - DEBUG_LOG(m_logger) << "Spontaneous error " << serialPortError << " doesn't have to be an error ..."; + if (!m_currentSerialPort) + return; + DEBUG_LOG(m_logger) << "Spontaneous error " << serialPortError << " doesn't have to be an error ..."; - const QString errStr(QStringLiteral("QSerialPort::SerialPortError ") + QString::number(serialPortError) + - QStringLiteral(" from serial port ") + m_currentSerialPort->portName() + - QStringLiteral(" error: ") + m_currentSerialPort->errorString()); + const QString errStr(QStringLiteral("QSerialPort::SerialPortError ") + QString::number(serialPortError) + + QStringLiteral(" from serial port ") + m_currentSerialPort->portName() + + QStringLiteral(" error: ") + m_currentSerialPort->errorString()); - switch (serialPortError) - { - case QSerialPort::SerialPortError::NoError: - { - - break; - } - case QSerialPort::SerialPortError::DeviceNotFoundError: - case QSerialPort::SerialPortError::PermissionError: - case QSerialPort::SerialPortError::OpenError: - case QSerialPort::SerialPortError::NotOpenError: - case QSerialPort::SerialPortError::UnknownError: - { - ERROR_LOG(m_logger) << "Closing port and try to reopen it. " << m_currentSerialPort->portName(); - continueQuerry(); - - Q_FALLTHROUGH(); - } - case QSerialPort::SerialPortError::UnsupportedOperationError: - { - ERROR_LOG(m_logger) << errStr; - break; - } - default: - { - ERROR_LOG(m_logger) << "Got an Error> " << errStr << "restarting"; - continueQuerry(); - - break; - } - } + switch (serialPortError) + { + case QSerialPort::SerialPortError::NoError: { + break; + } + case QSerialPort::SerialPortError::DeviceNotFoundError: + case QSerialPort::SerialPortError::PermissionError: + case QSerialPort::SerialPortError::OpenError: + case QSerialPort::SerialPortError::NotOpenError: + case QSerialPort::SerialPortError::UnknownError: { + ERROR_LOG(m_logger) << "Closing port and try to reopen it. " << m_currentSerialPort->portName(); + continueQuerry(); + + Q_FALLTHROUGH(); + } + case QSerialPort::SerialPortError::UnsupportedOperationError: { + ERROR_LOG(m_logger) << errStr; + break; + } + default: { + ERROR_LOG(m_logger) << "Got an Error> " << errStr << "restarting"; + continueQuerry(); + + break; + } + } } -} +} // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h old mode 100755 new mode 100644 index 9ed48076d..422842c31 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSerialPortQuerry/lts_serial_port_querry.h @@ -1,57 +1,53 @@ #pragma once +#include "logger.h" #include "ltsserialportquerry_export.h" -#include "logger.h" - #include -#include #include +#include namespace LtsSerialPortQuerry { class LTSSERIALPORTQUERRY_EXPORT LtsSerialPortQuerry : public QObject { - Q_OBJECT -public: - explicit LtsSerialPortQuerry(QObject *parent = nullptr); + Q_OBJECT + public: + explicit LtsSerialPortQuerry(QObject* parent = nullptr); - void setSerialPortSettings(const QSerialPort::BaudRate &baudRate, - const QSerialPort::OpenModeFlag &openModeFlag, - const QSerialPort::DataBits &dataBits, - const QSerialPort::FlowControl &flowControll, - const QSerialPort::Parity &parity, - const QSerialPort::StopBits &stopBits); - - void restartQuerry(); - QSerialPort *currentSerialPort(); + void setSerialPortSettings(const QSerialPort::BaudRate& baudRate, const QSerialPort::OpenModeFlag& openModeFlag, + const QSerialPort::DataBits& dataBits, const QSerialPort::FlowControl& flowControll, + const QSerialPort::Parity& parity, const QSerialPort::StopBits& stopBits); -public slots: - void continueQuerry(); + void restartQuerry(); + QSerialPort* currentSerialPort(); -signals: - void connectionEstablished(); + public slots: + void continueQuerry(); -private: - NGL::INGLLogger &m_logger; - void querrySerialPort(const QSerialPortInfo &info); - void closeAndDeleteCurrentPort(); + signals: + void connectionEstablished(); -private: - NGL::INGLLogger &m_logger; - void onSerialPortError(QSerialPort::SerialPortError serialPortError); + private: + NGL::INGLLogger& m_logger; + void querrySerialPort(const QSerialPortInfo& info); + void closeAndDeleteCurrentPort(); -private: - NGL::INGLLogger &m_logger; - QList m_serialPortInfos; - int m_currentQuerry; - QSerialPort::BaudRate m_baudRate; - QSerialPort::OpenModeFlag m_openModeFlag; - QSerialPort::DataBits m_dataBits; - QSerialPort::FlowControl m_flowControll; - QSerialPort::Parity m_parity; - QSerialPort::StopBits m_stopBits; - QSerialPort *m_currentSerialPort; + private: + NGL::INGLLogger& m_logger; + void onSerialPortError(QSerialPort::SerialPortError serialPortError); + + private: + NGL::INGLLogger& m_logger; + QList m_serialPortInfos; + int m_currentQuerry; + QSerialPort::BaudRate m_baudRate; + QSerialPort::OpenModeFlag m_openModeFlag; + QSerialPort::DataBits m_dataBits; + QSerialPort::FlowControl m_flowControll; + QSerialPort::Parity m_parity; + QSerialPort::StopBits m_stopBits; + QSerialPort* m_currentSerialPort; }; -} +} // namespace LtsSerialPortQuerry diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.cpp old mode 100755 new mode 100644 index e6bd1eac8..6600b4583 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.cpp @@ -9,44 +9,39 @@ */ #include "lts_session.h" -#include "lts_session_manager.h" + #include "lts_session_data_dds.h" #include "lts_session_lock_handler.h" +#include "lts_session_manager.h" -#include -#include +#include +#include +#include +#include +#include +#include +#include // app icons +#include // TODO: rm on release ! #include #include #include #include -#include -#include -#include -#include -#include -#include -#include // TODO: rm on release ! -#include // app icons +#include +#include #include // XXX: grrr.. - -#include #include -#include -#include #include -#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include - - - -#include -//#include - - +#include +// #include using namespace LtsWidgets; @@ -55,1615 +50,1541 @@ namespace LtsSession bool LtsSession::s_valgrind = false; int LtsSession::s_nextSessionId = 0; - -LtsSession::LtsSession(LtsSessionManager *sessionManager) - : m_sessionManager(sessionManager) - , m_mainBackground(nullptr) - , m_hasBaseLayout(false) - , m_baseLayout(nullptr) - , m_markedForDeletion(false) - , m_payloads(false) - , m_initDone(false) - , m_menuVisible(true) - , m_firstActionsFetch(true) - , m_exerciseData(new LtsWidgets::ExerciseData) - , m_currentInitIfc(nullptr) - , m_slotPluginInitDoneMutex(false) - , m_pluginInitDone(false) - , m_hidden(false) - , m_loadedFromSavegame(false) - , m_foreverInvisible(false) - , m_id(s_nextSessionId++) +LtsSession::LtsSession(LtsSessionManager* sessionManager) + : m_sessionManager(sessionManager), m_mainBackground(nullptr), m_hasBaseLayout(false), m_baseLayout(nullptr), + m_markedForDeletion(false), m_payloads(false), m_initDone(false), m_menuVisible(true), m_firstActionsFetch(true), + m_exerciseData(new LtsWidgets::ExerciseData), m_currentInitIfc(nullptr), m_slotPluginInitDoneMutex(false), + m_pluginInitDone(false), m_hidden(false), m_loadedFromSavegame(false), m_foreverInvisible(false), + m_id(s_nextSessionId++) { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(); - connect(this, &LtsSession::signalDoneInitializingSession, - this, &LtsSession::slotStopWaitDialog); - connect(this, &LtsSession::signalInitializationAborted, - this, &LtsSession::slotStopWaitDialog); + connect(this, &LtsSession::signalDoneInitializingSession, this, &LtsSession::slotStopWaitDialog); + connect(this, &LtsSession::signalInitializationAborted, this, &LtsSession::slotStopWaitDialog); + // preparations for stack connect + connect(this, &LtsSession::_signalDoneInitializingSession, this, [this]() { + // if (m_initDone) + // qWarning() << "blub"; + disconnect(this, &LtsSession::_signalDoneInitializingSession, this, nullptr); + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + m_initDone = true; + emit signalDoneInitializingSession(); + }); - // preparations for stack connect - connect(this, &LtsSession::_signalDoneInitializingSession, - this, [this]() - { -// if (m_initDone) -// qWarning() << "blub"; - disconnect(this, &LtsSession::_signalDoneInitializingSession, - this, nullptr); - // qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - m_initDone = true; - emit signalDoneInitializingSession(); - }); + QTimer* t = new QTimer(this); + t->setInterval(1000); + connect(t, &QTimer::timeout, this, &LtsSession::signalStillAlive); + t->start(); + m_scriptEditorTimer = new QTimer(this); + // [Qatar MNQ-474] Crash open Script Editor application Hack + if (strcmp(PROJECTBUILD, "qatarmout") == 0 || strcmp(PROJECTBUILD, "qatar") == 0) + { + DEBUG_LOG(m_logger) << "qatarmout Timer = 4000"; + m_scriptEditorTimer->setInterval(4000); + } + else + { + DEBUG_LOG(m_logger) << "qatarmout Timer = 0"; + m_scriptEditorTimer->setInterval(0); + } - - QTimer *t = new QTimer(this); - t->setInterval(1000); - connect(t, &QTimer::timeout, - this, &LtsSession::signalStillAlive); - t->start(); - m_scriptEditorTimer = new QTimer(this); - // [Qatar MNQ-474] Crash open Script Editor application Hack - if ( strcmp(PROJECTBUILD, "qatarmout") == 0 - || strcmp(PROJECTBUILD, "qatar") == 0) - { - DEBUG_LOG(m_logger) << "qatarmout Timer = 4000"; - m_scriptEditorTimer->setInterval(4000); - } - else - { - DEBUG_LOG(m_logger) << "qatarmout Timer = 0"; - m_scriptEditorTimer->setInterval(0); - } - - m_scriptEditorTimer->setSingleShot(true); - connect(m_scriptEditorTimer, &QTimer::timeout, this, &LtsSession::delayScriptEditorStart); + m_scriptEditorTimer->setSingleShot(true); + connect(m_scriptEditorTimer, &QTimer::timeout, this, &LtsSession::delayScriptEditorStart); } - LtsSession::~LtsSession() { -// qCritical() << "~LtsSession"; + // qCritical() << "~LtsSession"; -//delete m_mainBackground; parented on hiddenWidget! - delete m_baseLayout; // TODO: deleteLater? problem: clear interfaces! - //qWarning() << this << "deleted" << m_baseLayout; + // delete m_mainBackground; parented on hiddenWidget! + delete m_baseLayout; // TODO: deleteLater? problem: clear interfaces! + // qWarning() << this << "deleted" << m_baseLayout; - // Don't: qDeleteAll(m_notiCtlList); + // Don't: qDeleteAll(m_notiCtlList); - // make sure to unref the data plugins, as they carry this LtsSession, and the erase method would not delete the Session (avoid circular dependencies) - clearGuiPluginInterfaces(); - clearDataPluginInterfaces(); + // make sure to unref the data plugins, as they carry this LtsSession, and the erase method would not delete the + // Session (avoid circular dependencies) + clearGuiPluginInterfaces(); + clearDataPluginInterfaces(); - delete m_exerciseData; + delete m_exerciseData; } - QString LtsSession::toString() const { - std::ostringstream stream; - stream << "LtsSession:" - << " this=" << this - << ", domainId=" << this->domainId() - << ", partitionId=" << this->partitionId() - << ", partitionType=" << this->partitionType() - << ", exerciseId='" << this->exerciseId() << "'" - << ", workspaceId='" << this->workspaceId() << "'" - << ", appToString='" << this->appToString(this->app()) << "'" - << ", LtsSessionDataDds=" << LtsSessionDataDds::toString(); - return QString::fromStdString(stream.str()); - -// QString str; -// str.append(QStringLiteral(" domainId='%1'").arg())); -// str.append(QStringLiteral(", ='%1'").arg(this->partitionId())); -// str.append(QStringLiteral(", partitionType='%1'").arg(this->partitionType())); -// str.append(QStringLiteral(", exerciseId='%1'").arg(this->exerciseId())); -// str.append(QStringLiteral(", workspaceId='%1'").arg(this->workspaceId())); -// return str; + std::ostringstream stream; + stream << "LtsSession:" + << " this=" << this << ", domainId=" << this->domainId() << ", partitionId=" << this->partitionId() + << ", partitionType=" << this->partitionType() << ", exerciseId='" << this->exerciseId() << "'" + << ", workspaceId='" << this->workspaceId() << "'" + << ", appToString='" << this->appToString(this->app()) << "'" + << ", LtsSessionDataDds=" << LtsSessionDataDds::toString(); + return QString::fromStdString(stream.str()); + // QString str; + // str.append(QStringLiteral(" domainId='%1'").arg())); + // str.append(QStringLiteral(", ='%1'").arg(this->partitionId())); + // str.append(QStringLiteral(", partitionType='%1'").arg(this->partitionType())); + // str.append(QStringLiteral(", exerciseId='%1'").arg(this->exerciseId())); + // str.append(QStringLiteral(", workspaceId='%1'").arg(this->workspaceId())); + // return str; } - -QWidget *LtsSession::baseLayoutWidget() +QWidget* LtsSession::baseLayoutWidget() { - // qWarning() << "baseLayoutWidget" << m_baseLayout; - // qWarning() << "baseLayoutWidget (widget)" << static_cast(m_baseLayout); - return static_cast(m_baseLayout); + // qWarning() << "baseLayoutWidget" << m_baseLayout; + // qWarning() << "baseLayoutWidget (widget)" << static_cast(m_baseLayout); + return static_cast(m_baseLayout); } - void LtsSession::aboutToCloseTab(LayoutArea area) { - m_baseLayout->getTabFromLayoutArea(area)->aboutToClose(); + m_baseLayout->getTabFromLayoutArea(area)->aboutToClose(); } - -void LtsSession::setDependency(LtsSession *session) +void LtsSession::setDependency(LtsSession* session) { - if (session == this) - { - Q_ASSERT(session != this); - ERROR_LOG(m_logger) << "Tried to set session dependency on self"; - return; - } + if (session == this) + { + Q_ASSERT(session != this); + ERROR_LOG(m_logger) << "Tried to set session dependency on self"; + return; + } - m_dependency = session; + m_dependency = session; } - void LtsSession::aboutToClose() { - emit sessionAboutToBeDestroyed(this); + emit sessionAboutToBeDestroyed(this); - if (m_baseLayout == nullptr) - return; + if (m_baseLayout == nullptr) + return; - aboutToCloseTab(LayoutArea::eDialogTab); - aboutToCloseTab(LayoutArea::eInfoTab); - aboutToCloseTab(LayoutArea::eSpecialTab); - aboutToCloseTab(LayoutArea::eMainTab); + aboutToCloseTab(LayoutArea::eDialogTab); + aboutToCloseTab(LayoutArea::eInfoTab); + aboutToCloseTab(LayoutArea::eSpecialTab); + aboutToCloseTab(LayoutArea::eMainTab); } - void LtsSession::slotStopWaitDialog() { - disconnect(this, &LtsSession::signalDoneInitializingSession, - this, &LtsSession::slotStopWaitDialog); - disconnect(this, &LtsSession::signalInitializationAborted, - this, &LtsSession::slotStopWaitDialog); + disconnect(this, &LtsSession::signalDoneInitializingSession, this, &LtsSession::slotStopWaitDialog); + disconnect(this, &LtsSession::signalInitializationAborted, this, &LtsSession::slotStopWaitDialog); - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); } - QString LtsSession::appToString(LtsAppDescriptor::App app) { - using namespace LtsAppDescriptor; - switch (app) - { - case App::Situation: - return tr("Situation"); - case App::ResourceManager: - return tr("Resource Manager"); - case App::PlanEditor: - return tr("Plan Editor"); - case App::BuildingViewer: - return tr("Building Viewer"); - case App::OC: - return tr("O/C"); - case App::OrgChart: - return tr("Organisation Chart"); - case App::Scripts: - return tr("Scripts"); - case App::Snapshot: - return tr("Snapshot"); - case App::SystemMonitor: - return tr("System Monitor"); - case App::Timeline: - return tr("Timeline"); - case App::SymbolEditor: - return tr("Symbol Editor"); - case App::ScriptEditorEssentialsView: - return tr("Scripts Essentials View"); - case App::BaseDownloader: - return tr("Base Downloader"); - case App::OnlineHelp: - return tr("Online Help"); - case App::ThpSituationReplay: - return tr("THP Situation Replay"); - case App::SituationTablet: - return tr("Situation (Tablet)"); - case App::SilhouetteEditor: - return tr("Silhouette Editor"); - case App::Shootback: - return tr("Shootback"); - case App::Login: - return tr("Login"); - break; - case App::SAAs: - return tr("SAAs"); - break; - } + using namespace LtsAppDescriptor; + switch (app) + { + case App::Situation: + return tr("Situation"); + case App::ResourceManager: + return tr("Resource Manager"); + case App::PlanEditor: + return tr("Plan Editor"); + case App::BuildingViewer: + return tr("Building Viewer"); + case App::OC: + return tr("O/C"); + case App::OrgChart: + return tr("Organisation Chart"); + case App::Scripts: + return tr("Scripts"); + case App::Snapshot: + return tr("Snapshot"); + case App::SystemMonitor: + return tr("System Monitor"); + case App::Timeline: + return tr("Timeline"); + case App::SymbolEditor: + return tr("Symbol Editor"); + case App::ScriptEditorEssentialsView: + return tr("Scripts Essentials View"); + case App::BaseDownloader: + return tr("Base Downloader"); + case App::OnlineHelp: + return tr("Online Help"); + case App::ThpSituationReplay: + return tr("THP Situation Replay"); + case App::SituationTablet: + return tr("Situation (Tablet)"); + case App::SilhouetteEditor: + return tr("Silhouette Editor"); + case App::Shootback: + return tr("Shootback"); + case App::Login: + return tr("Login"); + break; + case App::SAAs: + return tr("SAAs"); + break; + } - return tr("Unknown"); + return tr("Unknown"); } QString LtsSession::appIconFilename(LtsAppDescriptor::App app) { - using namespace LtsAppDescriptor; - switch (app) - { - case App::Situation: - return QStringLiteral("icon:situation.svg"); - case App::ResourceManager: - return QStringLiteral("icon:player_equipment.svg"); - case App::PlanEditor: - return QStringLiteral("icon:plan_editor.svg"); - case App::BuildingViewer: - return QStringLiteral("icon:3d_viewer.svg"); - case App::OC: - return QStringLiteral("icon:display_oc_evaluations.svg"); - case App::OrgChart: - return QStringLiteral("icon:org_chart.svg"); - case App::Scripts: - return QStringLiteral("icon:insert_script.svg"); - case App::Snapshot: - return QStringLiteral("icon:snapshots.svg"); - case App::SystemMonitor: - return QStringLiteral("icon:system_status.svg"); - case App::Timeline: - return QStringLiteral("icon:timeline.svg"); - case App::SymbolEditor: - return QStringLiteral("icon:define_tactical_symbols.svg"); - case App::ScriptEditorEssentialsView: - return QStringLiteral("icon:evaluation_elements.svg"); - case App::BaseDownloader: - return QStringLiteral("icon:download.svg"); - case App::OnlineHelp: - return QStringLiteral("icon:help.svg"); - case App::ThpSituationReplay: - return QStringLiteral("icon:restart.svg"); - case App::SituationTablet: - return QStringLiteral("icon:situation.svg"); - case App::SilhouetteEditor: - return QStringLiteral("icon:situation.svg"); - case App::Shootback: - return QStringLiteral("icon:target.svg"); - case App::SAAs: - return QStringLiteral("icon:saa_remote_desktop.svg"); - case App::Login: - break; - } + using namespace LtsAppDescriptor; + switch (app) + { + case App::Situation: + return QStringLiteral("icon:situation.svg"); + case App::ResourceManager: + return QStringLiteral("icon:player_equipment.svg"); + case App::PlanEditor: + return QStringLiteral("icon:plan_editor.svg"); + case App::BuildingViewer: + return QStringLiteral("icon:3d_viewer.svg"); + case App::OC: + return QStringLiteral("icon:display_oc_evaluations.svg"); + case App::OrgChart: + return QStringLiteral("icon:org_chart.svg"); + case App::Scripts: + return QStringLiteral("icon:insert_script.svg"); + case App::Snapshot: + return QStringLiteral("icon:snapshots.svg"); + case App::SystemMonitor: + return QStringLiteral("icon:system_status.svg"); + case App::Timeline: + return QStringLiteral("icon:timeline.svg"); + case App::SymbolEditor: + return QStringLiteral("icon:define_tactical_symbols.svg"); + case App::ScriptEditorEssentialsView: + return QStringLiteral("icon:evaluation_elements.svg"); + case App::BaseDownloader: + return QStringLiteral("icon:download.svg"); + case App::OnlineHelp: + return QStringLiteral("icon:help.svg"); + case App::ThpSituationReplay: + return QStringLiteral("icon:restart.svg"); + case App::SituationTablet: + return QStringLiteral("icon:situation.svg"); + case App::SilhouetteEditor: + return QStringLiteral("icon:situation.svg"); + case App::Shootback: + return QStringLiteral("icon:target.svg"); + case App::SAAs: + return QStringLiteral("icon:saa_remote_desktop.svg"); + case App::Login: + break; + } - return {}; + return {}; } QIcon LtsSession::appToIcon(LtsAppDescriptor::App app) { - return LtsUtils::iconFromSvg(appIconFilename(app)); + return LtsUtils::iconFromSvg(appIconFilename(app)); } - -bool LtsSession::removeMenuAction(LtsWidgets::LtsDragIcon *icon) +bool LtsSession::removeMenuAction(LtsWidgets::LtsDragIcon* icon) { - if (!m_baseLayout) - return false; - return m_baseLayout->removeMenuAction(icon); + if (!m_baseLayout) + return false; + return m_baseLayout->removeMenuAction(icon); } - void LtsSession::setMenuVisible(bool visible) { - m_menuVisible = visible; + m_menuVisible = visible; - if (m_baseLayout == nullptr) - return; + if (m_baseLayout == nullptr) + return; - m_baseLayout->getMenu()->setVisible(visible); + m_baseLayout->getMenu()->setVisible(visible); } -LtsDragIcon *LtsSession::addAction(const LtsWidgets::PluginData &plData, bool isFirstRun) +LtsDragIcon* LtsSession::addAction(const LtsWidgets::PluginData& plData, bool isFirstRun) { - if (!m_baseLayout) - { - ERROR_LOG(m_logger) << "No BaseLayout available atm, cannot add action!"; - return nullptr; - } + if (!m_baseLayout) + { + ERROR_LOG(m_logger) << "No BaseLayout available atm, cannot add action!"; + return nullptr; + } - return m_baseLayout->addMenuAction(plData, isFirstRun); + return m_baseLayout->addMenuAction(plData, isFirstRun); } - -LtsNotification::LtsNotification *LtsSession::createNotification(const QString &identifier) +LtsNotification::LtsNotification* LtsSession::createNotification(const QString& identifier) { - LtsNotification::LtsNotificationController *c = new LtsNotification::LtsNotificationController(identifier); - LtsNotification::LtsNotification *n = new LtsNotification::LtsNotification(c); + LtsNotification::LtsNotificationController* c = new LtsNotification::LtsNotificationController(identifier); + LtsNotification::LtsNotification* n = new LtsNotification::LtsNotification(c); - if (m_baseLayout) - m_baseLayout->addNotification(c->createWidget()); + if (m_baseLayout) + m_baseLayout->addNotification(c->createWidget()); - m_notiCtlList.append(c); - // Wenn die notification getötet wird, auch wieder austragen... - connect(c, &LtsNotification::LtsNotificationController::destroyed, - this, [this, c]() { m_notiCtlList.removeAll(c); }); + m_notiCtlList.append(c); + // Wenn die notification getötet wird, auch wieder austragen... + connect(c, &LtsNotification::LtsNotificationController::destroyed, this, + [this, c]() { m_notiCtlList.removeAll(c); }); - return n; + return n; } - -bool LtsSession::init(const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList, - bool hidden) +bool LtsSession::init(const DdsConnectionParams& connParams, + const QVector& dataPluginList, + const QVector& guiPluginList, bool hidden) { - m_foreverInvisible = hidden; - if (!LtsSessionDataDds::init(connParams)) - return false; - initializePlugins(dataPluginList, guiPluginList); - return true; + m_foreverInvisible = hidden; + if (!LtsSessionDataDds::init(connParams)) + return false; + initializePlugins(dataPluginList, guiPluginList); + return true; } - -bool LtsSession::init(const dds::domain::DomainParticipant &dp, - const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList) +bool LtsSession::init(const dds::domain::DomainParticipant& dp, const DdsConnectionParams& connParams, + const QVector& dataPluginList, + const QVector& guiPluginList) { - if (!LtsSessionDataDds::init(dp, connParams)) - return false; - initializePlugins(dataPluginList, guiPluginList); - return true; + if (!LtsSessionDataDds::init(dp, connParams)) + return false; + initializePlugins(dataPluginList, guiPluginList); + return true; } - -void LtsSession::initializePlugins(const QVector &dataPluginList, const QVector &guiPluginList) +void LtsSession::initializePlugins(const QVector& dataPluginList, + const QVector& guiPluginList) { - initializeDataPlugins(dataPluginList); - initializeGuiPlugins(guiPluginList); + initializeDataPlugins(dataPluginList); + initializeGuiPlugins(guiPluginList); } - -void LtsSession::initializeDataPlugins(const QVector &dataPluginList) // TODO: DOC: no gui ifcs in data ifcs ! (as fetchInterfaces() is done before gui ifcs are loaded) +void LtsSession::initializeDataPlugins(const QVector& + dataPluginList) // TODO: DOC: no gui ifcs in data ifcs ! (as + // fetchInterfaces() is done before gui ifcs are loaded) { - QMap> newDataPluginInterfaces; + QMap> newDataPluginInterfaces; - for (const LtsPluginManager::AppPluginInstance &api : dataPluginList) - { - DataPluginBase::Plugin *plugin = qobject_cast(api.pluginInstance.plugin); - - if (!plugin) + for (const LtsPluginManager::AppPluginInstance& api : dataPluginList) { - WARNING_LOG(m_logger) << "Session: invalid data plugin (" << api.pluginInstance.plugin->metaObject()->className() << ")" << api.pluginInstance.fileName; - continue; - } + DataPluginBase::Plugin* plugin = qobject_cast(api.pluginInstance.plugin); - // super heavy hardcore hack to speed up login -> we need to check what plugins are needed for an app! - if (app() == LtsAppDescriptor::App::Login - && (!plugin->pluginName().contains(QStringLiteral("AssetManagement")) - && !plugin->pluginName().contains(QStringLiteral("OperatorManagement")) - && !plugin->pluginName().contains(QStringLiteral("ExerciseManagement"))) - ) - continue; - - // check if plugin has to be loaded in this session type - if (!plugin->availableInPartition(partitionType())) - { - DEBUG_LOG(m_logger) << "Data plugin " << api.pluginInstance.pluginName << " is not available in this partition type " << partitionType(); - continue; - } - - // super heavy hardcore hack to speed up login - if ((!plugin->pluginName().contains(QStringLiteral("AssetManagement")) - && !plugin->pluginName().contains(QStringLiteral("OperatorManagement")) - && !plugin->pluginName().contains(QStringLiteral("ExerciseManagement")) - ) && app() == LtsAppDescriptor::App::Login - ) - continue; - std::shared_ptr ifc = plugin->createDataInterface(this); - if (!ifc) - { - WARNING_LOG(m_logger) << "Create data interface failed for '" << api.pluginInstance.pluginName << "' !"; - continue; - } - - m_dataPluginInterfaces[plugin->pluginName()] = ifc; - newDataPluginInterfaces[plugin->pluginName()] = ifc; - DEBUG_LOG(m_logger) << "Adding data plugin " << plugin->pluginName() << " for " << partitionType() << " - " << this; - } - - addAvailablaeDataPluginInterfaces(newDataPluginInterfaces); -} - - -void LtsSession::initializeGuiPlugins(const QVector &guiPluginList) -{ - m_failedFetches.clear(); - - /* important to create gui interfaces even if they are not available in a session, - * but foreign plugins can still use their ForeignGuiInterface to use - * their windows */ - - for (auto i = guiPluginList.constBegin(); i != guiPluginList.constEnd(); ++i) - { - const LtsPluginManager::AppPluginInstance &api = *i; - - GuiPluginBase::Plugin *plugin = qobject_cast(api.pluginInstance.plugin); - - if (!plugin) - { - WARNING_LOG(m_logger) << "Session: invalid gui plugin (" << api.pluginInstance.plugin->metaObject()->className() << ")" << api.pluginInstance.fileName; - continue; - } - - - // check if plugin has to be loaded in this session type - if (!plugin->availableInPartition(partitionType())) - { - DEBUG_LOG(m_logger) << "Gui plugin " << api.pluginInstance.pluginName << " is not available in this partition type " << partitionType(); - continue; - } - - - std::shared_ptr ifc = plugin->createGuiInterface(this); - - if (!ifc) - { - WARNING_LOG(m_logger) << "Create gui interface failed for '" << api.pluginInstance.pluginName << "' (" << api.pluginInstance.plugin->metaObject()->className() << ") !"; - continue; - } - - - QFlags flags = api.m_flags; // copy flags - - if (api.pluginInstance.pluginName == QStringLiteral("dev")) - flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; - - ifc->setFlags(flags); // durchreichen.. raw plugin => plugin instance - ifc->setOptions(api.m_options); // s.a.a. - ifc->setAppId(api.m_appId); // s.a.a. - m_guiPluginInterfaces[plugin->pluginName()] = ifc; - DEBUG_LOG(m_logger) << "Adding gui plugin " << plugin->pluginName() << " for " << partitionType() << " - " << this; - } - - - /*/ - * there are all plugin instances in this list - * if fetchInterface of a single plugin failes, that plugin instance will be removed (does not find his obligatory plugin(s) in this list) - * a refetch has to be done, in case some other plugin(s) used that plugin which is now deleted - /*/ - QMutableMapIterator > it(m_guiPluginInterfaces); // modify a list while iterating through it - while (it.hasNext()) - { - const auto val = it.next(); - const QString &guiPluginKey = val.key(); - std::shared_ptr guiPlugin = val.value(); - - if (!guiPlugin->fetchInterfaces()) - { - DEBUG_LOG(m_logger) << "Fetching interfaces failed for Gui Plugin '" << guiPluginKey << "' - removing and refetching !"; - m_failedFetches.append(guiPluginKey); - it.remove(); - it.toFront(); // rewind! - - // remove from payloads list if failed, because payload might already be added before refetching, but we don't want payloads of plugins that failed fetching interfaces.. - for (auto i = m_payloadPriorityMap.begin(); i != m_payloadPriorityMap.end(); ++i) - { - std::shared_ptr payloadIfc = *i; - - if (payloadIfc == guiPlugin) - break; - } - - m_payloadList.removeAll(guiPlugin); - } - else - { - //ERROR_LOG(m_logger) << "GUI FETCH INTERFACE OKAY!"; - - int executionPriority = guiPlugin->executionPriority(); - - if (executionPriority > -1) - { - if (m_payloads && guiPlugin->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD)) + if (!plugin) { - if (executionPriority == 9999) - { - if (!m_payloadList.contains(guiPlugin)) - m_payloadList.append(guiPlugin); - } - else - m_payloadPriorityMap.insert(executionPriority, guiPlugin); // addPayload(executionPriority, guiPlugin); - //DEBUG_LOG(m_logger) << " > has payloads, adding payload request to session"; + WARNING_LOG(m_logger) << "Session: invalid data plugin (" + << api.pluginInstance.plugin->metaObject()->className() << ")" + << api.pluginInstance.fileName; + continue; } - } - //DEBUG_LOG(m_logger) << " > done"; + // super heavy hardcore hack to speed up login -> we need to check what plugins are needed for an app! + if (app() == LtsAppDescriptor::App::Login && + (!plugin->pluginName().contains(QStringLiteral("AssetManagement")) && + !plugin->pluginName().contains(QStringLiteral("OperatorManagement")) && + !plugin->pluginName().contains(QStringLiteral("ExerciseManagement")))) + continue; + + // check if plugin has to be loaded in this session type + if (!plugin->availableInPartition(partitionType())) + { + DEBUG_LOG(m_logger) << "Data plugin " << api.pluginInstance.pluginName + << " is not available in this partition type " << partitionType(); + continue; + } + + // super heavy hardcore hack to speed up login + if ((!plugin->pluginName().contains(QStringLiteral("AssetManagement")) && + !plugin->pluginName().contains(QStringLiteral("OperatorManagement")) && + !plugin->pluginName().contains(QStringLiteral("ExerciseManagement"))) && + app() == LtsAppDescriptor::App::Login) + continue; + std::shared_ptr ifc = plugin->createDataInterface(this); + if (!ifc) + { + WARNING_LOG(m_logger) << "Create data interface failed for '" << api.pluginInstance.pluginName << "' !"; + continue; + } + + m_dataPluginInterfaces[plugin->pluginName()] = ifc; + newDataPluginInterfaces[plugin->pluginName()] = ifc; + DEBUG_LOG(m_logger) << "Adding data plugin " << plugin->pluginName() << " for " << partitionType() << " - " + << this; } - } - - QTimer::singleShot(100, this, &LtsSession::slotStartPluginInit); - //executePayloads(); // does not execute when there are no payloads, but is needed to be called here ! + addAvailablaeDataPluginInterfaces(newDataPluginInterfaces); } - -LtsTabWidget *LtsSession::locateWidget(QWidget *widgetToLocate, LayoutArea area) +void LtsSession::initializeGuiPlugins(const QVector& guiPluginList) { - if (!m_baseLayout) - return nullptr; + m_failedFetches.clear(); - LtsTabWidget *tabWidget = m_baseLayout->getTabFromLayoutArea(area); + /* important to create gui interfaces even if they are not available in a session, + * but foreign plugins can still use their ForeignGuiInterface to use + * their windows */ - if (tabWidget->indexOf(widgetToLocate) >= 0) - return tabWidget; + for (auto i = guiPluginList.constBegin(); i != guiPluginList.constEnd(); ++i) + { + const LtsPluginManager::AppPluginInstance& api = *i; - return nullptr; // not found! + GuiPluginBase::Plugin* plugin = qobject_cast(api.pluginInstance.plugin); + + if (!plugin) + { + WARNING_LOG(m_logger) << "Session: invalid gui plugin (" + << api.pluginInstance.plugin->metaObject()->className() << ")" + << api.pluginInstance.fileName; + continue; + } + + // check if plugin has to be loaded in this session type + if (!plugin->availableInPartition(partitionType())) + { + DEBUG_LOG(m_logger) << "Gui plugin " << api.pluginInstance.pluginName + << " is not available in this partition type " << partitionType(); + continue; + } + + std::shared_ptr ifc = plugin->createGuiInterface(this); + + if (!ifc) + { + WARNING_LOG(m_logger) << "Create gui interface failed for '" << api.pluginInstance.pluginName << "' (" + << api.pluginInstance.plugin->metaObject()->className() << ") !"; + continue; + } + + QFlags flags = api.m_flags; // copy flags + + if (api.pluginInstance.pluginName == QStringLiteral("dev")) + flags |= LtsAppDescriptor::PluginInfo::Flag::ACTIONS; + + ifc->setFlags(flags); // durchreichen.. raw plugin => plugin instance + ifc->setOptions(api.m_options); // s.a.a. + ifc->setAppId(api.m_appId); // s.a.a. + m_guiPluginInterfaces[plugin->pluginName()] = ifc; + DEBUG_LOG(m_logger) << "Adding gui plugin " << plugin->pluginName() << " for " << partitionType() << " - " + << this; + } + + /*/ + * there are all plugin instances in this list + * if fetchInterface of a single plugin failes, that plugin instance will be removed (does not find his obligatory + plugin(s) in this list) + * a refetch has to be done, in case some other plugin(s) used that plugin which is now deleted + /*/ + QMutableMapIterator> it( + m_guiPluginInterfaces); // modify a list while iterating through it + while (it.hasNext()) + { + const auto val = it.next(); + const QString& guiPluginKey = val.key(); + std::shared_ptr guiPlugin = val.value(); + + if (!guiPlugin->fetchInterfaces()) + { + DEBUG_LOG(m_logger) << "Fetching interfaces failed for Gui Plugin '" << guiPluginKey + << "' - removing and refetching !"; + m_failedFetches.append(guiPluginKey); + it.remove(); + it.toFront(); // rewind! + + // remove from payloads list if failed, because payload might already be added before refetching, but we + // don't want payloads of plugins that failed fetching interfaces.. + for (auto i = m_payloadPriorityMap.begin(); i != m_payloadPriorityMap.end(); ++i) + { + std::shared_ptr payloadIfc = *i; + + if (payloadIfc == guiPlugin) + break; + } + + m_payloadList.removeAll(guiPlugin); + } + else + { + // ERROR_LOG(m_logger) << "GUI FETCH INTERFACE OKAY!"; + + int executionPriority = guiPlugin->executionPriority(); + + if (executionPriority > -1) + { + if (m_payloads && guiPlugin->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::PAYLOAD)) + { + if (executionPriority == 9999) + { + if (!m_payloadList.contains(guiPlugin)) + m_payloadList.append(guiPlugin); + } + else + m_payloadPriorityMap.insert(executionPriority, + guiPlugin); // addPayload(executionPriority, guiPlugin); + // DEBUG_LOG(m_logger) << " > has payloads, adding payload request to session"; + } + } + + // DEBUG_LOG(m_logger) << " > done"; + } + } + + QTimer::singleShot(100, this, &LtsSession::slotStartPluginInit); + // executePayloads(); // does not execute when there are no payloads, but is needed to be called here ! } +LtsTabWidget* LtsSession::locateWidget(QWidget* widgetToLocate, LayoutArea area) +{ + if (!m_baseLayout) + return nullptr; + + LtsTabWidget* tabWidget = m_baseLayout->getTabFromLayoutArea(area); + + if (tabWidget->indexOf(widgetToLocate) >= 0) + return tabWidget; + + return nullptr; // not found! +} void LtsSession::enableBaseLayoutMenu(bool on) { - if (m_baseLayout) - { - QWidget *ltsMenu = m_baseLayout->getMenu(); + if (m_baseLayout) + { + QWidget* ltsMenu = m_baseLayout->getMenu(); - if (ltsMenu) - ltsMenu->setEnabled(on); - } + if (ltsMenu) + ltsMenu->setEnabled(on); + } } - void LtsSession::enableBaseLayoutArea(LtsWidgets::LayoutArea area, bool on) { - if (m_baseLayout) - { - QWidget *ltsWidget = m_baseLayout->getTabFromLayoutArea(area); - if (ltsWidget) - ltsWidget->setEnabled(on); - } + if (m_baseLayout) + { + QWidget* ltsWidget = m_baseLayout->getTabFromLayoutArea(area); + if (ltsWidget) + ltsWidget->setEnabled(on); + } } - int LtsSession::workstationIp() { - static int wsId = -1; - if (wsId == -1) - { + static int wsId = -1; + if (wsId == -1) + { #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const QString hostname = workstationName(); - const auto addreses = QHostInfo::fromName(hostname).addresses(); - for (const QHostAddress &ha : addreses) - { - if (ha.isLoopback()) - continue; - if (ha.protocol() != QAbstractSocket::NetworkLayerProtocol::IPv4Protocol) - continue; - wsId = static_cast(ha.toIPv4Address()); - break; - } + const QString hostname = workstationName(); + const auto addreses = QHostInfo::fromName(hostname).addresses(); + for (const QHostAddress& ha : addreses) + { + if (ha.isLoopback()) + continue; + if (ha.protocol() != QAbstractSocket::NetworkLayerProtocol::IPv4Protocol) + continue; + wsId = static_cast(ha.toIPv4Address()); + break; + } #else - const QList interfaces = QNetworkInterface::allInterfaces(); - for (const QNetworkInterface &ninterface : interfaces) - { - if (ninterface.type() == QNetworkInterface::InterfaceType::Wifi) - continue; - const auto addreseEntry = ninterface.addressEntries(); - for (const QNetworkAddressEntry &ent : addreseEntry) - { - const QHostAddress ha = ent.ip(); - if (ha.isLoopback()) - continue; - if (ha.protocol() != QAbstractSocket::NetworkLayerProtocol::IPv4Protocol) - continue; - wsId = static_cast(ha.toIPv4Address()); - break; - } - if (wsId != -1) - break; - } + const QList interfaces = QNetworkInterface::allInterfaces(); + for (const QNetworkInterface& ninterface : interfaces) + { + if (ninterface.type() == QNetworkInterface::InterfaceType::Wifi) + continue; + const auto addreseEntry = ninterface.addressEntries(); + for (const QNetworkAddressEntry& ent : addreseEntry) + { + const QHostAddress ha = ent.ip(); + if (ha.isLoopback()) + continue; + if (ha.protocol() != QAbstractSocket::NetworkLayerProtocol::IPv4Protocol) + continue; + wsId = static_cast(ha.toIPv4Address()); + break; + } + if (wsId != -1) + break; + } #endif - } - return wsId; + } + return wsId; } - - QString LtsSession::workstationName() { - return QHostInfo::localHostName().toUpper(); + return QHostInfo::localHostName().toUpper(); } - const QString LtsSession::workspaceId() const { - if (isReplayPartition()) - return QStringLiteral("replay_%1").arg(QString::number(partitionId())); - return m_workspaceId;//sessionManager->workspaceId(); + if (isReplayPartition()) + return QStringLiteral("replay_%1").arg(QString::number(partitionId())); + return m_workspaceId; // sessionManager->workspaceId(); } - void LtsSession::setWorkspaceId(const QString &newWorkspaceId /* <= MW: that's why I like "get" in getter names (needed to prepend "new" because of already existing method with the name "workspaceId") */) { - DEBUG_LOG(m_logger) << LOGFUNCTION << " change workspaceId: cur = '" << m_workspaceId << "' for app '" << appToString(app()) << "'"; - DEBUG_LOG(m_logger) << LOGFUNCTION << " change workspaceId: new = '" << newWorkspaceId << "' for app '" << appToString(app()) << "'"; - m_workspaceId = newWorkspaceId;//m_sessionManager->setWorkspaceId(workspaceId); + DEBUG_LOG(m_logger) << LOGFUNCTION << " change workspaceId: cur = '" << m_workspaceId << "' for app '" + << appToString(app()) << "'"; + DEBUG_LOG(m_logger) << LOGFUNCTION << " change workspaceId: new = '" << newWorkspaceId << "' for app '" + << appToString(app()) << "'"; + m_workspaceId = newWorkspaceId; // m_sessionManager->setWorkspaceId(workspaceId); - if (m_baseLayout) - m_baseLayout->setWorkspaceId(workspaceId() /* use getter instead of member var, as replay partition strings can only be retrieved with the getter */); + if (m_baseLayout) + m_baseLayout->setWorkspaceId(workspaceId() /* use getter instead of member var, as replay partition strings can only be retrieved with the getter */); - emit workspaceIdChanged(newWorkspaceId); + emit workspaceIdChanged(newWorkspaceId); } - ExcState LtsSession::exerciseState() const { - return m_exerciseData ? m_exerciseData->exState : ExerciseState::eUnknown; + return m_exerciseData ? m_exerciseData->exState : ExerciseState::eUnknown; } - -void LtsSession::connectOnlineHelpButton(LtsWidgets::LtsDialog *widget) +void LtsSession::connectOnlineHelpButton(LtsWidgets::LtsDialog* widget) { - // FIXME: HACK: also connect show online help here !! - connect(widget, &LtsDialog::signalShowOnlineHelp, - this, &LtsSession::slotShowOnlineHelp, - Qt::UniqueConnection); + // FIXME: HACK: also connect show online help here !! + connect(widget, &LtsDialog::signalShowOnlineHelp, this, &LtsSession::slotShowOnlineHelp, Qt::UniqueConnection); } - -void LtsSession::slotStapleTopicLockHandler(LtsWidgets::LtsDialog *widget) +void LtsSession::slotStapleTopicLockHandler(LtsWidgets::LtsDialog* widget) { - if (widget->property("topicLockStapled").isValid()) - { - Q_ASSERT(false); - return; - } - widget->setProperty("topicLockStapled", true); + if (widget->property("topicLockStapled").isValid()) + { + Q_ASSERT(false); + return; + } + widget->setProperty("topicLockStapled", true); #ifdef BUILD_RTI - connectOnlineHelpButton(widget); - if (m_coreFtc == nullptr) - { - DEBUG_LOG(m_logger) << "no core ftc, no TopicLockHandler for " << toString(); - return; - } + connectOnlineHelpButton(widget); + if (m_coreFtc == nullptr) + { + DEBUG_LOG(m_logger) << "no core ftc, no TopicLockHandler for " << toString(); + return; + } - auto *topicLockHandler = new TopicLockHandler(/* widget <= see comment below */); - /*/ - * Conceptional: widgets is closing, widget deletes lock handler, lock handler unlocks via ftc, - * lock handler was deleted, ftc answers to already deleted lock handler => crash - * This is a conceptional problem in all the ftc handlers - /*/ + auto* topicLockHandler = new TopicLockHandler(/* widget <= see comment below */); + /*/ + * Conceptional: widgets is closing, widget deletes lock handler, lock handler unlocks via ftc, + * lock handler was deleted, ftc answers to already deleted lock handler => crash + * This is a conceptional problem in all the ftc handlers + /*/ - if (!topicLockHandler->init(m_coreFtc, m_exerciseId)) - { - WARNING_LOG(m_logger) << "LtsSession::addWidget: init of TopicLockHandler failed!"; - delete topicLockHandler; - return; - } + if (!topicLockHandler->init(m_coreFtc, m_exerciseId)) + { + WARNING_LOG(m_logger) << "LtsSession::addWidget: init of TopicLockHandler failed!"; + delete topicLockHandler; + return; + } - connect(topicLockHandler, &TopicLockHandler::signalLockDialog, - widget, &LtsDialog::slotLock, Qt::QueuedConnection); - connect(topicLockHandler, &TopicLockHandler::signalUnlockDialog, - widget, &LtsDialog::slotUnlock, Qt::QueuedConnection); - connect(widget, &LtsDialog::signalLockTopic, - topicLockHandler, &TopicLockHandler::slotTryLock, Qt::DirectConnection); // sync! + connect(topicLockHandler, &TopicLockHandler::signalLockDialog, widget, &LtsDialog::slotLock, Qt::QueuedConnection); + connect(topicLockHandler, &TopicLockHandler::signalUnlockDialog, widget, &LtsDialog::slotUnlock, + Qt::QueuedConnection); + connect(widget, &LtsDialog::signalLockTopic, topicLockHandler, &TopicLockHandler::slotTryLock, + Qt::DirectConnection); // sync! - //widget->setTopicLockHandler(topicLockHandler); + // widget->setTopicLockHandler(topicLockHandler); - connect(widget, &LtsDialog::destroyed, - topicLockHandler, &TopicLockHandler::slotFinalize, Qt::QueuedConnection); + connect(widget, &LtsDialog::destroyed, topicLockHandler, &TopicLockHandler::slotFinalize, Qt::QueuedConnection); - //qWarning() << "added tlh to" << widget->windowTitle(); + // qWarning() << "added tlh to" << widget->windowTitle(); - - connectOnlineHelpButton(widget); + connectOnlineHelpButton(widget); #else - Q_UNUSED(widget) - DEBUG_LOG(m_logger) << "BUILD_RTI=OFF, skipping TopicLockHandler setup"; + Q_UNUSED(widget) + DEBUG_LOG(m_logger) << "BUILD_RTI=OFF, skipping TopicLockHandler setup"; #endif } - -bool LtsSession::focusTab(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area) +bool LtsSession::focusTab(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area) { - if (!m_baseLayout) - { - ERROR_LOG(m_logger) << "no base layout to focus a tab on! menuGroup: " << menuGroup << "ident: " << identifier; - return false; - } + if (!m_baseLayout) + { + ERROR_LOG(m_logger) << "no base layout to focus a tab on! menuGroup: " << menuGroup << "ident: " << identifier; + return false; + } - return m_baseLayout->focusTab(menuGroup, identifier, area); + return m_baseLayout->focusTab(menuGroup, identifier, area); } - -LtsWidgets::LtsDialog *LtsSession::getWidget(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area) +LtsWidgets::LtsDialog* LtsSession::getWidget(const QString& menuGroup, const QString& identifier, + LtsWidgets::LayoutArea area) { - if (!m_baseLayout) - { - ERROR_LOG(m_logger) << "no base layout to get a widget from! menuGroup: " << menuGroup << "ident: " << identifier; - return nullptr; - } + if (!m_baseLayout) + { + ERROR_LOG(m_logger) << "no base layout to get a widget from! menuGroup: " << menuGroup + << "ident: " << identifier; + return nullptr; + } - return m_baseLayout->getWidget(menuGroup, identifier, area); + return m_baseLayout->getWidget(menuGroup, identifier, area); } - -bool LtsSession::widgetExists(const QString &menuGroup, const QString &identifier, LayoutArea area) const +bool LtsSession::widgetExists(const QString& menuGroup, const QString& identifier, LayoutArea area) const { - if (!m_baseLayout) - return false; - LtsTabWidget *tab = m_baseLayout->getTabFromLayoutArea(area); - if (!tab) - return false; - QWidget *existingWidget = tab->getWidget(menuGroup, identifier); - return existingWidget != nullptr; + if (!m_baseLayout) + return false; + LtsTabWidget* tab = m_baseLayout->getTabFromLayoutArea(area); + if (!tab) + return false; + QWidget* existingWidget = tab->getWidget(menuGroup, identifier); + return existingWidget != nullptr; } - -bool LtsSession::addWidget(LtsDialog *widget, const QString &menuGroup, const QString &identifier, LayoutArea area, bool setClosable) +bool LtsSession::addWidget(LtsDialog* widget, const QString& menuGroup, const QString& identifier, LayoutArea area, + bool setClosable) { - // TODO: operator selection + possibility to permanent select base layout until its dissolving + // TODO: operator selection + possibility to permanent select base layout until its dissolving - if (!m_baseLayout) - { - ERROR_LOG(m_logger) << "no base layout to put a widget on! menuGroup: " << menuGroup << "ident: " << identifier; - return false; - } + if (!m_baseLayout) + { + ERROR_LOG(m_logger) << "no base layout to put a widget on! menuGroup: " << menuGroup << "ident: " << identifier; + return false; + } - //slotStapleTopicLockHandler(widget); => already done in blw's addWidget (below!) -// FIXMe: connect(widget, &LtsDialog::signalShowOnlineHelp, -// this, &LtsSession::slotShowOnlineHelp, -// Qt::UniqueConnection); done in slotStaple.. because using LtsDialog::addDialog does NOT reach this code here ! + // slotStapleTopicLockHandler(widget); => already done in blw's addWidget (below!) + // FIXMe: connect(widget, &LtsDialog::signalShowOnlineHelp, + // this, &LtsSession::slotShowOnlineHelp, + // Qt::UniqueConnection); done in slotStaple.. because using LtsDialog::addDialog does NOT reach this + // code here ! - return m_baseLayout->addWidget(widget, menuGroup, identifier, area, setClosable); + return m_baseLayout->addWidget(widget, menuGroup, identifier, area, setClosable); } - -void LtsSession::setExerciseData(const LtsWidgets::ExerciseData &exerciseData) +void LtsSession::setExerciseData(const LtsWidgets::ExerciseData& exerciseData) { - // avoid mutiple calls (and signal to emitted multiple times) - if ((*m_exerciseData) == exerciseData) - return; + // avoid mutiple calls (and signal to emitted multiple times) + if ((*m_exerciseData) == exerciseData) + return; - *m_exerciseData = exerciseData; - // partitionType(); ?!? - if (!m_baseLayout) - return; - m_baseLayout->setExerciseData(exerciseData); - emit signalExerciseDataChanged(); + *m_exerciseData = exerciseData; + // partitionType(); ?!? + if (!m_baseLayout) + return; + m_baseLayout->setExerciseData(exerciseData); + emit signalExerciseDataChanged(); } - -const LtsWidgets::ExerciseData *LtsSession::exerciseData() const +const LtsWidgets::ExerciseData* LtsSession::exerciseData() const { - return m_exerciseData; + return m_exerciseData; } - -void LtsSession::setProfilePicture(const QPixmap &pixmap) +void LtsSession::setProfilePicture(const QPixmap& pixmap) { - // partitionType(); ?!? - if (!m_baseLayout) - return; - m_baseLayout->setProfilePicture(pixmap); + // partitionType(); ?!? + if (!m_baseLayout) + return; + m_baseLayout->setProfilePicture(pixmap); } - void LtsSession::makeVisible() { - Q_ASSERT(m_baseLayout == nullptr); - if (m_baseLayout) // onyl create a new base layout when there was not one before ! - { - qCritical() << "base layout already visible"; - return; - } + Q_ASSERT(m_baseLayout == nullptr); + if (m_baseLayout) // onyl create a new base layout when there was not one before ! + { + qCritical() << "base layout already visible"; + return; + } - createBaseLayout(); + createBaseLayout(); } - void LtsSession::refetchActions() { - // get actions - for (auto i = m_guiPluginInterfaces.cbegin(); i != m_guiPluginInterfaces.cend(); ++i) - { - std::shared_ptr ifc = *i; - - if (!ifc->availableInPartition(partitionType())) + // get actions + for (auto i = m_guiPluginInterfaces.cbegin(); i != m_guiPluginInterfaces.cend(); ++i) { - DEBUG_LOG(m_logger) << i.key() << " is not available in this partition type " << partitionType(); - continue; - } + std::shared_ptr ifc = *i; - if (m_firstActionsFetch && ifc->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN) && !ifc->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS)) // respect the MAIN flag, even though ACTIONS is not set (main, but NOT actions) [but only if this is NOT a refetch] - { - ERROR_LOG(m_logger) << "Plugin '" << i.key() << "' has flag 'MAIN' but is missing the 'ACTIONS' flag - ingoring actions!"; - continue; - } + if (!ifc->availableInPartition(partitionType())) + { + DEBUG_LOG(m_logger) << i.key() << " is not available in this partition type " << partitionType(); + continue; + } - if (ifc->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS)) - { - // get gui plugin's actions (only when init was successful) - const QVector plData = ifc->getActions(); + if (m_firstActionsFetch && ifc->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::MAIN) && + !ifc->getFlags().testFlag( + LtsAppDescriptor::PluginInfo::Flag::ACTIONS)) // respect the MAIN flag, even though ACTIONS is not set + // (main, but NOT actions) [but only if this is NOT a + // refetch] + { + ERROR_LOG(m_logger) << "Plugin '" << i.key() + << "' has flag 'MAIN' but is missing the 'ACTIONS' flag - ingoring actions!"; + continue; + } - if (plData.isEmpty()) - DEBUG_LOG(m_logger) << i.key() << " (" << ifc->menuGroup() << ") does not provide actions"; + if (ifc->getFlags().testFlag(LtsAppDescriptor::PluginInfo::Flag::ACTIONS)) + { + // get gui plugin's actions (only when init was successful) + const QVector plData = ifc->getActions(); - //WARNING_LOG(m_logger) << " > " << plData.count() << " Actions"; + if (plData.isEmpty()) + DEBUG_LOG(m_logger) << i.key() << " (" << ifc->menuGroup() << ") does not provide actions"; - for (const LtsWidgets::PluginData &pd : plData) - { - if (!pd.menuGroup.isEmpty() && !pd.menuText.isEmpty() && pd.identifier.isEmpty()) // check if identifier is missing - ERROR_LOG(m_logger) << "Identifier for Action " << pd.menuGroup << " - " << pd.menuText << " missing - not added!"; + // WARNING_LOG(m_logger) << " > " << plData.count() << " Actions"; + + for (const LtsWidgets::PluginData& pd : plData) + { + if (!pd.menuGroup.isEmpty() && !pd.menuText.isEmpty() && + pd.identifier.isEmpty()) // check if identifier is missing + ERROR_LOG(m_logger) << "Identifier for Action " << pd.menuGroup << " - " << pd.menuText + << " missing - not added!"; + else + { + if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(pd.operatorRight)) + m_missingRightActions += pd; + + m_baseLayout->addMenuAction(pd, m_firstActionsFetch); + } + } + } else { - if (!LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(pd.operatorRight)) - m_missingRightActions += pd; - - m_baseLayout->addMenuAction(pd, m_firstActionsFetch); + // WARNING_LOG(m_logger) << " > " << plData.count() << " Actions - but ignored by flag"; } - } } - else - { - //WARNING_LOG(m_logger) << " > " << plData.count() << " Actions - but ignored by flag"; - } - } #ifdef LTS_DEBUG - if (m_firstActionsFetch) - { - const QString &executeAction(qEnvironmentVariable("EXCON_EXECUTE_ACTION", {})); - if (!executeAction.isEmpty()) + if (m_firstActionsFetch) { - WARNING_LOG(m_logger) << "EXCON_EXECUTE_ACTION was set to: " << executeAction; - m_baseLayout->executeAction(executeAction); + const QString& executeAction(qEnvironmentVariable("EXCON_EXECUTE_ACTION", {})); + if (!executeAction.isEmpty()) + { + WARNING_LOG(m_logger) << "EXCON_EXECUTE_ACTION was set to: " << executeAction; + m_baseLayout->executeAction(executeAction); + } } - } #endif - m_firstActionsFetch = false; + m_firstActionsFetch = false; } void LtsSession::slotSwap() { - LtsMultiMonitor::LtsMultiMonitor::getInstance()->selectAndSwap(m_baseLayout); + LtsMultiMonitor::LtsMultiMonitor::getInstance()->selectAndSwap(m_baseLayout); } - int LtsSession::screenId() const { - if (m_baseLayout == nullptr) - return -1; + if (m_baseLayout == nullptr) + return -1; - LtsMultiMonitor::LtsScreenBase *screen = LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); + LtsMultiMonitor::LtsScreenBase* screen = + LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); - if (screen == nullptr) - return -2; + if (screen == nullptr) + return -2; - return screen->screenId(); + return screen->screenId(); } - int LtsSession::screenContainerId() const { - if (m_baseLayout == nullptr) - return -1; + if (m_baseLayout == nullptr) + return -1; - LtsMultiMonitor::LtsScreenBase *screen = LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); + LtsMultiMonitor::LtsScreenBase* screen = + LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); - if (screen == nullptr) - return -2; + if (screen == nullptr) + return -2; - try - { - return screen->containerIdOfWidget(m_baseLayout); - } - catch(...){} + try + { + return screen->containerIdOfWidget(m_baseLayout); + } + catch (...) + { + } - return -3; + return -3; } - int LtsSession::screenTypeId() const { - if (m_baseLayout == nullptr) - return -1; + if (m_baseLayout == nullptr) + return -1; - LtsMultiMonitor::LtsScreenBase *screen = LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); + LtsMultiMonitor::LtsScreenBase* screen = + LtsMultiMonitor::LtsMultiMonitor::getInstance()->widgetsScreen(m_baseLayout); - if (screen == nullptr) - return -2; + if (screen == nullptr) + return -2; - return screen->screenType(); + return screen->screenType(); } - LtsAppDescriptor::App LtsSession::app() const { - return m_sessionManager ? m_sessionManager->appId() : LtsAppDescriptor::App::Login; + return m_sessionManager ? m_sessionManager->appId() : LtsAppDescriptor::App::Login; } - -bool LtsSession::event(QEvent *e) +bool LtsSession::event(QEvent* e) { - if (e->type() == QEvent::LanguageChange) - m_baseLayout->setAppName(appToString(app())); + if (e->type() == QEvent::LanguageChange) + m_baseLayout->setAppName(appToString(app())); - return LtsSessionDataDds::event(e); + return LtsSessionDataDds::event(e); } - void LtsSession::addDeveloperActions() { - // DEVELOPER / DEBUG MENU - { - LtsWidgets::PluginData p; - p.menuGroup = QStringLiteral("[Dev]"); - p.menuText = QStringLiteral("Open Admin Session"); - p.identifier = QStringLiteral("OpenAdminSession"); - - p.directFunc = [&](const LtsWidgets::PluginData &) + // DEVELOPER / DEBUG MENU { - LtsSession *adminSession = m_sessionManager->getSession(IDL::PartitionType::Global, 0); - if (!adminSession) - { - //QMessageBox::information(nullptr, QString(), QStringLiteral("no admin session")); - DdsConnectionParams connParams; - connParams.domainId = domainId(); - connParams.partitionId = 0; - connParams.exerciseId = 0; - connParams.partitionType = IDL::PartitionType::Global; - connParams.tcpConnectionUrl = tcpConnectionUrl(); - connParams.qos_file = m_qosFileList; - adminSession = m_sessionManager->createSession(connParams, - true, - false); // no payloads !! TODO: is this a real domainId or a dead var ?? - return; - } - else - adminSession->makeVisible(); - }; + LtsWidgets::PluginData p; + p.menuGroup = QStringLiteral("[Dev]"); + p.menuText = QStringLiteral("Open Admin Session"); + p.identifier = QStringLiteral("OpenAdminSession"); - m_baseLayout->addMenuAction(p); - } + p.directFunc = [&](const LtsWidgets::PluginData&) { + LtsSession* adminSession = m_sessionManager->getSession(IDL::PartitionType::Global, 0); + if (!adminSession) + { + // QMessageBox::information(nullptr, QString(), QStringLiteral("no admin session")); + DdsConnectionParams connParams; + connParams.domainId = domainId(); + connParams.partitionId = 0; + connParams.exerciseId = 0; + connParams.partitionType = IDL::PartitionType::Global; + connParams.tcpConnectionUrl = tcpConnectionUrl(); + connParams.qos_file = m_qosFileList; + adminSession = m_sessionManager->createSession( + connParams, true, + false); // no payloads !! TODO: is this a real domainId or a dead var ?? + return; + } + else + adminSession->makeVisible(); + }; - { - LtsWidgets::PluginData p; - p.menuGroup = QStringLiteral("[Dev]"); - p.menuText = QStringLiteral("Slow down RequestHelper"); - p.identifier = QStringLiteral("SlowDownRequestHelper"); + m_baseLayout->addMenuAction(p); + } - p.directFunc = [&](const LtsWidgets::PluginData &) { - LtsUtils::RequestHelper::s_debug = true; - }; + LtsWidgets::PluginData p; + p.menuGroup = QStringLiteral("[Dev]"); + p.menuText = QStringLiteral("Slow down RequestHelper"); + p.identifier = QStringLiteral("SlowDownRequestHelper"); - m_baseLayout->addMenuAction(p); - } + p.directFunc = [&](const LtsWidgets::PluginData&) { LtsUtils::RequestHelper::s_debug = true; }; - { - LtsWidgets::PluginData p; - p.menuGroup = QStringLiteral("[Dev]"); - p.menuText = QStringLiteral("Reset RequestHelper"); - p.identifier = QStringLiteral("ResetRequestHelper"); + m_baseLayout->addMenuAction(p); + } - p.directFunc = [&](const LtsWidgets::PluginData &) { - LtsUtils::RequestHelper::s_debug = false; - }; + LtsWidgets::PluginData p; + p.menuGroup = QStringLiteral("[Dev]"); + p.menuText = QStringLiteral("Reset RequestHelper"); + p.identifier = QStringLiteral("ResetRequestHelper"); - m_baseLayout->addMenuAction(p); - } + p.directFunc = [&](const LtsWidgets::PluginData&) { LtsUtils::RequestHelper::s_debug = false; }; - { - LtsWidgets::PluginData p; - p.menuGroup = QStringLiteral("[Dev]"); - p.menuText = QStringLiteral("fake DoneInitializingSession"); - p.identifier = QStringLiteral("fakeDoneInitializingSession"); + m_baseLayout->addMenuAction(p); + } - p.directFunc = [&](const LtsWidgets::PluginData &) { - m_initDone = true; - emit _signalDoneInitializingSession(); - }; + LtsWidgets::PluginData p; + p.menuGroup = QStringLiteral("[Dev]"); + p.menuText = QStringLiteral("fake DoneInitializingSession"); + p.identifier = QStringLiteral("fakeDoneInitializingSession"); - m_baseLayout->addMenuAction(p); - } - // END DEVELOPER / DEBUG MENU + p.directFunc = [&](const LtsWidgets::PluginData&) { + m_initDone = true; + emit _signalDoneInitializingSession(); + }; + + m_baseLayout->addMenuAction(p); + } + // END DEVELOPER / DEBUG MENU } - bool LtsSession::notifyUnsavedChanges() { - if (m_baseLayout == nullptr) - return true; + if (m_baseLayout == nullptr) + return true; - return m_baseLayout->notifyUnsavedChanges(); + return m_baseLayout->notifyUnsavedChanges(); } - void LtsSession::createBaseLayout() { - //qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - using namespace LtsAppDescriptor; + using namespace LtsAppDescriptor; - TRACE_LOG(m_logger) << LOGFUNCTION << " START, Creating Base Layout for Session " << partitionId(); + TRACE_LOG(m_logger) << LOGFUNCTION << " START, Creating Base Layout for Session " << partitionId(); - Q_ASSERT(m_baseLayout == nullptr); - if (m_baseLayout != nullptr) - { - WARNING_LOG(m_logger) << "Base Layout already exists for Session" << this; - return; // already exists - } - - m_baseLayout = new LtsBaseLayoutWidget; // main widget - - connect(m_baseLayout, &LtsBaseLayoutWidget::signalSuccessfullyPlaced, - this, [this]() - { - DEBUG_LOG(m_logger) << "current APP "<app()); -// qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - if ( this->app() == App::Scripts) + Q_ASSERT(m_baseLayout == nullptr); + if (m_baseLayout != nullptr) { - m_scriptEditorTimer->start(); + WARNING_LOG(m_logger) << "Base Layout already exists for Session" << this; + return; // already exists } - else - { - if (m_needsToBeSuccessfullyPlaced) - { -// qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - emit _signalDoneInitializingSession(); // needs to be emitted here, as if 'm_needsToBeSuccessfullyPlaced' is TRUE, it was not emitted before - } - } - }); - connect(m_baseLayout, &LtsBaseLayoutWidget::destroyed, - this, [this]() - { - m_baseLayout = nullptr; // sec - //qWarning() << "baseLayout deleted"; - }); + m_baseLayout = new LtsBaseLayoutWidget; // main widget - m_baseLayout->hide(); // hide - m_baseLayout->setSessionInfo(domainId(), partitionType(), partitionId(), workspaceId()); // this shd ptr has a different counter .. - m_baseLayout->setWindowIcon(appToIcon(app())); // for the magic corner to have an icon to show for switching to / from secondaries + connect(m_baseLayout, &LtsBaseLayoutWidget::signalSuccessfullyPlaced, this, [this]() { + DEBUG_LOG(m_logger) << "current APP " << appToString(this->app()); + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + if (this->app() == App::Scripts) + { + m_scriptEditorTimer->start(); + } + else + { + if (m_needsToBeSuccessfullyPlaced) + { + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + emit + _signalDoneInitializingSession(); // needs to be emitted here, as if 'm_needsToBeSuccessfullyPlaced' is + // TRUE, it was not emitted before + } + } + }); -// auto *x = new QLabel; -// x->setPixmap(m_baseLayout->windowIcon().pixmap(128, 128)); -// x->show(); + connect(m_baseLayout, &LtsBaseLayoutWidget::destroyed, this, [this]() { + m_baseLayout = nullptr; // sec + // qWarning() << "baseLayout deleted"; + }); + m_baseLayout->hide(); // hide + m_baseLayout->setSessionInfo(domainId(), partitionType(), partitionId(), + workspaceId()); // this shd ptr has a different counter .. + m_baseLayout->setWindowIcon( + appToIcon(app())); // for the magic corner to have an icon to show for switching to / from secondaries - if (app() == App::ScriptEditorEssentialsView || // NOTE: timeline's replay app and snapshot's edit plan are secondaries, too - setSecondaryWidget needs to be called from timeline & snapshot app, too - m_presetBaseLayoutAsSecondaryWidget) - m_baseLayout->setSecondaryWidget(); + // auto *x = new QLabel; + // x->setPixmap(m_baseLayout->windowIcon().pixmap(128, 128)); + // x->show(); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalRetranslateActions, - this, &LtsSession::refetchActions); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalClose, - this, &LtsSession::signalClose); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalLogout, - this, &LtsSession::signalLogout); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalShowOperatorSettings, - this, &LtsSession::slotShowOperatorSettings); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalSwap, - this, &LtsSession::slotSwap); - connect(this, &LtsSession::partitionTimeChanged, - m_baseLayout, &LtsBaseLayoutWidget::setExerciseTime); - connect(m_baseLayout, &LtsBaseLayoutWidget::signalStapleTopicLockHandler, - this, &LtsSession::slotStapleTopicLockHandler, Qt::DirectConnection); + if (app() == App::ScriptEditorEssentialsView || // NOTE: timeline's replay app and snapshot's edit plan are + // secondaries, too - setSecondaryWidget needs to be called from + // timeline & snapshot app, too + m_presetBaseLayoutAsSecondaryWidget) + m_baseLayout->setSecondaryWidget(); - const auto *sessionData = LtsSessionData::LtsSessionData::getInstance(); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalRetranslateActions, this, &LtsSession::refetchActions); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalClose, this, &LtsSession::signalClose); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalLogout, this, &LtsSession::signalLogout); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalShowOperatorSettings, this, + &LtsSession::slotShowOperatorSettings); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalSwap, this, &LtsSession::slotSwap); + connect(this, &LtsSession::partitionTimeChanged, m_baseLayout, &LtsBaseLayoutWidget::setExerciseTime); + connect(m_baseLayout, &LtsBaseLayoutWidget::signalStapleTopicLockHandler, this, + &LtsSession::slotStapleTopicLockHandler, Qt::DirectConnection); - const QString &operatorName = sessionData->getOperatorName(); - bool showTerminalWindow = sessionData->getShowTerminalWindow(); - m_baseLayout->setOperatorName(operatorName, showTerminalWindow); - m_baseLayout->setProfilePicture(sessionData->getProfilePicture()); - m_baseLayout->setAppName(appToString(app())); + const auto* sessionData = LtsSessionData::LtsSessionData::getInstance(); - refetchActions(); + const QString& operatorName = sessionData->getOperatorName(); + bool showTerminalWindow = sessionData->getShowTerminalWindow(); + m_baseLayout->setOperatorName(operatorName, showTerminalWindow); + m_baseLayout->setProfilePicture(sessionData->getProfilePicture()); + m_baseLayout->setAppName(appToString(app())); + + refetchActions(); #ifdef LTS_DEBUG - bool showDeveloperActions = true; + bool showDeveloperActions = true; #else - bool showDeveloperActions = false; + bool showDeveloperActions = false; #endif - if (sessionData->hasDebugFlag(QStringLiteral("DeveloperTools.Active"))) - showDeveloperActions = true; + if (sessionData->hasDebugFlag(QStringLiteral("DeveloperTools.Active"))) + showDeveloperActions = true; - if (showDeveloperActions) - addDeveloperActions(); + if (showDeveloperActions) + addDeveloperActions(); - - for (LtsNotification::LtsNotificationController *ctl : qAsConst(m_notiCtlList)) - { - if (!m_baseLayout->notificationExists(ctl->identifier())) // add if non-existent only - m_baseLayout->addNotification(ctl->createWidget()); // FIXME: crash when no icons? - } - - m_hasBaseLayout = true; // not needed anymore, but for its correctness..... - - m_baseLayout->getMenu()->setVisible(m_menuVisible); - m_baseLayout->initilizationFinished(); - - //QMessageBox::warning(nullptr, QStringLiteral("attach!"), QString()); - - if (!m_foreverInvisible) - { - // build list of irreplacable widgets by the dependency tree of its dependencies and their dependencies' dependencies - QVector irreplacableWidgets {baseLayoutWidget()}; - LtsSession *dependencySession = dependency(); - int runaway = 100; - while (dependencySession && runaway > 0) + for (LtsNotification::LtsNotificationController* ctl : qAsConst(m_notiCtlList)) { - irreplacableWidgets += dependencySession->baseLayoutWidget(); - dependencySession = dependencySession->dependency(); - runaway--; + if (!m_baseLayout->notificationExists(ctl->identifier())) // add if non-existent only + m_baseLayout->addNotification(ctl->createWidget()); // FIXME: crash when no icons? } -// qWarning() << "#2 irreplacableWidgets count" << irreplacableWidgets.count() << "from" << this; + m_hasBaseLayout = true; // not needed anymore, but for its correctness..... -// for (QWidget *w : irreplacableWidgets) -// qWarning() << "irre" << w; + m_baseLayout->getMenu()->setVisible(m_menuVisible); + m_baseLayout->initilizationFinished(); + // QMessageBox::warning(nullptr, QStringLiteral("attach!"), QString()); + if (!m_foreverInvisible) + { + // build list of irreplacable widgets by the dependency tree of its dependencies and their dependencies' + // dependencies + QVector irreplacableWidgets{baseLayoutWidget()}; + LtsSession* dependencySession = dependency(); + int runaway = 100; + while (dependencySession && runaway > 0) + { + irreplacableWidgets += dependencySession->baseLayoutWidget(); + dependencySession = dependencySession->dependency(); + runaway--; + } - LtsMultiMonitor::LtsMultiMonitor *multiMonitor = LtsMultiMonitor::LtsMultiMonitor::getInstance(); + // qWarning() << "#2 irreplacableWidgets count" << irreplacableWidgets.count() << "from" << this; - WARNING_LOG(m_logger) << "Presets: ScreenId: " << m_screenIdPreset << ", screenContainerId: " << m_screenContainerIdPreset; - if (m_screenIdPreset >= 0) - multiMonitor->putScreen(m_baseLayout, m_screenIdPreset, m_screenContainerIdPreset); - else - multiMonitor->selectScreen(m_baseLayout, nullptr, true, false, irreplacableWidgets); + // for (QWidget *w : irreplacableWidgets) + // qWarning() << "irre" << w; - slotMonitorSelected(); - connect(multiMonitor, &LtsMultiMonitor::LtsMultiMonitor::signalSelected, - this, &LtsSession::slotMonitorSelected, Qt::UniqueConnection); + LtsMultiMonitor::LtsMultiMonitor* multiMonitor = LtsMultiMonitor::LtsMultiMonitor::getInstance(); - connect(multiMonitor, &LtsMultiMonitor::LtsMultiMonitor::signalScreenCountChanged, - m_baseLayout, &LtsBaseLayoutWidget::slotScreenCountChanged); + WARNING_LOG(m_logger) << "Presets: ScreenId: " << m_screenIdPreset + << ", screenContainerId: " << m_screenContainerIdPreset; + if (m_screenIdPreset >= 0) + multiMonitor->putScreen(m_baseLayout, m_screenIdPreset, m_screenContainerIdPreset); + else + multiMonitor->selectScreen(m_baseLayout, nullptr, true, false, irreplacableWidgets); - m_baseLayout->slotScreenCountChanged(multiMonitor->screenCount()); - } + slotMonitorSelected(); + connect(multiMonitor, &LtsMultiMonitor::LtsMultiMonitor::signalSelected, this, &LtsSession::slotMonitorSelected, + Qt::UniqueConnection); + connect(multiMonitor, &LtsMultiMonitor::LtsMultiMonitor::signalScreenCountChanged, m_baseLayout, + &LtsBaseLayoutWidget::slotScreenCountChanged); - if (!sessionData->isTablet()) - return; // done here if not a tablet + m_baseLayout->slotScreenCountChanged(multiMonitor->screenCount()); + } + if (!sessionData->isTablet()) + return; // done here if not a tablet - LtsNotification::LtsNotification *noti = createNotification(QStringLiteral("TabletWindowSwitcher")); + LtsNotification::LtsNotification* noti = createNotification(QStringLiteral("TabletWindowSwitcher")); - noti->setIcon(QIcon(QStringLiteral("icon:switch_display.svg"))); - noti->setAction([this]() - { - emit taskSwitch(this /* tell it that we are the caller, don't hide US! */); - }); + noti->setIcon(QIcon(QStringLiteral("icon:switch_display.svg"))); + noti->setAction([this]() { emit taskSwitch(this /* tell it that we are the caller, don't hide US! */); }); - - emit hideAllOtherBLWs(this); + emit hideAllOtherBLWs(this); } - void LtsSession::slotMonitorSelected() { - auto mmm = LtsMultiMonitor::LtsMultiMonitor::getInstance(); - LtsMultiMonitor::LtsScreenBase *screen = mmm->widgetsScreen(m_baseLayout); + auto mmm = LtsMultiMonitor::LtsMultiMonitor::getInstance(); + LtsMultiMonitor::LtsScreenBase* screen = mmm->widgetsScreen(m_baseLayout); - if (!screen) - return; + if (!screen) + return; - int newScreenContainerId; - try - { - newScreenContainerId = screen->containerIdOfWidget(m_baseLayout); - } - catch (...) - { - WARNING_LOG(m_logger) << "cannot find container for base layout"; - return; - } + int newScreenContainerId; + try + { + newScreenContainerId = screen->containerIdOfWidget(m_baseLayout); + } + catch (...) + { + WARNING_LOG(m_logger) << "cannot find container for base layout"; + return; + } - const int newScreenId = screen->screenId(); - if (m_screenId != newScreenId) - { - m_screenId = newScreenId; - m_screenContainerId = newScreenContainerId; - emit signalScreenIdChanged(m_screenId, m_screenContainerId, screen->screenType()); - } + const int newScreenId = screen->screenId(); + if (m_screenId != newScreenId) + { + m_screenId = newScreenId; + m_screenContainerId = newScreenContainerId; + emit signalScreenIdChanged(m_screenId, m_screenContainerId, screen->screenType()); + } } void LtsSession::delayScriptEditorStart() { - DEBUG_LOG(m_logger)<<"LtsSession::delayScriptEditorStart "; - if (m_needsToBeSuccessfullyPlaced) - { - // qWarning() << "delayScriptEditorStart mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + DEBUG_LOG(m_logger) << "LtsSession::delayScriptEditorStart "; + if (m_needsToBeSuccessfullyPlaced) + { + // qWarning() << "delayScriptEditorStart mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - emit _signalDoneInitializingSession(); // needs to be emitted here, as if 'm_needsToBeSuccessfullyPlaced' is TRUE, it was not emitted before - } + emit _signalDoneInitializingSession(); // needs to be emitted here, as if 'm_needsToBeSuccessfullyPlaced' is + // TRUE, it was not emitted before + } } -bool LtsSession::isChildOfSession(QWidget *child) +bool LtsSession::isChildOfSession(QWidget* child) { - if (!child) - { - return false; - } - return baseLayout()->isAncestorOf(child); + if (!child) + { + return false; + } + return baseLayout()->isAncestorOf(child); } void LtsSession::doneInitializingSession() { - LtsGlobalWaitDialog::getInstance()->done(); + LtsGlobalWaitDialog::getInstance()->done(); - // qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - if (m_markedForDeletion) - { - emit signalInitializationAborted(); // to call done() on global wait dialog - emit signalClose(); // session manager removes us from his list and then deletes us - return; - } + if (m_markedForDeletion) + { + emit signalInitializationAborted(); // to call done() on global wait dialog + emit signalClose(); // session manager removes us from his list and then deletes us + return; + } - if (!m_sessionManager->isHeadless()) // disallow base layout creation if app is headless - { - int sessionCount = m_sessionManager->sessionCount(); + if (!m_sessionManager->isHeadless()) // disallow base layout creation if app is headless + { + int sessionCount = m_sessionManager->sessionCount(); - if (!m_hidden && (m_hasBaseLayout || sessionCount < 1)) // show base layout if m_hasBaseLayout is true OR IF there is only this session (e.g. Payloads have not started any sessions) - makeVisible(); + if (!m_hidden && + (m_hasBaseLayout || sessionCount < 1)) // show base layout if m_hasBaseLayout is true OR IF there is only + // this session (e.g. Payloads have not started any sessions) + makeVisible(); -// if (!m_hasBaseLayout) // delete session if it's useless & empty -// { -// emit signalClose(); -// return; -// } - } + // if (!m_hasBaseLayout) // delete session if it's useless & empty + // { + // emit signalClose(); + // return; + // } + } -// qWarning() << "emit signalDoneInitializingSession();"; + // qWarning() << "emit signalDoneInitializingSession();"; - if (!createTopicClient(m_coreFtc)) - WARNING_LOG(m_logger) << "could not create core ftc - no tlh"; - m_coreFtc->enableAll(); + if (!createTopicClient(m_coreFtc)) + WARNING_LOG(m_logger) << "could not create core ftc - no tlh"; + m_coreFtc->enableAll(); - if (!getForeignGuiInterface(m_ohvIfc)) - WARNING_LOG(m_logger) << "no ovh ifc, no Help-Button !"; + if (!getForeignGuiInterface(m_ohvIfc)) + WARNING_LOG(m_logger) << "no ovh ifc, no Help-Button !"; - INFO_LOG(m_logger) << "emit signalDoneInitializingSession, session=" << this; -// qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); -// qWarning() << !m_needsToBeSuccessfullyPlaced << m_sessionManager->isHeadless() << !m_hasBaseLayout; - if (!m_needsToBeSuccessfullyPlaced || m_sessionManager->isHeadless() || !m_hasBaseLayout) // can't be placed if without something to show .. :) - { - // qWarning() << "mep" << QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); - // qWarning() << "!! headless !"; - emit _signalDoneInitializingSession(); - } + INFO_LOG(m_logger) << "emit signalDoneInitializingSession, session=" << this; + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + // qWarning() << !m_needsToBeSuccessfullyPlaced << m_sessionManager->isHeadless() << !m_hasBaseLayout; + if (!m_needsToBeSuccessfullyPlaced || m_sessionManager->isHeadless() || + !m_hasBaseLayout) // can't be placed if without something to show .. :) + { + // qWarning() << "mep" << + // QStringLiteral("%1:%2").arg(QString::fromUtf8(__FILE__).split(QStringLiteral("/")).last()).arg(__LINE__); + // qWarning() << "!! headless !"; + emit _signalDoneInitializingSession(); + } - //qWarning() << "not headless !"; + // qWarning() << "not headless !"; } - -void LtsSession::slotShowOnlineHelp(const QString &fileName) +void LtsSession::slotShowOnlineHelp(const QString& fileName) { - if (m_ohvIfc == nullptr) - { - LtsWidgets::LtsMessageDialog::showMessage(baseLayout() /* can be 0ptr */, tr("Online Help not available.")); - return; - } + if (m_ohvIfc == nullptr) + { + LtsWidgets::LtsMessageDialog::showMessage(baseLayout() /* can be 0ptr */, tr("Online Help not available.")); + return; + } - m_ohvIfc->showHelp(fileName); + m_ohvIfc->showHelp(fileName); } - void LtsSession::slotShowOperatorSettings() { - const QMap &mapButtons = m_baseLayout->mapButtons(); + const QMap& mapButtons = m_baseLayout->mapButtons(); - for (auto i = mapButtons.constBegin(); i != mapButtons.constEnd(); ++i) - { - const PluginData &pd = *i; - - if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) + for (auto i = mapButtons.constBegin(); i != mapButtons.constEnd(); ++i) { - LtsDialog *showOperatorSettingsDlg = pd.createWidgetFunc(nullptr); + const PluginData& pd = *i; - if (showOperatorSettingsDlg != nullptr) - { - addWidget(showOperatorSettingsDlg, pd.menuGroup, pd.identifier, pd.layoutArea, pd.closable); - //qWarning() << "showing operator settings"; - } - else - WARNING_LOG(m_logger) << "could not create operator settings dialog from action"; + if (pd.identifier == QStringLiteral("_OpmShowOperatorSettings")) + { + LtsDialog* showOperatorSettingsDlg = pd.createWidgetFunc(nullptr); - return; + if (showOperatorSettingsDlg != nullptr) + { + addWidget(showOperatorSettingsDlg, pd.menuGroup, pd.identifier, pd.layoutArea, pd.closable); + // qWarning() << "showing operator settings"; + } + else + WARNING_LOG(m_logger) << "could not create operator settings dialog from action"; + + return; + } } - } - WARNING_LOG(m_logger) << "action for showing operator settings not found !!"; + WARNING_LOG(m_logger) << "action for showing operator settings not found !!"; } - void LtsSession::slotStartPluginInit() { - m_initializeThesePlugins = m_guiPluginInterfaces; // copy - slotPluginInitDone(); + m_initializeThesePlugins = m_guiPluginInterfaces; // copy + slotPluginInitDone(); } - void LtsSession::slotPluginInitDone() // NEVER call this directly, queue a signal to this slot ! { - //qWarning() << "LtsSession::slotPluginInitDone: sender" << sender(); + // qWarning() << "LtsSession::slotPluginInitDone: sender" << sender(); - if (m_pluginInitDone) - return; + if (m_pluginInitDone) + return; - if (m_slotPluginInitDoneMutex) - { - //qWarning() << "<< never call slotPluginInitDone directly or after all initialization was done! bad sender was" << sender(); - //abort(); - return; - } - - m_slotPluginInitDoneMutex = true; // lock - - GuiPluginBase::Interface *theSender = dynamic_cast(sender()); - - if (theSender != m_currentInitIfc) - { - WARNING_LOG(m_logger) << this << " called slotPluginInitDone from plugin which was not currently active for initialization - ignoring"; -#ifdef LTS_DEBUG - WARNING_LOG(m_logger) << "current init ifc: " << m_currentInitIfc << ", sender: " << sender(); -#endif - m_slotPluginInitDoneMutex = false; // unlock - return; - } - - //qWarning() << "currently initializing ifc"< ifc = i.value(); - - if (ifc->availableInPartition(partitionType())) - { - m_currentInitIfc = ifc.get(); - //qWarning() << "set m_currentInitIfc to" << m_currentInitIfc; - - //qWarning() << "initializing" << i.key() << (void *)ifc.get(); - - ifc->init(); - if (!ifc->m_hasInit) // workaround for ifcs without init method (which needs quitting by signals) + if (m_slotPluginInitDoneMutex) { - //qWarning() << "resetting m_currentInitIfc to nullptr"; - m_currentInitIfc = nullptr; - QTimer::singleShot(0, this, &LtsSession::slotPluginInitDone); + // qWarning() << "<< never call slotPluginInitDone directly or after all initialization was done! bad sender + // was" << sender(); abort(); + return; } - } - else // do not initialize plugins that are not available in partition x - { + + m_slotPluginInitDoneMutex = true; // lock + + GuiPluginBase::Interface* theSender = dynamic_cast(sender()); + + if (theSender != m_currentInitIfc) + { + WARNING_LOG(m_logger) + << this + << " called slotPluginInitDone from plugin which was not currently active for initialization - ignoring"; +#ifdef LTS_DEBUG + WARNING_LOG(m_logger) << "current init ifc: " << m_currentInitIfc << ", sender: " << sender(); +#endif + m_slotPluginInitDoneMutex = false; // unlock + return; + } + + // qWarning() << "currently initializing ifc"< ifc = i.value(); + + if (ifc->availableInPartition(partitionType())) + { + m_currentInitIfc = ifc.get(); + // qWarning() << "set m_currentInitIfc to" << m_currentInitIfc; + + // qWarning() << "initializing" << i.key() << (void *)ifc.get(); + + ifc->init(); + if (!ifc->m_hasInit) // workaround for ifcs without init method (which needs quitting by signals) + { + // qWarning() << "resetting m_currentInitIfc to nullptr"; + m_currentInitIfc = nullptr; + QTimer::singleShot(0, this, &LtsSession::slotPluginInitDone); + } + } + else // do not initialize plugins that are not available in partition x + { + m_currentInitIfc = nullptr; + QTimer::singleShot(0, this, &LtsSession::slotPluginInitDone); + } + + m_initializeThesePlugins.erase(i); + + m_slotPluginInitDoneMutex = false; // unlock } - void LtsSession::slotExecuteNextPayload() { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(); // show wait dialog again + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(); // show wait dialog again - /* there is currently a problem when executing a secondary event loop, - * which leads to resending already sent signals, as they might not be - * marked as executed by Qt itself. So this is a workaround.. */ -// if (m_ignoreSignalInLoop) -// return; -// m_ignoreSignalInLoop = true; + /* there is currently a problem when executing a secondary event loop, + * which leads to resending already sent signals, as they might not be + * marked as executed by Qt itself. So this is a workaround.. */ + // if (m_ignoreSignalInLoop) + // return; + // m_ignoreSignalInLoop = true; - // execute in order - auto it1 = m_payloadPriorityMap.begin(); // largest key (see qt doc) + // execute in order + auto it1 = m_payloadPriorityMap.begin(); // largest key (see qt doc) - if (it1 != m_payloadPriorityMap.end()) - { - std::shared_ptr ifc = (*it1); - m_payloadPriorityMap.erase(it1); // delete first, as executePayload can be stuck here when the connection is not queued ! - - DEBUG_LOG(m_logger) << "Executing priorized Payload in Partition " << partitionId() << ", Type " << partitionType(); - - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); // don't interrupt payload uis with the wait dialog - - - if (m_blub) + if (it1 != m_payloadPriorityMap.end()) { - m_blub->stop(); - m_blub->deleteLater(); - // qWarning() << "killing blub"; + std::shared_ptr ifc = (*it1); + m_payloadPriorityMap.erase( + it1); // delete first, as executePayload can be stuck here when the connection is not queued ! + + DEBUG_LOG(m_logger) << "Executing priorized Payload in Partition " << partitionId() << ", Type " + << partitionType(); + + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); // don't interrupt payload uis with the wait dialog + + if (m_blub) + { + m_blub->stop(); + m_blub->deleteLater(); + // qWarning() << "killing blub"; + } + m_blub = new QTimer(this); + m_blub2 = 0; + QString name(QString::fromUtf8(typeid(ifc.get()).name())); + connect(m_blub, &QObject::destroyed, this, [name]() { + // qWarning() << "prio-payload for" << name << "DESTROYED!!!!"; + }); + connect(m_blub, &QTimer::timeout, this, [this, name]() { + m_blub2++; + // qWarning() << "prio-payload for" << name << "running since" << m_blub2 << "seconds"; + }); + m_blub->start(1000); + + ifc->executePayload(m_mainBackground); } - m_blub = new QTimer(this); - m_blub2 = 0; - QString name(QString::fromUtf8(typeid(ifc.get()).name())); - connect(m_blub, &QObject::destroyed, - this, [name]() + else // no priority payloads left, check for unpriorized payloads { - // qWarning() << "prio-payload for" << name << "DESTROYED!!!!"; - }); - connect(m_blub, &QTimer::timeout, - this, [this, name]() - { - m_blub2++; - // qWarning() << "prio-payload for" << name << "running since" << m_blub2 << "seconds"; - }); - m_blub->start(1000); + auto it2 = m_payloadList.begin(); + if (it2 != m_payloadList.end()) + { + std::shared_ptr ifc = (*it2); + m_payloadList.erase( + it2); // delete first, as executePayload can be stuck here when the connection is not queued ! - ifc->executePayload(m_mainBackground); - } - else // no priority payloads left, check for unpriorized payloads - { - auto it2 = m_payloadList.begin(); + DEBUG_LOG(m_logger) << "Executing unpriorized Payload in Partition " << partitionId() << ", Type " + << partitionType(); - if (it2 != m_payloadList.end()) - { - std::shared_ptr ifc = (*it2); - m_payloadList.erase(it2); // delete first, as executePayload can be stuck here when the connection is not queued ! + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); // don't interrupt payload uis with the wait dialog - DEBUG_LOG(m_logger) << "Executing unpriorized Payload in Partition " << partitionId() << ", Type " << partitionType(); + if (m_blub) + { + m_blub->stop(); + m_blub->deleteLater(); + // qWarning() << "killing blub"; + } + m_blub = new QTimer(this); + m_blub2 = 0; + QString name(QString::fromUtf8(typeid(ifc.get()).name())); + connect(m_blub, &QObject::destroyed, this, [name]() { + // qWarning() << "prio-payload for" << name << "DESTROYED!!!!"; + }); + connect(m_blub, &QTimer::timeout, this, [this, name]() { + m_blub2++; + // qWarning() << "prio-payload for" << name << "running since" << m_blub2 << "seconds"; + }); + m_blub->start(1000); - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); // don't interrupt payload uis with the wait dialog + ifc->executePayload(m_mainBackground); + } + else // no payloads left, delete background widget(s) and say that all plugins have been loaded + { + Q_ASSERT(m_payloadsDone == false); + m_payloadsDone = true; + m_mainBackground = nullptr; // as it was parented to m_hiddenWidget - if (m_blub) - { - m_blub->stop(); - m_blub->deleteLater(); - // qWarning() << "killing blub"; - } - m_blub = new QTimer(this); - m_blub2 = 0; - QString name(QString::fromUtf8(typeid(ifc.get()).name())); - connect(m_blub, &QObject::destroyed, - this, [name]() - { - // qWarning() << "prio-payload for" << name << "DESTROYED!!!!"; - }); - connect(m_blub, &QTimer::timeout, - this, [this, name]() - { - m_blub2++; - // qWarning() << "prio-payload for" << name << "running since" << m_blub2 << "seconds"; - }); - m_blub->start(1000); + if (m_blub) + { + m_blub->stop(); + m_blub->deleteLater(); + // qWarning() << "killing blub - no payloads left"; + m_blub = nullptr; + } + // qWarning() << "no payloads left"; - ifc->executePayload(m_mainBackground); + doneInitializingSession(); + } } - else // no payloads left, delete background widget(s) and say that all plugins have been loaded - { - Q_ASSERT(m_payloadsDone == false); - m_payloadsDone = true; - m_mainBackground = nullptr; // as it was parented to m_hiddenWidget - - if (m_blub) - { - m_blub->stop(); - m_blub->deleteLater(); - // qWarning() << "killing blub - no payloads left"; - m_blub = nullptr; - } - - // qWarning() << "no payloads left"; - - doneInitializingSession(); - } - } - - //m_ignoreSignalInLoop = false; // executing payload is done, clear the ignore-flag + // m_ignoreSignalInLoop = false; // executing payload is done, clear the ignore-flag } - void LtsSession::executePayloads() { - // look for gui plugins (needed to get execution priority and run payloads) - if (!m_payloadPriorityMap.isEmpty() || !m_payloadList.isEmpty()) - { - //DEBUG_LOG(m_logger) << m_payloadPriorityMap.count() << " priorized payload(s), " << m_payloadList.count() << " unpriorized payload(s) - " << m_payloadPriorityMap.count() + m_payloadList.count() << " total."; - - - - //QMetaObject::invokeMethod(this, &LtsSession::slotExecuteNextPayload); - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); // ugly workaround: as the next method says wait even if we call it the first time (LtsSession c_tor called wait already) - - slotExecuteNextPayload(); - } - else - { - // qWarning() << "this session has no payloads assigned!!"; - DEBUG_LOG(m_logger) << "no payloads"; - - if (partitionType() == IDL::PartitionType::Global) + // look for gui plugins (needed to get execution priority and run payloads) + if (!m_payloadPriorityMap.isEmpty() || !m_payloadList.isEmpty()) { - m_hasBaseLayout = true; // admin session has no payloads, so show base layout, otherwise there is nothing to show.. + // DEBUG_LOG(m_logger) << m_payloadPriorityMap.count() << " priorized payload(s), " << m_payloadList.count() << + // " unpriorized payload(s) - " << m_payloadPriorityMap.count() + m_payloadList.count() << " total."; + + // QMetaObject::invokeMethod(this, &LtsSession::slotExecuteNextPayload); + LtsWidgets::LtsGlobalWaitDialog::getInstance() + ->done(); // ugly workaround: as the next method says wait even if we call it the first time (LtsSession + // c_tor called wait already) + + slotExecuteNextPayload(); } + else + { + // qWarning() << "this session has no payloads assigned!!"; + DEBUG_LOG(m_logger) << "no payloads"; - doneInitializingSession(); - } + if (partitionType() == IDL::PartitionType::Global) + { + m_hasBaseLayout = + true; // admin session has no payloads, so show base layout, otherwise there is nothing to show.. + } + + doneInitializingSession(); + } } - void LtsSession::clearDataPluginInterfaces() { - QMap> weakDataPluginInterfaces; - for (auto i = m_dataPluginInterfaces.cbegin(); i != m_dataPluginInterfaces.cend(); ++i) - { - //i.value()->clearInterfaces(); - weakDataPluginInterfaces.insert(i.key(), i.value()); - } + QMap> weakDataPluginInterfaces; + for (auto i = m_dataPluginInterfaces.cbegin(); i != m_dataPluginInterfaces.cend(); ++i) + { + // i.value()->clearInterfaces(); + weakDataPluginInterfaces.insert(i.key(), i.value()); + } - DEBUG_LOG(m_logger) << "Clearing data plugin interfaces for " << partitionType() << " - " << this; - m_dataPluginInterfaces.clear(); + DEBUG_LOG(m_logger) << "Clearing data plugin interfaces for " << partitionType() << " - " << this; + m_dataPluginInterfaces.clear(); #ifdef LTS_DEBUG - // in global plugins somehow are not unloaded - if (partitionType() != IDL::PartitionType::Global) - { - for (auto i = weakDataPluginInterfaces.cbegin(); i != weakDataPluginInterfaces.cend(); ++i) + // in global plugins somehow are not unloaded + if (partitionType() != IDL::PartitionType::Global) { - std::shared_ptr sp = i.value().lock(); - if (!sp) - continue; - WARNING_LOG(m_logger) << "still referenced Data Plugin '" << i.key() - << "' in partition type " << partitionType() - << " (use_count=" << sp.use_count() << ")" - << " - application may crash on exit! " << this; + for (auto i = weakDataPluginInterfaces.cbegin(); i != weakDataPluginInterfaces.cend(); ++i) + { + std::shared_ptr sp = i.value().lock(); + if (!sp) + continue; + WARNING_LOG(m_logger) << "still referenced Data Plugin '" << i.key() << "' in partition type " + << partitionType() << " (use_count=" << sp.use_count() << ")" + << " - application may crash on exit! " << this; + } } - } #endif } - void LtsSession::clearGuiPluginInterfaces() { - bool bInClearPluginInterfaces = true; - auto cbCheckEventLoop = [this, &bInClearPluginInterfaces]() - { - if (bInClearPluginInterfaces) + bool bInClearPluginInterfaces = true; + auto cbCheckEventLoop = [this, &bInClearPluginInterfaces]() { + if (bInClearPluginInterfaces) + { + ERROR_LOG(m_logger) << "QEventLoop was called within clearGuiPluginInterfaces which is not allowed!"; + Q_ASSERT(false); + } + }; + QTimer::singleShot(0, this, cbCheckEventLoop); + m_ohvIfc = nullptr; + QMap> weakGuiPluginInterfaces; + for (auto i = m_guiPluginInterfaces.cbegin(); i != m_guiPluginInterfaces.cend(); ++i) { - ERROR_LOG(m_logger) << "QEventLoop was called within clearGuiPluginInterfaces which is not allowed!"; - Q_ASSERT(false); + i.value()->clearInterfaces(); + weakGuiPluginInterfaces.insert(i.key(), i.value()); } - }; - QTimer::singleShot(0, this, cbCheckEventLoop); - m_ohvIfc = nullptr; - QMap> weakGuiPluginInterfaces; - for (auto i = m_guiPluginInterfaces.cbegin(); i != m_guiPluginInterfaces.cend(); ++i) - { - i.value()->clearInterfaces(); - weakGuiPluginInterfaces.insert(i.key(), i.value()); - } - bInClearPluginInterfaces = false; + bInClearPluginInterfaces = false; - DEBUG_LOG(m_logger) << "Clearing gui plugin interfaces for " << partitionType() << " - " << this; - m_guiPluginInterfaces.clear(); + DEBUG_LOG(m_logger) << "Clearing gui plugin interfaces for " << partitionType() << " - " << this; + m_guiPluginInterfaces.clear(); #ifdef LTS_DEBUG - // in global plugins somehow are not unloaded - if (partitionType() != IDL::PartitionType::Global) - { - for (auto i = weakGuiPluginInterfaces.cbegin(); i != weakGuiPluginInterfaces.cend(); ++i) + // in global plugins somehow are not unloaded + if (partitionType() != IDL::PartitionType::Global) { - std::shared_ptr sp = i.value().lock(); - if (!sp) - continue; - WARNING_LOG(m_logger) << "still referenced Gui Plugin '" << i.key() - << "'in partition type " << partitionType() - << " (use_count=" << sp.use_count() << ")" - << " Gui Plugin '" << i.key() << "'" - << " - application may crash on exit! " << this; + for (auto i = weakGuiPluginInterfaces.cbegin(); i != weakGuiPluginInterfaces.cend(); ++i) + { + std::shared_ptr sp = i.value().lock(); + if (!sp) + continue; + WARNING_LOG(m_logger) << "still referenced Gui Plugin '" << i.key() << "'in partition type " + << partitionType() << " (use_count=" << sp.use_count() << ")" + << " Gui Plugin '" << i.key() << "'" + << " - application may crash on exit! " << this; + } } - } #endif } -LtsSessionManager *LtsSession::getSessionManager() +LtsSessionManager* LtsSession::getSessionManager() { - return m_sessionManager; + return m_sessionManager; } } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.h old mode 100755 new mode 100644 index ac268e8a6..ca8aff689 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session.h @@ -15,17 +15,13 @@ #include #include -#include // for connections - -#include -#include +#include #include +#include #include #include - - -#include - +#include // for connections +#include namespace LtsWidgets { @@ -35,285 +31,390 @@ class LtsBaseLayoutWidget; struct ExerciseData; class LtsDialog; class LtsDragIcon; -} +} // namespace LtsWidgets + namespace LtsNotification { class LtsNotification; class LtsNotificationController; -} +} // namespace LtsNotification + namespace LtsPluginManager { struct PluginInstance; struct AppPluginInstance; -} +} // namespace LtsPluginManager + namespace DeveloperTools { class DevDialog; class AppWidget; -} +} // namespace DeveloperTools + namespace Core { namespace Interface { class Ftc; } -} +} // namespace Core + namespace OnlineHelp { class ForeignOnlineHelpViewerGuiInterface; } - - namespace LtsSession { class LTSSESSION_EXPORT LtsSession : public LtsSessionDataDds { - Q_OBJECT -public: - static bool s_valgrind; - static int s_nextSessionId; + Q_OBJECT + public: + static bool s_valgrind; + static int s_nextSessionId; - enum class PluginInstanceStatus - { - UNKNOWN = 0, - LOADED, - FAILED, // e.g. fetchInterfaces gone wrong - }; + enum class PluginInstanceStatus { + UNKNOWN = 0, + LOADED, + FAILED, // e.g. fetchInterfaces gone wrong + }; - static QString appToString(LtsAppDescriptor::App app); - static QString appIconFilename(LtsAppDescriptor::App app); - static QIcon appToIcon(LtsAppDescriptor::App app); + static QString appToString(LtsAppDescriptor::App app); + static QString appIconFilename(LtsAppDescriptor::App app); + static QIcon appToIcon(LtsAppDescriptor::App app); - explicit LtsSession(LtsSessionManager *sessionManager); - ~LtsSession(); + explicit LtsSession(LtsSessionManager* sessionManager); + ~LtsSession(); - QString toString() const; + QString toString() const; - LtsSessionManager *getSessionManager(); - bool init(const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList, bool hidden); - bool init(const dds::domain::DomainParticipant &dp, - const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList); - void makeVisible(); - void setPayloadsEnabled() { m_payloads = true; } // cannot be reverted - void aboutToClose(); - bool isInitializationDone() const { return m_initDone; } - void presetBaseLayoutAsSecondaryWidget() { m_presetBaseLayoutAsSecondaryWidget = true; } + LtsSessionManager* getSessionManager(); + bool init(const DdsConnectionParams& connParams, const QVector& dataPluginList, + const QVector& guiPluginList, bool hidden); + bool init(const dds::domain::DomainParticipant& dp, const DdsConnectionParams& connParams, + const QVector& dataPluginList, + const QVector& guiPluginList); + void makeVisible(); - /** - * @brief addAction - IMPORTANT: Actions have to be translated on retranslate by adding the same action (with same identifier) - * but with translated text & menu group! This replaces the text & menu group only. The pointer to the action stays the same. - * @param plData - * @param isFirstRun - * @return - */ - LtsWidgets::LtsDragIcon *addAction(const LtsWidgets::PluginData &plData, bool isFirstRun = false); - void setMenuVisible(bool visible = true); - bool removeMenuAction(LtsWidgets::LtsDragIcon *icon); - int screenId() const; - int screenContainerId() const; - int screenTypeId() const; - LtsAppDescriptor::App app() const; - void setScreenIdPreset(int screenId) { m_screenIdPreset = screenId; } - void setScreenContainerIdPreset(int screenPart) { m_screenContainerIdPreset = screenPart; } - bool isForeverInvisible() const { return m_foreverInvisible; } + void setPayloadsEnabled() + { + m_payloads = true; + } // cannot be reverted - LtsNotification::LtsNotification *createNotification(const QString &identifier); + void aboutToClose(); + + bool isInitializationDone() const + { + return m_initDone; + } + + void presetBaseLayoutAsSecondaryWidget() + { + m_presetBaseLayoutAsSecondaryWidget = true; + } - /** - * @brief setExerciseData is called by the ExerciseManagement plugin and sets the human reabale name of the exercise and puts the text into all base layouts of this session - * @param exerciseData the human reable exercise name of the current exercise - */ - void setExerciseData(const LtsWidgets::ExerciseData &exerciseData); - const LtsWidgets::ExerciseData *exerciseData() const; - void setProfilePicture(const QPixmap &pixmap); - void setBaseLayoutVisible() { m_hasBaseLayout = true; } // cannot be reverted after base layout was created (creation begins after all payloads have been executed OR if makeVisible was called)! - bool isVisible() const { return (m_baseLayout != nullptr); } - const QString &name() const { return m_name; } - void setName(const QString &name) { m_name = name; } /** - * @brief isChildOfSession can be used to check if a fiven QWidget is part of the current Session's application - * - * @param child widget to check against. - * @return true if widget is child of session baselayout - */ - bool isChildOfSession(QWidget* child); - LtsWidgets::LtsBaseLayoutWidget* baseLayout() { return m_baseLayout; } - QWidget *baseLayoutWidget(); // prevents some classes to include LtsBaseLayoutWidget.h just to specify the blw as a parent widget - void setMarkForDeletion() { m_markedForDeletion = true; } // session not needed anymore after payloads? then mark for deletion and after payloads, this session will be deleted(Later) - void doneInitializingSession(); // TODO: private - bool notifyUnsavedChanges(); // true if NO unsaved changes - const QVector &bgWidgets() const { return m_bgWidgets; } + * @brief addAction - IMPORTANT: Actions have to be translated on retranslate by adding the same action (with same + * identifier) but with translated text & menu group! This replaces the text & menu group only. The pointer to the + * action stays the same. + * @param plData + * @param isFirstRun + * @return + */ + LtsWidgets::LtsDragIcon* addAction(const LtsWidgets::PluginData& plData, bool isFirstRun = false); + void setMenuVisible(bool visible = true); + bool removeMenuAction(LtsWidgets::LtsDragIcon* icon); + int screenId() const; + int screenContainerId() const; + int screenTypeId() const; + LtsAppDescriptor::App app() const; - // checks if a widget with the given data already exists - bool widgetExists(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area) const; - /** - * @brief addWidget - * keep identifier empty to prevent checking for existing tabs - * @return (see addWidget in LtsBaseLayoutWidget) - */ - bool addWidget(LtsWidgets::LtsDialog *widget, - const QString &menuGroup, - const QString &identifier, - LtsWidgets::LayoutArea area = LtsWidgets::LayoutArea::eUnknown, - bool setClosable = true); + void setScreenIdPreset(int screenId) + { + m_screenIdPreset = screenId; + } - LtsWidgets::LtsDialog *getWidget(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area); - bool focusTab(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area); + void setScreenContainerIdPreset(int screenPart) + { + m_screenContainerIdPreset = screenPart; + } - /** WARNING: do not save the returned value, as baseLayouts can die (which kills LtsTabWidget also), so reuse this method instead of saving the pointer to the LtsTabWidget - * @brief locateWidget locates the given widget 'widget' and returning the TabWidget on which it is on - widgets can be available in one of many LayoutAreas (TabWidgets) of many LtsBaseLayoutWidgets - * @param widgetToLocate the widget to look for in the given layoutArea which is located in one of many LtsBaseLayoutWidget - * @param area the area the widget is located - * @return LtsTabWidget on which the widget is located - */ - LtsWidgets::LtsTabWidget *locateWidget(QWidget *widgetToLocate, LtsWidgets::LayoutArea area); + bool isForeverInvisible() const + { + return m_foreverInvisible; + } + LtsNotification::LtsNotification* createNotification(const QString& identifier); - /** - * @brief enable/disable baseLayout menu - * @param on if true enable otherwise disable - */ - void enableBaseLayoutMenu(bool on = true); + /** + * @brief setExerciseData is called by the ExerciseManagement plugin and sets the human reabale name of the exercise + * and puts the text into all base layouts of this session + * @param exerciseData the human reable exercise name of the current exercise + */ + void setExerciseData(const LtsWidgets::ExerciseData& exerciseData); + const LtsWidgets::ExerciseData* exerciseData() const; + void setProfilePicture(const QPixmap& pixmap); - /** - * @brief enable/disable LayoutArea - * @param area the area to enable/disable - * @param on if true enable otherwise disable - */ - void enableBaseLayoutArea(LtsWidgets::LayoutArea area, bool on = true); + void setBaseLayoutVisible() + { + m_hasBaseLayout = true; + } // cannot be reverted after base layout was created (creation begins after all payloads have been executed OR if + // makeVisible was called)! - /** - * @brief Return the workstation ip for this workstation (== full ipv4 adress) - workstation id comes later from Asm - */ - static int workstationIp(); // really in LtsSession? - /** - * @brief Return the workstation name - */ - static QString workstationName(); // really in LtsSession? + bool isVisible() const + { + return (m_baseLayout != nullptr); + } - /** - * @brief missingRightActions Do not use. - * @return - */ - /*const*/ QVector &missingRightActions() /*const*/ { return m_missingRightActions; } + const QString& name() const + { + return m_name; + } - void setSavegame(const QJsonObject &sg) { m_savegame = sg; } - const QJsonObject &getSavegame() const { return m_savegame; } + void setName(const QString& name) + { + m_name = name; + } - void setHidden() { m_hidden = true; } + /** + * @brief isChildOfSession can be used to check if a fiven QWidget is part of the current Session's application + * + * @param child widget to check against. + * @return true if widget is child of session baselayout + */ + bool isChildOfSession(QWidget* child); - const QString workspaceId() const; - void setWorkspaceId(const QString &newWorkspaceId); + LtsWidgets::LtsBaseLayoutWidget* baseLayout() + { + return m_baseLayout; + } - LtsWidgets::ExcState exerciseState() const; + QWidget* baseLayoutWidget(); // prevents some classes to include LtsBaseLayoutWidget.h just to specify the blw as a + // parent widget - void setLoadedFromSavegame() { m_loadedFromSavegame = true; } - bool isLoadedFromSavegame() const { return m_loadedFromSavegame; } - void addDeveloperActions(); - void refetchActions(); // Do not use. - void setDependency(LtsSession *session); - bool hasDependency(LtsSession *session) { return (m_dependency.data() == session); } - LtsSession *dependency() const { return m_dependency; } + void setMarkForDeletion() + { + m_markedForDeletion = true; + } // session not needed anymore after payloads? then mark for deletion and after payloads, this session will be + // deleted(Later) - // bogus. - void setNeedsToBeSuccessfullyPlaced(bool needed = true) { m_needsToBeSuccessfullyPlaced = needed; } // works even after session creation as 'slotStartPluginInit', which finalizes the session (creates blw, etc.) is called async! + void doneInitializingSession(); // TODO: private + bool notifyUnsavedChanges(); // true if NO unsaved changes - int id() const { return m_id; } + const QVector& bgWidgets() const + { + return m_bgWidgets; + } -public slots: - void slotExecuteNextPayload(); // NEVER call this directly, queue a signal to this slot ! - void slotPluginInitDone(); // NEVER call this directly, queue a signal to this slot ! - void slotShowOnlineHelp(const QString &fileName); - //void takeOverBdv(); + // checks if a widget with the given data already exists + bool widgetExists(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area) const; + /** + * @brief addWidget keep identifier empty to prevent checking for existing tabs + * @return (see addWidget in LtsBaseLayoutWidget) + */ + bool addWidget(LtsWidgets::LtsDialog* widget, const QString& menuGroup, const QString& identifier, + LtsWidgets::LayoutArea area = LtsWidgets::LayoutArea::eUnknown, bool setClosable = true); -private slots: - void slotShowOperatorSettings(); - void slotSwap(); - void slotStapleTopicLockHandler(LtsWidgets::LtsDialog *widget); - void slotStopWaitDialog(); - void slotStartPluginInit(); - void slotMonitorSelected(); - void delayScriptEditorStart(); + LtsWidgets::LtsDialog* getWidget(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area); + bool focusTab(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area); -signals: - void signalInitializationAborted(); - void _signalDoneInitializingSession(); // internal - void signalDoneInitializingSession(); // is called AFTER all payloads have been executed (on no payloads, called after session was created) FOR LTSLOGIN ! - void signalClose(); // tells the session manager to close this session - void signalLogout(); - void signalQuit(); // for payloads, so that they can quit an app - void signalStillAlive(); - void signalExerciseDataChanged(); - void signalScreenIdChanged(int screenId, int screenContainerId, int screenTypeId); - void sessionAboutToBeDestroyed(LtsSession *session); - void workspaceIdChanged(const QString &newWorkspaceId); - void signalTakeOverBdv(); - void hideAllOtherBLWs(QObject *caller); - void taskSwitch(QObject *caller); + /** WARNING: do not save the returned value, as baseLayouts can die (which kills LtsTabWidget also), so reuse this + * method instead of saving the pointer to the LtsTabWidget + * @brief locateWidget locates the given widget 'widget' and returning the TabWidget on which it is on - widgets can + * be available in one of many LayoutAreas (TabWidgets) of many LtsBaseLayoutWidgets + * @param widgetToLocate the widget to look for in the given layoutArea which is located in one of many + * LtsBaseLayoutWidget + * @param area the area the widget is located + * @return LtsTabWidget on which the widget is located + */ + LtsWidgets::LtsTabWidget* locateWidget(QWidget* widgetToLocate, LtsWidgets::LayoutArea area); -private: - friend class DeveloperTools::DevDialog; - friend class DeveloperTools::AppWidget; - friend class LtsSessionManager; + /** + * @brief enable/disable baseLayout menu + * @param on if true enable otherwise disable + */ + void enableBaseLayoutMenu(bool on = true); - bool event(QEvent *e) override; - void createBaseLayout(); - void initializePlugins(const QVector &dataPluginList, const QVector &guiPluginList); - void initializeDataPlugins(const QVector &dataPluginList); - void initializeGuiPlugins(const QVector &guiPluginList); - bool tryInitGuiPlugin(const QString &guiPluginKey, std::shared_ptr &guiPlugin); - void clearDataPluginInterfaces(); - void clearGuiPluginInterfaces(); - void executePayloads(); - void connectOnlineHelpButton(LtsWidgets::LtsDialog *widget); - // TODO: AFTER FAT !! void stapleWidget(LtsWidgets::LtsDialog *dialog); // FIXME: HACK: because an LtsDialog can directly add widgets to the base layout and misses the staples... - void aboutToCloseTab(LtsWidgets::LayoutArea area); + /** + * @brief enable/disable LayoutArea + * @param area the area to enable/disable + * @param on if true enable otherwise disable + */ + void enableBaseLayoutArea(LtsWidgets::LayoutArea area, bool on = true); - QPointer m_sessionManager; - QMap > m_payloadPriorityMap; // QMap automatically sorts by key on iteration and overwrites multiple occurences with the latest) - QList > m_payloadList; // for payloads that don't care when they are executed (prio '9999' plugins) - LtsWidgets::LtsBackgroundWidget *m_mainBackground; - bool m_hasBaseLayout; - LtsWidgets::LtsBaseLayoutWidget *m_baseLayout; - bool m_markedForDeletion; - bool m_payloads; - QVector m_notiCtlList; - bool m_initDone; // set by doneInitializingSession / signalDoneInitializingSession - bool m_payloadsDone { false }; // for debug - bool m_menuVisible; - //bool m_ignoreSignalInLoop = false; - bool m_firstActionsFetch; - LtsWidgets::ExerciseData *m_exerciseData; - QVector m_missingRightActions; - std::shared_ptr m_coreFtc; - GuiPluginBase::Interface *m_currentInitIfc; // not owning - bool m_slotPluginInitDoneMutex; - bool m_pluginInitDone; // set by slotPluginInitDone - QJsonObject m_savegame; - bool m_hidden; // if true, does not create BLW - int m_screenId { -1 }; - int m_screenContainerId { -1 }; - int m_screenIdPreset { -1 }; - int m_screenContainerIdPreset { -1 }; - bool m_loadedFromSavegame; - std::shared_ptr m_ohvIfc; - bool m_foreverInvisible; // if true, creates BLW but hides it and does not use MMM - QStringList m_failedFetches; - QVector m_bgWidgets; - QString m_workspaceId; - bool m_needsToBeSuccessfullyPlaced { true /* ALWAYS! */ /*false*/ }; // if set to true, 'signalDoneInitializingSession' will only be called after the blw was successfully placed by MMM (even works if MMM inavtive (off)) - QString m_name; - QTimer *m_blub { nullptr }; - QTimer *m_scriptEditorTimer { nullptr }; - int m_blub2; - QPointer m_dependency; // when MMM iprovides the screen selection for this app, it isn't allowed to replace apps that are dependencies of this app (e.g. logout bug) - bool m_presetBaseLayoutAsSecondaryWidget { false }; - int m_id; + /** + * @brief Return the workstation ip for this workstation (== full ipv4 adress) - workstation id comes later from Asm + */ + static int workstationIp(); // really in LtsSession? + /** + * @brief Return the workstation name + */ + static QString workstationName(); // really in LtsSession? + + /** + * @brief missingRightActions Do not use. + * @return + */ + /*const*/ QVector& missingRightActions() /*const*/ + { + return m_missingRightActions; + } + + void setSavegame(const QJsonObject& sg) + { + m_savegame = sg; + } + + const QJsonObject& getSavegame() const + { + return m_savegame; + } + + void setHidden() + { + m_hidden = true; + } + + const QString workspaceId() const; + void setWorkspaceId(const QString& newWorkspaceId); + + LtsWidgets::ExcState exerciseState() const; + + void setLoadedFromSavegame() + { + m_loadedFromSavegame = true; + } + + bool isLoadedFromSavegame() const + { + return m_loadedFromSavegame; + } + + void addDeveloperActions(); + void refetchActions(); // Do not use. + void setDependency(LtsSession* session); + + bool hasDependency(LtsSession* session) + { + return (m_dependency.data() == session); + } + + LtsSession* dependency() const + { + return m_dependency; + } + + // bogus. + void setNeedsToBeSuccessfullyPlaced(bool needed = true) + { + m_needsToBeSuccessfullyPlaced = needed; + } // works even after session creation as 'slotStartPluginInit', which finalizes the session (creates blw, etc.) is + // called async! + + int id() const + { + return m_id; + } + + public slots: + void slotExecuteNextPayload(); // NEVER call this directly, queue a signal to this slot ! + void slotPluginInitDone(); // NEVER call this directly, queue a signal to this slot ! + void slotShowOnlineHelp(const QString& fileName); + // void takeOverBdv(); + + private slots: + void slotShowOperatorSettings(); + void slotSwap(); + void slotStapleTopicLockHandler(LtsWidgets::LtsDialog* widget); + void slotStopWaitDialog(); + void slotStartPluginInit(); + void slotMonitorSelected(); + void delayScriptEditorStart(); + + signals: + void signalInitializationAborted(); + void _signalDoneInitializingSession(); // internal + void signalDoneInitializingSession(); // is called AFTER all payloads have been executed (on no payloads, called + // after session was created) FOR LTSLOGIN ! + void signalClose(); // tells the session manager to close this session + void signalLogout(); + void signalQuit(); // for payloads, so that they can quit an app + void signalStillAlive(); + void signalExerciseDataChanged(); + void signalScreenIdChanged(int screenId, int screenContainerId, int screenTypeId); + void sessionAboutToBeDestroyed(LtsSession* session); + void workspaceIdChanged(const QString& newWorkspaceId); + void signalTakeOverBdv(); + void hideAllOtherBLWs(QObject* caller); + void taskSwitch(QObject* caller); + + private: + friend class DeveloperTools::DevDialog; + friend class DeveloperTools::AppWidget; + friend class LtsSessionManager; + + bool event(QEvent* e) override; + void createBaseLayout(); + void initializePlugins(const QVector& dataPluginList, + const QVector& guiPluginList); + void initializeDataPlugins(const QVector& dataPluginList); + void initializeGuiPlugins(const QVector& guiPluginList); + bool tryInitGuiPlugin(const QString& guiPluginKey, std::shared_ptr& guiPlugin); + void clearDataPluginInterfaces(); + void clearGuiPluginInterfaces(); + void executePayloads(); + void connectOnlineHelpButton(LtsWidgets::LtsDialog* widget); + // TODO: AFTER FAT !! void stapleWidget(LtsWidgets::LtsDialog *dialog); // FIXME: HACK: because an LtsDialog can + // directly add widgets to the base layout and misses the staples... + void aboutToCloseTab(LtsWidgets::LayoutArea area); + + QPointer m_sessionManager; + QMap> + m_payloadPriorityMap; // QMap automatically sorts by key on iteration and overwrites multiple occurences with + // the latest) + QList> + m_payloadList; // for payloads that don't care when they are executed (prio '9999' plugins) + LtsWidgets::LtsBackgroundWidget* m_mainBackground; + bool m_hasBaseLayout; + LtsWidgets::LtsBaseLayoutWidget* m_baseLayout; + bool m_markedForDeletion; + bool m_payloads; + QVector m_notiCtlList; + bool m_initDone; // set by doneInitializingSession / signalDoneInitializingSession + bool m_payloadsDone{false}; // for debug + bool m_menuVisible; + // bool m_ignoreSignalInLoop = false; + bool m_firstActionsFetch; + LtsWidgets::ExerciseData* m_exerciseData; + QVector m_missingRightActions; + std::shared_ptr m_coreFtc; + GuiPluginBase::Interface* m_currentInitIfc; // not owning + bool m_slotPluginInitDoneMutex; + bool m_pluginInitDone; // set by slotPluginInitDone + QJsonObject m_savegame; + bool m_hidden; // if true, does not create BLW + int m_screenId{-1}; + int m_screenContainerId{-1}; + int m_screenIdPreset{-1}; + int m_screenContainerIdPreset{-1}; + bool m_loadedFromSavegame; + std::shared_ptr m_ohvIfc; + bool m_foreverInvisible; // if true, creates BLW but hides it and does not use MMM + QStringList m_failedFetches; + QVector m_bgWidgets; + QString m_workspaceId; + bool m_needsToBeSuccessfullyPlaced{ + true /* ALWAYS! */ /*false*/}; // if set to true, 'signalDoneInitializingSession' will only be called after the + // blw was successfully placed by MMM (even works if MMM inavtive (off)) + QString m_name; + QTimer* m_blub{nullptr}; + QTimer* m_scriptEditorTimer{nullptr}; + int m_blub2; + QPointer m_dependency; // when MMM iprovides the screen selection for this app, it isn't allowed to + // replace apps that are dependencies of this app (e.g. logout bug) + bool m_presetBaseLayoutAsSecondaryWidget{false}; + int m_id; }; } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.cpp old mode 100755 new mode 100644 index 69f91ac17..68341fbfd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.cpp @@ -1,107 +1,92 @@ #include "lts_session_data.h" - namespace LtsSessionData { struct LtsSessionDataHandler { - LtsSessionData ltsSessionData; + LtsSessionData ltsSessionData; }; Q_GLOBAL_STATIC(LtsSessionDataHandler, s_ltsSessionData) - LtsSessionData::LtsSessionData() - : m_domainIdPreset(-1) - , m_partitionIdPreset(-1) - , m_partitionTypePreset(IDL::PartitionType::Any) - , m_operatorId(-1) - , m_scriptId(0) - , m_showTerminalWindow(false) - , m_requestedAppId(LtsAppDescriptor::App::Login) - , m_workstationId(-1) - , m_isTablet(false) - , m_placeScriptScreens(false) + : m_domainIdPreset(-1), m_partitionIdPreset(-1), m_partitionTypePreset(IDL::PartitionType::Any), m_operatorId(-1), + m_scriptId(0), m_showTerminalWindow(false), m_requestedAppId(LtsAppDescriptor::App::Login), m_workstationId(-1), + m_isTablet(false), m_placeScriptScreens(false) { - //setAsTablet(true); // IMPORTANT: if you want to set this to true for testing, you have to set TABLET_MODE cmake flag to true, otherwise this will crash - setAsTablet(false); + // setAsTablet(true); // IMPORTANT: if you want to set this to true for testing, you have to set TABLET_MODE cmake + // flag to true, otherwise this will crash + setAsTablet(false); - clear(); + clear(); } - -LtsSessionData *LtsSessionData::getInstance() +LtsSessionData* LtsSessionData::getInstance() { - return &s_ltsSessionData->ltsSessionData; + return &s_ltsSessionData->ltsSessionData; } - void LtsSessionData::loggedOut() { - m_operatorId = -1; - m_operatorRights.clear(); - m_operatorName.clear(); - m_showTerminalWindow = false; - m_profilePicture = QPixmap(); - m_visibleParties.clear(); + m_operatorId = -1; + m_operatorRights.clear(); + m_operatorName.clear(); + m_showTerminalWindow = false; + m_profilePicture = QPixmap(); + m_visibleParties.clear(); } - void LtsSessionData::removePresets() { - //m_domainIdPreset = -1; keep domain ID ! - m_partitionIdPreset = -1; - m_partitionTypePreset = IDL::PartitionType::Any; // FIXME: make invalid !? + // m_domainIdPreset = -1; keep domain ID ! + m_partitionIdPreset = -1; + m_partitionTypePreset = IDL::PartitionType::Any; // FIXME: make invalid !? - m_operatorNamePreset.clear(); - m_passwordPreset.clear(); + m_operatorNamePreset.clear(); + m_passwordPreset.clear(); } - void LtsSessionData::clear() { - removePresets(); - loggedOut(); + removePresets(); + loggedOut(); } - bool LtsSessionData::hasOperatorRight(int operatorRight) const { - if (operatorRight == 0) - return true; - if (m_operatorRights.contains(operatorRight)) - return true; - return m_operatorRights.contains(-1); + if (operatorRight == 0) + return true; + if (m_operatorRights.contains(operatorRight)) + return true; + return m_operatorRights.contains(-1); } - bool LtsSessionData::isVisibleParty(int exerciseId, int partyId) const { - for (const auto &visibleParties : m_visibleParties) - { - if (visibleParties.exerciseId != exerciseId) - continue; - return visibleParties.visibleParties.contains(partyId); - } - return false; + for (const auto& visibleParties : m_visibleParties) + { + if (visibleParties.exerciseId != exerciseId) + continue; + return visibleParties.visibleParties.contains(partyId); + } + return false; } const QVector LtsSessionData::getVisibleParties(int exerciseId) const { - for(auto visibleParties : m_visibleParties) - { - if (visibleParties.exerciseId == exerciseId) - return visibleParties.visibleParties; - } - return {}; + for (auto visibleParties : m_visibleParties) + { + if (visibleParties.exerciseId == exerciseId) + return visibleParties.visibleParties; + } + return {}; } - void LtsSessionData::setAsTablet(bool isTablet) { - m_isTablet = isTablet; - //m_debugFlags.insert(QStringLiteral("isTablet"), isTablet); + m_isTablet = isTablet; + // m_debugFlags.insert(QStringLiteral("isTablet"), isTablet); } } // namespace LtsSessionData diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.h old mode 100755 new mode 100644 index a68b140db..cdf676a12 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data.h @@ -1,134 +1,277 @@ #pragma once -#include #include #include - -#include -#include -#include -#include -#include -#include +#include #include - +#include +#include +#include +#include +#include +#include namespace LtsSessionData { struct PartiesByExercise { - int exerciseId = 0; - QVector visibleParties; + int exerciseId = 0; + QVector visibleParties; }; class LTSSESSIONDATA_EXPORT LtsSessionData { -public: - static LtsSessionData *getInstance(); + public: + static LtsSessionData* getInstance(); - // Presets: - const QString &getOperatorNamePreset() const { return m_operatorNamePreset; } - const QString &getPasswordPreset() const { return m_passwordPreset; } - void setOperatorPreset(const QString &operatorName, const QString &password) { m_operatorNamePreset = operatorName; m_passwordPreset = password; } + // Presets: + const QString& getOperatorNamePreset() const + { + return m_operatorNamePreset; + } - int getDomainIdPreset() const { return m_domainIdPreset; } - void setDomainIdPreset(int domainIdPreset) { m_domainIdPreset = domainIdPreset; } + const QString& getPasswordPreset() const + { + return m_passwordPreset; + } - QStringList getQosFile() const {return m_qosFile; } - void setQosFile(const QStringList &qosFile) { m_qosFile = qosFile; } + void setOperatorPreset(const QString& operatorName, const QString& password) + { + m_operatorNamePreset = operatorName; + m_passwordPreset = password; + } - int getPartitionIdPreset() const { return m_partitionIdPreset; } - IDL::PartitionType getPartitionTypePreset() const { return m_partitionTypePreset; } - void setPartitionPreset(const int partitionId, IDL::PartitionType partitionType) { m_partitionIdPreset = partitionId; m_partitionTypePreset = partitionType; } + int getDomainIdPreset() const + { + return m_domainIdPreset; + } - /** - * @brief removePresets IMPORTANT: call removePresets after using a Preset, otherwise other apps / sessions will pick these old Presets up.. - */ - void removePresets(); + void setDomainIdPreset(int domainIdPreset) + { + m_domainIdPreset = domainIdPreset; + } + QStringList getQosFile() const + { + return m_qosFile; + } - // Other: - int getScriptId() const { return m_scriptId; } - void setScriptId(int scriptId) { m_scriptId = scriptId; } + void setQosFile(const QStringList& qosFile) + { + m_qosFile = qosFile; + } - int getOperatorId() const { return m_operatorId; } - void setOperatorId(int operatorId) { m_operatorId = operatorId; } + int getPartitionIdPreset() const + { + return m_partitionIdPreset; + } - const QString &getOperatorName() const { return m_operatorName; } - void setOperatorName(const QString &operatorName) { m_operatorName = operatorName; } + IDL::PartitionType getPartitionTypePreset() const + { + return m_partitionTypePreset; + } - const QSet &getOperatorRights() const { return m_operatorRights; } - void setOperatorRights(const QSet &operatorRights) { m_operatorRights = operatorRights; } // Todo: Emit newOperatorRights() if changed? - bool hasOperatorRight(int operatorRight) const; + void setPartitionPreset(const int partitionId, IDL::PartitionType partitionType) + { + m_partitionIdPreset = partitionId; + m_partitionTypePreset = partitionType; + } - const QPixmap &getProfilePicture() const { return m_profilePicture; } - void setProfilePicture(const QPixmap &profilePicture) { m_profilePicture = profilePicture; } + /** + * @brief removePresets IMPORTANT: call removePresets after using a Preset, otherwise other apps / sessions will + * pick these old Presets up.. + */ + void removePresets(); - bool isVisibleParty(int exerciseId, int partyId) const; - const QVector &getVisibleParties() const { return m_visibleParties; } - const QVector getVisibleParties(int exerciseId) const; - void setVisibleParties(const QVector &visibleParties) { m_visibleParties = visibleParties; } + // Other: + int getScriptId() const + { + return m_scriptId; + } - QUrl getTcpConnectionUrl() const { return m_tcpConnectionUrl; } - void setTcpConnectionUrl(const QUrl &tcpConnectionUrl) { m_tcpConnectionUrl = tcpConnectionUrl; } + void setScriptId(int scriptId) + { + m_scriptId = scriptId; + } - bool getShowTerminalWindow() const { return m_showTerminalWindow; } - void setShowTerminalWindow(bool showTerminalWindow) { m_showTerminalWindow = showTerminalWindow; } + int getOperatorId() const + { + return m_operatorId; + } - LtsAppDescriptor::App getRequestedAppId() const { return m_requestedAppId; } - void setRequestedAppId(LtsAppDescriptor::App requestedAppId) { m_requestedAppId = requestedAppId; } + void setOperatorId(int operatorId) + { + m_operatorId = operatorId; + } - int getWorkstationId() const { return m_workstationId; } - void setWorkstationId(int workstationId) { m_workstationId = workstationId; } + const QString& getOperatorName() const + { + return m_operatorName; + } - bool isTablet() const { return m_isTablet; } - void setAsTablet(bool isTablet = true); + void setOperatorName(const QString& operatorName) + { + m_operatorName = operatorName; + } - bool getPlaceScriptScreens() const { return m_placeScriptScreens; } - void setPlaceScriptScreens(bool placeScriptScreens) { m_placeScriptScreens = placeScriptScreens; } + const QSet& getOperatorRights() const + { + return m_operatorRights; + } - bool hasDebugFlag(const QString &debugFlag) const { return m_debugFlags.constEnd() != m_debugFlags.constFind(debugFlag); } - QVariant debugFlagValue(const QString &debugFlag) const { QVariant result; auto it = m_debugFlags.constFind(debugFlag); if (it != m_debugFlags.constEnd()) result = *it; return result; } - void setDebugFlagValue(const QString &debugFlag, const QVariant &value) { m_debugFlags.insert(debugFlag, value); } - const QMap &debugFlags() const { return m_debugFlags; } - void removeDebugFlag(const QString &debugFlag) { m_debugFlags.remove(debugFlag); } + void setOperatorRights(const QSet& operatorRights) + { + m_operatorRights = operatorRights; + } // Todo: Emit newOperatorRights() if changed? - void clear(); - void loggedOut(); + bool hasOperatorRight(int operatorRight) const; -private: - LtsSessionData(); - ~LtsSessionData() = default; - friend struct LtsSessionDataHandler; + const QPixmap& getProfilePicture() const + { + return m_profilePicture; + } - // Presets to skip some Payloads - QString m_operatorNamePreset; - QString m_passwordPreset; - QStringList m_qosFile; - QUrl m_tcpConnectionUrl; - int m_domainIdPreset; - int m_partitionIdPreset; - IDL::PartitionType m_partitionTypePreset; + void setProfilePicture(const QPixmap& profilePicture) + { + m_profilePicture = profilePicture; + } - int m_operatorId; - int m_scriptId; - QString m_operatorName; - bool m_showTerminalWindow; - QSet m_operatorRights; - QPixmap m_profilePicture; - QVector m_visibleParties; - QMap m_debugFlags; - LtsAppDescriptor::App m_requestedAppId; - int m_workstationId; - bool m_isTablet; - bool m_placeScriptScreens; + bool isVisibleParty(int exerciseId, int partyId) const; + + const QVector& getVisibleParties() const + { + return m_visibleParties; + } + + const QVector getVisibleParties(int exerciseId) const; + + void setVisibleParties(const QVector& visibleParties) + { + m_visibleParties = visibleParties; + } + + QUrl getTcpConnectionUrl() const + { + return m_tcpConnectionUrl; + } + + void setTcpConnectionUrl(const QUrl& tcpConnectionUrl) + { + m_tcpConnectionUrl = tcpConnectionUrl; + } + + bool getShowTerminalWindow() const + { + return m_showTerminalWindow; + } + + void setShowTerminalWindow(bool showTerminalWindow) + { + m_showTerminalWindow = showTerminalWindow; + } + + LtsAppDescriptor::App getRequestedAppId() const + { + return m_requestedAppId; + } + + void setRequestedAppId(LtsAppDescriptor::App requestedAppId) + { + m_requestedAppId = requestedAppId; + } + + int getWorkstationId() const + { + return m_workstationId; + } + + void setWorkstationId(int workstationId) + { + m_workstationId = workstationId; + } + + bool isTablet() const + { + return m_isTablet; + } + + void setAsTablet(bool isTablet = true); + + bool getPlaceScriptScreens() const + { + return m_placeScriptScreens; + } + + void setPlaceScriptScreens(bool placeScriptScreens) + { + m_placeScriptScreens = placeScriptScreens; + } + + bool hasDebugFlag(const QString& debugFlag) const + { + return m_debugFlags.constEnd() != m_debugFlags.constFind(debugFlag); + } + + QVariant debugFlagValue(const QString& debugFlag) const + { + QVariant result; + auto it = m_debugFlags.constFind(debugFlag); + if (it != m_debugFlags.constEnd()) + result = *it; + return result; + } + + void setDebugFlagValue(const QString& debugFlag, const QVariant& value) + { + m_debugFlags.insert(debugFlag, value); + } + + const QMap& debugFlags() const + { + return m_debugFlags; + } + + void removeDebugFlag(const QString& debugFlag) + { + m_debugFlags.remove(debugFlag); + } + + void clear(); + void loggedOut(); + + private: + LtsSessionData(); + ~LtsSessionData() = default; + friend struct LtsSessionDataHandler; + + // Presets to skip some Payloads + QString m_operatorNamePreset; + QString m_passwordPreset; + QStringList m_qosFile; + QUrl m_tcpConnectionUrl; + int m_domainIdPreset; + int m_partitionIdPreset; + IDL::PartitionType m_partitionTypePreset; + + int m_operatorId; + int m_scriptId; + QString m_operatorName; + bool m_showTerminalWindow; + QSet m_operatorRights; + QPixmap m_profilePicture; + QVector m_visibleParties; + QMap m_debugFlags; + LtsAppDescriptor::App m_requestedAppId; + int m_workstationId; + bool m_isTablet; + bool m_placeScriptScreens; }; static inline bool hasOperatorRight(int operatorRight) { - auto instance = LtsSessionData::getInstance(); - return instance->hasOperatorRight(operatorRight); + auto instance = LtsSessionData::getInstance(); + return instance->hasOperatorRight(operatorRight); } } // namespace LtsSessionData diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.cpp old mode 100755 new mode 100644 index 5efd38ce2..9cfad9ccb --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.cpp @@ -9,13 +9,14 @@ */ #include "lts_session_data_dds.h" + #include #include +#include #include +#include #include #include -#include -#include namespace LtsSession { @@ -30,370 +31,357 @@ namespace LtsSession // class DdsConnectionContainer { - struct DdsConnection : public DdsConnectionParams - { - std::weak_ptr ddsConnector = std::weak_ptr(); - - DdsConnection() = default; - explicit DdsConnection(const DdsConnectionParams &p) - : DdsConnectionParams(p) - {} - }; - QVector ddsConnections; -public: - - std::shared_ptr findGlobalConnection() - { - for (int i = ddsConnections.size() - 1; i >= 0; --i) + struct DdsConnection : public DdsConnectionParams { - const DdsConnection &conn = ddsConnections.at(i); - if (conn.partitionType != IDL::PartitionType::Global) - continue; - auto ret = conn.ddsConnector.lock(); - if (ret != nullptr) - return ret; - // ddsConnector is a nullptr -> useless -> remove - ddsConnections.removeAt(i); - } - Q_ASSERT(false); - return std::shared_ptr(); - } + std::weak_ptr ddsConnector = std::weak_ptr(); - std::shared_ptr findConnection(const DdsConnectionParams &connParams) - { - for (int i = ddsConnections.size() - 1; i >= 0; --i) + DdsConnection() = default; + + explicit DdsConnection(const DdsConnectionParams& p) : DdsConnectionParams(p) {} + }; + + QVector ddsConnections; + + public: + std::shared_ptr findGlobalConnection() { - const DdsConnection &conn = ddsConnections.at(i); - if (conn != connParams) - continue; - auto ret = conn.ddsConnector.lock(); - if (ret != nullptr) - return ret; - // ddsConnector is a nullptr -> useless -> remove - ddsConnections.removeAt(i); + for (int i = ddsConnections.size() - 1; i >= 0; --i) + { + const DdsConnection& conn = ddsConnections.at(i); + if (conn.partitionType != IDL::PartitionType::Global) + continue; + auto ret = conn.ddsConnector.lock(); + if (ret != nullptr) + return ret; + // ddsConnector is a nullptr -> useless -> remove + ddsConnections.removeAt(i); + } + Q_ASSERT(false); + return std::shared_ptr(); } - return std::shared_ptr(); - } - dds::domain::DomainParticipant findMatchingDomainParticipant(const DdsConnectionParams &connParams) - { - for (int i = ddsConnections.size() - 1; i >= 0; --i) + std::shared_ptr findConnection(const DdsConnectionParams& connParams) { - const DdsConnection &conn = ddsConnections.at(i); - if (!connParams.hasSameDomainParams(conn)) - continue; - auto ret = conn.ddsConnector.lock(); - if (ret != nullptr) - return ret->getDomainParticipant(); - // ddsConnector is a nullptr -> useless -> remove - ddsConnections.removeAt(i); + for (int i = ddsConnections.size() - 1; i >= 0; --i) + { + const DdsConnection& conn = ddsConnections.at(i); + if (conn != connParams) + continue; + auto ret = conn.ddsConnector.lock(); + if (ret != nullptr) + return ret; + // ddsConnector is a nullptr -> useless -> remove + ddsConnections.removeAt(i); + } + return std::shared_ptr(); } - return nullptr; - } - void insertConnection(const DdsConnectionParams &connParams, - const std::shared_ptr &ddsConnector) - { - DdsConnection val(connParams); - val.ddsConnector = ddsConnector; + dds::domain::DomainParticipant findMatchingDomainParticipant(const DdsConnectionParams& connParams) + { + for (int i = ddsConnections.size() - 1; i >= 0; --i) + { + const DdsConnection& conn = ddsConnections.at(i); + if (!connParams.hasSameDomainParams(conn)) + continue; + auto ret = conn.ddsConnector.lock(); + if (ret != nullptr) + return ret->getDomainParticipant(); + // ddsConnector is a nullptr -> useless -> remove + ddsConnections.removeAt(i); + } + return nullptr; + } - ddsConnections += val; - } + void insertConnection(const DdsConnectionParams& connParams, + const std::shared_ptr& ddsConnector) + { + DdsConnection val(connParams); + val.ddsConnector = ddsConnector; + + ddsConnections += val; + } }; Q_GLOBAL_STATIC(DdsConnectionContainer, s_ddsConnections) - - class DataPluginContainer { -public: - struct DataPluginValue - { - QString identifier; - std::weak_ptr weakIfc; - - bool operator==(const DataPluginValue &o) const + public: + struct DataPluginValue { - return identifier == o.identifier && weakIfc.lock().get() == o.weakIfc.lock().get(); - } - }; + QString identifier; + std::weak_ptr weakIfc; - QMap> m_dataPlugins; -public: - QMap> findDataPlugins(const DdsConnectionParams &connParams); - void insertDataPlugins(const DdsConnectionParams &connParams, - const QMap> &dataPlugins); + bool operator==(const DataPluginValue& o) const + { + return identifier == o.identifier && weakIfc.lock().get() == o.weakIfc.lock().get(); + } + }; + + QMap> m_dataPlugins; + + public: + QMap> findDataPlugins(const DdsConnectionParams& connParams); + void insertDataPlugins(const DdsConnectionParams& connParams, + const QMap>& dataPlugins); }; -uint qHash(const DataPluginContainer::DataPluginValue &val) +uint qHash(const DataPluginContainer::DataPluginValue& val) { - qint64 ptr = reinterpret_cast(val.weakIfc.lock().get()); - return ::qHash(val.identifier) ^ ::qHash(ptr); + qint64 ptr = reinterpret_cast(val.weakIfc.lock().get()); + return ::qHash(val.identifier) ^ ::qHash(ptr); } -QMap> DataPluginContainer::findDataPlugins(const DdsConnectionParams &connParams) +QMap> +DataPluginContainer::findDataPlugins(const DdsConnectionParams& connParams) { - QMap> ret; - DdsConnectionParams key(connParams); - key.exerciseId = 0; + QMap> ret; + DdsConnectionParams key(connParams); + key.exerciseId = 0; - auto it = m_dataPlugins.find(key); - if (it != m_dataPlugins.end()) - { - QSet &cont = it.value(); - auto itCont = cont.begin(); - while (itCont != cont.end()) + auto it = m_dataPlugins.find(key); + if (it != m_dataPlugins.end()) { - auto spPlugin = itCont->weakIfc.lock(); - if (spPlugin) - { - ret[itCont->identifier] = spPlugin; - ++itCont; - } - else - { - itCont = cont.erase(itCont); - } + QSet& cont = it.value(); + auto itCont = cont.begin(); + while (itCont != cont.end()) + { + auto spPlugin = itCont->weakIfc.lock(); + if (spPlugin) + { + ret[itCont->identifier] = spPlugin; + ++itCont; + } + else + { + itCont = cont.erase(itCont); + } + } } - } - return ret; + return ret; } -void DataPluginContainer::insertDataPlugins(const DdsConnectionParams &connParams, - const QMap> &dataPlugins) +void DataPluginContainer::insertDataPlugins( + const DdsConnectionParams& connParams, const QMap>& dataPlugins) { - DdsConnectionParams key(connParams); - key.exerciseId = 0; + DdsConnectionParams key(connParams); + key.exerciseId = 0; - QSet cont; - cont.reserve(dataPlugins.size()); - for (auto it = dataPlugins.begin(); it != dataPlugins.end(); ++it) - { - DataPluginValue val; - val.identifier = it.key(); - val.weakIfc = it.value(); - cont += val; - } + QSet cont; + cont.reserve(dataPlugins.size()); + for (auto it = dataPlugins.begin(); it != dataPlugins.end(); ++it) + { + DataPluginValue val; + val.identifier = it.key(); + val.weakIfc = it.value(); + cont += val; + } - m_dataPlugins[key].unite(cont); + m_dataPlugins[key].unite(cont); } Q_GLOBAL_STATIC(DataPluginContainer, s_dataPlugins) - - - // // LtsSessionDataDds // -LtsSessionDataDds::LtsSessionDataDds(QObject *parent) - : QObject(parent) - , m_exerciseId(-1) - , m_emittedTime(0) - , m_curMSecSinceEpoch(0) - , m_active(true) - , m_fetcher(nullptr) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Session")) -{} +LtsSessionDataDds::LtsSessionDataDds(QObject* parent) + : QObject(parent), m_exerciseId(-1), m_emittedTime(0), m_curMSecSinceEpoch(0), m_active(true), m_fetcher(nullptr), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Session")) +{ +} LtsSessionDataDds::~LtsSessionDataDds() { - m_dtcPartitionTime = nullptr; - m_ddsConnector = nullptr; - delete m_fetcher; + m_dtcPartitionTime = nullptr; + m_ddsConnector = nullptr; + delete m_fetcher; } -bool LtsSessionDataDds::init(const DdsConnectionParams &connParams) +bool LtsSessionDataDds::init(const DdsConnectionParams& connParams) { - m_ddsConnector = s_ddsConnections->findConnection(connParams); - m_exerciseId = connParams.exerciseId; - m_qosFileList = QStringList(connParams.qos_file); - if (m_ddsConnector == nullptr) - { - // maybe we can at least find a useful DomainParticipant? - dds::domain::DomainParticipant dp = s_ddsConnections->findMatchingDomainParticipant(connParams); - if (dp != nullptr) - return init(dp, connParams); - #ifdef WIN_32 - DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Tablet; - #else - DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Client; - #endif - - m_ddsConnector = std::make_shared(connParams.domainId, - connParams.partitionType, - connParams.partitionId, - connParams.exerciseId, //same as partition Id in live but not in replay - type); - s_ddsConnections()->insertConnection(connParams, m_ddsConnector); - } - return initInternal(); -} - -bool LtsSessionDataDds::init(const dds::domain::DomainParticipant &dp, const DdsConnectionParams &connParams) -{ - Q_ASSERT(dp.domain_id() == connParams.domainId); - - m_ddsConnector = s_ddsConnections->findConnection(connParams); - m_exerciseId = connParams.exerciseId; - - - - QStringList qosList; - if (!connParams.qos_file.isEmpty()) - { - qosList.append(connParams.qos_file); - } - - if (!qosList.isEmpty()) - m_qosFileList = qosList; - else - m_qosFileList.clear(); - + m_ddsConnector = s_ddsConnections->findConnection(connParams); + m_exerciseId = connParams.exerciseId; + m_qosFileList = QStringList(connParams.qos_file); + if (m_ddsConnector == nullptr) + { + // maybe we can at least find a useful DomainParticipant? + dds::domain::DomainParticipant dp = s_ddsConnections->findMatchingDomainParticipant(connParams); + if (dp != nullptr) + return init(dp, connParams); #ifdef WIN_32 - DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Tablet; + DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Tablet; #else - DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Client; + DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Client; #endif - if (m_ddsConnector == nullptr) - { - m_ddsConnector = std::make_shared(dp, - connParams.partitionType, - type, - connParams.partitionId - ); - - - - s_ddsConnections()->insertConnection(connParams, m_ddsConnector); - } - return initInternal(); + m_ddsConnector = std::make_shared( + connParams.domainId, connParams.partitionType, connParams.partitionId, + connParams.exerciseId, // same as partition Id in live but not in replay + type); + s_ddsConnections()->insertConnection(connParams, m_ddsConnector); + } + return initInternal(); } -Fetcher *LtsSessionDataDds::fetcher(const QString &yourPluginsName) +bool LtsSessionDataDds::init(const dds::domain::DomainParticipant& dp, const DdsConnectionParams& connParams) { - if (m_fetcher == nullptr) - m_fetcher = new Fetcher(this, yourPluginsName); + Q_ASSERT(dp.domain_id() == connParams.domainId); - return m_fetcher; + m_ddsConnector = s_ddsConnections->findConnection(connParams); + m_exerciseId = connParams.exerciseId; + + QStringList qosList; + if (!connParams.qos_file.isEmpty()) + { + qosList.append(connParams.qos_file); + } + + if (!qosList.isEmpty()) + m_qosFileList = qosList; + else + m_qosFileList.clear(); + +#ifdef WIN_32 + DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Tablet; +#else + DDS::QosProfile::ConnectionType type = DDS::QosProfile::ConnectionType::Client; +#endif + + if (m_ddsConnector == nullptr) + { + m_ddsConnector = + std::make_shared(dp, connParams.partitionType, type, connParams.partitionId); + + s_ddsConnections()->insertConnection(connParams, m_ddsConnector); + } + return initInternal(); +} + +Fetcher* LtsSessionDataDds::fetcher(const QString& yourPluginsName) +{ + if (m_fetcher == nullptr) + m_fetcher = new Fetcher(this, yourPluginsName); + + return m_fetcher; } QString LtsSessionDataDds::partitionTypeString(IDL::PartitionType partitionType) { - switch (partitionType) - { - case IDL::PartitionType::AllExercises: - return QStringLiteral("AllExercises"); - case IDL::PartitionType::Any: - return QStringLiteral("Any"); - case IDL::PartitionType::Exercise: - return QStringLiteral("Exercise"); - case IDL::PartitionType::Global: - return QStringLiteral("Global"); - case IDL::PartitionType::Replay: - return QStringLiteral("Replay"); - } + switch (partitionType) + { + case IDL::PartitionType::AllExercises: + return QStringLiteral("AllExercises"); + case IDL::PartitionType::Any: + return QStringLiteral("Any"); + case IDL::PartitionType::Exercise: + return QStringLiteral("Exercise"); + case IDL::PartitionType::Global: + return QStringLiteral("Global"); + case IDL::PartitionType::Replay: + return QStringLiteral("Replay"); + } - return QStringLiteral("Invalid (%1)").arg(int(partitionType)); + return QStringLiteral("Invalid (%1)").arg(int(partitionType)); } QString LtsSessionDataDds::toString() const { - return QStringLiteral("(LtsSessionDataDds: id=%1, partitionId=%2, partitionType=%3(%4), exerciseId=%5)").arg((qulonglong)this).arg(partitionId()).arg(static_cast(partitionType())).arg(partitionTypeString(partitionType())).arg(exerciseId()); + return QStringLiteral("(LtsSessionDataDds: id=%1, partitionId=%2, partitionType=%3(%4), exerciseId=%5)") + .arg((qulonglong)this) + .arg(partitionId()) + .arg(static_cast(partitionType())) + .arg(partitionTypeString(partitionType())) + .arg(exerciseId()); } int LtsSessionDataDds::domainId() const { - return m_ddsConnector ? m_ddsConnector->getDomainId() : -1; + return m_ddsConnector ? m_ddsConnector->getDomainId() : -1; } int LtsSessionDataDds::exerciseId() const { - return m_exerciseId; + return m_exerciseId; } int LtsSessionDataDds::partitionId() const { - return m_ddsConnector ? m_ddsConnector->getPartitionId() : -1; + return m_ddsConnector ? m_ddsConnector->getPartitionId() : -1; } IDL::PartitionType LtsSessionDataDds::partitionType() const { - return m_ddsConnector ? m_ddsConnector->getPartitionType() : IDL::PartitionType::Global; + return m_ddsConnector ? m_ddsConnector->getPartitionType() : IDL::PartitionType::Global; } QStringList LtsSessionDataDds::qosFile() const { - return m_ddsConnector ? m_qosFileList : QStringList(); + return m_ddsConnector ? m_qosFileList : QStringList(); } QUrl LtsSessionDataDds::tcpConnectionUrl() const { - return m_ddsConnector ? m_ddsConnector->getTcpConnectionUrl() : QUrl(); + return m_ddsConnector ? m_ddsConnector->getTcpConnectionUrl() : QUrl(); } DdsConnectionParams LtsSessionDataDds::connParams() const { - DdsConnectionParams connParams; - connParams.domainId = domainId(); - connParams.exerciseId = exerciseId(); - connParams.partitionId = partitionId(); - connParams.partitionType = partitionType(); - connParams.qos_file = qosFile(); - connParams.tcpConnectionUrl = tcpConnectionUrl(); - return connParams; + DdsConnectionParams connParams; + connParams.domainId = domainId(); + connParams.exerciseId = exerciseId(); + connParams.partitionId = partitionId(); + connParams.partitionType = partitionType(); + connParams.qos_file = qosFile(); + connParams.tcpConnectionUrl = tcpConnectionUrl(); + return connParams; } - bool LtsSessionDataDds::initInternal() { - if (!m_ddsConnector || !m_ddsConnector->init(m_qosFileList)) - { - ERROR_LOG(m_logger) << "DDS connector could not be initialized - session aborted!"; - m_ddsConnector = nullptr; - return false; - } + if (!m_ddsConnector || !m_ddsConnector->init(m_qosFileList)) + { + ERROR_LOG(m_logger) << "DDS connector could not be initialized - session aborted!"; + m_ddsConnector = nullptr; + return false; + } - m_ddsConnector->initPublisherSubscriber(); - m_ddsConnectorGlobal = s_ddsConnections->findGlobalConnection(); - if (!m_ddsConnectorGlobal) - m_ddsConnectorGlobal = m_ddsConnector; + m_ddsConnector->initPublisherSubscriber(); + m_ddsConnectorGlobal = s_ddsConnections->findGlobalConnection(); + if (!m_ddsConnectorGlobal) + m_ddsConnectorGlobal = m_ddsConnector; - m_dtcPartitionTime.reset(m_ddsConnector->createDTC()); - assert(m_dtcPartitionTime.get()); + m_dtcPartitionTime.reset(m_ddsConnector->createDTC()); + assert(m_dtcPartitionTime.get()); - m_dtcPartitionTime->setSubscriberCallback([this](const Core::PartitionTime & data, DataModification) - { - m_curMSecSinceEpoch = data.timeStamp(); - emit partitionTimeChangedInternal(); - }); - connect(this, &LtsSessionDataDds::partitionTimeChangedInternal, - this, &LtsSessionDataDds::onPartitionTimeChangedInternal, Qt::QueuedConnection); - return true; + m_dtcPartitionTime->setSubscriberCallback([this](const Core::PartitionTime& data, DataModification) { + m_curMSecSinceEpoch = data.timeStamp(); + emit partitionTimeChangedInternal(); + }); + connect(this, &LtsSessionDataDds::partitionTimeChangedInternal, this, + &LtsSessionDataDds::onPartitionTimeChangedInternal, Qt::QueuedConnection); + return true; } void LtsSessionDataDds::onPartitionTimeChangedInternal() { - if (!m_active) - return; - if (m_emittedTime == m_curMSecSinceEpoch) - return; - m_emittedTime = m_curMSecSinceEpoch; - emit partitionTimeChanged(m_curMSecSinceEpoch); + if (!m_active) + return; + if (m_emittedTime == m_curMSecSinceEpoch) + return; + m_emittedTime = m_curMSecSinceEpoch; + emit partitionTimeChanged(m_curMSecSinceEpoch); } QMap> LtsSessionDataDds::availableDataPluginInterfaces() const { - return s_dataPlugins->findDataPlugins(connParams()); - + return s_dataPlugins->findDataPlugins(connParams()); } -void LtsSessionDataDds::addAvailablaeDataPluginInterfaces(const QMap> &dataPlugins) +void LtsSessionDataDds::addAvailablaeDataPluginInterfaces( + const QMap>& dataPlugins) { - s_dataPlugins->insertDataPlugins(connParams(), - dataPlugins); + s_dataPlugins->insertDataPlugins(connParams(), dataPlugins); } } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.h old mode 100755 new mode 100644 index 72997d43e..d8eeb76a9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds.h @@ -12,15 +12,15 @@ #ifdef BUILD_RTI // Full DDS implementation -#include +#include #include +#include #include #include -#include //#include -#include #include #include +#include #else // Stub implementation when BUILD_RTI=OFF #include "lts_session_data_dds_stub.h" @@ -28,250 +28,282 @@ #ifdef BUILD_RTI +namespace DataPluginBase +{ +class Interface; +} -namespace DataPluginBase { class Interface; } -namespace DDSConnector { class DdsConnector; } -namespace GuiPluginBase { class Interface; } +namespace DDSConnector +{ +class DdsConnector; +} + +namespace GuiPluginBase +{ +class Interface; +} namespace LtsSession { struct DdsConnectionParams { - int domainId = -1; - int partitionId = 0; - int exerciseId = 0; - IDL::PartitionType partitionType = IDL::PartitionType::Any; - QUrl tcpConnectionUrl; - QStringList qos_file; + int domainId = -1; + int partitionId = 0; + int exerciseId = 0; + IDL::PartitionType partitionType = IDL::PartitionType::Any; + QUrl tcpConnectionUrl; + QStringList qos_file; - DdsConnectionParams() = default; - explicit DdsConnectionParams(const Core::ReplayPartition &rp) - : domainId(rp.domainId()) - , partitionId(rp.id()) - , exerciseId(rp.exerciseId()) - , partitionType(IDL::PartitionType::Replay) - { - setTcpConnectionUrl(rp.tcpConnectionUrl()); - } + DdsConnectionParams() = default; - bool isValid() const { return domainId >= 0 && partitionType != IDL::PartitionType::Any; } - bool hasSameDomainParams(const DdsConnectionParams &o) const - { - return domainId == o.domainId && - tcpConnectionUrl == o.tcpConnectionUrl; - } - bool operator==(const DdsConnectionParams &o) const - { - return domainId == o.domainId && - partitionId == o.partitionId && - exerciseId == o.exerciseId && - qos_file == o.qos_file && - partitionType == o.partitionType && - tcpConnectionUrl == o.tcpConnectionUrl; - } - bool operator !=(const DdsConnectionParams &o) const - { - return !operator==(o); - } - bool operator <(const DdsConnectionParams &o) const - { - if (domainId != o.domainId) - return domainId < o.domainId; - if (partitionId != o.partitionId) - return partitionId < o.partitionId; - if (exerciseId != o.exerciseId) - return exerciseId < o.exerciseId; - if (qos_file != o.qos_file) - return qos_file < o.qos_file; - if (partitionType != o.partitionType) - return partitionType < o.partitionType; - return tcpConnectionUrl.toString() < o.tcpConnectionUrl.toString(); - } + explicit DdsConnectionParams(const Core::ReplayPartition& rp) + : domainId(rp.domainId()), partitionId(rp.id()), exerciseId(rp.exerciseId()), + partitionType(IDL::PartitionType::Replay) + { + setTcpConnectionUrl(rp.tcpConnectionUrl()); + } - void setTcpConnectionUrl(const std::string &url) - { - tcpConnectionUrl = QUrl::fromUserInput(QString::fromStdString(url)); - } + bool isValid() const + { + return domainId >= 0 && partitionType != IDL::PartitionType::Any; + } + + bool hasSameDomainParams(const DdsConnectionParams& o) const + { + return domainId == o.domainId && tcpConnectionUrl == o.tcpConnectionUrl; + } + + bool operator==(const DdsConnectionParams& o) const + { + return domainId == o.domainId && partitionId == o.partitionId && exerciseId == o.exerciseId && + qos_file == o.qos_file && partitionType == o.partitionType && tcpConnectionUrl == o.tcpConnectionUrl; + } + + bool operator!=(const DdsConnectionParams& o) const + { + return !operator==(o); + } + + bool operator<(const DdsConnectionParams& o) const + { + if (domainId != o.domainId) + return domainId < o.domainId; + if (partitionId != o.partitionId) + return partitionId < o.partitionId; + if (exerciseId != o.exerciseId) + return exerciseId < o.exerciseId; + if (qos_file != o.qos_file) + return qos_file < o.qos_file; + if (partitionType != o.partitionType) + return partitionType < o.partitionType; + return tcpConnectionUrl.toString() < o.tcpConnectionUrl.toString(); + } + + void setTcpConnectionUrl(const std::string& url) + { + tcpConnectionUrl = QUrl::fromUserInput(QString::fromStdString(url)); + } }; - class Fetcher; - -class LTSSESSIONDATADDS_EXPORT LtsSessionDataDds /* FIXME: Name ist irrefuehrend. "LtsSessionData" hat mit "LtsSessionDataDds" nichts zu tun, klingen aber fast identisch. */ +class LTSSESSIONDATADDS_EXPORT LtsSessionDataDds /* FIXME: Name ist irrefuehrend. "LtsSessionData" hat mit + "LtsSessionDataDds" nichts zu tun, klingen aber fast identisch. */ : public QObject { - Q_OBJECT -protected: - // only used from LtsSession, no direct instantiation - explicit LtsSessionDataDds(QObject *parent = nullptr); -public: - ~LtsSessionDataDds(); + Q_OBJECT + protected: + // only used from LtsSession, no direct instantiation + explicit LtsSessionDataDds(QObject* parent = nullptr); - bool init(const DdsConnectionParams &connParams); - bool init(const dds::domain::DomainParticipant &dp, - const DdsConnectionParams &connParams); + public: + ~LtsSessionDataDds(); - std::shared_ptr ddsConnector() { return m_ddsConnector; } - std::shared_ptr ddsConnectorGlobal() { return m_ddsConnectorGlobal; } - int domainId() const; - int exerciseId() const; - int partitionId() const; - QStringList qosFile() const; - IDL::PartitionType partitionType() const; - static QString partitionTypeString(IDL::PartitionType partitionType); - bool isExercisePartition() const { return (partitionType() == IDL::PartitionType::Exercise); } - bool isReplayPartition() const { return (partitionType() == IDL::PartitionType::Replay); } - QString toString() const; - Fetcher *fetcher(const QString &yourPluginsName); + bool init(const DdsConnectionParams& connParams); + bool init(const dds::domain::DomainParticipant& dp, const DdsConnectionParams& connParams); - QUrl tcpConnectionUrl() const; - DdsConnectionParams connParams() const; - - qint64 partitionTime() const { return m_curMSecSinceEpoch; } - - // retrieve DTC/FTC inside DataPlugin::createDataInterface() - template - bool createTopicClient(std::shared_ptr &member, bool bEnableAll = false, bool bGlobal = false) - { - member = T::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); - if ( bEnableAll && !member->enableAll()) + std::shared_ptr ddsConnector() { - member = nullptr; - ERROR_LOG(m_logger) << "Error initializing dtc/ftc for service " << T::identifier(); - return false; + return m_ddsConnector; } - return true; - } - template - bool createTopicClient(std::shared_ptr &dtc, std::shared_ptr &ftc, bool bEnableAll = false, bool bGlobal = false) - { - dtc = T::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); - ftc = S::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); - if ( (bEnableAll && !dtc->enableAll()) || !ftc->enableAll()) + std::shared_ptr ddsConnectorGlobal() { - dtc = nullptr; - ftc = nullptr; - ERROR_LOG(m_logger) << "Error initializing dtc/ftc for service " << T::identifier(); - return false; + return m_ddsConnectorGlobal; } - return true; - } - template - bool getDtc(std::shared_ptr &val) const - { - for (const auto &i : m_dataPluginInterfaces) + int domainId() const; + int exerciseId() const; + int partitionId() const; + QStringList qosFile() const; + IDL::PartitionType partitionType() const; + static QString partitionTypeString(IDL::PartitionType partitionType); + + bool isExercisePartition() const { - auto ifc = std::dynamic_pointer_cast(i); - if (ifc) - { - val = ifc->getDtc(); - return val != nullptr; - } + return (partitionType() == IDL::PartitionType::Exercise); } - val.reset(); - DEBUG_LOG(m_logger) << "Trying to load dtc " << typeid(T).name() << " - " << typeid(S).name() << " failed!" - << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; - return false; - } - // TODO: merge with getDtc() --> std::is_same, std::enable_if - template - bool getFtc(std::shared_ptr &val) const - { - for (const auto &i : m_dataPluginInterfaces) + bool isReplayPartition() const { - auto ifc = std::dynamic_pointer_cast(i); - if (ifc) - { - val = ifc->getFtc(); - return val != nullptr; - } + return (partitionType() == IDL::PartitionType::Replay); } - val.reset(); - DEBUG_LOG(m_logger) << "Trying to load ftc " << typeid(T).name() << " - " << typeid(S).name() << " failed!" - << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; - return false; - } + QString toString() const; + Fetcher* fetcher(const QString& yourPluginsName); - // TODO: merge with getDtc() --> std::is_same, std::enable_if - template - bool getForeignDataInterface(std::shared_ptr &val) const - { - //qWarning() << "getForeignDataInterface is deprecated! get the plugin's dtc/ftc directly with getDtc or getFtc!"; + QUrl tcpConnectionUrl() const; + DdsConnectionParams connParams() const; - for (const auto &i : m_dataPluginInterfaces) + qint64 partitionTime() const { - auto ifc = std::dynamic_pointer_cast(i); - if (ifc) - { - val = ifc->getForeignDataInterface(); - return val != nullptr; - } + return m_curMSecSinceEpoch; } - val.reset(); - DEBUG_LOG(m_logger) << "Trying to load foreign data ifc " << typeid(T).name() << " - " << typeid(S).name() << " failed!" - << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; - return false; - } + // retrieve DTC/FTC inside DataPlugin::createDataInterface() + template + bool createTopicClient(std::shared_ptr& member, bool bEnableAll = false, bool bGlobal = false) + { + member = T::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); + if (bEnableAll && !member->enableAll()) + { + member = nullptr; + ERROR_LOG(m_logger) << "Error initializing dtc/ftc for service " << T::identifier(); + return false; + } + return true; + } - /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW */ - /* MW DEPRECATED - DO NOT USE IN NEW IMPLEMENTATIONS - CAN BE REMOVED AT ANY TIME WITHOUT WARNING ! MW */ - /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW */ - /* MW */ /* MW */ - /* MW */ template /* MW */ - /* MW */ bool getForeignDataInterface_NEW(std::shared_ptr &val) const /* MW */ - /* MW */ { /* MW */ - /* MW */ //qWarning() << "getForeignDataInterface is deprecated! get the plugin's dtc/ftc directly with getDtc or getFtc!"; /* MW */ - /* MW */ /* MW */ - /* MW */ for (const auto &i : m_dataPluginInterfaces) /* MW */ - /* MW */ { /* MW */ - /* MW */ val = std::dynamic_pointer_cast(i); /* MW */ - /* MW */ if (val) /* MW */ - /* MW */ return true; /* MW */ + template + bool createTopicClient(std::shared_ptr& dtc, std::shared_ptr& ftc, bool bEnableAll = false, + bool bGlobal = false) + { + dtc = T::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); + ftc = S::create(bGlobal ? m_ddsConnectorGlobal : m_ddsConnector); + if ((bEnableAll && !dtc->enableAll()) || !ftc->enableAll()) + { + dtc = nullptr; + ftc = nullptr; + ERROR_LOG(m_logger) << "Error initializing dtc/ftc for service " << T::identifier(); + return false; + } + return true; + } + + template bool getDtc(std::shared_ptr& val) const + { + for (const auto& i : m_dataPluginInterfaces) + { + auto ifc = std::dynamic_pointer_cast(i); + if (ifc) + { + val = ifc->getDtc(); + return val != nullptr; + } + } + val.reset(); + DEBUG_LOG(m_logger) << "Trying to load dtc " << typeid(T).name() << " - " << typeid(S).name() << " failed!" + << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; + return false; + } + + // TODO: merge with getDtc() --> std::is_same, std::enable_if + template bool getFtc(std::shared_ptr& val) const + { + for (const auto& i : m_dataPluginInterfaces) + { + auto ifc = std::dynamic_pointer_cast(i); + if (ifc) + { + val = ifc->getFtc(); + return val != nullptr; + } + } + val.reset(); + DEBUG_LOG(m_logger) << "Trying to load ftc " << typeid(T).name() << " - " << typeid(S).name() << " failed!" + << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; + return false; + } + + // TODO: merge with getDtc() --> std::is_same, std::enable_if + template bool getForeignDataInterface(std::shared_ptr& val) const + { + // qWarning() << "getForeignDataInterface is deprecated! get the plugin's dtc/ftc directly with getDtc or + // getFtc!"; + + for (const auto& i : m_dataPluginInterfaces) + { + auto ifc = std::dynamic_pointer_cast(i); + if (ifc) + { + val = ifc->getForeignDataInterface(); + return val != nullptr; + } + } + val.reset(); + DEBUG_LOG(m_logger) << "Trying to load foreign data ifc " << typeid(T).name() << " - " << typeid(S).name() + << " failed!" + << ", m_dataPluginInterfaces.size() = " << m_dataPluginInterfaces.size() << " - " << this; + return false; + } + + /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW + */ + /* MW DEPRECATED - DO NOT USE IN NEW IMPLEMENTATIONS - CAN BE REMOVED AT ANY TIME WITHOUT WARNING ! MW */ + /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW + */ + /* MW */ /* MW */ + /* MW */ template /* MW */ + /* MW */ bool getForeignDataInterface_NEW(std::shared_ptr& val) const /* MW */ + + /* MW */ { /* MW */ + /* MW */ // qWarning() << "getForeignDataInterface is deprecated! get the plugin's dtc/ftc directly with getDtc + // or getFtc!"; /* MW */ + /* MW */ /* MW */ + /* MW */ for (const auto& i : m_dataPluginInterfaces) /* MW */ + /* MW */ { /* MW */ + /* MW */ val = std::dynamic_pointer_cast(i); /* MW */ + /* MW */ if (val) /* MW */ + /* MW */ return true; /* MW */ /* MW */ } /* MW */ - /* MW */ val.reset(); /* MW */ - /* MW */ DEBUG_LOG(m_logger) << "Trying to load foreign data ifc " << typeid(S).name() << " failed!" /* MW */ - /* MW */ << ", m_guiPluginInterfaces.size() = " << m_guiPluginInterfaces.size() << " - " << this; /* MW */ - /* MW */ return false; /* MW */ + /* MW */ val.reset(); /* MW */ + /* MW */ DEBUG_LOG(m_logger) << "Trying to load foreign data ifc " << typeid(S).name() + << " failed!" /* MW */ + /* MW */ + << ", m_guiPluginInterfaces.size() = " << m_guiPluginInterfaces.size() << " - " + << this; /* MW */ + /* MW */ return false; /* MW */ /* MW */ } /* MW */ - /* MW */ /* MW */ - /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW */ + /* MW */ /* MW */ + /* MWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMW + */ - - template - bool getForeignGuiInterface(std::shared_ptr &val) const + template bool getForeignGuiInterface(std::shared_ptr& val) const { - for (const auto &i : m_guiPluginInterfaces) - { - val = std::dynamic_pointer_cast(i); - if (val) - return true; - } - val.reset(); - DEBUG_LOG(m_logger) << "Cannot find foreign gui ifc " << typeid(S).name() << " in " << toString(); + for (const auto& i : m_guiPluginInterfaces) + { + val = std::dynamic_pointer_cast(i); + if (val) + return true; + } + val.reset(); + DEBUG_LOG(m_logger) << "Cannot find foreign gui ifc " << typeid(S).name() << " in " << toString(); - return false; + return false; } - - template - bool interfaceFromGui(std::shared_ptr &val) const // for generic gui interfaces + template bool interfaceFromGui(std::shared_ptr& val) const // for generic gui interfaces { - for (const auto &i : m_guiPluginInterfaces) - { - val = std::dynamic_pointer_cast(i); - if (val) - return true; - } - val.reset(); - DEBUG_LOG(m_logger) << "Trying to load foreign gui ifc #2 " << typeid(S).name() << " failed!" + for (const auto& i : m_guiPluginInterfaces) + { + val = std::dynamic_pointer_cast(i); + if (val) + return true; + } + val.reset(); + DEBUG_LOG(m_logger) << "Trying to load foreign gui ifc #2 " << typeid(S).name() << " failed!" << ", m_guiPluginInterfaces.size() = " << m_guiPluginInterfaces.size() << " - " << this; - return false; + return false; } signals: @@ -290,75 +322,76 @@ protected: qint64 m_emittedTime; qint64 m_curMSecSinceEpoch; bool m_active; - void setInactive() { m_active = false; } + void setInactive() + { + m_active = false; + } QMap> availableDataPluginInterfaces() const; - void addAvailablaeDataPluginInterfaces(const QMap> &dataPlugins); + void addAvailablaeDataPluginInterfaces(const QMap>& dataPlugins); QMap> m_dataPluginInterfaces; QMap> m_guiPluginInterfaces; QMap> m_initializeThesePlugins; - Fetcher *m_fetcher; + Fetcher* m_fetcher; QStringList m_qosFileList; - NGL::INGLLogger &m_logger; + NGL::INGLLogger& m_logger; }; - class Fetcher { -public: - Fetcher(LtsSessionDataDds *sessionDataDds, const QString &caller) - : m_sessionDataDds(sessionDataDds) - , m_errors(false) - , m_caller(caller) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Fetcher")) - , m_optional(false) - { - - } - - LtsSessionDataDds *m_sessionDataDds; - bool m_errors; - QString m_caller; - QString m_whatWillNotWork; - NGL::INGLLogger &m_logger; - bool m_optional; - QString m_resultType; - QString m_getterFunctionType; - - template - void getForeignGuiInterface(std::shared_ptr &foreignGuiInterface, const QString &whatWillNotWork /* only fill if optional */, bool optional) - { - if (!m_sessionDataDds->getForeignGuiInterface(foreignGuiInterface)) + public: + Fetcher(LtsSessionDataDds* sessionDataDds, const QString& caller) + : m_sessionDataDds(sessionDataDds), m_errors(false), m_caller(caller), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Fetcher")), m_optional(false) { - m_whatWillNotWork = whatWillNotWork; - m_optional = optional; - m_resultType = QString::fromUtf8(typeid(ForeignGuiInterface).name()); - m_getterFunctionType = QStringLiteral("gui interface"); - print(); } - } - bool status() const - { - return !m_errors; - } + LtsSessionDataDds* m_sessionDataDds; + bool m_errors; + QString m_caller; + QString m_whatWillNotWork; + NGL::INGLLogger& m_logger; + bool m_optional; + QString m_resultType; + QString m_getterFunctionType; - void print() - { - m_errors = true; - - QString msg(QStringLiteral("%1 cannot find '%2' in %3 %4")); - - if (m_optional) + template + void getForeignGuiInterface(std::shared_ptr& foreignGuiInterface, + const QString& whatWillNotWork /* only fill if optional */, bool optional) { - INFO_LOG(m_logger) << msg.arg(m_caller, m_resultType, m_sessionDataDds->toString(), QStringLiteral("' - optional but %1 will not work").arg(m_whatWillNotWork)); + if (!m_sessionDataDds->getForeignGuiInterface(foreignGuiInterface)) + { + m_whatWillNotWork = whatWillNotWork; + m_optional = optional; + m_resultType = QString::fromUtf8(typeid(ForeignGuiInterface).name()); + m_getterFunctionType = QStringLiteral("gui interface"); + print(); + } } - else // critical + + bool status() const { - ERROR_LOG(m_logger) << msg.arg(m_caller, m_resultType, m_sessionDataDds->toString(), QStringLiteral(" which is required")); + return !m_errors; + } + + void print() + { + m_errors = true; + + QString msg(QStringLiteral("%1 cannot find '%2' in %3 %4")); + + if (m_optional) + { + INFO_LOG(m_logger) << msg.arg(m_caller, m_resultType, m_sessionDataDds->toString(), + QStringLiteral("' - optional but %1 will not work").arg(m_whatWillNotWork)); + } + else // critical + { + ERROR_LOG(m_logger) << msg.arg(m_caller, m_resultType, m_sessionDataDds->toString(), + QStringLiteral(" which is required")); + } } - } }; } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds_stub.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds_stub.h index fc96665e0..e47d55f13 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds_stub.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_data_dds_stub.h @@ -6,11 +6,11 @@ #pragma once -#include #include -#include +#include #include #include +#include #include namespace LtsSession @@ -19,64 +19,137 @@ namespace LtsSession // Stub DdsConnectionParams - minimal version without DDS dependencies struct DdsConnectionParams { - int domainId = -1; - int partitionId = 0; - int exerciseId = 0; - QUrl tcpConnectionUrl; - QStringList qos_file; + int domainId = -1; + int partitionId = 0; + int exerciseId = 0; + QUrl tcpConnectionUrl; + QStringList qos_file; - DdsConnectionParams() = default; - - bool isValid() const { return false; } // Always invalid without DDS - bool hasSameDomainParams(const DdsConnectionParams &) const { return false; } - bool operator==(const DdsConnectionParams &) const { return false; } - bool operator!=(const DdsConnectionParams &) const { return true; } - bool operator<(const DdsConnectionParams &) const { return false; } + DdsConnectionParams() = default; + + bool isValid() const + { + return false; + } // Always invalid without DDS + + bool hasSameDomainParams(const DdsConnectionParams&) const + { + return false; + } + + bool operator==(const DdsConnectionParams&) const + { + return false; + } + + bool operator!=(const DdsConnectionParams&) const + { + return true; + } + + bool operator<(const DdsConnectionParams&) const + { + return false; + } }; // Forward declare internal classes -namespace DDSConnector { class DdsConnector; } -namespace DataPluginBase { class Interface; } -namespace GuiPluginBase { class Interface; } +namespace DDSConnector +{ +class DdsConnector; +} + +namespace DataPluginBase +{ +class Interface; +} + +namespace GuiPluginBase +{ +class Interface; +} // Stub LtsSessionDataDds class - minimal version without DDS functionality class LtsSessionDataDds : public QObject { - Q_OBJECT -public: - explicit LtsSessionDataDds(QObject *parent = nullptr) : QObject(parent) {} - ~LtsSessionDataDds() override = default; + Q_OBJECT + public: + explicit LtsSessionDataDds(QObject* parent = nullptr) : QObject(parent) {} - bool init(const DdsConnectionParams &) { return false; } - - std::shared_ptr ddsConnector() { return nullptr; } - std::shared_ptr ddsConnectorGlobal() { return nullptr; } - int domainId() const { return -1; } - int exerciseId() const { return -1; } - int partitionId() const { return -1; } - QStringList qosFile() const { return QStringList(); } - QString toString() const { return QStringLiteral("LtsSessionDataDds(stub)"); } - - QUrl tcpConnectionUrl() const { return QUrl(); } - DdsConnectionParams connParams() const { return DdsConnectionParams(); } - - qint64 partitionTime() const { return 0; } + ~LtsSessionDataDds() override = default; -signals: - void partitionTimeChanged(qint64); - void partitionTimeChangedInternal(); + bool init(const DdsConnectionParams&) + { + return false; + } + + std::shared_ptr ddsConnector() + { + return nullptr; + } + + std::shared_ptr ddsConnectorGlobal() + { + return nullptr; + } + + int domainId() const + { + return -1; + } + + int exerciseId() const + { + return -1; + } + + int partitionId() const + { + return -1; + } + + QStringList qosFile() const + { + return QStringList(); + } + + QString toString() const + { + return QStringLiteral("LtsSessionDataDds(stub)"); + } + + QUrl tcpConnectionUrl() const + { + return QUrl(); + } + + DdsConnectionParams connParams() const + { + return DdsConnectionParams(); + } + + qint64 partitionTime() const + { + return 0; + } + + signals: + void partitionTimeChanged(qint64); + void partitionTimeChangedInternal(); }; // Stub Fetcher class class Fetcher { -public: - Fetcher(LtsSessionDataDds *, const QString &) {} - - template - void getForeignGuiInterface(std::shared_ptr &, const QString &, bool) {} - - bool status() const { return false; } + public: + Fetcher(LtsSessionDataDds*, const QString&) {} + + template void getForeignGuiInterface(std::shared_ptr&, const QString&, bool) {} + + bool status() const + { + return false; + } }; } // namespace LtsSession \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.cpp old mode 100755 new mode 100644 index cbd573859..7d9cfa695 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.cpp @@ -1,290 +1,271 @@ #include "lts_session_lock_handler.h" -#include #include - +#include #include - #include - namespace LtsSession { TopicLockHandler::TopicLockHandler() - : QObject() - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.TopicLockHandler")) + : QObject(), m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.TopicLockHandler")) { - TRACE_LOG(m_logger) << LOGFUNCTION << " START"; - TRACE_LOG(m_logger) << LOGFUNCTION << " END"; + TRACE_LOG(m_logger) << LOGFUNCTION << " START"; + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; } TopicLockHandler::~TopicLockHandler() { - TRACE_LOG(m_logger) << LOGFUNCTION << " START"; - TRACE_LOG(m_logger) << LOGFUNCTION << " END"; + TRACE_LOG(m_logger) << LOGFUNCTION << " START"; + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; } -bool TopicLockHandler::init(const std::shared_ptr &coreFtc, - int exerciseId) +bool TopicLockHandler::init(const std::shared_ptr& coreFtc, int exerciseId) { - TRACE_LOG(m_logger) << LOGFUNCTION << " START"; - if (coreFtc == nullptr) - return false; - coreFtc->enableAll(); - m_exerciseId = exerciseId; - m_coreFtc = coreFtc; + TRACE_LOG(m_logger) << LOGFUNCTION << " START"; + if (coreFtc == nullptr) + return false; + coreFtc->enableAll(); + m_exerciseId = exerciseId; + m_coreFtc = coreFtc; - TRACE_LOG(m_logger) << LOGFUNCTION << " END"; - return true; + TRACE_LOG(m_logger) << LOGFUNCTION << " END"; + return true; } - bool TopicLockHandler::lock() { - INFO_LOG(m_logger) << "LOCK " << m_topicInfo.topicName(); - TRACE_LOG(m_logger) << LOGFUNCTION << objStateAsString(); + INFO_LOG(m_logger) << "LOCK " << m_topicInfo.topicName(); + TRACE_LOG(m_logger) << LOGFUNCTION << objStateAsString(); - if (m_coreFtc == nullptr) - return false; + if (m_coreFtc == nullptr) + return false; - if (m_locked) - { - ERROR_LOG(m_logger) << LOGFUNCTION << ": called lock while still locked! " << m_lockEntityId; - Q_ASSERT(false); - return false; - } - - const auto *sessionData = LtsSessionData::LtsSessionData::getInstance(); - - Core::TryLockEntityRequest req; - req.id(m_lockEntityId); // m_lockEntityId > 0 means that a lock is updated - // svcKey : - req.entityTypeName(m_topicInfo.topicName().toStdString()/* + m_topicInfo.workspaceId().toStdString()*/); - req.entityId(m_topicInfo.entityId()); - req.exerciseId(m_exerciseId); - // : svcKey - req.operatorId(sessionData->getOperatorId()); - req.workstationId(sessionData->getWorkstationId()); - - try - { - const Core::TryLockEntityReply reply(m_coreFtc->tryLockEntityRequest(req)); - - TRACE_LOG(m_logger) << LOGFUNCTION << ": Reply received - state=" << objStateAsString() - << " - reply=" << reply; - - if (reply.alreadyLocked().is_set()) //has_value not support on windows yet so we need depricated is_set + if (m_locked) { - const Core::LockEntityError &alreadyLocked = reply.alreadyLocked().get(); - INFO_LOG(m_logger) << LOGFUNCTION << ": Topic already locked by ws " << alreadyLocked.workstationName() << " and op " << alreadyLocked.operatorName(); - - // N. Thoden, 23.09.2020: Since Locking is more often, the dialog is annoying. So skip and pay attention to title - // LtsWidgets::LtsMessageDialog::showMessage(nullptr, fro.translated(), tr("Unable to lock data record")); - - const auto lockedBy(QStringLiteral("%2/%1").arg(QString::fromStdString(alreadyLocked.operatorName()), QString::fromStdString(alreadyLocked.workstationName()))); - - emit signalLockDialog(lockedBy); // -> READ_ONLY / lock the dialog as the topic could not be locked + ERROR_LOG(m_logger) << LOGFUNCTION << ": called lock while still locked! " << m_lockEntityId; + Q_ASSERT(false); + return false; } - else // lock was successful + + const auto* sessionData = LtsSessionData::LtsSessionData::getInstance(); + + Core::TryLockEntityRequest req; + req.id(m_lockEntityId); // m_lockEntityId > 0 means that a lock is updated + // svcKey : + req.entityTypeName(m_topicInfo.topicName().toStdString() /* + m_topicInfo.workspaceId().toStdString()*/); + req.entityId(m_topicInfo.entityId()); + req.exerciseId(m_exerciseId); + // : svcKey + req.operatorId(sessionData->getOperatorId()); + req.workstationId(sessionData->getWorkstationId()); + + try { - DEBUG_LOG(m_logger) << LOGFUNCTION << ": Topic NOT already locked"; + const Core::TryLockEntityReply reply(m_coreFtc->tryLockEntityRequest(req)); - Q_ASSERT(reply.id() > 0); - m_locked = true; - m_lockEntityId = reply.id(); // only set id if *new lock* was created + TRACE_LOG(m_logger) << LOGFUNCTION << ": Reply received - state=" << objStateAsString() << " - reply=" << reply; + + if (reply.alreadyLocked().is_set()) // has_value not support on windows yet so we need depricated is_set + { + const Core::LockEntityError& alreadyLocked = reply.alreadyLocked().get(); + INFO_LOG(m_logger) << LOGFUNCTION << ": Topic already locked by ws " << alreadyLocked.workstationName() + << " and op " << alreadyLocked.operatorName(); + + // N. Thoden, 23.09.2020: Since Locking is more often, the dialog is annoying. So skip and pay attention to + // title LtsWidgets::LtsMessageDialog::showMessage(nullptr, fro.translated(), tr("Unable to lock data + // record")); + + const auto lockedBy(QStringLiteral("%2/%1").arg(QString::fromStdString(alreadyLocked.operatorName()), + QString::fromStdString(alreadyLocked.workstationName()))); + + emit signalLockDialog(lockedBy); // -> READ_ONLY / lock the dialog as the topic could not be locked + } + else // lock was successful + { + DEBUG_LOG(m_logger) << LOGFUNCTION << ": Topic NOT already locked"; + + Q_ASSERT(reply.id() > 0); + m_locked = true; + m_lockEntityId = reply.id(); // only set id if *new lock* was created + } + } + catch (const std::runtime_error& err) + { + ERROR_LOG(m_logger) << LOGFUNCTION << ": Failed to lock topic! " << err.what(); + Q_ASSERT(false); + return false; } - } - catch (const std::runtime_error &err) - { - ERROR_LOG(m_logger) << LOGFUNCTION << ": Failed to lock topic! " << err.what(); - Q_ASSERT(false); - return false; - } - return true; + return true; } bool TopicLockHandler::unlock() { - INFO_LOG(m_logger) << "UNLOCK " << m_topicInfo.topicName() << " - " << m_lockEntityId; - TRACE_LOG(m_logger) << LOGFUNCTION << objStateAsString(); + INFO_LOG(m_logger) << "UNLOCK " << m_topicInfo.topicName() << " - " << m_lockEntityId; + TRACE_LOG(m_logger) << LOGFUNCTION << objStateAsString(); - if (m_coreFtc == nullptr) - return false; + if (m_coreFtc == nullptr) + return false; - if (!m_locked) - { - ERROR_LOG(m_logger) << LOGFUNCTION << ": Tried to unlock while unlocked.. " << objStateAsString(); - Q_ASSERT(false); - return false; - } + if (!m_locked) + { + ERROR_LOG(m_logger) << LOGFUNCTION << ": Tried to unlock while unlocked.. " << objStateAsString(); + Q_ASSERT(false); + return false; + } - Q_ASSERT(m_lockEntityId > 0); // if unlocking, we need an existing lock id! + Q_ASSERT(m_lockEntityId > 0); // if unlocking, we need an existing lock id! - const Core::TryUnlockEntityRequest req(m_lockEntityId); + const Core::TryUnlockEntityRequest req(m_lockEntityId); - // always set locked to false and remove id - so that a new call to lock is possible - m_locked = false; - m_lockEntityId = 0; + // always set locked to false and remove id - so that a new call to lock is possible + m_locked = false; + m_lockEntityId = 0; - try - { - const auto reply(m_coreFtc->tryUnlockEntityRequest(req)); + try + { + const auto reply(m_coreFtc->tryUnlockEntityRequest(req)); - TRACE_LOG(m_logger) << LOGFUNCTION << ": Reply received - state=" << objStateAsString() - << " - reply=" << reply; + TRACE_LOG(m_logger) << LOGFUNCTION << ": Reply received - state=" << objStateAsString() << " - reply=" << reply; - DEBUG_LOG(m_logger) << LOGFUNCTION << ": Topic unlocked!"; - } - catch (const std::runtime_error &err) - { - ERROR_LOG(m_logger) << LOGFUNCTION << ": Failed to unlock topic! " << err.what(); - return false; - } + DEBUG_LOG(m_logger) << LOGFUNCTION << ": Topic unlocked!"; + } + catch (const std::runtime_error& err) + { + ERROR_LOG(m_logger) << LOGFUNCTION << ": Failed to unlock topic! " << err.what(); + return false; + } + // success + emit signalUnlockDialog(); // -> READ_WRITE - // success - emit signalUnlockDialog(); // -> READ_WRITE + // TODO: emit signalUnlockDialog(); // unlock the dialog (initial state /*is*/ SHOULD be locked) - // TODO: emit signalUnlockDialog(); // unlock the dialog (initial state /*is*/ SHOULD be locked) - - return true; + return true; } - std::string TopicLockHandler::objStateAsString() const { - std::ostringstream o; - o << " m_topicInfoId=" << m_lockEntityId - << ", entityId=" << m_topicInfo.entityId() - << ", exId=" << m_exerciseId - << ", lckd=" << m_locked - << ", asked=" << m_askedForLock - << ", delftrAnwr=" << m_deleteAfterAnswer; - return o.str(); + std::ostringstream o; + o << " m_topicInfoId=" << m_lockEntityId << ", entityId=" << m_topicInfo.entityId() << ", exId=" << m_exerciseId + << ", lckd=" << m_locked << ", asked=" << m_askedForLock << ", delftrAnwr=" << m_deleteAfterAnswer; + return o.str(); } - bool TopicLockHandler::slotUnlock() { - TRACE_LOG(m_logger) << LOGFUNCTION << " slotUnlock" << objStateAsString(); - return unlock(); + TRACE_LOG(m_logger) << LOGFUNCTION << " slotUnlock" << objStateAsString(); + return unlock(); } - -void TopicLockHandler::slotTryLock(const LtsWidgets::TopicInfo &topicInfo) +void TopicLockHandler::slotTryLock(const LtsWidgets::TopicInfo& topicInfo) { - TRACE_LOG(m_logger) << LOGFUNCTION << " START " << objStateAsString(); + TRACE_LOG(m_logger) << LOGFUNCTION << " START " << objStateAsString(); - m_topicInfo = topicInfo; + m_topicInfo = topicInfo; - if (m_topicInfo.topicName().isEmpty() || !topicInfo.isValid()) - { - DEBUG_LOG(m_logger) << LOGFUNCTION << " no lockable topic, that's okay"; - return; - } + if (m_topicInfo.topicName().isEmpty() || !topicInfo.isValid()) + { + DEBUG_LOG(m_logger) << LOGFUNCTION << " no lockable topic, that's okay"; + return; + } - lock(); - TRACE_LOG(m_logger) << LOGFUNCTION << " END " << objStateAsString(); + lock(); + TRACE_LOG(m_logger) << LOGFUNCTION << " END " << objStateAsString(); } - void TopicLockHandler::slotFinalize() { - TRACE_LOG(m_logger) << LOGFUNCTION << " START " << objStateAsString(); + TRACE_LOG(m_logger) << LOGFUNCTION << " START " << objStateAsString(); - if (m_locked) - { - slotUnlock(); // only unlock if locked - } + if (m_locked) + { + slotUnlock(); // only unlock if locked + } - deleteLater(); + deleteLater(); - TRACE_LOG(m_logger) << LOGFUNCTION << " END " << objStateAsString(); + TRACE_LOG(m_logger) << LOGFUNCTION << " END " << objStateAsString(); } //****************************************************************************** // class TopicLockHanderData, used at TacticalOrganisation, OrgChart //****************************************************************************** -TopicLockHanderData::TopicLockHanderData() - : QObject() -{ -} +TopicLockHanderData::TopicLockHanderData() : QObject() {} -void TopicLockHanderData::init(const std::shared_ptr &coreFtc, int exerciseId) +void TopicLockHanderData::init(const std::shared_ptr& coreFtc, int exerciseId) { - m_topicLockHandler = new TopicLockHandler(); - m_topicLockHandler->init(coreFtc, exerciseId); + m_topicLockHandler = new TopicLockHandler(); + m_topicLockHandler->init(coreFtc, exerciseId); - connect(m_topicLockHandler.data(), &TopicLockHandler::signalLockDialog, - this, &TopicLockHanderData::slotLock, Qt::UniqueConnection); - connect(m_topicLockHandler.data(), &TopicLockHandler::signalUnlockDialog, - this, &TopicLockHanderData::slotUnlock, Qt::UniqueConnection); + connect(m_topicLockHandler.data(), &TopicLockHandler::signalLockDialog, this, &TopicLockHanderData::slotLock, + Qt::UniqueConnection); + connect(m_topicLockHandler.data(), &TopicLockHandler::signalUnlockDialog, this, &TopicLockHanderData::slotUnlock, + Qt::UniqueConnection); } TopicLockHanderData::~TopicLockHanderData() { - // ensure cleanup: (must be delayed to process unlock) reply - if (m_topicLockHandler) - m_topicLockHandler->slotFinalize(); + // ensure cleanup: (must be delayed to process unlock) reply + if (m_topicLockHandler) + m_topicLockHandler->slotFinalize(); } void TopicLockHanderData::unlock() { - qDebug() << "Debugname=" << m_debugName << ": " - << " slotUnlock"; - if (m_topicLockHandler) - m_topicLockHandler->slotUnlock(); + qDebug() << "Debugname=" << m_debugName << ": " + << " slotUnlock"; + if (m_topicLockHandler) + m_topicLockHandler->slotUnlock(); } bool TopicLockHanderData::isLocked() const { - if (!m_topicLockHandler) - { + if (!m_topicLockHandler) + { + qDebug() << "Debugname=" << m_debugName << ": " + << " isLocked -> no handler"; + return false; + } qDebug() << "Debugname=" << m_debugName << ": " - << " isLocked -> no handler"; - return false; - } - qDebug() << "Debugname=" << m_debugName << ": " - << " isLocked = " << m_topicLockHandler->isLocked(); - return m_topicLockHandler->isLocked(); + << " isLocked = " << m_topicLockHandler->isLocked(); + return m_topicLockHandler->isLocked(); } LtsWidgets::TopicInfo TopicLockHanderData::getTopicInfo() const { - if (m_topicLockHandler) - return m_topicLockHandler->getTopicInfo(); - return {}; + if (m_topicLockHandler) + return m_topicLockHandler->getTopicInfo(); + return {}; } -void TopicLockHanderData::slotTryLock(const LtsWidgets::TopicInfo &topicInfo) +void TopicLockHanderData::slotTryLock(const LtsWidgets::TopicInfo& topicInfo) { - qDebug() << "Debugname=" << m_debugName << ": " - << "slotTryLock " << m_topicLockHandler; - if (!m_topicLockHandler) - return; - m_topicLockHandler->slotTryLock(topicInfo); + qDebug() << "Debugname=" << m_debugName << ": " + << "slotTryLock " << m_topicLockHandler; + if (!m_topicLockHandler) + return; + m_topicLockHandler->slotTryLock(topicInfo); } - -void TopicLockHanderData::slotLock(const QString &lockedBy) +void TopicLockHanderData::slotLock(const QString& lockedBy) { -// TopicLockHanderData *sender = qobject_cast(sender()); + // TopicLockHanderData *sender = qobject_cast(sender()); - qDebug() << "Debugname=" << m_debugName << ": " - << "slotLock"; - m_lockedBy = lockedBy; - emit lockDataChanged(); + qDebug() << "Debugname=" << m_debugName << ": " + << "slotLock"; + m_lockedBy = lockedBy; + emit lockDataChanged(); } void TopicLockHanderData::slotUnlock() { - qDebug() << "Debugname=" << m_debugName << ": " - << "slotUnlock"; - m_lockedBy.clear(); - emit lockDataChanged(); + qDebug() << "Debugname=" << m_debugName << ": " + << "slotUnlock"; + m_lockedBy.clear(); + emit lockDataChanged(); } - } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.h old mode 100755 new mode 100644 index 835400548..f5780591b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler.h @@ -2,16 +2,13 @@ #ifdef BUILD_RTI +#include #include #include -#include - +#include #include #include -#include - - /* Anmerkungen: slotTryLock @@ -38,73 +35,84 @@ namespace LtsSession { class LTSSESSION_EXPORT TopicLockHandler : public QObject { - Q_OBJECT -public: - TopicLockHandler(); - ~TopicLockHandler(); + Q_OBJECT + public: + TopicLockHandler(); + ~TopicLockHandler(); - bool init(const std::shared_ptr &coreFtc, int exerciseId); + bool init(const std::shared_ptr& coreFtc, int exerciseId); - bool isLocked() const { return m_locked; } - LtsWidgets::TopicInfo getTopicInfo() const { return m_topicInfo; } + bool isLocked() const + { + return m_locked; + } -public slots: - void slotTryLock(const LtsWidgets::TopicInfo &topicInfo); - bool slotUnlock(); - void slotFinalize(); // unlock, finally delete + LtsWidgets::TopicInfo getTopicInfo() const + { + return m_topicInfo; + } -signals: - void signalLockDialog(const QString &lockedBy); - void signalUnlockDialog(); + public slots: + void slotTryLock(const LtsWidgets::TopicInfo& topicInfo); + bool slotUnlock(); + void slotFinalize(); // unlock, finally delete -private: - bool lock(); - bool unlock(); - std::string objStateAsString() const; + signals: + void signalLockDialog(const QString& lockedBy); + void signalUnlockDialog(); - std::shared_ptr m_coreFtc; + private: + bool lock(); + bool unlock(); + std::string objStateAsString() const; - LtsWidgets::TopicInfo m_topicInfo; - int m_lockEntityId{0}; // reply.id(); / set by reply of ddsCall + std::shared_ptr m_coreFtc; - int m_exerciseId{0}; - bool m_locked{false}; - bool m_askedForLock{false}; // reply does not tell.. - bool m_deleteAfterAnswer{false}; + LtsWidgets::TopicInfo m_topicInfo; + int m_lockEntityId{0}; // reply.id(); / set by reply of ddsCall - NGL::INGLLogger &m_logger; + int m_exerciseId{0}; + bool m_locked{false}; + bool m_askedForLock{false}; // reply does not tell.. + bool m_deleteAfterAnswer{false}; + + NGL::INGLLogger& m_logger; }; - class LTSSESSION_EXPORT TopicLockHanderData : public QObject { - Q_OBJECT + Q_OBJECT -public: - TopicLockHanderData(); - ~TopicLockHanderData(); - void init(const std::shared_ptr &coreFtc, int exerciseId); + public: + TopicLockHanderData(); + ~TopicLockHanderData(); + void init(const std::shared_ptr& coreFtc, int exerciseId); - void unlock(); - void slotTryLock(const LtsWidgets::TopicInfo &topicInfo); - bool isLocked() const; - LtsWidgets::TopicInfo getTopicInfo() const; - const QString &getLockedBy() const { return m_lockedBy; } + void unlock(); + void slotTryLock(const LtsWidgets::TopicInfo& topicInfo); + bool isLocked() const; + LtsWidgets::TopicInfo getTopicInfo() const; -Q_SIGNALS: - void lockDataChanged(); + const QString& getLockedBy() const + { + return m_lockedBy; + } -private Q_SLOTS: - void slotLock(const QString &lockedBy); - void slotUnlock(); -public: - QString m_debugName; -private: - QPointer m_topicLockHandler; - QString m_lockedBy; + Q_SIGNALS: + void lockDataChanged(); + + private Q_SLOTS: + void slotLock(const QString& lockedBy); + void slotUnlock(); + + public: + QString m_debugName; + + private: + QPointer m_topicLockHandler; + QString m_lockedBy; }; - } // namespace LtsSession #else // BUILD_RTI diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler_stub.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler_stub.h index 647c51759..3ba1e6456 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler_stub.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_lock_handler_stub.h @@ -8,12 +8,10 @@ #include #include - +#include +#include #include #include -#include - -#include namespace LtsSession { @@ -21,61 +19,100 @@ namespace LtsSession // Stub TopicLockHandler class - minimal version without DDS functionality class LTSSESSION_EXPORT TopicLockHandler : public QObject { - Q_OBJECT -public: - explicit TopicLockHandler(QObject *parent = nullptr) : QObject(parent) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.TopicLockHandler")) - {} - ~TopicLockHandler() override = default; + Q_OBJECT + public: + explicit TopicLockHandler(QObject* parent = nullptr) + : QObject(parent), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.TopicLockHandler")) + { + } - bool init(const void * /*coreFtc*/, int /*exerciseId*/) { return false; } + ~TopicLockHandler() override = default; - bool isLocked() const { return false; } - LtsWidgets::TopicInfo getTopicInfo() const { return LtsWidgets::TopicInfo(); } + bool init(const void* /*coreFtc*/, int /*exerciseId*/) + { + return false; + } -public slots: - void slotTryLock(const LtsWidgets::TopicInfo & /*topicInfo*/) {} - bool slotUnlock() { return false; } - void slotFinalize() { deleteLater(); } + bool isLocked() const + { + return false; + } -signals: - void signalLockDialog(const QString & /*lockedBy*/) {} - void signalUnlockDialog() {} + LtsWidgets::TopicInfo getTopicInfo() const + { + return LtsWidgets::TopicInfo(); + } -private: - NGL::INGLLogger &m_logger; + public slots: + + void slotTryLock(const LtsWidgets::TopicInfo& /*topicInfo*/) {} + + bool slotUnlock() + { + return false; + } + + void slotFinalize() + { + deleteLater(); + } + + signals: + + void signalLockDialog(const QString& /*lockedBy*/) {} + + void signalUnlockDialog() {} + + private: + NGL::INGLLogger& m_logger; }; - class LTSSESSION_EXPORT TopicLockHanderData : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit TopicLockHanderData(QObject *parent = nullptr) : QObject(parent) {} - ~TopicLockHanderData() override = default; - - void init(const void * /*coreFtc*/, int /*exerciseId*/) {} + public: + explicit TopicLockHanderData(QObject* parent = nullptr) : QObject(parent) {} - void unlock() {} - void slotTryLock(const LtsWidgets::TopicInfo & /*topicInfo*/) {} - bool isLocked() const { return false; } - LtsWidgets::TopicInfo getTopicInfo() const { return LtsWidgets::TopicInfo(); } - const QString &getLockedBy() const { return m_lockedBy; } + ~TopicLockHanderData() override = default; -Q_SIGNALS: - void lockDataChanged(); + void init(const void* /*coreFtc*/, int /*exerciseId*/) {} -private Q_SLOTS: - void slotLock(const QString & /*lockedBy*/) {} - void slotUnlock() {} + void unlock() {} -public: - QString m_debugName; -private: - QPointer m_topicLockHandler; - QString m_lockedBy; + void slotTryLock(const LtsWidgets::TopicInfo& /*topicInfo*/) {} + + bool isLocked() const + { + return false; + } + + LtsWidgets::TopicInfo getTopicInfo() const + { + return LtsWidgets::TopicInfo(); + } + + const QString& getLockedBy() const + { + return m_lockedBy; + } + + Q_SIGNALS: + void lockDataChanged(); + + private Q_SLOTS: + + void slotLock(const QString& /*lockedBy*/) {} + + void slotUnlock() {} + + public: + QString m_debugName; + + private: + QPointer m_topicLockHandler; + QString m_lockedBy; }; - } // namespace LtsSession \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.cpp old mode 100755 new mode 100644 index 2c42f3eda..a6ea0a1ad --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.cpp @@ -8,15 +8,15 @@ * Created by Mike Wille, SLSE, 2016-05-15 */ - #include "lts_session_manager.h" + #include "lts_session.h" -#include #include #include -#include #include +#include +#include #include #include #ifdef BUILD_RTI @@ -25,228 +25,212 @@ #include - namespace LtsSession { LtsSessionManager::LtsSessionManager() - : QObject() - , m_appId(LtsAppDescriptor::App::Login) - , m_headless(false) - , m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Manager")) -{} - + : QObject(), m_appId(LtsAppDescriptor::App::Login), m_headless(false), + m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("LtsSession.Manager")) +{ +} LtsSessionManager::~LtsSessionManager() { -// qCritical() << "~LtsSessionManager"; + // qCritical() << "~LtsSessionManager"; - for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) - { - LtsSession *session = i.value(); - session->setInactive(); - session->deleteLater(); - } + for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) + { + LtsSession* session = i.value(); + session->setInactive(); + session->deleteLater(); + } } -bool LtsSessionManager::init(const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList, - LtsAppDescriptor::App appId, - const QString &workspaceId, - bool headless, +bool LtsSessionManager::init(const DdsConnectionParams& connParams, + const QVector& dataPluginList, + const QVector& guiPluginList, + LtsAppDescriptor::App appId, const QString& workspaceId, bool headless, bool hidden) // TODO: what to return ? { - // TODO: check if maps empty? - m_dataPluginList = dataPluginList; - m_guiPluginList = guiPluginList; - m_appId = appId; - m_headless = headless; + // TODO: check if maps empty? + m_dataPluginList = dataPluginList; + m_guiPluginList = guiPluginList; + m_appId = appId; + m_headless = headless; - // shortcut: on first login etc. we go through ExerciseChooser to select an exercise - // but when we're already in the exercise and starting an app from within, - // we don't want to have the exercise chooser a second time -> directly go through app - // and show the base layout + // shortcut: on first login etc. we go through ExerciseChooser to select an exercise + // but when we're already in the exercise and starting an app from within, + // we don't want to have the exercise chooser a second time -> directly go through app + // and show the base layout - // ????? Der Kommentar stimmt leider nicht. Loest leider nicht das Problem. + // ????? Der Kommentar stimmt leider nicht. Loest leider nicht das Problem. - bool bHasBaseLayout = connParams.exerciseId > 0; + bool bHasBaseLayout = connParams.exerciseId > 0; - LtsSession *session = createSession(connParams, bHasBaseLayout, true, hidden); // start Admin Session (for login, etc.) - session->setWorkspaceId(workspaceId); - return session; + LtsSession* session = + createSession(connParams, bHasBaseLayout, true, hidden); // start Admin Session (for login, etc.) + session->setWorkspaceId(workspaceId); + return session; } - -QVector LtsSessionManager::sessions() +QVector LtsSessionManager::sessions() { - return m_sessionMap.values().toVector(); + return m_sessionMap.values().toVector(); -// QVector result; -// for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) -// result.append(i.value()); + // QVector result; + // for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) + // result.append(i.value()); -// return result; + // return result; } - void LtsSessionManager::softQuit() { - for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) - { - LtsSession *session = *i; - session->aboutToClose(); - session->setInactive(); - session->deleteLater(); - } + for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) + { + LtsSession* session = *i; + session->aboutToClose(); + session->setInactive(); + session->deleteLater(); + } - m_sessionMap.clear(); + m_sessionMap.clear(); - emit hideAllOtherBLWs(nullptr); // for tablet mode! shows another hidden session from some other app or maybe the same app, after the visible one was hidden + emit hideAllOtherBLWs(nullptr); // for tablet mode! shows another hidden session from some other app or maybe the + // same app, after the visible one was hidden - QMetaObject::invokeMethod(this, &LtsSessionManager::signalQuit, Qt::QueuedConnection); // wait until all Session's deleteLater is done + QMetaObject::invokeMethod(this, &LtsSessionManager::signalQuit, + Qt::QueuedConnection); // wait until all Session's deleteLater is done } - -LtsSession *LtsSessionManager::createSession(const DdsConnectionParams &connParams, - bool hasBaseLayout, - bool payloads, +LtsSession* LtsSessionManager::createSession(const DdsConnectionParams& connParams, bool hasBaseLayout, bool payloads, bool hidden) { - LtsSession *session = getSession(connParams.partitionType, connParams.partitionId); + LtsSession* session = getSession(connParams.partitionType, connParams.partitionId); - if (session != nullptr) - { - WARNING_LOG(m_logger) << "Tried to create a Session that already exists"; - return nullptr; - } - - session = new LtsSession(this); - - connect(session, &LtsSession::signalQuit, - this, &LtsSessionManager::signalQuit); - // QueuedConnection since Qt5.9.1 seems to send the buttonRelease event again when entering an - // eventloop within this slot. Not yet clear why this happens - connect(session, &LtsSession::signalClose, - this, &LtsSessionManager::slotCloseSession, Qt::QueuedConnection); - connect(session, &LtsSession::signalLogout, - this, &LtsSessionManager::signalLogout); - connect(session, &LtsSession::signalInitializationAborted, - this, &LtsSessionManager::signalInitializationAborted); - connect(session, &LtsSession::hideAllOtherBLWs, - this, &LtsSessionManager::hideAllOtherBLWs); - connect(session, &LtsSession::taskSwitch, - this, &LtsSessionManager::taskSwitch); -#ifdef LTS_DEBUG - connect(session, &LtsSession::signalStillAlive, - this, [this]() - { - LtsSession *session = qobject_cast(sender()); - - for (auto i = m_sessionMap.constBegin(); i != m_sessionMap.constEnd(); ++i) + if (session != nullptr) { - if (i.value() == session) - return; + WARNING_LOG(m_logger) << "Tried to create a Session that already exists"; + return nullptr; } - WARNING_LOG(m_logger) << "Previously deleted Session " << session->partitionId() << "/" - << session->partitionType() << " is still alive!"; - }); + session = new LtsSession(this); + + connect(session, &LtsSession::signalQuit, this, &LtsSessionManager::signalQuit); + // QueuedConnection since Qt5.9.1 seems to send the buttonRelease event again when entering an + // eventloop within this slot. Not yet clear why this happens + connect(session, &LtsSession::signalClose, this, &LtsSessionManager::slotCloseSession, Qt::QueuedConnection); + connect(session, &LtsSession::signalLogout, this, &LtsSessionManager::signalLogout); + connect(session, &LtsSession::signalInitializationAborted, this, &LtsSessionManager::signalInitializationAborted); + connect(session, &LtsSession::hideAllOtherBLWs, this, &LtsSessionManager::hideAllOtherBLWs); + connect(session, &LtsSession::taskSwitch, this, &LtsSessionManager::taskSwitch); +#ifdef LTS_DEBUG + connect(session, &LtsSession::signalStillAlive, this, [this]() { + LtsSession* session = qobject_cast(sender()); + + for (auto i = m_sessionMap.constBegin(); i != m_sessionMap.constEnd(); ++i) + { + if (i.value() == session) + return; + } + + WARNING_LOG(m_logger) << "Previously deleted Session " << session->partitionId() << "/" + << session->partitionType() << " is still alive!"; + }); #endif - if (hasBaseLayout) - session->setBaseLayoutVisible(); // after payloads are done (if any), the base layout will be created + if (hasBaseLayout) + session->setBaseLayoutVisible(); // after payloads are done (if any), the base layout will be created - if (payloads) - session->setPayloadsEnabled(); + if (payloads) + session->setPayloadsEnabled(); - m_sessionMap[SessionKey(connParams.partitionType, connParams.partitionId)] = session; + m_sessionMap[SessionKey(connParams.partitionType, connParams.partitionId)] = session; - - LtsSession *globSession = getSession(IDL::PartitionType::Global, 0); - if (globSession && globSession->ddsConnector() && globSession->domainId() == connParams.domainId) - { - - dds::domain::DomainParticipant dp = globSession->ddsConnector()->getDomainParticipant(); - if (!session->init(dp, connParams, m_dataPluginList, m_guiPluginList)) // init not successful? return invalid ptr + LtsSession* globSession = getSession(IDL::PartitionType::Global, 0); + if (globSession && globSession->ddsConnector() && globSession->domainId() == connParams.domainId) { - session->deleteLater(); - return nullptr; - } - } - else - { - /* - * init SOLLTE asynchron ablaufen. - * init läuft aber synchron, da die Payloads der Plugins DIrectConnections benutzen. - * AUf QueuedCOnnections umbauen ist schwerer, da init mit einem SessionCount von 0 rechnet, da init blocking ist und es daher nicht zum aufruf m_sessionMap[...] = ...; kommt...... - */ - if (!session->init(connParams, m_dataPluginList, m_guiPluginList, hidden)) // init not successful? return invalid ptr + dds::domain::DomainParticipant dp = globSession->ddsConnector()->getDomainParticipant(); + if (!session->init(dp, connParams, m_dataPluginList, + m_guiPluginList)) // init not successful? return invalid ptr + { + session->deleteLater(); + return nullptr; + } + } + else { - session->deleteLater(); - return nullptr; + /* + * init SOLLTE asynchron ablaufen. + * init läuft aber synchron, da die Payloads der Plugins DIrectConnections benutzen. + * AUf QueuedCOnnections umbauen ist schwerer, da init mit einem SessionCount von 0 rechnet, da init blocking + * ist und es daher nicht zum aufruf m_sessionMap[...] = ...; kommt...... + */ + + if (!session->init(connParams, m_dataPluginList, m_guiPluginList, + hidden)) // init not successful? return invalid ptr + { + session->deleteLater(); + return nullptr; + } } - } + if (session->isInitializationDone()) + QMetaObject::invokeMethod(this, &LtsSessionManager::signalInitializationFinished, Qt::QueuedConnection); + else + connect(session, &LtsSession::signalDoneInitializingSession, this, + &LtsSessionManager::signalInitializationFinished, Qt::QueuedConnection); - if (session->isInitializationDone()) - QMetaObject::invokeMethod(this, &LtsSessionManager::signalInitializationFinished, - Qt::QueuedConnection); - else - connect(session, &LtsSession::signalDoneInitializingSession, - this, &LtsSessionManager::signalInitializationFinished, - Qt::QueuedConnection); - - - return session; + return session; } - void LtsSessionManager::slotCloseSession() { - LtsSession *session = qobject_cast(QObject::sender()); + LtsSession* session = qobject_cast(QObject::sender()); - if (!session) - { - FATAL_LOG(m_logger) << "LtsSessionManager: slot called without object - so it cannot be deleted from the session list!"; - return; - } - - bool found = false; - for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) - { - if (i.value() == session) + if (!session) { - const auto key = i.key(); - session->aboutToClose(); - session->setInactive(); - session->deleteLater(); - m_sessionMap.remove(key); // when destruction takes a long time, a new session may have been added which invalidated the iterator - - found = true; - break; + FATAL_LOG(m_logger) + << "LtsSessionManager: slot called without object - so it cannot be deleted from the session list!"; + return; } - } - if (!found) - FATAL_LOG(m_logger) << "LtsSessionManager: Cannot find Session in map!"; + bool found = false; + for (auto i = m_sessionMap.begin(); i != m_sessionMap.end(); ++i) + { + if (i.value() == session) + { + const auto key = i.key(); + session->aboutToClose(); + session->setInactive(); + session->deleteLater(); + m_sessionMap.remove(key); // when destruction takes a long time, a new session may have been added which + // invalidated the iterator - emit hideAllOtherBLWs(nullptr); // for tablet mode! shows another hidden session from some other app or maybe the same app, after the visible one was hidden + found = true; + break; + } + } - if (m_sessionMap.isEmpty()) // quit app if all sessions closed - emit signalQuit(); + if (!found) + FATAL_LOG(m_logger) << "LtsSessionManager: Cannot find Session in map!"; + + emit hideAllOtherBLWs(nullptr); // for tablet mode! shows another hidden session from some other app or maybe the + // same app, after the visible one was hidden + + if (m_sessionMap.isEmpty()) // quit app if all sessions closed + emit signalQuit(); } - -LtsSession *LtsSessionManager::getSession(IDL::PartitionType partitionType, int partitionId) +LtsSession* LtsSessionManager::getSession(IDL::PartitionType partitionType, int partitionId) { - auto it = m_sessionMap.find(SessionKey(partitionType, partitionId)); + auto it = m_sessionMap.find(SessionKey(partitionType, partitionId)); - if (it != m_sessionMap.end()) // session found? return it! - return it.value(); + if (it != m_sessionMap.end()) // session found? return it! + return it.value(); - return nullptr; // not found + return nullptr; // not found } } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.h old mode 100755 new mode 100644 index f67217dc3..c6eb0b22d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsSession/lts_session_manager.h @@ -10,28 +10,26 @@ #pragma once -#include +#include #include #include -#include - -#include -#include -#include -#include +#include #include - +#include +#include +#include +#include namespace NGL { class INGLLogger; } + namespace DeveloperTools { class AppWidget; } - namespace LtsSession { class LtsSession; @@ -39,76 +37,86 @@ struct DdsConnectionParams; class LTSSESSION_EXPORT LtsSessionManager : public QObject { - Q_OBJECT + Q_OBJECT -public: - LtsSessionManager(); - ~LtsSessionManager(); + public: + LtsSessionManager(); + ~LtsSessionManager(); - // create a new session, return old session if already exists [allowClosingSession => true => base layout close = close session | false => base layout close = base layout hide + session still open] - LtsSession *createSession(const DdsConnectionParams &connParams, - bool hasBaseLayout = true, - bool payloads = true, - bool hidden = false); - // return an already created session or null + // create a new session, return old session if already exists [allowClosingSession => true => base layout close = + // close session | false => base layout close = base layout hide + session still open] + LtsSession* createSession(const DdsConnectionParams& connParams, bool hasBaseLayout = true, bool payloads = true, + bool hidden = false); + // return an already created session or null - LtsSession *getSession(IDL::PartitionType partitionType, int partitionId); - bool init(const DdsConnectionParams &connParams, - const QVector &dataPluginList, - const QVector &guiPluginList, - LtsAppDescriptor::App appId, const QString &workspaceId, - bool headless, bool hidden); - int sessionCount() const { return m_sessionMap.count(); } - LtsAppDescriptor::App appId() const { return m_appId; } - bool isHeadless() const { return m_headless; } - QVector sessions(); - void softQuit(); + LtsSession* getSession(IDL::PartitionType partitionType, int partitionId); + bool init(const DdsConnectionParams& connParams, const QVector& dataPluginList, + const QVector& guiPluginList, LtsAppDescriptor::App appId, + const QString& workspaceId, bool headless, bool hidden); -private: - friend class DeveloperTools::DevDialog; - friend class DeveloperTools::AppWidget; - - struct SessionKey - { - SessionKey(IDL::PartitionType pt = IDL::PartitionType::Any, int pId = 0) - : partitionType(pt) - , partitionId(pId) - {} - IDL::PartitionType partitionType; - int partitionId; - - bool operator<(const SessionKey &o) const + int sessionCount() const { - if (partitionType != o.partitionType) - return partitionType < o.partitionType; - return partitionId < o.partitionId; + return m_sessionMap.count(); } - }; - void logout(); - void addPayloads(LtsSession *session); + LtsAppDescriptor::App appId() const + { + return m_appId; + } - QMap m_sessionMap; - QVector m_dataPluginList; - QVector m_guiPluginList; - LtsAppDescriptor::App m_appId; - bool m_headless; - NGL::INGLLogger &m_logger; + bool isHeadless() const + { + return m_headless; + } -private slots: - void slotCloseSession(); + QVector sessions(); + void softQuit(); -signals: - /** - * @brief signalStopBlock (see slotCloseRequest) - */ - void signalStopBlock(); - void signalLogout(); - void signalQuit(); - void signalInitializationFinished(); - void signalInitializationAborted(); - void hideAllOtherBLWs(QObject *caller); - void taskSwitch(QObject *caller); + private: + friend class DeveloperTools::DevDialog; + friend class DeveloperTools::AppWidget; + + struct SessionKey + { + SessionKey(IDL::PartitionType pt = IDL::PartitionType::Any, int pId = 0) : partitionType(pt), partitionId(pId) + { + } + + IDL::PartitionType partitionType; + int partitionId; + + bool operator<(const SessionKey& o) const + { + if (partitionType != o.partitionType) + return partitionType < o.partitionType; + return partitionId < o.partitionId; + } + }; + + void logout(); + void addPayloads(LtsSession* session); + + QMap m_sessionMap; + QVector m_dataPluginList; + QVector m_guiPluginList; + LtsAppDescriptor::App m_appId; + bool m_headless; + NGL::INGLLogger& m_logger; + + private slots: + void slotCloseSession(); + + signals: + /** + * @brief signalStopBlock (see slotCloseRequest) + */ + void signalStopBlock(); + void signalLogout(); + void signalQuit(); + void signalInitializationFinished(); + void signalInitializationAborted(); + void hideAllOtherBLWs(QObject* caller); + void taskSwitch(QObject* caller); }; } // namespace LtsSession diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.cpp old mode 100755 new mode 100644 index 2eec74152..180efdeba --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.cpp @@ -1,16 +1,13 @@ - #include "item.h" #include -#include -#include -#include -#include - #include - +#include +#include +#include +#include namespace LtsTimeline { @@ -19,27 +16,21 @@ QString Item::mimetype = QStringLiteral("application/rheinmetall.timeline.item") QColor Item::s_highlightColor = QRgb(0x43b0e0); - -Item::Item(qint64 startTime, int duration, const QColor &color, bool isEditable) - : m_color(color) - , m_startTime(startTime) - , m_duration(duration) - , m_isEditable(isEditable) -{} - - - - -void Item::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &, bool highlight) const +Item::Item(qint64 startTime, int duration, const QColor& color, bool isEditable) + : m_color(color), m_startTime(startTime), m_duration(duration), m_isEditable(isEditable) { - painter->save(); - if (highlight) - painter->setPen(QPen(QBrush(s_highlightColor), 5)); - else - painter->setPen(QPen(QBrush(Qt::black), 1)); - painter->setBrush(QBrush(m_color)); - painter->drawRect(option.rect); - painter->restore(); } -} +void Item::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex&, bool highlight) const +{ + painter->save(); + if (highlight) + painter->setPen(QPen(QBrush(s_highlightColor), 5)); + else + painter->setPen(QPen(QBrush(Qt::black), 1)); + painter->setBrush(QBrush(m_color)); + painter->drawRect(option.rect); + painter->restore(); +} + +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.h old mode 100755 new mode 100644 index 759133f4c..497840f81 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item.h @@ -1,15 +1,12 @@ - #pragma once #include "ltstimeline_export.h" #include - +#include #include -#include - class QPainter; class QStyleOptionViewItem; @@ -20,61 +17,102 @@ namespace PresentationManagement class ScriptModel; } - namespace LtsTimeline { class ItemDelegate; - class LTSTIMELINE_EXPORT Item { - friend class ItemDelegate; + friend class ItemDelegate; -public: - static QString mimetype; - static QColor s_highlightColor; + public: + static QString mimetype; + static QColor s_highlightColor; - Item() = default; - Item(qint64 startTime, int duration, const QColor &color, bool isEditable = true); - Item(const Item &) = delete; - Item &operator=(const Item &) = delete; - Item(Item &&) noexcept = default; - virtual ~Item() = default; + Item() = default; + Item(qint64 startTime, int duration, const QColor& color, bool isEditable = true); + Item(const Item&) = delete; + Item& operator=(const Item&) = delete; + Item(Item&&) noexcept = default; + virtual ~Item() = default; - int id() const { return m_id; } - int parentTrackId() const { return m_parentTrackId; } + int id() const + { + return m_id; + } - QColor color() const { return m_color; } - void setColor(const QColor &color) { m_color = color; } + int parentTrackId() const + { + return m_parentTrackId; + } - qint64 startTime() const { return m_startTime; } - [[deprecated("use model's setItemStartTime instead, needed to notify the model that it has to re-sort items")]] - void setStartTime(qint64 startTime) { m_startTime = startTime; } + QColor color() const + { + return m_color; + } - int duration() const { return m_duration; } - void setDuration(int duration) { m_duration = duration; } + void setColor(const QColor& color) + { + m_color = color; + } - bool isEditable() const { return m_isEditable; } - void setEditable(bool editable) { m_isEditable = editable; } + qint64 startTime() const + { + return m_startTime; + } - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index, bool highlight = false) const; + [[deprecated("use model's setItemStartTime instead, needed to notify the model that it has to re-sort items")]] void + setStartTime(qint64 startTime) + { + m_startTime = startTime; + } - void _setStartTime(qint64 startTime) { m_startTime = startTime; } - void _setDuration(int duration) { m_duration = duration; } + int duration() const + { + return m_duration; + } -protected: - QColor m_color; - qint64 m_startTime { -1 }; - int m_duration { -1 }; - bool m_isEditable { false }; + void setDuration(int duration) + { + m_duration = duration; + } -private: - friend class TimelineModel; - friend class PresentationManagement::ScriptModel; + bool isEditable() const + { + return m_isEditable; + } - int m_id { -1 }; - int m_parentTrackId { -1 }; + void setEditable(bool editable) + { + m_isEditable = editable; + } + + virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index, + bool highlight = false) const; + + void _setStartTime(qint64 startTime) + { + m_startTime = startTime; + } + + void _setDuration(int duration) + { + m_duration = duration; + } + + protected: + QColor m_color; + qint64 m_startTime{-1}; + int m_duration{-1}; + bool m_isEditable{false}; + + private: + friend class TimelineModel; + friend class PresentationManagement::ScriptModel; + + int m_id{-1}; + int m_parentTrackId{-1}; }; typedef std::unique_ptr ItemPtr; @@ -84,4 +122,4 @@ typedef std::reference_wrapper ItemPtrNCVRef; typedef std::vector ItemPtrNCVRefs; typedef std::vector ItemPtrRefs; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.cpp old mode 100755 new mode 100644 index 51aeb4b31..c60835039 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.cpp @@ -1,185 +1,171 @@  - #include "item_delegate.h" -#include "item.h" -#include "track.h" -#include "timeline_view.h" +#include "item.h" +#include "timeline_view.h" +#include "track.h" + +#include #include #include #include #include -#include - namespace LtsTimeline { -ItemDelegate::ItemDelegate(TimelineView *parent) - : QStyledItemDelegate(parent) - , m_view(parent) - , m_pushButton(new QPushButton) - , m_pushButtonPressed(new QPushButton) +ItemDelegate::ItemDelegate(TimelineView* parent) + : QStyledItemDelegate(parent), m_view(parent), m_pushButton(new QPushButton), m_pushButtonPressed(new QPushButton) { - m_pushButtonPressed->setDown(true); + m_pushButtonPressed->setDown(true); } ItemDelegate::~ItemDelegate() { - m_pushButton->deleteLater(); - m_pushButton = nullptr; - m_pushButtonPressed->deleteLater(); - m_pushButtonPressed = nullptr; + m_pushButton->deleteLater(); + m_pushButton = nullptr; + m_pushButtonPressed->deleteLater(); + m_pushButtonPressed = nullptr; } - - - -QSize ItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +QSize ItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - Q_UNUSED(option); - Q_UNUSED(index); - return QSize(100, 50); + Q_UNUSED(option); + Q_UNUSED(index); + return QSize(100, 50); } -void ItemDelegate::paintDragItems(QPainter *painter) const +void ItemDelegate::paintDragItems(QPainter* painter) const { - painter->save(); - - const QRect rightSectionRect = QRect(QPoint(m_view->m_header->sectionPosition(Section::eItems), 0), - QPoint(m_view->geometry().right(), m_view->geometry().bottom())); - painter->setClipRect(rightSectionRect); - - int dx = m_view->m_dragHandler->deltaX(); - int dy = m_view->m_dragHandler->deltaY(); - try - { - for (const int &itemId : m_view->m_dragHandler->m_dragItemIds) - { - Item &item = m_view->timelineModel()->item(itemId); - if (item.startTime() + item.duration() < m_view->currentTime()) - continue; - - if (item.startTime() > m_view->endTime()) - break; - - - - const QModelIndex rowIndex(m_view->timelineModel()->indexOfTrack(item.parentTrackId())); - const QModelIndex columnIndex(m_view->timelineModel()->index(rowIndex.row(), 1, rowIndex.parent())); - const QRect visualRect(m_view->visualRect(columnIndex)); - int left = m_view->toPixel(item.startTime()) + dx; - int right = m_view->toPixel(item.startTime() + item.duration()) + dx; - int top = visualRect.top() + dy; - int bottom = visualRect.bottom() + dy; - QStyleOptionViewItem option; - option.rect = QRect(left, top, right - left - 1, bottom - top); - item.paint(painter, option, columnIndex, m_view->selectedItemIds().contains(itemId)); - } - } - catch (...) {} - - painter->restore(); -} - - -void ItemDelegate::paintTrackButtons(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - try - { - - const Track &track = m_view->timelineModel()->track(index.data(Qt::UserRole).toInt()); - - int buttonLength = option.rect.height() / 2; - if (track.hasInsertButton()) - { - QPushButton *button = m_view->m_trackHandler->isInsertButtonPressed(index) ? m_pushButtonPressed : m_pushButton; - QRect rect = QRect(0, 0, buttonLength, buttonLength); - button->setGeometry(rect); - button->setText(QStringLiteral("+")); - button->setEnabled(m_view->timelineModel()->isEditable()); - QPixmap map = button->grab(); - painter->drawPixmap(option.rect.right() - buttonLength, option.rect.top(), map); - } - if (track.hasRemoveButton()) - { - QPushButton *button = m_view->m_trackHandler->isRemoveButtonPressed(index) ? m_pushButtonPressed : m_pushButton; - QRect rect = QRect(0, 0, buttonLength, buttonLength); - button->setGeometry(rect); - button->setText(QStringLiteral("-")); - button->setEnabled(m_view->timelineModel()->isEditable()); - QPixmap map = button->grab(); - painter->drawPixmap(option.rect.right() - buttonLength, option.rect.center().y(), map); - } - } - catch (...) {} -} - - - - -void ItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - if (index.column() == Section::eActuator) - { painter->save(); - QStyledItemDelegate::paint(painter, option, index); - paintTrackButtons(painter, option, index); + + const QRect rightSectionRect = QRect(QPoint(m_view->m_header->sectionPosition(Section::eItems), 0), + QPoint(m_view->geometry().right(), m_view->geometry().bottom())); + painter->setClipRect(rightSectionRect); + + int dx = m_view->m_dragHandler->deltaX(); + int dy = m_view->m_dragHandler->deltaY(); + try + { + for (const int& itemId : m_view->m_dragHandler->m_dragItemIds) + { + Item& item = m_view->timelineModel()->item(itemId); + if (item.startTime() + item.duration() < m_view->currentTime()) + continue; + + if (item.startTime() > m_view->endTime()) + break; + + const QModelIndex rowIndex(m_view->timelineModel()->indexOfTrack(item.parentTrackId())); + const QModelIndex columnIndex(m_view->timelineModel()->index(rowIndex.row(), 1, rowIndex.parent())); + const QRect visualRect(m_view->visualRect(columnIndex)); + int left = m_view->toPixel(item.startTime()) + dx; + int right = m_view->toPixel(item.startTime() + item.duration()) + dx; + int top = visualRect.top() + dy; + int bottom = visualRect.bottom() + dy; + QStyleOptionViewItem option; + option.rect = QRect(left, top, right - left - 1, bottom - top); + item.paint(painter, option, columnIndex, m_view->selectedItemIds().contains(itemId)); + } + } + catch (...) + { + } + painter->restore(); - return; - } +} - auto drawItem = [this, &option, &painter, &index](const Item &item) - { +void ItemDelegate::paintTrackButtons(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + try + { + const Track& track = m_view->timelineModel()->track(index.data(Qt::UserRole).toInt()); + int buttonLength = option.rect.height() / 2; + if (track.hasInsertButton()) + { + QPushButton* button = + m_view->m_trackHandler->isInsertButtonPressed(index) ? m_pushButtonPressed : m_pushButton; + QRect rect = QRect(0, 0, buttonLength, buttonLength); + button->setGeometry(rect); + button->setText(QStringLiteral("+")); + button->setEnabled(m_view->timelineModel()->isEditable()); + QPixmap map = button->grab(); + painter->drawPixmap(option.rect.right() - buttonLength, option.rect.top(), map); + } + if (track.hasRemoveButton()) + { + QPushButton* button = + m_view->m_trackHandler->isRemoveButtonPressed(index) ? m_pushButtonPressed : m_pushButton; + QRect rect = QRect(0, 0, buttonLength, buttonLength); + button->setGeometry(rect); + button->setText(QStringLiteral("-")); + button->setEnabled(m_view->timelineModel()->isEditable()); + QPixmap map = button->grab(); + painter->drawPixmap(option.rect.right() - buttonLength, option.rect.center().y(), map); + } + } + catch (...) + { + } +} - - - - if (m_view->timelineModel()->isEditable()) - if (m_view->m_dragHandler->m_dragItemIds.contains(item.id())) +void ItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + if (index.column() == Section::eActuator) + { + painter->save(); + QStyledItemDelegate::paint(painter, option, index); + paintTrackButtons(painter, option, index); + painter->restore(); return; - - QStyleOptionViewItem opt = option; - opt.rect.setLeft(std::max(m_view->toPixel(item.startTime()), option.rect.left())); - opt.rect.setRight(std::min(m_view->toPixel(item.startTime() + item.duration()), option.rect.right()) - 1); - item.paint(painter, opt, index, m_view->selectedItemIds().contains(item.id())); - }; - - try - { - const Track &track = m_view->timelineModel()->track(index.data().toInt()); - painter->save(); - - - painter->setClipping(true); - painter->setClipRect(option.rect); - - const Items &items = track.items(); - for (const ItemPtr &item : items) - drawItem(static_cast(*item.get())); - const QSet copyItemIds = track.copyItemIds(); - for (const int &itemId : copyItemIds) - { - try - { - const Item &item = m_view->timelineModel()->item(itemId); - drawItem(item); - } - catch(...) - { - fprintf(stderr, "ItemDelegate::paint: cannot find item copy of %d\n", itemId); - } } - painter->restore(); - } - catch (...) - { - ERROR_LOG(m_view->m_logger) << "ItemDelegate::paint -> CATCH"; - } + auto drawItem = [this, &option, &painter, &index](const Item& item) { + if (m_view->timelineModel()->isEditable()) + if (m_view->m_dragHandler->m_dragItemIds.contains(item.id())) + return; + + QStyleOptionViewItem opt = option; + opt.rect.setLeft(std::max(m_view->toPixel(item.startTime()), option.rect.left())); + opt.rect.setRight(std::min(m_view->toPixel(item.startTime() + item.duration()), option.rect.right()) - 1); + item.paint(painter, opt, index, m_view->selectedItemIds().contains(item.id())); + }; + + try + { + const Track& track = m_view->timelineModel()->track(index.data().toInt()); + painter->save(); + + painter->setClipping(true); + painter->setClipRect(option.rect); + + const Items& items = track.items(); + for (const ItemPtr& item : items) + drawItem(static_cast(*item.get())); + const QSet copyItemIds = track.copyItemIds(); + for (const int& itemId : copyItemIds) + { + try + { + const Item& item = m_view->timelineModel()->item(itemId); + drawItem(item); + } + catch (...) + { + fprintf(stderr, "ItemDelegate::paint: cannot find item copy of %d\n", itemId); + } + } + + painter->restore(); + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << "ItemDelegate::paint -> CATCH"; + } } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.h old mode 100755 new mode 100644 index 674281038..dc59281da --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/item_delegate.h @@ -1,14 +1,11 @@ - #pragma once -#include - #include "ltstimeline_export.h" -#include +#include #include - +#include namespace LtsTimeline { @@ -16,33 +13,28 @@ namespace LtsTimeline class TimelineView; class TimelineModel; - class LTSTIMELINE_EXPORT ItemDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT -public: - ItemDelegate(TimelineView *parent = nullptr); - ~ItemDelegate(); + public: + ItemDelegate(TimelineView* parent = nullptr); + ~ItemDelegate(); - + QSize sizeHint(const QStyleOptionViewItem& option = {}, const QModelIndex& index = {}) const override; - QSize sizeHint(const QStyleOptionViewItem &option = {}, const QModelIndex &index = {}) const override; + virtual void paintDragItems(QPainter* painter) const; + virtual void paintTrackButtons(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const; - + protected: + virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - virtual void paintDragItems(QPainter *painter) const; - virtual void paintTrackButtons(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; - -protected: - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - -protected: - TimelineView *m_view { nullptr }; - - QPushButton *m_pushButton { nullptr }; - QPushButton *m_pushButtonPressed { nullptr }; + protected: + TimelineView* m_view{nullptr}; + QPushButton* m_pushButton{nullptr}; + QPushButton* m_pushButtonPressed{nullptr}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/main.cpp old mode 100755 new mode 100644 index 36556030d..aba30c1d2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/main.cpp @@ -1,289 +1,218 @@ -#include -#include -#include -#include - #include -#include - #include #include - - - - - - - - - - - - +#include +#include +#include +#include +#include using namespace LtsTimeline; - - - - - - class AbstractStuff { -public: - virtual void thing() = 0; + public: + virtual void thing() = 0; }; - class TheStuff : public AbstractStuff { - void thing() override { fprintf(stderr, "thing() !\n"); } + void thing() override + { + fprintf(stderr, "thing() !\n"); + } }; - std::unique_ptr get() { - return std::make_unique(std::move(TheStuff())); + return std::make_unique(std::move(TheStuff())); } - std::vector> test; - -void move(std::unique_ptr &&stuff) +void move(std::unique_ptr&& stuff) { - test.push_back(std::move(stuff)); + test.push_back(std::move(stuff)); } - - - - -void populateModel(LtsTimeline::TimelineModel *model) +void populateModel(LtsTimeline::TimelineModel* model) { - { - std::unique_ptr asp = get(); - move(std::move(asp)); - } - - { - AbstractStuff &as = *test.front(); - as.thing(); - } - - + { + std::unique_ptr asp = get(); + move(std::move(asp)); + } + { + AbstractStuff& as = *test.front(); + as.thing(); + } #define l() qCritical() - qint64 rtlnau = QDateTime::currentMSecsSinceEpoch(); + qint64 rtlnau = QDateTime::currentMSecsSinceEpoch(); - class TestItem : public Item - { - public: - TestItem(qint64 startTime, int duration, const QColor &color, bool isEditable = true) - : Item(startTime, duration, color, isEditable) - , m_1234(1234) - {} + class TestItem : public Item + { + public: + TestItem(qint64 startTime, int duration, const QColor& color, bool isEditable = true) + : Item(startTime, duration, color, isEditable), m_1234(1234) + { + } - int get1234() const { return m_1234; } + int get1234() const + { + return m_1234; + } - private: - int m_1234 { 9876 }; - }; + private: + int m_1234{9876}; + }; + int trackId; + int itemId; - int trackId; - int itemId; + model->addTrack(0, Track(QStringLiteral("1st Track"))); + model->addItem(1, Item(rtlnau + 120'000, 30'000, Qt::green)); - + int firstChildId = model->addTrack(1, Track(QStringLiteral("1st Track's 1st Child"))); + model->addItem(2, Item(rtlnau + 180'000, 30'000, Qt::magenta)); + l() << "firstChildId:" << firstChildId; + model->addTrack(0, Track(QStringLiteral("2nd Track"))); + model->addItem(3, Item(rtlnau + 120'000, 60'000, Qt::blue)); + model->addItem(3, Item(rtlnau + 60'000, 30'000, Qt::red)); - - model->addTrack(0, Track(QStringLiteral("1st Track"))); - model->addItem(1, Item(rtlnau + 120'000, 30'000, Qt::green)); + model->addTrack(0, Track(QStringLiteral("3rd Track"))); + model->addItem(4, Item(rtlnau + 150'000, 60'000, Qt::yellow)); + model->addItem(4, TestItem(rtlnau + 90'000, 30'000, Qt::cyan)); - int firstChildId = - model->addTrack(1, Track(QStringLiteral("1st Track's 1st Child"))); - model->addItem(2, Item(rtlnau + 180'000, 30'000, Qt::magenta)); - l() << "firstChildId:" << firstChildId; + model->print(true); - model->addTrack(0, Track(QStringLiteral("2nd Track"))); - model->addItem(3, Item(rtlnau + 120'000, 60'000, Qt::blue)); - model->addItem(3, Item(rtlnau + 60'000, 30'000, Qt::red)); + try + { + const TestItem& testItem = dynamic_cast(model->item(5)); + } + catch (const std::exception& ex) + { + l() << "dynamic_cast back to TestItem failed!" << ex.what(); + } - model->addTrack(0, Track(QStringLiteral("3rd Track"))); - model->addItem(4, Item(rtlnau + 150'000, 60'000, Qt::yellow)); - model->addItem(4, TestItem(rtlnau + 90'000, 30'000, Qt::cyan)); + (void)itemId; + (void)trackId; + qint64 now = rtlnau; - - model->print(true); - - - - try - { - const TestItem &testItem = dynamic_cast(model->item(5)); - - } - catch(const std::exception &ex) - { - l() << "dynamic_cast back to TestItem failed!" << ex.what(); - } - - - (void)itemId; - (void)trackId; - - - - qint64 now = rtlnau; - - { + { #define non_strict false #define strict true #define recursive true #define sorted true #define unsorted false - QVector x; - bool y; + QVector x; + bool y; + x = model->itemIdsBetween(now + 60'000 + 1, now + 150'000 - 1, non_strict, recursive); - - x = model->itemIdsBetween(now + 60'000 + 1, now + 150'000 - 1, non_strict, recursive); - + x = model->itemIdsBetween(now + 60'000 + 1, now + 150'000 - 1, strict, recursive); - x = model->itemIdsBetween(now + 60'000 + 1, now + 150'000 - 1, strict, recursive); - + y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, -1, non_strict, recursive); + y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, -1, strict, recursive); - y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, -1, non_strict, recursive); - + y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, 5, non_strict, recursive); - y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, -1, strict, recursive); - + y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, 5, strict, recursive); + x = model->itemIdsBetween(now + 60'000, now + 150'000, non_strict, recursive); - y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, 5, non_strict, recursive); - + x = model->itemIdsBetween(now + 60'000, now + 150'000, strict, recursive); - y = model->isItemsBetween(now + 60'000 + 1, now + 150'000 - 1, 5, strict, recursive); - + y = model->isItemsBetween(now + 60'000, now + 150'000, -1, non_strict, recursive); + y = model->isItemsBetween(now + 60'000, now + 150'000, -1, strict, recursive); + y = model->isItemsBetween(now + 60'000, now + 150'000, 5, non_strict, recursive); - - x = model->itemIdsBetween(now + 60'000, now + 150'000, non_strict, recursive); - + y = model->isItemsBetween(now + 60'000, now + 150'000, 5, strict, recursive); - x = model->itemIdsBetween(now + 60'000, now + 150'000, strict, recursive); - + y = model->isItemsBetween(now + 60'000, now + 150'000, QVector({0, 3, 5}), strict, recursive); + y = model->isItemsBetween(now + 60'000, now + 150'000, QVector({0, 5}), strict, recursive); - y = model->isItemsBetween(now + 60'000, now + 150'000, -1, non_strict, recursive); - - - y = model->isItemsBetween(now + 60'000, now + 150'000, -1, strict, recursive); - - - - y = model->isItemsBetween(now + 60'000, now + 150'000, 5, non_strict, recursive); - - - y = model->isItemsBetween(now + 60'000, now + 150'000, 5, strict, recursive); - - - - y = model->isItemsBetween(now + 60'000, now + 150'000, QVector({ 0, 3, 5 }), strict, recursive); - - - y = model->isItemsBetween(now + 60'000, now + 150'000, QVector({ 0, 5 }), strict, recursive); - - - - - x = model->itemIdsBetween(0, now + 999'000, non_strict, recursive, sorted); - // l() << "itemIdsBetween(0, now + 999'000, non_strict, recursive, sorted)" << x << "- okay?" << (x == QVector({ 3, 5, 0, 2, 4, 1 })); + x = model->itemIdsBetween(0, now + 999'000, non_strict, recursive, sorted); + // l() << "itemIdsBetween(0, now + 999'000, non_strict, recursive, sorted)" << x << "- okay?" << (x == + // QVector({ 3, 5, 0, 2, 4, 1 })); #undef non_strict #undef strict #undef recursive #undef unsorted #undef sorted - } + } + try + { + // item 1 von track 2 auf track 3, zu startTime 210'000 + model->moveItemToTrack(1, 3, now + 210'000); + } + catch (...) + { + fprintf(stderr, "That didn't work. %s:%d\n", __FUNCTION__, __LINE__); + } - try - { - // item 1 von track 2 auf track 3, zu startTime 210'000 - model->moveItemToTrack(1, 3, now + 210'000); - } - catch(...) - { - fprintf(stderr, "That didn't work. %s:%d\n", __FUNCTION__, __LINE__); - } + model->print(true); + try + { + // item 3 von track 3 auf track 2, zu startTime 150'000 + model->moveItemToTrack(3, 2, now + 150'000); + } + catch (...) + { + fprintf(stderr, "That didn't work. %s:%d\n", __FUNCTION__, __LINE__); + } - model->print(true); - - - try - { - // item 3 von track 3 auf track 2, zu startTime 150'000 - model->moveItemToTrack(3, 2, now + 150'000); - } - catch(...) - { - fprintf(stderr, "That didn't work. %s:%d\n", __FUNCTION__, __LINE__); - } - - - /* now - /30 /60 /90 /120 /150 /180 /210 /240 - | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | - T1 000000000 - >T2 333333333 - T3 2222222222222222111111111 - T4 55555555 44444444444444444 - */ - - - model->print(true); + /* now + /30 /60 /90 /120 /150 /180 /210 /240 + | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | ' ' ' | + T1 000000000 + >T2 333333333 + T3 2222222222222222111111111 + T4 55555555 44444444444444444 + */ + model->print(true); #undef l } - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { -// qputenv("TDS_DEVEL", "yes, of course"); + // qputenv("TDS_DEVEL", "yes, of course"); - qWarning() << "LtsTimeline - Test"; - NGLApplication app(argc, argv); - app.createLogger("Timeline", "log4cxx_timeline.props"); + qWarning() << "LtsTimeline - Test"; + NGLApplication app(argc, argv); + app.createLogger("Timeline", "log4cxx_timeline.props"); - STARTUP_LOG(app.baseLogger()); + STARTUP_LOG(app.baseLogger()); - int ret = 0; + int ret = 0; - LtsTimeline::TimelineWidget *timeline = new LtsTimeline::TimelineWidget(); - LtsTimeline::TimelineModel *model = new LtsTimeline::TimelineModel(timeline->view()); - model->setSnapEnabled(true); - populateModel(model); - timeline->setModel(model); - timeline->showDebugWidget(); - timeline->setWindowState(Qt::WindowMaximized); - timeline->show(); + LtsTimeline::TimelineWidget* timeline = new LtsTimeline::TimelineWidget(); + LtsTimeline::TimelineModel* model = new LtsTimeline::TimelineModel(timeline->view()); + model->setSnapEnabled(true); + populateModel(model); + timeline->setModel(model); + timeline->showDebugWidget(); + timeline->setWindowState(Qt::WindowMaximized); + timeline->show(); -// timeline->setMaximumZoomFactor(LtsTimeline::ZoomFactor::ThirtyMinutes); - timeline->setZoomFactor(LtsTimeline::ZoomFactor::SixtyMinutes); - timeline->setStartTime(QDateTime::currentMSecsSinceEpoch()); - timeline->setDuration(12 * 60 * 60 * 1000); + // timeline->setMaximumZoomFactor(LtsTimeline::ZoomFactor::ThirtyMinutes); + timeline->setZoomFactor(LtsTimeline::ZoomFactor::SixtyMinutes); + timeline->setStartTime(QDateTime::currentMSecsSinceEpoch()); + timeline->setDuration(12 * 60 * 60 * 1000); - ret = app.exec(); + ret = app.exec(); - SHUTDOWN_LOG(app.baseLogger()); + SHUTDOWN_LOG(app.baseLogger()); - return ret; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.cpp old mode 100755 new mode 100644 index 7581992f9..91d43a743 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.cpp @@ -1,680 +1,636 @@ #include "timeline_header_view.h" -#include + #include "timeline_view.h" +#include +#include +#include #include #include #include -#include -#include -#include #include -#include -#include +#include +#include +#include #include #include -#include - +#include namespace LtsTimeline { QPixmap getMinLimitIndicator() { - QPixmap pixmap(11, 11); - pixmap.fill(Qt::transparent); - QPolygon triangle; - triangle << QPoint(4, 5); - triangle << QPoint(10, 0); - triangle << QPoint(10, 10); - triangle << QPoint(4, 5); - QPainter painter(&pixmap); - painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.setPen(QGuiApplication::palette().color(QPalette::Text)); - painter.setBrush(QBrush(QGuiApplication::palette().color(QPalette::Text))); - painter.drawLine(1, 0, 1, 10); - painter.drawConvexPolygon(triangle); - return pixmap; + QPixmap pixmap(11, 11); + pixmap.fill(Qt::transparent); + QPolygon triangle; + triangle << QPoint(4, 5); + triangle << QPoint(10, 0); + triangle << QPoint(10, 10); + triangle << QPoint(4, 5); + QPainter painter(&pixmap); + painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter.setPen(QGuiApplication::palette().color(QPalette::Text)); + painter.setBrush(QBrush(QGuiApplication::palette().color(QPalette::Text))); + painter.drawLine(1, 0, 1, 10); + painter.drawConvexPolygon(triangle); + return pixmap; } QPixmap getMaxLimitIndicator() { - QPixmap pixmap(11, 11); - pixmap.fill(Qt::transparent); - QPolygon triangle; - triangle << QPoint(6, 5); - triangle << QPoint(0, 0); - triangle << QPoint(0, 10); - triangle << QPoint(6, 5); - QPainter painter(&pixmap); - painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter.setPen(QGuiApplication::palette().color(QPalette::Text)); - painter.setBrush(QBrush(QGuiApplication::palette().color(QPalette::Text))); - painter.drawLine(10, 0, 10, 10); - painter.drawConvexPolygon(triangle); - return pixmap; + QPixmap pixmap(11, 11); + pixmap.fill(Qt::transparent); + QPolygon triangle; + triangle << QPoint(6, 5); + triangle << QPoint(0, 0); + triangle << QPoint(0, 10); + triangle << QPoint(6, 5); + QPainter painter(&pixmap); + painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter.setPen(QGuiApplication::palette().color(QPalette::Text)); + painter.setBrush(QBrush(QGuiApplication::palette().color(QPalette::Text))); + painter.drawLine(10, 0, 10, 10); + painter.drawConvexPolygon(triangle); + return pixmap; } - const QColor TimelineHeaderView::backgroundColor() { - return QGuiApplication::palette().color(QPalette::Base); + return QGuiApplication::palette().color(QPalette::Base); } const QColor TimelineHeaderView::highlightColor() { - return QRgb(0x43b0e0); + return QRgb(0x43b0e0); } - const int TimelineHeaderView::s_limitHeight = 22; - -TimelineHeaderView::TimelineHeaderView(QWidget *parent) - : QHeaderView(Qt::Horizontal, parent) - , m_mouseHandler(new TimelineHeaderViewMouseHandler(this)) - , m_liveTimer(new QTimer(this)) - , m_minLimitIndicator(getMinLimitIndicator()) - , m_maxLimitIndicator(getMaxLimitIndicator()) +TimelineHeaderView::TimelineHeaderView(QWidget* parent) + : QHeaderView(Qt::Horizontal, parent), m_mouseHandler(new TimelineHeaderViewMouseHandler(this)), + m_liveTimer(new QTimer(this)), m_minLimitIndicator(getMinLimitIndicator()), + m_maxLimitIndicator(getMaxLimitIndicator()) { - const QColor color = QGuiApplication::palette().color(QPalette::Inactive, QPalette::Highlight); - setStyleSheet(QStringLiteral("QTreeView { background-color: %1 }").arg(color.name(QColor::HexRgb))); - try - { - m_timelineView = qobject_cast(parent); - updateSection(Section::eActuator); - updateSection(Section::eItems); - if (m_timelineView) + const QColor color = QGuiApplication::palette().color(QPalette::Inactive, QPalette::Highlight); + setStyleSheet(QStringLiteral("QTreeView { background-color: %1 }").arg(color.name(QColor::HexRgb))); + try { - connect(m_timelineView, &TimelineView::currentTimeChanged, this, &TimelineHeaderView::onUpdateTicks); - connect(m_timelineView, &TimelineView::rangeChanged, this, &TimelineHeaderView::onUpdateTicks); - connect(m_timelineView, &TimelineView::zoomChanged, this, &TimelineHeaderView::onUpdateTicks); + m_timelineView = qobject_cast(parent); + updateSection(Section::eActuator); + updateSection(Section::eItems); + if (m_timelineView) + { + connect(m_timelineView, &TimelineView::currentTimeChanged, this, &TimelineHeaderView::onUpdateTicks); + connect(m_timelineView, &TimelineView::rangeChanged, this, &TimelineHeaderView::onUpdateTicks); + connect(m_timelineView, &TimelineView::zoomChanged, this, &TimelineHeaderView::onUpdateTicks); + } + else + qWarning() << "WARNING: main functionalities are inoperable without a TimelineView as parent."; } - else - qWarning() << "WARNING: main functionalities are inoperable without a TimelineView as parent."; - } - catch (...) - { - qWarning() << "WARNING: main functionalities are inoperable without a TimelineView as parent."; - } - setStretchLastSection(true); - setMinimumSectionSize(200); - setFixedHeight(50); - connect(this, &TimelineHeaderView::sectionResized, this, &TimelineHeaderView::onUpdateTicks); - connect(m_liveTimer, &QTimer::timeout, this, &TimelineHeaderView::onLiveTimeout); + catch (...) + { + qWarning() << "WARNING: main functionalities are inoperable without a TimelineView as parent."; + } + setStretchLastSection(true); + setMinimumSectionSize(200); + setFixedHeight(50); + connect(this, &TimelineHeaderView::sectionResized, this, &TimelineHeaderView::onUpdateTicks); + connect(m_liveTimer, &QTimer::timeout, this, &TimelineHeaderView::onLiveTimeout); - m_liveIndicatorColor = QGuiApplication::palette().color(QPalette::Link); + m_liveIndicatorColor = QGuiApplication::palette().color(QPalette::Link); } TimelineHeaderView::~TimelineHeaderView() { - m_timelineView = nullptr; + m_timelineView = nullptr; } - - - -void TimelineHeaderView::setParent(QWidget *) +void TimelineHeaderView::setParent(QWidget*) { - qWarning() << QStringLiteral("WARNING: setting parent after construction is not allowed."); + qWarning() << QStringLiteral("WARNING: setting parent after construction is not allowed."); } -void TimelineHeaderView::setTrackLabel(const QString &trackLabel) +void TimelineHeaderView::setTrackLabel(const QString& trackLabel) { - m_trackLabel = trackLabel; - updateSection(Section::eActuator); + m_trackLabel = trackLabel; + updateSection(Section::eActuator); } - void TimelineHeaderView::setDateTimeFormat(DateTimeFormat dateTimeFormat) { - if (!m_isDateTimeFormatChangable) - return; + if (!m_isDateTimeFormatChangable) + return; - m_dateTimeFormat = dateTimeFormat; - for (Tick &majorTick : m_majorTicks) - majorTick.label = DateTime::toString(majorTick.time, m_dateTimeFormat); - for (Tick &mediumTick : m_mediumTicks) - mediumTick.label = DateTime::toString(mediumTick.time, m_dateTimeFormat); - for (Tick &minorTick : m_minorTicks) - minorTick.label = DateTime::toString(minorTick.time, m_dateTimeFormat); - updateSection(Section::eItems); + m_dateTimeFormat = dateTimeFormat; + for (Tick& majorTick : m_majorTicks) + majorTick.label = DateTime::toString(majorTick.time, m_dateTimeFormat); + for (Tick& mediumTick : m_mediumTicks) + mediumTick.label = DateTime::toString(mediumTick.time, m_dateTimeFormat); + for (Tick& minorTick : m_minorTicks) + minorTick.label = DateTime::toString(minorTick.time, m_dateTimeFormat); + updateSection(Section::eItems); } - void TimelineHeaderView::setIndicatorScalingFactor(double factor) { - if (factor == m_indicatorScalingFactor || factor <= 0.) - return; + if (factor == m_indicatorScalingFactor || factor <= 0.) + return; - m_indicatorScalingFactor = factor; - viewport()->update(); + m_indicatorScalingFactor = factor; + viewport()->update(); } void TimelineHeaderView::setIndicatorTime(qint64 time) { - if (time != -1 && m_timelineView) - if (m_timelineView->timelineModel()) - if (m_timelineView->timelineModel()->isSnapEnabled()) - time = m_timelineView->timelineModel()->snapTime(time); + if (time != -1 && m_timelineView) + if (m_timelineView->timelineModel()) + if (m_timelineView->timelineModel()->isSnapEnabled()) + time = m_timelineView->timelineModel()->snapTime(time); + if (time == m_indicatorTime) + return; - - - if (time == m_indicatorTime) - return; - - m_indicatorTime = time; - viewport()->update(); - emit indicatorTimeChanged(m_indicatorTime); + m_indicatorTime = time; + viewport()->update(); + emit indicatorTimeChanged(m_indicatorTime); } void TimelineHeaderView::setIndicatorPosition(int position) { - setIndicatorTime(toTime(position)); + setIndicatorTime(toTime(position)); } void TimelineHeaderView::setIndicatorVisible(bool isIndicatorVisible) { - if (isIndicatorVisible == m_isIndicatorVisible) - return; + if (isIndicatorVisible == m_isIndicatorVisible) + return; - m_isIndicatorVisible = isIndicatorVisible; - m_timelineView->viewport()->update(); - emit indicatorVisibilityChanged(m_isIndicatorVisible); + m_isIndicatorVisible = isIndicatorVisible; + m_timelineView->viewport()->update(); + emit indicatorVisibilityChanged(m_isIndicatorVisible); } - void TimelineHeaderView::setLiveIndicatorScalingFactor(double factor) { - if (factor == m_liveIndicatorScalingFactor || factor <= 0.) - return; + if (factor == m_liveIndicatorScalingFactor || factor <= 0.) + return; - m_liveIndicatorScalingFactor = factor; - viewport()->update(); + m_liveIndicatorScalingFactor = factor; + viewport()->update(); } -void TimelineHeaderView::setLiveIndicatorColor(const QColor &color) +void TimelineHeaderView::setLiveIndicatorColor(const QColor& color) { - if (color == m_liveIndicatorColor) - return; + if (color == m_liveIndicatorColor) + return; - m_liveIndicatorColor = color; - viewport()->update(); + m_liveIndicatorColor = color; + viewport()->update(); } void TimelineHeaderView::setLiveIndicatorTime(qint64 time) { - if (time != -1 && m_timelineView) - if (m_timelineView->timelineModel()) - if (m_timelineView->timelineModel()->isSnapEnabled()) - time = m_timelineView->timelineModel()->snapTime(time); + if (time != -1 && m_timelineView) + if (m_timelineView->timelineModel()) + if (m_timelineView->timelineModel()->isSnapEnabled()) + time = m_timelineView->timelineModel()->snapTime(time); - if (time == m_liveIndicatorTime) - return; + if (time == m_liveIndicatorTime) + return; - m_liveIndicatorTime = time; - viewport()->update(); - emit liveIndicatorTimeChanged(m_liveIndicatorTime); + m_liveIndicatorTime = time; + viewport()->update(); + emit liveIndicatorTimeChanged(m_liveIndicatorTime); } void TimelineHeaderView::setLiveIndicatorPosition(int position) { - setLiveIndicatorTime(toTime(position)); + setLiveIndicatorTime(toTime(position)); } void TimelineHeaderView::setLiveIndicatorVisible(bool isLiveIndicatorVisible) { - if (isLiveIndicatorVisible == m_isLiveIndicatorVisible) - return; + if (isLiveIndicatorVisible == m_isLiveIndicatorVisible) + return; - m_isLiveIndicatorVisible = isLiveIndicatorVisible; - viewport()->update(); - m_timelineView->viewport()->update(); - emit liveIndicatorVisibilityChanged(m_isLiveIndicatorVisible); + m_isLiveIndicatorVisible = isLiveIndicatorVisible; + viewport()->update(); + m_timelineView->viewport()->update(); + emit liveIndicatorVisibilityChanged(m_isLiveIndicatorVisible); } void TimelineHeaderView::startLiveTimer(qint64 startTime, int interval) { - if (interval <= 0) - { - qCritical() << LOGFUNCTION << "invalid time interval:" << interval; - return; - } + if (interval <= 0) + { + qCritical() << LOGFUNCTION << "invalid time interval:" << interval; + return; + } - if (m_liveTimer->isActive()) - { - qWarning() << LOGFUNCTION << "timer is already active - restarting"; - m_liveTimer->stop(); - } + if (m_liveTimer->isActive()) + { + qWarning() << LOGFUNCTION << "timer is already active - restarting"; + m_liveTimer->stop(); + } - if (startTime < 0) - startTime = m_timelineView->currentTime(); + if (startTime < 0) + startTime = m_timelineView->currentTime(); - m_liveTimerInterval = interval; - setLiveIndicatorTime(startTime); - setLiveIndicatorVisible(true); - m_liveTimer->setSingleShot(false); - m_liveTimer->start(m_liveTimerInterval); + m_liveTimerInterval = interval; + setLiveIndicatorTime(startTime); + setLiveIndicatorVisible(true); + m_liveTimer->setSingleShot(false); + m_liveTimer->start(m_liveTimerInterval); } void TimelineHeaderView::stopLiveTimer() { - if (!m_liveTimer->isActive()) - return; + if (!m_liveTimer->isActive()) + return; - qDebug() << LOGFUNCTION; - m_liveTimer->stop(); - m_liveIndicatorTime = -1; - setLiveIndicatorVisible(false); + qDebug() << LOGFUNCTION; + m_liveTimer->stop(); + m_liveIndicatorTime = -1; + setLiveIndicatorVisible(false); } - void TimelineHeaderView::setHoverTime(qint64 time) { - if (!m_isHoverVisible) - return; + if (!m_isHoverVisible) + return; - if (time < m_timelineView->currentTime() || m_timelineView->currentTime() + m_timelineView->zoomFactor() < time) - time = -1; + if (time < m_timelineView->currentTime() || m_timelineView->currentTime() + m_timelineView->zoomFactor() < time) + time = -1; - m_hoverTime = time; - m_hoverPosition = toPixel(m_hoverTime); - updateSection(Section::eItems); - emit hoverPositionChanged(m_hoverPosition); + m_hoverTime = time; + m_hoverPosition = toPixel(m_hoverTime); + updateSection(Section::eItems); + emit hoverPositionChanged(m_hoverPosition); } void TimelineHeaderView::setHoverPosition(int position) { - if (!m_isHoverVisible) - return; + if (!m_isHoverVisible) + return; - m_hoverPosition = position; - m_hoverTime = toTime(m_hoverPosition); - updateSection(Section::eItems); - emit hoverPositionChanged(m_hoverPosition); + m_hoverPosition = position; + m_hoverTime = toTime(m_hoverPosition); + updateSection(Section::eItems); + emit hoverPositionChanged(m_hoverPosition); } void TimelineHeaderView::setHoverVisible(bool visible) { - if (visible == m_isHoverVisible) - return; + if (visible == m_isHoverVisible) + return; - m_isHoverVisible = visible; - updateSection(Section::eItems); - m_timelineView->viewport()->update(); - emit hoverVisibilityChanged(m_isHoverVisible); + m_isHoverVisible = visible; + updateSection(Section::eItems); + m_timelineView->viewport()->update(); + emit hoverVisibilityChanged(m_isHoverVisible); } void TimelineHeaderView::setHoverTimeVisible(bool visible) { - if (visible == m_isHoverTimeVisible) - return; + if (visible == m_isHoverTimeVisible) + return; - m_isHoverTimeVisible = visible; - updateSection(Section::eItems); - m_timelineView->viewport()->update(); + m_isHoverTimeVisible = visible; + updateSection(Section::eItems); + m_timelineView->viewport()->update(); } void TimelineHeaderView::setHoverDateTimeFormat(DateTimeFormat format) { - if (format == m_hoverDateTimeFormat) - return; + if (format == m_hoverDateTimeFormat) + return; - m_hoverDateTimeFormat = format; - updateSection(Section::eItems); - m_timelineView->viewport()->update(); + m_hoverDateTimeFormat = format; + updateSection(Section::eItems); + m_timelineView->viewport()->update(); } - void TimelineHeaderView::setLimitsVisible(bool visible) { - if (visible == m_isLimitsVisible) - return; + if (visible == m_isLimitsVisible) + return; - m_isLimitsVisible = visible; - if (m_isLimitsVisible) - setFixedHeight(70); - else - setFixedHeight(50); - viewport()->update(); + m_isLimitsVisible = visible; + if (m_isLimitsVisible) + setFixedHeight(70); + else + setFixedHeight(50); + viewport()->update(); } void TimelineHeaderView::setLimitsDateTimeFormat(DateTimeFormat format) { - if (format == m_limitsDateTimeFormat) - return; + if (format == m_limitsDateTimeFormat) + return; - m_limitsDateTimeFormat = format; - viewport()->update(); + m_limitsDateTimeFormat = format; + viewport()->update(); } - int TimelineHeaderView::toPixel(qint64 time) const { - if (time == -1) - return -1; + if (time == -1) + return -1; - return static_cast(double(time - m_timelineView->currentTime()) / m_timelineView->zoomFactor() * - (geometry().width() - sectionPosition(Section::eItems)) + sectionPosition(Section::eItems)); + return static_cast(double(time - m_timelineView->currentTime()) / m_timelineView->zoomFactor() * + (geometry().width() - sectionPosition(Section::eItems)) + + sectionPosition(Section::eItems)); } qint64 TimelineHeaderView::toTime(int pixel) const { - return m_timelineView->currentTime() + - (m_timelineView->zoomFactor() * (double(pixel - sectionPosition(Section::eItems)) / - (geometry().width() - sectionPosition(Section::eItems)))); + return m_timelineView->currentTime() + + (m_timelineView->zoomFactor() * (double(pixel - sectionPosition(Section::eItems)) / + (geometry().width() - sectionPosition(Section::eItems)))); } - - - -void TimelineHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const +void TimelineHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { - if (logicalIndex == Section::eActuator) - { + if (logicalIndex == Section::eActuator) + { + painter->save(); + painter->setRenderHints(QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing); + painter->setPen(backgroundColor()); + painter->setBrush(QBrush(backgroundColor())); + painter->drawRect(rect); + painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 2)); + painter->drawLine(rect.topRight(), QPoint(rect.right() - rect.height() / 2, rect.top() + rect.height() / 2)); + painter->drawLine(QPoint(rect.right() - rect.height() / 2, rect.top() + rect.height() / 2), rect.bottomRight()); + painter->setFont(m_font); + painter->drawText(rect, Qt::AlignCenter, m_trackLabel); + painter->restore(); + return; + } + painter->save(); + + painter->setClipping(true); + painter->setClipRect(rect); + painter->setFont(m_font); painter->setRenderHints(QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing); painter->setPen(backgroundColor()); - painter->setBrush(QBrush(backgroundColor())); + painter->setBrush(backgroundColor()); painter->drawRect(rect); - painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 2)); - painter->drawLine(rect.topRight(), QPoint(rect.right() - rect.height() / 2, rect.top() + rect.height() / 2)); - painter->drawLine(QPoint(rect.right() - rect.height() / 2, rect.top() + rect.height() / 2), rect.bottomRight()); - painter->setFont(m_font); - painter->drawText(rect, Qt::AlignCenter, m_trackLabel); - painter->restore(); - return; - } - painter->save(); + int bottom = m_isLimitsVisible ? rect.bottom() - s_limitHeight : rect.bottom(); + int height = (bottom - rect.top()) / 2; - painter->setClipping(true); - painter->setClipRect(rect); - painter->setFont(m_font); - painter->setRenderHints(QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing); - painter->setPen(backgroundColor()); - painter->setBrush(backgroundColor()); - painter->drawRect(rect); + for (const Tick& tick : std::as_const(m_majorTicks)) + { + painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 1)); + painter->drawText(QRect(tick.pos - 160 / 2, rect.top(), 160, height), Qt::AlignCenter, tick.label); + if (m_isLimitsVisible) + painter->drawLine(tick.pos, bottom, tick.pos, rect.bottom()); + painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 1)); + painter->drawLine(tick.pos, rect.top() + height, tick.pos, bottom); + } - int bottom = m_isLimitsVisible ? rect.bottom() - s_limitHeight : rect.bottom(); - int height = (bottom - rect.top()) / 2; - - - for (const Tick &tick : std::as_const(m_majorTicks)) - { painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 1)); - painter->drawText(QRect(tick.pos - 160 / 2, rect.top(), 160, height), Qt::AlignCenter, tick.label); + + for (const Tick& tick : std::as_const(m_mediumTicks)) + painter->drawLine(tick.pos, bottom - static_cast(double(height) * 2 / 3), tick.pos, bottom); + + for (const Tick& tick : std::as_const(m_minorTicks)) + painter->drawLine(tick.pos, bottom - static_cast(double(height) / 3), tick.pos, bottom); + if (m_isLimitsVisible) - painter->drawLine(tick.pos, bottom, tick.pos, rect.bottom()); - painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 1)); - painter->drawLine(tick.pos, rect.top() + height, tick.pos, bottom); - } - - painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Text), 1)); - - - for (const Tick &tick : std::as_const(m_mediumTicks)) - painter->drawLine(tick.pos, bottom - static_cast(double(height) * 2 / 3), tick.pos, bottom); - - - for (const Tick &tick : std::as_const(m_minorTicks)) - painter->drawLine(tick.pos, bottom - static_cast(double(height) / 3), tick.pos, bottom); - - - if (m_isLimitsVisible) - { - QString minLimitString = DateTime::toString(m_timelineView->m_currentTime, m_limitsDateTimeFormat); - QString maxLimitString = DateTime::toString(m_timelineView->m_currentTime + m_timelineView->m_zoomFactor, m_limitsDateTimeFormat); - int minLimitWidth = painter->fontMetrics().horizontalAdvance(minLimitString); - int maxLimitWidth = painter->fontMetrics().horizontalAdvance(maxLimitString); - painter->setPen(backgroundColor()); - painter->setBrush(QBrush(backgroundColor())); - painter->drawRect(rect.left() + 4, geometry().bottom() - s_limitHeight, minLimitWidth + 11, 19); - painter->drawRect(rect.right() - maxLimitWidth - 18, geometry().bottom() - s_limitHeight, maxLimitWidth + 11, 19); - painter->setPen(QGuiApplication::palette().color(QPalette::Text)); - painter->drawPixmap(rect.left() + 4, geometry().bottom() - 15, 11, 11, m_minLimitIndicator); - painter->drawPixmap(rect.right() - 15, geometry().bottom() - 15, 11, 11, m_maxLimitIndicator); - painter->drawText( - QRect(rect.left() + 18, geometry().bottom() - s_limitHeight, minLimitWidth, s_limitHeight - 1), - Qt::AlignLeft, minLimitString - ); - painter->drawText( - QRect(rect.right() - maxLimitWidth - 18, geometry().bottom() - s_limitHeight, maxLimitWidth, s_limitHeight - 1), - Qt::AlignRight, maxLimitString - ); - } - - - if (m_isHoverVisible) - { - if (m_hoverPosition != -1) { - painter->setPen(highlightColor()); - painter->drawLine(m_hoverPosition, rect.top(), m_hoverPosition, rect.bottom()); - if (m_isHoverTimeVisible) - { - QString dateTimeString = DateTime::toString(m_hoverTime, m_hoverDateTimeFormat); - - - - const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString) + 2; - const int textHeight = m_isLimitsVisible ? s_limitHeight - 1 : 19; - QRect dateTimeRect(m_hoverPosition, geometry().bottom() - textHeight, textWidth, textHeight - 1); - if (dateTimeRect.right() >= geometry().right()) - { - dateTimeRect.setLeft(m_hoverPosition - textWidth); - dateTimeRect.setWidth(textWidth); - } + QString minLimitString = DateTime::toString(m_timelineView->m_currentTime, m_limitsDateTimeFormat); + QString maxLimitString = + DateTime::toString(m_timelineView->m_currentTime + m_timelineView->m_zoomFactor, m_limitsDateTimeFormat); + int minLimitWidth = painter->fontMetrics().horizontalAdvance(minLimitString); + int maxLimitWidth = painter->fontMetrics().horizontalAdvance(maxLimitString); + painter->setPen(backgroundColor()); painter->setBrush(QBrush(backgroundColor())); - painter->drawRect(dateTimeRect); - painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); - } + painter->drawRect(rect.left() + 4, geometry().bottom() - s_limitHeight, minLimitWidth + 11, 19); + painter->drawRect(rect.right() - maxLimitWidth - 18, geometry().bottom() - s_limitHeight, maxLimitWidth + 11, + 19); + painter->setPen(QGuiApplication::palette().color(QPalette::Text)); + painter->drawPixmap(rect.left() + 4, geometry().bottom() - 15, 11, 11, m_minLimitIndicator); + painter->drawPixmap(rect.right() - 15, geometry().bottom() - 15, 11, 11, m_maxLimitIndicator); + painter->drawText( + QRect(rect.left() + 18, geometry().bottom() - s_limitHeight, minLimitWidth, s_limitHeight - 1), + Qt::AlignLeft, minLimitString); + painter->drawText(QRect(rect.right() - maxLimitWidth - 18, geometry().bottom() - s_limitHeight, maxLimitWidth, + s_limitHeight - 1), + Qt::AlignRight, maxLimitString); } - } - - if (m_isIndicatorVisible) - { - int pos = toPixel(m_indicatorTime); - if (m_indicatorTime != -1 && (m_timelineView->currentTime() <= m_indicatorTime && - m_indicatorTime <= m_timelineView->currentTime() + m_timelineView->zoomFactor())) + if (m_isHoverVisible) { - painter->setPen(highlightColor()); - painter->setBrush(QBrush(highlightColor())); - int sideLength = double(m_isLimitsVisible ? rect.height() - height : rect.height()) * m_indicatorScalingFactor; - int top = bottom - static_cast(0.866 * sideLength); - QPolygon polygon; - polygon << QPoint(pos, bottom); - polygon << QPoint(pos + sideLength / 2, top); - polygon << QPoint(pos - sideLength / 2, top); - polygon << QPoint(pos, bottom); - QString dateTimeString = DateTime::toString(m_indicatorTime, m_hoverDateTimeFormat); - const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString); - painter->setClipRect(rect.adjusted(-textWidth / 2, 0, 0, 0)); - painter->drawPolygon(polygon); - if (m_isLimitsVisible) - painter->drawLine(pos, bottom, pos, rect.bottom()); - QRect dateTimeRect(pos - textWidth / 2, geometry().top(), textWidth + 2, 19); - painter->setBrush(QBrush(backgroundColor())); - painter->drawRect(dateTimeRect); - painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); - painter->drawLine(pos, geometry().top() + 19, pos, bottom); - } - } + if (m_hoverPosition != -1) + { + painter->setPen(highlightColor()); + painter->drawLine(m_hoverPosition, rect.top(), m_hoverPosition, rect.bottom()); + if (m_isHoverTimeVisible) + { + QString dateTimeString = DateTime::toString(m_hoverTime, m_hoverDateTimeFormat); - - if (m_isLiveIndicatorVisible) - { - int pos = toPixel(m_liveIndicatorTime); - if (pos != -1 && (m_timelineView->currentTime() <= m_liveIndicatorTime && - m_liveIndicatorTime <= m_timelineView->currentTime() + m_timelineView->zoomFactor())) + const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString) + 2; + const int textHeight = m_isLimitsVisible ? s_limitHeight - 1 : 19; + QRect dateTimeRect(m_hoverPosition, geometry().bottom() - textHeight, textWidth, textHeight - 1); + if (dateTimeRect.right() >= geometry().right()) + { + dateTimeRect.setLeft(m_hoverPosition - textWidth); + dateTimeRect.setWidth(textWidth); + } + painter->setBrush(QBrush(backgroundColor())); + painter->drawRect(dateTimeRect); + painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); + } + } + } + + if (m_isIndicatorVisible) { - painter->setPen(m_liveIndicatorColor); - painter->setBrush(QBrush(m_liveIndicatorColor)); - int sideLength = double(m_isLimitsVisible ? rect.height() - height : rect.height()) * m_liveIndicatorScalingFactor; - int top = bottom - static_cast(0.866 * sideLength); - QPolygon polygon; - polygon << QPoint(pos, bottom); - polygon << QPoint(pos + sideLength / 2, top); - polygon << QPoint(pos - sideLength / 2, top); - polygon << QPoint(pos, bottom); - QString dateTimeString = DateTime::toString(m_liveIndicatorTime, m_hoverDateTimeFormat); - const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString); - painter->setClipRect(rect.adjusted(-textWidth / 2, 0, 0, 0)); - painter->drawPolygon(polygon); - QRect dateTimeRect(pos - textWidth / 2, geometry().top(), textWidth + 2, 19); - if (dateTimeRect.right() > geometry().right() - 20) - dateTimeRect.adjust(-22, 0, -22, 0); - painter->setBrush(QBrush(backgroundColor())); - painter->drawRect(dateTimeRect); - painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); + int pos = toPixel(m_indicatorTime); + if (m_indicatorTime != -1 && (m_timelineView->currentTime() <= m_indicatorTime && + m_indicatorTime <= m_timelineView->currentTime() + m_timelineView->zoomFactor())) + { + painter->setPen(highlightColor()); + painter->setBrush(QBrush(highlightColor())); + int sideLength = + double(m_isLimitsVisible ? rect.height() - height : rect.height()) * m_indicatorScalingFactor; + int top = bottom - static_cast(0.866 * sideLength); + QPolygon polygon; + polygon << QPoint(pos, bottom); + polygon << QPoint(pos + sideLength / 2, top); + polygon << QPoint(pos - sideLength / 2, top); + polygon << QPoint(pos, bottom); + QString dateTimeString = DateTime::toString(m_indicatorTime, m_hoverDateTimeFormat); + const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString); + painter->setClipRect(rect.adjusted(-textWidth / 2, 0, 0, 0)); + painter->drawPolygon(polygon); + if (m_isLimitsVisible) + painter->drawLine(pos, bottom, pos, rect.bottom()); + QRect dateTimeRect(pos - textWidth / 2, geometry().top(), textWidth + 2, 19); + painter->setBrush(QBrush(backgroundColor())); + painter->drawRect(dateTimeRect); + painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); + painter->drawLine(pos, geometry().top() + 19, pos, bottom); + } } - } - painter->restore(); + if (m_isLiveIndicatorVisible) + { + int pos = toPixel(m_liveIndicatorTime); + if (pos != -1 && (m_timelineView->currentTime() <= m_liveIndicatorTime && + m_liveIndicatorTime <= m_timelineView->currentTime() + m_timelineView->zoomFactor())) + { + painter->setPen(m_liveIndicatorColor); + painter->setBrush(QBrush(m_liveIndicatorColor)); + int sideLength = + double(m_isLimitsVisible ? rect.height() - height : rect.height()) * m_liveIndicatorScalingFactor; + int top = bottom - static_cast(0.866 * sideLength); + QPolygon polygon; + polygon << QPoint(pos, bottom); + polygon << QPoint(pos + sideLength / 2, top); + polygon << QPoint(pos - sideLength / 2, top); + polygon << QPoint(pos, bottom); + QString dateTimeString = DateTime::toString(m_liveIndicatorTime, m_hoverDateTimeFormat); + const int textWidth = painter->fontMetrics().horizontalAdvance(dateTimeString); + painter->setClipRect(rect.adjusted(-textWidth / 2, 0, 0, 0)); + painter->drawPolygon(polygon); + QRect dateTimeRect(pos - textWidth / 2, geometry().top(), textWidth + 2, 19); + if (dateTimeRect.right() > geometry().right() - 20) + dateTimeRect.adjust(-22, 0, -22, 0); + painter->setBrush(QBrush(backgroundColor())); + painter->drawRect(dateTimeRect); + painter->drawText(dateTimeRect, Qt::AlignCenter, dateTimeString); + } + } + + painter->restore(); } - - - void TimelineHeaderView::updateMajorTicks() { - m_majorTicks.clear(); + m_majorTicks.clear(); - if (m_timelineView->duration() <= 0) - return; + if (m_timelineView->duration() <= 0) + return; - const int interval = Zoom::majorInterval(m_timelineView->zoomFactor()); - if (interval == -1) - return; + const int interval = Zoom::majorInterval(m_timelineView->zoomFactor()); + if (interval == -1) + return; - qint64 time = m_timelineView->currentTime(); - const int mod = time % interval; - if (mod) - time += interval - mod; - const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); - while (time <= end) - { - QString label = DateTime::toString(time, m_dateTimeFormat); - Tick tick(toPixel(time), time, label); - m_majorTicks.append(tick); - time += interval; - } + qint64 time = m_timelineView->currentTime(); + const int mod = time % interval; + if (mod) + time += interval - mod; + const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); + while (time <= end) + { + QString label = DateTime::toString(time, m_dateTimeFormat); + Tick tick(toPixel(time), time, label); + m_majorTicks.append(tick); + time += interval; + } } void TimelineHeaderView::updateMediumTicks() { - m_mediumTicks.clear(); + m_mediumTicks.clear(); - if (m_timelineView->duration() <= 0) - return; + if (m_timelineView->duration() <= 0) + return; - const int interval = Zoom::mediumInterval(m_timelineView->zoomFactor()); - if (interval == -1) - return; + const int interval = Zoom::mediumInterval(m_timelineView->zoomFactor()); + if (interval == -1) + return; - qint64 time = m_timelineView->currentTime(); - const int mod = time % interval; - if (mod) - time += interval - mod; - const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); - while (time <= end) - { - Tick tick(time); - - - auto it = std::find_if(m_majorTicks.begin(), m_majorTicks.end(), [tick](const Tick &other) + qint64 time = m_timelineView->currentTime(); + const int mod = time % interval; + if (mod) + time += interval - mod; + const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); + while (time <= end) { - return tick.time == other.time; - }); - if (it != m_majorTicks.end()) - { - time += interval; - continue; + Tick tick(time); + + auto it = std::find_if(m_majorTicks.begin(), m_majorTicks.end(), + [tick](const Tick& other) { return tick.time == other.time; }); + if (it != m_majorTicks.end()) + { + time += interval; + continue; + } + + tick.pos = toPixel(tick.time); + tick.label = DateTime::toString(tick.time, m_dateTimeFormat); + m_mediumTicks.append(tick); + time += interval; } - - tick.pos = toPixel(tick.time); - tick.label = DateTime::toString(tick.time, m_dateTimeFormat); - m_mediumTicks.append(tick); - time += interval; - } } void TimelineHeaderView::updateMinorTicks() { - m_minorTicks.clear(); + m_minorTicks.clear(); - if (m_timelineView->duration() <= 0) - return; + if (m_timelineView->duration() <= 0) + return; - const int interval = Zoom::minorInterval(m_timelineView->zoomFactor()); - if (interval == -1) - return; + const int interval = Zoom::minorInterval(m_timelineView->zoomFactor()); + if (interval == -1) + return; - qint64 time = m_timelineView->currentTime(); - const int mod = time % interval; - if (mod) - time += interval - mod; - const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); - while (time <= end) - { - Tick tick(time); - - - auto it = std::find_if(m_majorTicks.begin(), m_majorTicks.end(), [tick](const Tick &other) + qint64 time = m_timelineView->currentTime(); + const int mod = time % interval; + if (mod) + time += interval - mod; + const qint64 end = m_timelineView->currentTime() + m_timelineView->zoomFactor(); + while (time <= end) { - return tick.time == other.time; - }); - if (it != m_majorTicks.end()) - { - time += interval; - continue; + Tick tick(time); + + auto it = std::find_if(m_majorTicks.begin(), m_majorTicks.end(), + [tick](const Tick& other) { return tick.time == other.time; }); + if (it != m_majorTicks.end()) + { + time += interval; + continue; + } + + it = std::find_if(m_mediumTicks.begin(), m_mediumTicks.end(), + [tick](const Tick& other) { return tick.time == other.time; }); + if (it != m_mediumTicks.end()) + { + time += interval; + continue; + } + + tick.pos = toPixel(tick.time); + tick.label = DateTime::toString(tick.time, m_dateTimeFormat); + m_minorTicks.append(tick); + time += interval; } - - - it = std::find_if(m_mediumTicks.begin(), m_mediumTicks.end(), [tick](const Tick &other) - { - return tick.time == other.time; - }); - if (it != m_mediumTicks.end()) - { - time += interval; - continue; - } - - tick.pos = toPixel(tick.time); - tick.label = DateTime::toString(tick.time, m_dateTimeFormat); - m_minorTicks.append(tick); - time += interval; - } } - - - void TimelineHeaderView::onUpdateTicks() { - updateMajorTicks(); - updateMediumTicks(); - updateMinorTicks(); + updateMajorTicks(); + updateMediumTicks(); + updateMinorTicks(); - if (m_isIndicatorVisible) - setIndicatorTime(m_indicatorTime); + if (m_isIndicatorVisible) + setIndicatorTime(m_indicatorTime); - if (m_isLiveIndicatorVisible) - setLiveIndicatorTime(m_liveIndicatorTime); + if (m_isLiveIndicatorVisible) + setLiveIndicatorTime(m_liveIndicatorTime); - updateSection(Section::eItems); - emit ticksChanged(m_majorTicks); + updateSection(Section::eItems); + emit ticksChanged(m_majorTicks); } - - - void TimelineHeaderView::onLiveTimeout() { - setLiveIndicatorTime(m_liveIndicatorTime + m_liveTimerInterval); + setLiveIndicatorTime(m_liveIndicatorTime + m_liveTimerInterval); } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.h old mode 100755 new mode 100644 index a80af95b3..509cb5cef --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view.h @@ -1,13 +1,10 @@ #pragma once -#include - +#include "ltstimeline_export.h" #include "timeline_header_view_mouse_handler.h" #include "timeline_utils.h" -#include "ltstimeline_export.h" - #include - +#include class QMouseEvent; class QPainter; @@ -15,159 +12,291 @@ class QRect; class QTimer; class QWheelEvent; - namespace LtsTimeline { class TimelineView; - class LTSTIMELINE_EXPORT TimelineHeaderView : public QHeaderView { - Q_OBJECT + Q_OBJECT - friend class TimelineHeaderViewMouseHandler; - friend class TimelineViewMouseHandler; + friend class TimelineHeaderViewMouseHandler; + friend class TimelineViewMouseHandler; -public: - static const QColor backgroundColor(); - static const QColor highlightColor(); + public: + static const QColor backgroundColor(); + static const QColor highlightColor(); - static const int s_limitHeight; + static const int s_limitHeight; - enum Section { eActuator = 0, eItems = 1 }; + enum Section { eActuator = 0, eItems = 1 }; - TimelineHeaderView(QWidget *parent = nullptr); - ~TimelineHeaderView(); + TimelineHeaderView(QWidget* parent = nullptr); + ~TimelineHeaderView(); - void setParent(QWidget *); - void setTrackLabel(const QString &trackLabel); + void setParent(QWidget*); + void setTrackLabel(const QString& trackLabel); - const Ticks &majorTicks() const { return m_majorTicks; } - const Ticks &mediumTicks() const { return m_mediumTicks; } - const Ticks &minorTicks() const { return m_minorTicks; } + const Ticks& majorTicks() const + { + return m_majorTicks; + } - DateTimeFormat dateTimeFormat() const { return m_dateTimeFormat; } - void setDateTimeFormat(DateTimeFormat dateTimeFormat); - void setDateTimeFormatChangable(bool changable) { m_isDateTimeFormatChangable = changable; } - bool isDateTimeFormatChangable() const { return m_isDateTimeFormatChangable; } + const Ticks& mediumTicks() const + { + return m_mediumTicks; + } - double indicatorScalingFactor() const { return m_indicatorScalingFactor; } - void setIndicatorScalingFactor(double factor); - qint64 indicatorTime() const { return m_indicatorTime; } - void setIndicatorTime(qint64 time); - int indicatorPosition() const { return toPixel(m_indicatorTime); } - void setIndicatorPosition(int position); - bool isIndicatorVisible() const { return m_isIndicatorVisible; } - void setIndicatorVisible(bool isIndicatorVisible); - bool indicatorLocked() const { return m_isIndicatorLocked; } - void setIndicatorLocked(bool locked) { m_isIndicatorLocked = locked; } - void lockIndicator() { setIndicatorLocked(true); } - void unlockIndicator() { setIndicatorLocked(false); } + const Ticks& minorTicks() const + { + return m_minorTicks; + } - double liveIndicatorScalingFactor() const { return m_liveIndicatorScalingFactor; } - void setLiveIndicatorScalingFactor(double factor); - QColor liveIndicatorColor() const { return m_liveIndicatorColor; } - void setLiveIndicatorColor(const QColor &color); - qint64 liveIndicatorTime() const { return m_liveIndicatorTime; } - void setLiveIndicatorTime(qint64 time); - int liveIndicatorPosition() const { return toPixel(m_liveIndicatorTime); } - void setLiveIndicatorPosition(int position); - bool isLiveIndicatorVisible() const { return m_isLiveIndicatorVisible; } - void setLiveIndicatorVisible(bool isLiveIndicatorVisible); - void startLiveTimer(qint64 startTime = -1, int interval = 1000); - void stopLiveTimer(); + DateTimeFormat dateTimeFormat() const + { + return m_dateTimeFormat; + } - qint64 hoverTime() const { return m_hoverTime; } - void setHoverTime(qint64 time); - int hoverPosition() const { return m_hoverPosition; } - void setHoverPosition(int position); - bool isHoverVisible() const { return m_isHoverVisible; } - void setHoverVisible(bool visible); - bool isHoverTimeVisible() const { return m_isHoverTimeVisible; } - void setHoverTimeVisible(bool visible); - DateTimeFormat hoverDateTimeFormat() const { return m_hoverDateTimeFormat; } - void setHoverDateTimeFormat(DateTimeFormat format); + void setDateTimeFormat(DateTimeFormat dateTimeFormat); - bool isLimitsVisible() const { return m_isLimitsVisible; } - void setLimitsVisible(bool visible); - DateTimeFormat limitsDateTimeFormat() const { return m_limitsDateTimeFormat; } - void setLimitsDateTimeFormat(DateTimeFormat format); + void setDateTimeFormatChangable(bool changable) + { + m_isDateTimeFormatChangable = changable; + } - int toPixel(qint64 time) const; - qint64 toTime(int pixel) const; + bool isDateTimeFormatChangable() const + { + return m_isDateTimeFormatChangable; + } - QFont &font() { return m_font; } + double indicatorScalingFactor() const + { + return m_indicatorScalingFactor; + } - TimelineHeaderViewMouseHandler *mouseHandler() { return m_mouseHandler; } + void setIndicatorScalingFactor(double factor); - void wheelEvent(QWheelEvent *e) override { m_mouseHandler->wheelEvent(e); } + qint64 indicatorTime() const + { + return m_indicatorTime; + } -protected: - void mouseMoveEvent(QMouseEvent *e) override { m_mouseHandler->mouseMoveEvent(e); } - void mousePressEvent(QMouseEvent *e) override { m_mouseHandler->mousePressEvent(e); } - void mouseReleaseEvent(QMouseEvent *e) override { m_mouseHandler->mouseReleaseEvent(e); } + void setIndicatorTime(qint64 time); - void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const; + int indicatorPosition() const + { + return toPixel(m_indicatorTime); + } -private: - void updateMajorTicks(); - void updateMediumTicks(); - void updateMinorTicks(); + void setIndicatorPosition(int position); -public slots: - void onUpdateTicks(); + bool isIndicatorVisible() const + { + return m_isIndicatorVisible; + } -private slots: - void onLiveTimeout(); + void setIndicatorVisible(bool isIndicatorVisible); -signals: - void ticksChanged(const Ticks &); - void indicatorTimeChanged(qint64); - void indicatorVisibilityChanged(bool); - void liveIndicatorTimeChanged(qint64); - void liveIndicatorVisibilityChanged(bool); - void hoverPositionChanged(int); - void hoverVisibilityChanged(bool); + bool indicatorLocked() const + { + return m_isIndicatorLocked; + } -private: - TimelineHeaderViewMouseHandler *m_mouseHandler{nullptr}; - TimelineView *m_timelineView{nullptr}; - Ticks m_majorTicks; - Ticks m_mediumTicks; - Ticks m_minorTicks; - DateTimeFormat m_dateTimeFormat{DateTimeFormat::DTG}; - bool m_isDateTimeFormatChangable{true}; + void setIndicatorLocked(bool locked) + { + m_isIndicatorLocked = locked; + } - double m_indicatorScalingFactor{0.5}; - qint64 m_indicatorTime{-1}; - bool m_isIndicatorVisible{true}; - bool m_isIndicatorLocked{false}; + void lockIndicator() + { + setIndicatorLocked(true); + } - double m_liveIndicatorScalingFactor{0.5}; - QColor m_liveIndicatorColor; - qint64 m_liveIndicatorTime{-1}; - bool m_isLiveIndicatorVisible{false}; - QTimer *m_liveTimer{nullptr}; - int m_liveTimerInterval{1000}; + void unlockIndicator() + { + setIndicatorLocked(false); + } - qint64 m_hoverTime{-1}; - int m_hoverPosition{-1}; - bool m_isHoverVisible{true}; - bool m_isHoverTimeVisible{true}; - DateTimeFormat m_hoverDateTimeFormat{DateTimeFormat::DTG}; + double liveIndicatorScalingFactor() const + { + return m_liveIndicatorScalingFactor; + } - bool m_isLimitsVisible{false}; - DateTimeFormat m_limitsDateTimeFormat{DateTimeFormat::DTG}; - const QPixmap m_minLimitIndicator; - const QPixmap m_maxLimitIndicator; + void setLiveIndicatorScalingFactor(double factor); - QString m_trackLabel; + QColor liveIndicatorColor() const + { + return m_liveIndicatorColor; + } - QFont m_font; + void setLiveIndicatorColor(const QColor& color); + qint64 liveIndicatorTime() const + { + return m_liveIndicatorTime; + } + + void setLiveIndicatorTime(qint64 time); + + int liveIndicatorPosition() const + { + return toPixel(m_liveIndicatorTime); + } + + void setLiveIndicatorPosition(int position); + + bool isLiveIndicatorVisible() const + { + return m_isLiveIndicatorVisible; + } + + void setLiveIndicatorVisible(bool isLiveIndicatorVisible); + void startLiveTimer(qint64 startTime = -1, int interval = 1000); + void stopLiveTimer(); + + qint64 hoverTime() const + { + return m_hoverTime; + } + + void setHoverTime(qint64 time); + + int hoverPosition() const + { + return m_hoverPosition; + } + + void setHoverPosition(int position); + + bool isHoverVisible() const + { + return m_isHoverVisible; + } + + void setHoverVisible(bool visible); + + bool isHoverTimeVisible() const + { + return m_isHoverTimeVisible; + } + + void setHoverTimeVisible(bool visible); + + DateTimeFormat hoverDateTimeFormat() const + { + return m_hoverDateTimeFormat; + } + + void setHoverDateTimeFormat(DateTimeFormat format); + + bool isLimitsVisible() const + { + return m_isLimitsVisible; + } + + void setLimitsVisible(bool visible); + + DateTimeFormat limitsDateTimeFormat() const + { + return m_limitsDateTimeFormat; + } + + void setLimitsDateTimeFormat(DateTimeFormat format); + + int toPixel(qint64 time) const; + qint64 toTime(int pixel) const; + + QFont& font() + { + return m_font; + } + + TimelineHeaderViewMouseHandler* mouseHandler() + { + return m_mouseHandler; + } + + void wheelEvent(QWheelEvent* e) override + { + m_mouseHandler->wheelEvent(e); + } + + protected: + void mouseMoveEvent(QMouseEvent* e) override + { + m_mouseHandler->mouseMoveEvent(e); + } + + void mousePressEvent(QMouseEvent* e) override + { + m_mouseHandler->mousePressEvent(e); + } + + void mouseReleaseEvent(QMouseEvent* e) override + { + m_mouseHandler->mouseReleaseEvent(e); + } + + void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const; + + private: + void updateMajorTicks(); + void updateMediumTicks(); + void updateMinorTicks(); + + public slots: + void onUpdateTicks(); + + private slots: + void onLiveTimeout(); + + signals: + void ticksChanged(const Ticks&); + void indicatorTimeChanged(qint64); + void indicatorVisibilityChanged(bool); + void liveIndicatorTimeChanged(qint64); + void liveIndicatorVisibilityChanged(bool); + void hoverPositionChanged(int); + void hoverVisibilityChanged(bool); + + private: + TimelineHeaderViewMouseHandler* m_mouseHandler{nullptr}; + TimelineView* m_timelineView{nullptr}; + Ticks m_majorTicks; + Ticks m_mediumTicks; + Ticks m_minorTicks; + DateTimeFormat m_dateTimeFormat{DateTimeFormat::DTG}; + bool m_isDateTimeFormatChangable{true}; + + double m_indicatorScalingFactor{0.5}; + qint64 m_indicatorTime{-1}; + bool m_isIndicatorVisible{true}; + bool m_isIndicatorLocked{false}; + + double m_liveIndicatorScalingFactor{0.5}; + QColor m_liveIndicatorColor; + qint64 m_liveIndicatorTime{-1}; + bool m_isLiveIndicatorVisible{false}; + QTimer* m_liveTimer{nullptr}; + int m_liveTimerInterval{1000}; + + qint64 m_hoverTime{-1}; + int m_hoverPosition{-1}; + bool m_isHoverVisible{true}; + bool m_isHoverTimeVisible{true}; + DateTimeFormat m_hoverDateTimeFormat{DateTimeFormat::DTG}; + + bool m_isLimitsVisible{false}; + DateTimeFormat m_limitsDateTimeFormat{DateTimeFormat::DTG}; + const QPixmap m_minLimitIndicator; + const QPixmap m_maxLimitIndicator; + + QString m_trackLabel; + + QFont m_font; }; typedef TimelineHeaderView::Section Section; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.cpp old mode 100755 new mode 100644 index 8b39e09ed..6a6dc4560 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.cpp @@ -1,160 +1,147 @@ #include "timeline_header_view_mouse_handler.h" + #include "timeline_header_view.h" #include "timeline_view.h" #include +#include #include #include -#include - namespace LtsTimeline { -TimelineHeaderViewMouseHandler::TimelineHeaderViewMouseHandler(TimelineHeaderView *header) - : m_header(header) -{} +TimelineHeaderViewMouseHandler::TimelineHeaderViewMouseHandler(TimelineHeaderView* header) : m_header(header) {} - - - - -void TimelineHeaderViewMouseHandler::mouseMoveEvent(QMouseEvent *e) +void TimelineHeaderViewMouseHandler::mouseMoveEvent(QMouseEvent* e) { - if (m_isLeftButtonPressed) - m_hasMouseMovedLeft = true; - if (m_isRightButtonPressed) - m_hasMouseMovedRight = true; + if (m_isLeftButtonPressed) + m_hasMouseMovedLeft = true; + if (m_isRightButtonPressed) + m_hasMouseMovedRight = true; - if (!m_isResizingSection) - { - if (m_header->sectionPosition(Section::eItems) - 10 < e->pos().x() && e->pos().x() < m_header->sectionPosition(Section::eItems)) - m_header->m_timelineView->setCursor(QCursor(Qt::SizeHorCursor)); - else if (e->pos().y() <= m_header->geometry().bottom()) - m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); - } - else - m_header->resizeSection(Section::eActuator, std::min(e->pos().x(), m_header->geometry().width() / 2)); - - const bool isWithinRangeX = isMouseWithinRangeX(e->pos().x()); - if (!isWithinRangeX && !m_isLeftButtonPressed) - { - m_header->setHoverPosition(-1); - return; - } - - if (isWithinRangeX) - m_header->setHoverPosition(e->pos().x()); - if (m_isLeftButtonPressed) - { - if (m_isIndicatorSelected && !m_header->m_isIndicatorLocked) + if (!m_isResizingSection) { - m_header->m_timelineView->setCursor(QCursor(Qt::ClosedHandCursor)); - if (isWithinRangeX) - m_header->setIndicatorPosition(e->pos().x()); + if (m_header->sectionPosition(Section::eItems) - 10 < e->pos().x() && + e->pos().x() < m_header->sectionPosition(Section::eItems)) + m_header->m_timelineView->setCursor(QCursor(Qt::SizeHorCursor)); + else if (e->pos().y() <= m_header->geometry().bottom()) + m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); } - } - else - { - if (isMouseOverIndicator(e->pos()) && m_header->m_isIndicatorVisible && !m_header->m_isIndicatorLocked) - m_header->m_timelineView->setCursor(QCursor(Qt::OpenHandCursor)); - else if (e->pos().y() <= m_header->geometry().bottom()) - m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); - } -} + else + m_header->resizeSection(Section::eActuator, std::min(e->pos().x(), m_header->geometry().width() / 2)); -void TimelineHeaderViewMouseHandler::mousePressEvent(QMouseEvent *e) -{ - if (e->button() == Qt::LeftButton) - { - m_lastPos = e->pos(); - m_isLeftButtonPressed = true; - if (isMouseOverIndicator(e->pos()) && m_header->m_isIndicatorVisible && !m_header->m_isIndicatorLocked) + const bool isWithinRangeX = isMouseWithinRangeX(e->pos().x()); + if (!isWithinRangeX && !m_isLeftButtonPressed) { - m_header->m_timelineView->setCursor(QCursor(Qt::ClosedHandCursor)); - m_isIndicatorSelected = true; + m_header->setHoverPosition(-1); + return; } - else if (m_header->m_timelineView->cursor().shape() == Qt::SizeHorCursor) + + if (isWithinRangeX) + m_header->setHoverPosition(e->pos().x()); + if (m_isLeftButtonPressed) { - m_isResizingSection = true; + if (m_isIndicatorSelected && !m_header->m_isIndicatorLocked) + { + m_header->m_timelineView->setCursor(QCursor(Qt::ClosedHandCursor)); + if (isWithinRangeX) + m_header->setIndicatorPosition(e->pos().x()); + } + } + else + { + if (isMouseOverIndicator(e->pos()) && m_header->m_isIndicatorVisible && !m_header->m_isIndicatorLocked) + m_header->m_timelineView->setCursor(QCursor(Qt::OpenHandCursor)); + else if (e->pos().y() <= m_header->geometry().bottom()) + m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); } - } - if (e->button() == Qt::RightButton) - m_isRightButtonPressed = true; } -void TimelineHeaderViewMouseHandler::mouseReleaseEvent(QMouseEvent *e) +void TimelineHeaderViewMouseHandler::mousePressEvent(QMouseEvent* e) { - if (e->button() == Qt::LeftButton) - { - if (!m_hasMouseMovedLeft && isMouseWithinRangeX(e->pos().x()) && !m_header->m_isIndicatorLocked) - m_header->setIndicatorPosition(e->pos().x()); - if (isMouseOverIndicator(e->pos())) - m_header->m_timelineView->setCursor(QCursor(Qt::OpenHandCursor)); - else - m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); - m_lastPos = {}; - m_isIndicatorSelected = false; - m_isResizingSection = false; - m_isLeftButtonPressed = false; - m_hasMouseMovedLeft = false; - } - if (e->button() == Qt::RightButton) - { - m_header->setDateTimeFormat(static_cast((m_header->dateTimeFormat() + 1) % DateTime::numberOfDateTimeFormats())); - m_isRightButtonPressed = false; - m_hasMouseMovedRight = false; - } + if (e->button() == Qt::LeftButton) + { + m_lastPos = e->pos(); + m_isLeftButtonPressed = true; + if (isMouseOverIndicator(e->pos()) && m_header->m_isIndicatorVisible && !m_header->m_isIndicatorLocked) + { + m_header->m_timelineView->setCursor(QCursor(Qt::ClosedHandCursor)); + m_isIndicatorSelected = true; + } + else if (m_header->m_timelineView->cursor().shape() == Qt::SizeHorCursor) + { + m_isResizingSection = true; + } + } + if (e->button() == Qt::RightButton) + m_isRightButtonPressed = true; } -void TimelineHeaderViewMouseHandler::wheelEvent(QWheelEvent *e) +void TimelineHeaderViewMouseHandler::mouseReleaseEvent(QMouseEvent* e) { - if (!m_header->m_timelineView) - return; - - if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) - { - if (e->angleDelta().y() < 0) - m_header->m_timelineView->setZoomFactor(Zoom::increment(m_header->m_timelineView->zoomFactor())); - else - m_header->m_timelineView->setZoomFactor(Zoom::decrement(m_header->m_timelineView->zoomFactor())); - } - else - { - if (e->angleDelta().y() > 0) - m_header->m_timelineView->setCurrentTime( - m_header->m_timelineView->currentTime() - Zoom::majorInterval(m_header->m_timelineView->zoomFactor()) - ); - else - m_header->m_timelineView->setCurrentTime( - m_header->m_timelineView->currentTime() + Zoom::majorInterval(m_header->m_timelineView->zoomFactor()) - ); - } + if (e->button() == Qt::LeftButton) + { + if (!m_hasMouseMovedLeft && isMouseWithinRangeX(e->pos().x()) && !m_header->m_isIndicatorLocked) + m_header->setIndicatorPosition(e->pos().x()); + if (isMouseOverIndicator(e->pos())) + m_header->m_timelineView->setCursor(QCursor(Qt::OpenHandCursor)); + else + m_header->m_timelineView->setCursor(QCursor(Qt::ArrowCursor)); + m_lastPos = {}; + m_isIndicatorSelected = false; + m_isResizingSection = false; + m_isLeftButtonPressed = false; + m_hasMouseMovedLeft = false; + } + if (e->button() == Qt::RightButton) + { + m_header->setDateTimeFormat( + static_cast((m_header->dateTimeFormat() + 1) % DateTime::numberOfDateTimeFormats())); + m_isRightButtonPressed = false; + m_hasMouseMovedRight = false; + } } +void TimelineHeaderViewMouseHandler::wheelEvent(QWheelEvent* e) +{ + if (!m_header->m_timelineView) + return; - - - - - - + if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) + { + if (e->angleDelta().y() < 0) + m_header->m_timelineView->setZoomFactor(Zoom::increment(m_header->m_timelineView->zoomFactor())); + else + m_header->m_timelineView->setZoomFactor(Zoom::decrement(m_header->m_timelineView->zoomFactor())); + } + else + { + if (e->angleDelta().y() > 0) + m_header->m_timelineView->setCurrentTime(m_header->m_timelineView->currentTime() - + Zoom::majorInterval(m_header->m_timelineView->zoomFactor())); + else + m_header->m_timelineView->setCurrentTime(m_header->m_timelineView->currentTime() + + Zoom::majorInterval(m_header->m_timelineView->zoomFactor())); + } +} bool TimelineHeaderViewMouseHandler::isMouseWithinRangeX(int x) const { - return m_header->sectionPosition(Section::eItems) < x && x < m_header->geometry().right(); + return m_header->sectionPosition(Section::eItems) < x && x < m_header->geometry().right(); } bool TimelineHeaderViewMouseHandler::isMouseWithinRangeY(int y) const { - return m_header->geometry().top() < y && y < m_header->geometry().bottom(); + return m_header->geometry().top() < y && y < m_header->geometry().bottom(); } -bool TimelineHeaderViewMouseHandler::isMouseOverIndicator(const QPoint &pos) const +bool TimelineHeaderViewMouseHandler::isMouseOverIndicator(const QPoint& pos) const { - const int height = m_header->height(); - return m_header->indicatorPosition() - height / 4 <= pos.x() && pos.x() <= m_header->indicatorPosition() + height / 4 && - m_header->geometry().center().y() <= pos.y() && pos.y() < m_header->geometry().bottom(); + const int height = m_header->height(); + return m_header->indicatorPosition() - height / 4 <= pos.x() && + pos.x() <= m_header->indicatorPosition() + height / 4 && m_header->geometry().center().y() <= pos.y() && + pos.y() < m_header->geometry().bottom(); } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.h old mode 100755 new mode 100644 index fc7dda80d..9ca3c0c77 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_header_view_mouse_handler.h @@ -4,46 +4,49 @@ #include - class QMouseEvent; class QWheelEvent; - namespace LtsTimeline { class TimelineHeaderView; - class LTSTIMELINE_EXPORT TimelineHeaderViewMouseHandler { -public: - explicit TimelineHeaderViewMouseHandler(TimelineHeaderView *header); + public: + explicit TimelineHeaderViewMouseHandler(TimelineHeaderView* header); - void mouseMoveEvent(QMouseEvent *e); - void mousePressEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void wheelEvent(QWheelEvent *e); + void mouseMoveEvent(QMouseEvent* e); + void mousePressEvent(QMouseEvent* e); + void mouseReleaseEvent(QMouseEvent* e); + void wheelEvent(QWheelEvent* e); - bool isBusy() const { return m_isIndicatorSelected || m_isResizingSection; } - bool isIndicatorSelected() const { return m_isIndicatorSelected; } + bool isBusy() const + { + return m_isIndicatorSelected || m_isResizingSection; + } -private: + bool isIndicatorSelected() const + { + return m_isIndicatorSelected; + } - bool isMouseWithinRangeX(int x) const; - bool isMouseWithinRangeY(int y) const; - bool isMouseOverIndicator(const QPoint &pos) const; + private: + bool isMouseWithinRangeX(int x) const; + bool isMouseWithinRangeY(int y) const; + bool isMouseOverIndicator(const QPoint& pos) const; -private: - TimelineHeaderView *m_header{nullptr}; - QPoint m_lastPos; - bool m_isLeftButtonPressed{false}; - bool m_isRightButtonPressed{false}; - bool m_hasMouseMovedLeft{false}; - bool m_hasMouseMovedRight{false}; - bool m_isIndicatorSelected{false}; - bool m_isResizingSection{false}; + private: + TimelineHeaderView* m_header{nullptr}; + QPoint m_lastPos; + bool m_isLeftButtonPressed{false}; + bool m_isRightButtonPressed{false}; + bool m_hasMouseMovedLeft{false}; + bool m_hasMouseMovedRight{false}; + bool m_isIndicatorSelected{false}; + bool m_isResizingSection{false}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.cpp old mode 100755 new mode 100644 index b7812d44b..9b0207c82 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.cpp @@ -1,16 +1,13 @@ - #include "timeline_model.h" -#include + #include "timeline_view_drag_handler.h" #include "track.h" #include - - #include - +#include namespace LtsTimeline { @@ -20,743 +17,678 @@ TimelineModel::TimelineModel(TimelineView *view, QObject *parent) , m_view(view) .getNGLLogger("Timeline.TimelineModel")) { - m_rootTrack.m_id = nextFreeTrackId(); - m_trackCache.insert(std::pair(m_rootTrack.m_id, &m_rootTrack)); + m_rootTrack.m_id = nextFreeTrackId(); + m_trackCache.insert(std::pair(m_rootTrack.m_id, &m_rootTrack)); } - void TimelineModel::clear() { - m_rootTrack.m_childrenTracks.clear(); - m_rootTrack.m_items.clear(); + m_rootTrack.m_childrenTracks.clear(); + m_rootTrack.m_items.clear(); + m_rootTrack.m_copyItemIds.clear(); + m_trackCache.clear(); - m_rootTrack.m_copyItemIds.clear(); - m_trackCache.clear(); - - m_itemCache.clear(); + m_itemCache.clear(); - m_currentTrackId = 1; - m_currentItemId = 0; - m_trackCache.insert(std::pair(m_rootTrack.m_id, &m_rootTrack)); + m_currentTrackId = 1; + m_currentItemId = 0; + m_trackCache.insert(std::pair(m_rootTrack.m_id, &m_rootTrack)); } - void TimelineModel::clearItems() { - for (std::pair p : m_trackCache) - p.second->clearItems(); + for (std::pair p : m_trackCache) + p.second->clearItems(); - m_itemCache.clear(); - m_currentItemId = 0; + m_itemCache.clear(); + m_currentItemId = 0; } - -Track &TimelineModel::track(int id) noexcept(false) +Track& TimelineModel::track(int id) noexcept(false) { - if (!m_trackCaching) - { - if (id == m_rootTrack.id()) - return m_rootTrack; - return m_rootTrack.track(id); - } + if (!m_trackCaching) + { + if (id == m_rootTrack.id()) + return m_rootTrack; + return m_rootTrack.track(id); + } - auto it = m_trackCache.find(id); + auto it = m_trackCache.find(id); - if (it == m_trackCache.end()) - throw QStringLiteral("Model: track with id %1 not found in cache").arg(id); + if (it == m_trackCache.end()) + throw QStringLiteral("Model: track with id %1 not found in cache").arg(id); - return *it->second; + return *it->second; } - -const Track &TimelineModel::track(int id) const noexcept(false) +const Track& TimelineModel::track(int id) const noexcept(false) { - if (!m_trackCaching) - { - if (id == m_rootTrack.id()) - return m_rootTrack; - return m_rootTrack.track(id); - } + if (!m_trackCaching) + { + if (id == m_rootTrack.id()) + return m_rootTrack; + return m_rootTrack.track(id); + } - std::map::const_iterator it = m_trackCache.find(id); + std::map::const_iterator it = m_trackCache.find(id); - if (it == m_trackCache.cend()) - throw QStringLiteral("Model: const track with id %1 not found in cache").arg(id); + if (it == m_trackCache.cend()) + throw QStringLiteral("Model: const track with id %1 not found in cache").arg(id); - return *it->second; + return *it->second; } - -Item &TimelineModel::item(int id) noexcept(false) +Item& TimelineModel::item(int id) noexcept(false) { - if (!m_itemCaching) - return m_rootTrack.item(id); + if (!m_itemCaching) + return m_rootTrack.item(id); - auto it = m_itemCache.find(id); + auto it = m_itemCache.find(id); - if (it == m_itemCache.end()) - throw QStringLiteral("Model: item with id %1 not found in cache").arg(id); + if (it == m_itemCache.end()) + throw QStringLiteral("Model: item with id %1 not found in cache").arg(id); - return *it->second; + return *it->second; } - -const Item &TimelineModel::item(int id) const noexcept(false) +const Item& TimelineModel::item(int id) const noexcept(false) { - if (!m_itemCaching) - return m_rootTrack.item(id); + if (!m_itemCaching) + return m_rootTrack.item(id); - decltype(m_itemCache)::const_iterator it = m_itemCache.find(id); + decltype(m_itemCache)::const_iterator it = m_itemCache.find(id); - if (it == m_itemCache.cend()) - throw QStringLiteral("Model: const item with id %1 not found in cache").arg(id); + if (it == m_itemCache.cend()) + throw QStringLiteral("Model: const item with id %1 not found in cache").arg(id); - return *it->second; + return *it->second; } - const QVector TimelineModel::itemIds() const { - if (!m_itemCaching) - return m_rootTrack.itemIds(true); + if (!m_itemCaching) + return m_rootTrack.itemIds(true); - QVector ids; - std::transform(m_itemCache.cbegin(), m_itemCache.cend(), std::back_inserter(ids), - [](const std::pair &pair) - { - return pair.first; - }); + QVector ids; + std::transform(m_itemCache.cbegin(), m_itemCache.cend(), std::back_inserter(ids), + [](const std::pair& pair) { return pair.first; }); - return ids; + return ids; } - - -const QVector TimelineModel::itemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted) const +const QVector TimelineModel::itemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, + bool sorted) const { - return m_rootTrack.itemIdsBetween(start, end, strict, complete, recursive, sorted); + return m_rootTrack.itemIdsBetween(start, end, strict, complete, recursive, sorted); } -bool TimelineModel::isItemsBetween(qint64 start, qint64 end, const QVector &ignoreIds, bool strict, bool complete, bool recursive) const +bool TimelineModel::isItemsBetween(qint64 start, qint64 end, const QVector& ignoreIds, bool strict, bool complete, + bool recursive) const { - return m_rootTrack.isItemsBetween(start, end, ignoreIds, strict, complete, recursive); + return m_rootTrack.isItemsBetween(start, end, ignoreIds, strict, complete, recursive); } -const QVector TimelineModel::copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool sorted) const +const QVector TimelineModel::copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, + bool sorted) const { - return m_rootTrack.copyItemIdsBetween(start, end, strict, complete, true, sorted); + return m_rootTrack.copyItemIdsBetween(start, end, strict, complete, true, sorted); } -bool TimelineModel::isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict, bool complete, bool recursive) const +bool TimelineModel::isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict, bool complete, + bool recursive) const { - return m_rootTrack.isItemsBetween(start, end, ignoreId, strict, complete, recursive); + return m_rootTrack.isItemsBetween(start, end, ignoreId, strict, complete, recursive); } - -const QVector TimelineModel::_copyItemIdsBetween(Track &t, qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const +const QVector TimelineModel::_copyItemIdsBetween(Track& t, qint64 start, qint64 end, bool strict, bool complete, + bool recursive, bool sorted, qint64 minimumDuration) const { - QVector itemIds; - itemIds.reserve(t.itemCount()); + QVector itemIds; + itemIds.reserve(t.itemCount()); - - for (const int itemId : std::as_const(t.copyItemIds())) - { - const Item &i = item(itemId); - if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) - itemIds += i.id(); - } - - if (recursive) - for (const TrackPtr &trackPtr : std::as_const(t.tracks())) - itemIds += _copyItemIdsBetween(*trackPtr.get(), start, end, strict, complete, true, false, minimumDuration); - - - itemIds.erase(std::unique(itemIds.begin(), itemIds.end()), itemIds.end()); - - itemIds.squeeze(); - - if (!sorted) - return itemIds; - - - std::sort(itemIds.begin(), itemIds.end(), [this](const int itemIdA, const int itemIdB) - { - try + for (const int itemId : std::as_const(t.copyItemIds())) { - return item(itemIdA).startTime() < item(itemIdB).startTime(); + const Item& i = item(itemId); + if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) + itemIds += i.id(); } - catch (...) { return false; } - }); - return itemIds; -} + if (recursive) + for (const TrackPtr& trackPtr : std::as_const(t.tracks())) + itemIds += _copyItemIdsBetween(*trackPtr.get(), start, end, strict, complete, true, false, minimumDuration); + itemIds.erase(std::unique(itemIds.begin(), itemIds.end()), itemIds.end()); -const QVector TimelineModel::_itemIdsBetween(Track &t, qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const -{ - QVector itemIds; - itemIds.reserve(t.itemCount()); + itemIds.squeeze(); - for (const ItemPtr &itemPtr : std::as_const(t.items())) - { - const Item &i = *itemPtr; - if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) - itemIds += i.id(); - } + if (!sorted) + return itemIds; - if (recursive) - for (const TrackPtr &trackPtr : std::as_const(t.tracks())) - itemIds += _itemIdsBetween(*trackPtr.get(), start, end, strict, complete, true, false, minimumDuration); + std::sort(itemIds.begin(), itemIds.end(), [this](const int itemIdA, const int itemIdB) { + try + { + return item(itemIdA).startTime() < item(itemIdB).startTime(); + } + catch (...) + { + return false; + } + }); - - - - itemIds.squeeze(); - - if (!sorted) return itemIds; - - - std::sort(itemIds.begin(), itemIds.end(), [this](const int itemIdA, const int itemIdB) - { - try - { - return item(itemIdA).startTime() < item(itemIdB).startTime(); - } - catch (...) { return false; } - }); - - return itemIds; } - -bool TimelineModel::_isItemsBetween(const Track &t, qint64 start, qint64 end, const QVector &ignoreIds, bool strict, bool complete, bool recursive, qint64 minimumDuration) const +const QVector TimelineModel::_itemIdsBetween(Track& t, qint64 start, qint64 end, bool strict, bool complete, + bool recursive, bool sorted, qint64 minimumDuration) const { - for (const ItemPtr &itemPtr : std::as_const(t.items())) - { - const Item &i = *itemPtr; - if (!ignoreIds.contains(i.id())) - if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) - return true; - } + QVector itemIds; + itemIds.reserve(t.itemCount()); + + for (const ItemPtr& itemPtr : std::as_const(t.items())) + { + const Item& i = *itemPtr; + if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) + itemIds += i.id(); + } + + if (recursive) + for (const TrackPtr& trackPtr : std::as_const(t.tracks())) + itemIds += _itemIdsBetween(*trackPtr.get(), start, end, strict, complete, true, false, minimumDuration); + + itemIds.squeeze(); + + if (!sorted) + return itemIds; + + std::sort(itemIds.begin(), itemIds.end(), [this](const int itemIdA, const int itemIdB) { + try + { + return item(itemIdA).startTime() < item(itemIdB).startTime(); + } + catch (...) + { + return false; + } + }); + + return itemIds; +} + +bool TimelineModel::_isItemsBetween(const Track& t, qint64 start, qint64 end, const QVector& ignoreIds, + bool strict, bool complete, bool recursive, qint64 minimumDuration) const +{ + for (const ItemPtr& itemPtr : std::as_const(t.items())) + { + const Item& i = *itemPtr; + if (!ignoreIds.contains(i.id())) + if (Track::isItemBetween(i, start, end, strict, complete, minimumDuration)) + return true; + } + + if (!recursive) + return false; + + for (const TrackPtr& trackPtr : std::as_const(t.tracks())) + if (_isItemsBetween(*trackPtr.get(), start, end, ignoreIds, strict, complete, true, minimumDuration)) + return true; - if (!recursive) return false; - - for (const TrackPtr &trackPtr : std::as_const(t.tracks())) - if (_isItemsBetween(*trackPtr.get(), start, end, ignoreIds, strict, complete, true, minimumDuration)) - return true; - - return false; } - -bool TimelineModel::_isItemsBetween(const Track &t, qint64 start, qint64 end, int ignoreId, bool strict, bool complete, bool recursive, qint64 minimumDuration) const +bool TimelineModel::_isItemsBetween(const Track& t, qint64 start, qint64 end, int ignoreId, bool strict, bool complete, + bool recursive, qint64 minimumDuration) const { - return _isItemsBetween(t, start, end, QVector({ ignoreId }), strict, complete, recursive, minimumDuration); + return _isItemsBetween(t, start, end, QVector({ignoreId}), strict, complete, recursive, minimumDuration); } - -QVariant TimelineModel::data(const QModelIndex &index, int role) const +QVariant TimelineModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole && role != Qt::UserRole) || !index.isValid()) - return {}; + if ((role != Qt::DisplayRole && role != Qt::UserRole) || !index.isValid()) + return {}; - int trackId = index.internalId(); - int column = index.column(); + int trackId = index.internalId(); + int column = index.column(); - if (column == 1 && role == Qt::DisplayRole) - return trackId; + if (column == 1 && role == Qt::DisplayRole) + return trackId; - if (role == Qt::UserRole) - { - if (column == 0) - return trackId; + if (role == Qt::UserRole) + { + if (column == 0) + return trackId; + + try + { + const Track& t = track(trackId); + return t.userData(); + } + catch (...) + { + Q_ASSERT(false); + return {}; + } + } + + if (column != 0) + return {}; + + QString text; try { - const Track &t = track(trackId); - return t.userData(); - } - catch(...) - { - Q_ASSERT(false); - return {}; - } - } - - - if (column != 0) - return {}; - - - QString text; - - try - { - const Track &t = track(trackId); + const Track& t = track(trackId); #if 0 text = QStringLiteral("[%1] %3").arg(t.id()).arg(t.text()); #else - text = t.text(); + text = t.text(); #endif - } - catch(...) - { - Q_ASSERT(false); - return QStringLiteral("[?????]"); - } + } + catch (...) + { + Q_ASSERT(false); + return QStringLiteral("[?????]"); + } - if (text.isEmpty()) - text = tr("[unknown]"); + if (text.isEmpty()) + text = tr("[unknown]"); - return text; + return text; } - -Qt::ItemFlags TimelineModel::flags(const QModelIndex &index) const +Qt::ItemFlags TimelineModel::flags(const QModelIndex& index) const { - if (!index.isValid()) - return {}; + if (!index.isValid()) + return {}; - return QAbstractItemModel::flags(index); + return QAbstractItemModel::flags(index); } - -QModelIndex TimelineModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex TimelineModel::index(int row, int column, const QModelIndex& parent) const { - if (!hasIndex(row, column, parent)) - return {}; + if (!hasIndex(row, column, parent)) + return {}; - int childTrackId; - try - { - const Track &parentTrack = parent.isValid() ? track(parent.internalId()) : m_rootTrack; - const Track &childTrack = parentTrack.trackAt(row); - childTrackId = childTrack.id(); - } - catch (const QString &msg) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get parent track " << msg; - return {}; - } - catch (const std::out_of_range &oor) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get child track " << QString::fromUtf8(oor.what()); - return {}; - } + int childTrackId; + try + { + const Track& parentTrack = parent.isValid() ? track(parent.internalId()) : m_rootTrack; + const Track& childTrack = parentTrack.trackAt(row); + childTrackId = childTrack.id(); + } + catch (const QString& msg) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get parent track " << msg; + return {}; + } + catch (const std::out_of_range& oor) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get child track " << QString::fromUtf8(oor.what()); + return {}; + } - return createIndex(row, column, childTrackId); + return createIndex(row, column, childTrackId); } - int TimelineModel::rowOfTrackId(int id) const noexcept(false) { - const Track &parent = track(track(id).parentId()); + const Track& parent = track(track(id).parentId()); - if (parent.items().empty()) - throw("parent doesn't have items"); + if (parent.items().empty()) + throw("parent doesn't have items"); - int row = 0; + int row = 0; - for (const TrackPtr &trackPtr : std::as_const(parent.tracks())) - { - if (trackPtr->id() == id) - return row; - row++; - } + for (const TrackPtr& trackPtr : std::as_const(parent.tracks())) + { + if (trackPtr->id() == id) + return row; + row++; + } - throw("not found"); + throw("not found"); } - -const Track &TimelineModel::trackOfIndex(const QModelIndex &index) const +const Track& TimelineModel::trackOfIndex(const QModelIndex& index) const { - if (!index.isValid()) - throw QStringLiteral("trackOfIndex: index is invalid!"); - - - try - { - return track(index.internalId()); - } - catch (const QString &msg) - { - throw QStringLiteral("trackOfIndex: cannot find track by internal id %1: %2").arg(index.internalId()).arg(msg); - } - - - return m_rootTrack; -} - - - - - - - - - - - - - - - - - - -const Track &TimelineModel::parentOfTrackId(int id) const noexcept(false) -{ - if (!m_trackCaching) - { - if (m_rootTrack.hasTrack(id)) - return m_rootTrack; - - - } - - const Track &theTrack = track(id); - - if (theTrack.parentId() == m_rootTrack.id()) - return m_rootTrack; - - return track(theTrack.parentId()); -} - - -QModelIndex TimelineModel::parent(const QModelIndex &index) const -{ - if (!index.isValid()) - return {}; - - - - - - - - - - - - - - int trackId = index.internalId(); - int parentId; - int superParentId; - try - { - const Track &parent = parentOfTrackId(trackId); - parentId = parent.id(); - superParentId = parent.parentId(); - } - catch (const QString &msg) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get parent of track with id" << trackId << msg; - return {}; - } - - if (parentId == m_rootTrack.id()) - return {}; - - int parentsRow; - try - { - const Track &superParent = track(superParentId); + if (!index.isValid()) + throw QStringLiteral("trackOfIndex: index is invalid!"); try { - parentsRow = superParent.rowOfTrack(parentId); + return track(index.internalId()); } - catch (const QString &msg) + catch (const QString& msg) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "row of track for parent not found for parent id" << parentId << "-" << msg; - return {}; + throw QStringLiteral("trackOfIndex: cannot find track by internal id %1: %2").arg(index.internalId()).arg(msg); } - } - catch (const QString &msg) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "super parent not found for super parent id" << superParentId << "-" << msg; - return {}; - } - return createIndex(parentsRow, 0, parentId); + return m_rootTrack; } - -void TimelineModel::setItemStartTime(Track &t, Item &i, qint64 newStart) +const Track& TimelineModel::parentOfTrackId(int id) const noexcept(false) { - i._setStartTime(newStart); - t.sort(); + if (!m_trackCaching) + { + if (m_rootTrack.hasTrack(id)) + return m_rootTrack; + } + + const Track& theTrack = track(id); + + if (theTrack.parentId() == m_rootTrack.id()) + return m_rootTrack; + + return track(theTrack.parentId()); } - -void TimelineModel::setItemStartTime(Item &i, qint64 newStart) noexcept(false) +QModelIndex TimelineModel::parent(const QModelIndex& index) const { - setItemStartTime(track(i.parentTrackId()), i, newStart); + if (!index.isValid()) + return {}; + + int trackId = index.internalId(); + int parentId; + int superParentId; + try + { + const Track& parent = parentOfTrackId(trackId); + parentId = parent.id(); + superParentId = parent.parentId(); + } + catch (const QString& msg) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "cannot get parent of track with id" << trackId << msg; + return {}; + } + + if (parentId == m_rootTrack.id()) + return {}; + + int parentsRow; + try + { + const Track& superParent = track(superParentId); + + try + { + parentsRow = superParent.rowOfTrack(parentId); + } + catch (const QString& msg) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "row of track for parent not found for parent id" << parentId << "-" + << msg; + return {}; + } + } + catch (const QString& msg) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "super parent not found for super parent id" << superParentId << "-" + << msg; + return {}; + } + + return createIndex(parentsRow, 0, parentId); } +void TimelineModel::setItemStartTime(Track& t, Item& i, qint64 newStart) +{ + i._setStartTime(newStart); + t.sort(); +} + +void TimelineModel::setItemStartTime(Item& i, qint64 newStart) noexcept(false) +{ + setItemStartTime(track(i.parentTrackId()), i, newStart); +} void TimelineModel::setItemStartTime(int itemId, qint64 newStart) noexcept(false) { - setItemStartTime(item(itemId), newStart); + setItemStartTime(item(itemId), newStart); } - -void TimelineModel::setItemDuration(Track &t, Item &i, int duration) +void TimelineModel::setItemDuration(Track& t, Item& i, int duration) { - i._setDuration(std::max(duration, m_minItemDuration)); - t.sort(); + i._setDuration(std::max(duration, m_minItemDuration)); + t.sort(); } -void TimelineModel::setItemDuration(Item &i, int duration) noexcept(false) +void TimelineModel::setItemDuration(Item& i, int duration) noexcept(false) { - setItemDuration(track(i.parentTrackId()), i, duration); + setItemDuration(track(i.parentTrackId()), i, duration); } void TimelineModel::setItemDuration(int itemId, int duration) noexcept(false) { - setItemDuration(item(itemId), duration); + setItemDuration(item(itemId), duration); } - -void TimelineModel::copyToClipboard(const QVector &ids) noexcept(false) +void TimelineModel::copyToClipboard(const QVector& ids) noexcept(false) { - m_clipboard.clear(); - m_clipboard.reserve(ids.size()); - qint64 tStartMin = LLONG_MAX; - for (int itemId : std::as_const(ids)) - { - const Item &i = item(itemId); - ItemPtr iPtr = std::make_unique(Item(i.startTime(), i.duration(), i.color())); - iPtr->m_parentTrackId = i.m_parentTrackId; - m_clipboard.push_back(std::move(iPtr)); - tStartMin = std::min(tStartMin, i.startTime()); - } - for (ItemPtr &iPtr : m_clipboard) - iPtr->_setStartTime(iPtr->startTime() - tStartMin); + m_clipboard.clear(); + m_clipboard.reserve(ids.size()); + qint64 tStartMin = LLONG_MAX; + for (int itemId : std::as_const(ids)) + { + const Item& i = item(itemId); + ItemPtr iPtr = std::make_unique(Item(i.startTime(), i.duration(), i.color())); + iPtr->m_parentTrackId = i.m_parentTrackId; + m_clipboard.push_back(std::move(iPtr)); + tStartMin = std::min(tStartMin, i.startTime()); + } + for (ItemPtr& iPtr : m_clipboard) + iPtr->_setStartTime(iPtr->startTime() - tStartMin); } -void TimelineModel::cutToClipboard(const QVector &ids) noexcept(false) +void TimelineModel::cutToClipboard(const QVector& ids) noexcept(false) { - copyToClipboard(ids); - for (int itemId : std::as_const(ids)) - removeItem(itemId); + copyToClipboard(ids); + for (int itemId : std::as_const(ids)) + removeItem(itemId); } void TimelineModel::pasteFromClipboard(qint64 time) noexcept(false) { - if (m_isSnapEnabled) - time -= (time % m_snapStep); - for (ItemPtr &iPtr : m_clipboard) - { - iPtr->_setStartTime(time + iPtr->startTime()); - addItem(iPtr->parentTrackId(), std::move(iPtr)); - } - m_clipboard.clear(); + if (m_isSnapEnabled) + time -= (time % m_snapStep); + for (ItemPtr& iPtr : m_clipboard) + { + iPtr->_setStartTime(time + iPtr->startTime()); + addItem(iPtr->parentTrackId(), std::move(iPtr)); + } + m_clipboard.clear(); } - -int TimelineModel::rowCount(const QModelIndex &parent) const +int TimelineModel::rowCount(const QModelIndex& parent) const { - if (parent.column() > 0) + if (parent.column() > 0) + return 0; + + if (!parent.isValid()) + return m_rootTrack.tracks().size(); + + try + { + return track(parent.internalId()).tracks().size(); + } + catch (...) + { + } + return 0; - - if (!parent.isValid()) - return m_rootTrack.tracks().size(); - - try - { - return track(parent.internalId()).tracks().size(); - } - catch(...) {} - - return 0; } - QModelIndex TimelineModel::indexOfTrack(int trackId) const { - for (int row = 0; row < rowCount(); ++row) - { - QModelIndex idx = indexOfTrackFromIndex(index(row, 0, {}), trackId); - if (idx.isValid()) - return idx; - } - return {}; + for (int row = 0; row < rowCount(); ++row) + { + QModelIndex idx = indexOfTrackFromIndex(index(row, 0, {}), trackId); + if (idx.isValid()) + return idx; + } + return {}; } - -QModelIndex TimelineModel::indexOfTrackFromIndex(const QModelIndex &idx, int trackId) const +QModelIndex TimelineModel::indexOfTrackFromIndex(const QModelIndex& idx, int trackId) const { - if (static_cast(idx.internalId()) == trackId) - return index(idx.row(), 1, idx.parent()); + if (static_cast(idx.internalId()) == trackId) + return index(idx.row(), 1, idx.parent()); - for (int row = 0; row < rowCount(idx); ++row) - { - const QModelIndex i = indexOfTrackFromIndex(index(row, 0, idx), trackId); - if (i.isValid()) - return i; - } + for (int row = 0; row < rowCount(idx); ++row) + { + const QModelIndex i = indexOfTrackFromIndex(index(row, 0, idx), trackId); + if (i.isValid()) + return i; + } - return {}; + return {}; } - QModelIndex TimelineModel::indexOfTrackSafe(int trackId) const noexcept(false) { - for (int row = 0; row < rowCount(); ++row) - { - const QModelIndex idx(indexOfTrackFromIndex(index(row, 0 , {}), trackId)); - if (idx.isValid()) - return idx; - } + for (int row = 0; row < rowCount(); ++row) + { + const QModelIndex idx(indexOfTrackFromIndex(index(row, 0, {}), trackId)); + if (idx.isValid()) + return idx; + } - QString trackText; - try - { - trackText = track(trackId).text(); - } catch(...){} + QString trackText; + try + { + trackText = track(trackId).text(); + } + catch (...) + { + } - throw QStringLiteral("indexOfTrackSafe: index for trackId %1 ('%2') not found ").arg(trackId).arg(trackText.isEmpty() ? QStringLiteral("(unknown)") : trackText); + throw QStringLiteral("indexOfTrackSafe: index for trackId %1 ('%2') not found ") + .arg(trackId) + .arg(trackText.isEmpty() ? QStringLiteral("(unknown)") : trackText); } - -QModelIndex TimelineModel::indexOfTrackFromIndexSafe(const QModelIndex &idx, int trackId) const noexcept(false) +QModelIndex TimelineModel::indexOfTrackFromIndexSafe(const QModelIndex& idx, int trackId) const noexcept(false) { - if (static_cast(idx.internalId()) == trackId) - return idx; + if (static_cast(idx.internalId()) == trackId) + return idx; - for (int row = 0; row < rowCount(idx); ++row) - { - const QModelIndex i = indexOfTrackFromIndex(index(row, 1, idx), trackId); - if (i.isValid()) - return i; - } + for (int row = 0; row < rowCount(idx); ++row) + { + const QModelIndex i = indexOfTrackFromIndex(index(row, 1, idx), trackId); + if (i.isValid()) + return i; + } - throw QStringLiteral("indexOfTrackFromIndexSafe: index for trackId %1 not found").arg(trackId); + throw QStringLiteral("indexOfTrackFromIndexSafe: index for trackId %1 not found").arg(trackId); } - void TimelineModel::moveItemToTrack(int itemId, int trackId, qint64 time) noexcept(false) { - + const Item& theItem = item(itemId); + Track& oldTrack = track(theItem.parentTrackId()); + Track& newTrack = track(trackId); - const Item &theItem = item(itemId); - Track &oldTrack = track(theItem.parentTrackId()); - Track &newTrack = track(trackId); + ItemPtr itemPtr = oldTrack.takeItem(itemId); - ItemPtr itemPtr = oldTrack.takeItem(itemId); - - Item *theItemPtr = newTrack.addItem(std::move(itemPtr)); - setItemStartTime(newTrack, *theItemPtr, time); - theItemPtr->m_parentTrackId = trackId; + Item* theItemPtr = newTrack.addItem(std::move(itemPtr)); + setItemStartTime(newTrack, *theItemPtr, time); + theItemPtr->m_parentTrackId = trackId; } - void TimelineModel::removeItem(int itemId) noexcept(false) { - const Item &i = item(itemId); - Track &t = track(i.parentTrackId()); + const Item& i = item(itemId); + Track& t = track(i.parentTrackId()); - t.removeItem(itemId); + t.removeItem(itemId); - auto it = m_itemCache.find(itemId); - if (it == m_itemCache.end()) - { - Q_ASSERT(false); - throw QStringLiteral("removeItem: item with id %1 not found").arg(itemId); - } - - m_itemCache.erase(it); - - - -} - - -void TimelineModel::removeTrack(int trackId) noexcept(false) -{ - if (trackId == m_rootTrack.id()) - { - Q_ASSERT(false); - throw QStringLiteral("removeTrack: the root track shouldn't and *can't* be deleted"); - } - - - const Track &t = track(trackId); - Track &parentTrack = track(t.parentId()); - - for (int itemId : t.itemIds(true)) - { auto it = m_itemCache.find(itemId); - if (it == m_itemCache.end()) { - Q_ASSERT(false); - continue; + Q_ASSERT(false); + throw QStringLiteral("removeItem: item with id %1 not found").arg(itemId); } m_itemCache.erase(it); - } - - - parentTrack.removeTrack(trackId); - - auto it = m_trackCache.find(trackId); - if (it == m_trackCache.end()) - { - Q_ASSERT(false); - return; - } - - m_trackCache.erase(it); } +void TimelineModel::removeTrack(int trackId) noexcept(false) +{ + if (trackId == m_rootTrack.id()) + { + Q_ASSERT(false); + throw QStringLiteral("removeTrack: the root track shouldn't and *can't* be deleted"); + } + + const Track& t = track(trackId); + Track& parentTrack = track(t.parentId()); + + for (int itemId : t.itemIds(true)) + { + auto it = m_itemCache.find(itemId); + + if (it == m_itemCache.end()) + { + Q_ASSERT(false); + continue; + } + + m_itemCache.erase(it); + } + + parentTrack.removeTrack(trackId); + + auto it = m_trackCache.find(trackId); + if (it == m_trackCache.end()) + { + Q_ASSERT(false); + return; + } + + m_trackCache.erase(it); +} void TimelineModel::setMinimumDuration(int duration) { - if (duration < 0) - { - WARNING_LOG(m_logger) << "negative duration is not possible -> setting minimum duration to 0"; - duration = 0; - } - if (duration % 1000 && m_isSnapEnabled) - WARNING_LOG(m_logger) << "Snapping to 1000ms enabled, yet minimum duration is not a multiple of 1000ms: " << duration; - m_minItemDuration = duration; + if (duration < 0) + { + WARNING_LOG(m_logger) << "negative duration is not possible -> setting minimum duration to 0"; + duration = 0; + } + if (duration % 1000 && m_isSnapEnabled) + WARNING_LOG(m_logger) << "Snapping to 1000ms enabled, yet minimum duration is not a multiple of 1000ms: " + << duration; + m_minItemDuration = duration; } -bool TimelineModel::canDropItem(const Item &item, int trackId, qint64 start) const +bool TimelineModel::canDropItem(const Item& item, int trackId, qint64 start) const { - Q_UNUSED(item); - Q_UNUSED(trackId); - Q_UNUSED(start); - return true; + Q_UNUSED(item); + Q_UNUSED(trackId); + Q_UNUSED(start); + return true; } -bool TimelineModel::canMoveItem(const Item &item, qint64 start) const +bool TimelineModel::canMoveItem(const Item& item, qint64 start) const { - Q_UNUSED(item); - Q_UNUSED(start); - return true; + Q_UNUSED(item); + Q_UNUSED(start); + return true; } -bool TimelineModel::canResizeItem(const Item &item, qint64 start, int duration) const +bool TimelineModel::canResizeItem(const Item& item, qint64 start, int duration) const { - Q_UNUSED(item); - Q_UNUSED(start); - Q_UNUSED(duration); - return true; + Q_UNUSED(item); + Q_UNUSED(start); + Q_UNUSED(duration); + return true; } - bool TimelineModel::isItemDragged(int _itemId) const { - return m_view->dragHandler() ? m_view->dragHandler()->dragItemIds().contains(_itemId) : false; + return m_view->dragHandler() ? m_view->dragHandler()->dragItemIds().contains(_itemId) : false; } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.h old mode 100755 new mode 100644 index 8ae84e87d..ae64643c8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_model.h @@ -1,248 +1,301 @@ - #pragma once -#include - #include "item.h" +#include "ltstimeline_export.h" #include "track.h" -#include "ltstimeline_export.h" - -#include #include - +#include +#include #include - namespace LtsTimeline { class TimelineView; - class LTSTIMELINE_EXPORT TimelineModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT - friend class TimelineViewSelectHandler; + friend class TimelineViewSelectHandler; -public: - explicit TimelineModel(TimelineView *view, QObject *parent = nullptr); - virtual ~TimelineModel() = default; + public: + explicit TimelineModel(TimelineView* view, QObject* parent = nullptr); + virtual ~TimelineModel() = default; - void clear(); - Track &rootTrack() { return m_rootTrack; } - Track &track(int id) noexcept(false); - const Track &track(int id) const noexcept(false); - const Item &item(int id) const noexcept(false); - Item &item(int id) noexcept(false); - const QVector itemIds() const; - const QVector itemIdsBetween(qint64 start, qint64 end, bool strict = false, bool complete = false, bool recursive = false, bool sorted = false) const; - const QVector copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool sorted) const; - - bool isItemsBetween(qint64 start, qint64 end, const QVector &ignoreIds = {}, bool strict = false, bool complete = false, bool recursive = false) const; - bool isItemsBetween(qint64 start, qint64 end, int ignoreId = -1 , bool strict = false, bool complete = false, bool recursive = false) const; - const Track &parentOfTrackId(int id) const noexcept(false); + void clear(); - virtual void setItemStartTime(Track &t, Item &i, qint64 newStart); - virtual void setItemStartTime(Item &i, qint64 newStart) noexcept(false); - virtual void setItemStartTime(int itemId, qint64 newStart) noexcept(false); - - virtual void setItemDuration(Track &t, Item &i, int duration); - virtual void setItemDuration(Item &i, int duration) noexcept(false); - virtual void setItemDuration(int itemId, int duration) noexcept(false); - - - void print(bool withItems = false) const { m_rootTrack.printTrackIds(withItems); } - - template ::value, TrackClass>::type> - int addTrack(int parentTrackId, TrackClass &&newTrack ) noexcept(false) - { - int id = nextFreeTrackId(); - - TrackClass _track(std::move(newTrack)); - _track.m_id = id; - _track.m_parentId = parentTrackId; - - - - - - auto *ptr = track(parentTrackId).addTrack(std::move(_track)); - m_trackCache.insert(std::pair(id, ptr)); - - - - return id; - } - - template ::value, ItemClass>::type> - int addItem(int parentTrackId, ItemClass &&item) noexcept(false) - { - int id = nextFreeItemId(); - - ItemClass _item(std::move(item)); - _item.m_id = id; - _item.m_parentTrackId = parentTrackId; - - if (m_isSnapEnabled) + Track& rootTrack() { - _item.m_startTime = _item.m_startTime - (_item.m_startTime % 1000); - _item.m_duration = _item.m_duration - (_item.m_duration % 1000); + return m_rootTrack; } - Item *ptr = track(parentTrackId).addItem(std::move(_item)); - m_itemCache.insert(std::pair(id, ptr)); + Track& track(int id) noexcept(false); + const Track& track(int id) const noexcept(false); + const Item& item(int id) const noexcept(false); + Item& item(int id) noexcept(false); + const QVector itemIds() const; + const QVector itemIdsBetween(qint64 start, qint64 end, bool strict = false, bool complete = false, + bool recursive = false, bool sorted = false) const; + const QVector copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool sorted) const; - QModelIndex idx = indexOfTrack(parentTrackId); - emit dataChanged(idx, idx); + bool isItemsBetween(qint64 start, qint64 end, const QVector& ignoreIds = {}, bool strict = false, + bool complete = false, bool recursive = false) const; + bool isItemsBetween(qint64 start, qint64 end, int ignoreId = -1, bool strict = false, bool complete = false, + bool recursive = false) const; + const Track& parentOfTrackId(int id) const noexcept(false); - return id; - } + virtual void setItemStartTime(Track& t, Item& i, qint64 newStart); + virtual void setItemStartTime(Item& i, qint64 newStart) noexcept(false); + virtual void setItemStartTime(int itemId, qint64 newStart) noexcept(false); - bool isEditable() const { return m_isEditable; } - void setEditable(bool editable) { m_isEditable = editable; } - bool isSnapEnabled() const { return m_isSnapEnabled; } - void setSnapEnabled(bool enabled) { m_isSnapEnabled = enabled; } - int snapStep() const { return m_snapStep; } - void setSnapStep(int step) { m_snapStep = step; } - int snapTolerance() const { return m_snapTol; } - void setSnapTolerance(int tolerance) { m_snapTol = tolerance; } - qint64 snapTime(qint64 time) const { return m_isSnapEnabled ? time / m_snapStep * m_snapStep : time; } - int minimumDuration() const { return m_minItemDuration; } - void setMinimumDuration(int duration); + virtual void setItemDuration(Track& t, Item& i, int duration); + virtual void setItemDuration(Item& i, int duration) noexcept(false); + virtual void setItemDuration(int itemId, int duration) noexcept(false); - QModelIndex indexOfTrack(int trackId) const; - QModelIndex indexOfTrackSafe(int trackId) const noexcept(false); - - virtual void moveItemToTrack(int itemId, int trackId, qint64 time) noexcept(false); - virtual void removeItem(int itemId) noexcept(false); - virtual void removeTrack(int trackId) noexcept(false); - - virtual bool canDropItem(const Item &item, int trackId, qint64 start) const; - virtual bool canMoveItem(const Item &item, qint64 start) const; - virtual bool canResizeItem(const Item &item, qint64 start, int duration) const; - - virtual bool isItemDragged(int _itemId) const; - - virtual void copyToClipboard(const QVector &ids) noexcept(false); - virtual void cutToClipboard(const QVector &ids) noexcept(false); - virtual void pasteFromClipboard(qint64 time) noexcept(false); - - bool isClipboardEmpty() const { return m_clipboard.empty(); } - - - int rowCount(const QModelIndex &parent = {}) const override; - QVariant data(const QModelIndex &index, int role) const override; - QModelIndex index(int row, int column, const QModelIndex &parent) const override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QModelIndex parent(const QModelIndex &index) const override; - int columnCount(const QModelIndex &) const override { return 2; } - -protected: - NGL::INGLLogger &m_logger; - ItemPtrNCVRef _itemNCV(Track &track, int id) noexcept(false) - { - return track._itemNCV(id); - } - - ItemPtrNCVRef _itemNCV(const TrackPtr &trackPtr, int id) noexcept(false) - { - return trackPtr->_itemNCV(id); - } - - const ItemPtrRefs _items(const TrackPtr &trackPtr, bool recursive) const - { - return trackPtr->_items(recursive); - } - - ItemPtrNCVRefs _itemsNCV(const TrackPtr &trackPtr, bool recursive) - { - return trackPtr->_itemsNCV(recursive); - } - - - - int addItem(int parentTrackId, ItemPtr &&itemPtr, bool forceTheCompilerToUseMe = false) noexcept(false) - { - (void)forceTheCompilerToUseMe; - - int id = nextFreeItemId(); - - ItemPtr _itemPtr(std::move(itemPtr)); - - _itemPtr->m_id = id; - - _itemPtr->m_parentTrackId = parentTrackId; - - if (m_isSnapEnabled) + void print(bool withItems = false) const { - _itemPtr->m_startTime = _itemPtr->m_startTime - (_itemPtr->m_startTime % 1000); - _itemPtr->m_duration = _itemPtr->m_duration - (_itemPtr->m_duration % 1000); + m_rootTrack.printTrackIds(withItems); } - Item *ptr = track(parentTrackId).addItem(std::move(_itemPtr)); - - m_itemCache.insert(std::pair(id, ptr)); - QModelIndex idx = indexOfTrack(parentTrackId); - emit dataChanged(idx, idx); + template ::value, TrackClass>::type> + int addTrack(int parentTrackId, TrackClass&& newTrack) noexcept(false) + { + int id = nextFreeTrackId(); - return id; - } + TrackClass _track(std::move(newTrack)); + _track.m_id = id; + _track.m_parentId = parentTrackId; + auto* ptr = track(parentTrackId).addTrack(std::move(_track)); + m_trackCache.insert(std::pair(id, ptr)); + return id; + } + template ::value, ItemClass>::type> + int addItem(int parentTrackId, ItemClass&& item) noexcept(false) + { + int id = nextFreeItemId(); + ItemClass _item(std::move(item)); + _item.m_id = id; + _item.m_parentTrackId = parentTrackId; + if (m_isSnapEnabled) + { + _item.m_startTime = _item.m_startTime - (_item.m_startTime % 1000); + _item.m_duration = _item.m_duration - (_item.m_duration % 1000); + } + Item* ptr = track(parentTrackId).addItem(std::move(_item)); + m_itemCache.insert(std::pair(id, ptr)); + QModelIndex idx = indexOfTrack(parentTrackId); + emit dataChanged(idx, idx); + return id; + } - void clearItems(); - int rowOfTrackId(int id) const noexcept(false); + bool isEditable() const + { + return m_isEditable; + } - + void setEditable(bool editable) + { + m_isEditable = editable; + } - const Track &trackOfIndex(const QModelIndex &index) const; - int indexOf(int id) const; + bool isSnapEnabled() const + { + return m_isSnapEnabled; + } - const QVector _itemIdsBetween(Track &t, qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const; - const QVector _copyItemIdsBetween(Track &t, qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const; - bool _isItemsBetween(const Track &t, qint64 start, qint64 end, const QVector &ignoreIds, bool strict, bool complete, bool recursive, qint64 minimumDuration) const; - bool _isItemsBetween(const Track &t, qint64 start, qint64 end, int ignoreId, bool strict, bool complete, bool recursive, qint64 minimumDuration) const; + void setSnapEnabled(bool enabled) + { + m_isSnapEnabled = enabled; + } -private: - int nextFreeTrackId() { return m_currentTrackId++; } - int nextFreeItemId() { return m_currentItemId++; } + int snapStep() const + { + return m_snapStep; + } - QModelIndex indexOfTrackFromIndex(const QModelIndex &idx, int trackId) const; - QModelIndex indexOfTrackFromIndexSafe(const QModelIndex &idx, int trackId) const noexcept(false); + void setSnapStep(int step) + { + m_snapStep = step; + } -public slots: - virtual void onInsertTrack(const QModelIndex &index) { Q_UNUSED(index); } - virtual void onRemoveTrack(const QModelIndex &index) { Q_UNUSED(index); } + int snapTolerance() const + { + return m_snapTol; + } -protected: - NGL::INGLLogger &m_logger; - TimelineView *m_view{nullptr}; + void setSnapTolerance(int tolerance) + { + m_snapTol = tolerance; + } - Track m_rootTrack; - int m_currentTrackId{0}; - int m_currentItemId{0}; - bool m_isEditable{true}; - bool m_isSnapEnabled{false}; - int m_snapStep{500}; - int m_snapTol{1000}; - int m_minItemDuration{0}; + qint64 snapTime(qint64 time) const + { + return m_isSnapEnabled ? time / m_snapStep * m_snapStep : time; + } - - bool m_itemCaching{true}; - bool m_trackCaching{true}; - std::map m_trackCache; - - std::map m_itemCache; - Items m_clipboard; + int minimumDuration() const + { + return m_minItemDuration; + } + + void setMinimumDuration(int duration); + + QModelIndex indexOfTrack(int trackId) const; + QModelIndex indexOfTrackSafe(int trackId) const noexcept(false); + + virtual void moveItemToTrack(int itemId, int trackId, qint64 time) noexcept(false); + virtual void removeItem(int itemId) noexcept(false); + virtual void removeTrack(int trackId) noexcept(false); + + virtual bool canDropItem(const Item& item, int trackId, qint64 start) const; + virtual bool canMoveItem(const Item& item, qint64 start) const; + virtual bool canResizeItem(const Item& item, qint64 start, int duration) const; + + virtual bool isItemDragged(int _itemId) const; + + virtual void copyToClipboard(const QVector& ids) noexcept(false); + virtual void cutToClipboard(const QVector& ids) noexcept(false); + virtual void pasteFromClipboard(qint64 time) noexcept(false); + + bool isClipboardEmpty() const + { + return m_clipboard.empty(); + } + + int rowCount(const QModelIndex& parent = {}) const override; + QVariant data(const QModelIndex& index, int role) const override; + QModelIndex index(int row, int column, const QModelIndex& parent) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QModelIndex parent(const QModelIndex& index) const override; + + int columnCount(const QModelIndex&) const override + { + return 2; + } + + protected: + NGL::INGLLogger& m_logger; + + ItemPtrNCVRef _itemNCV(Track& track, int id) noexcept(false) + { + return track._itemNCV(id); + } + + ItemPtrNCVRef _itemNCV(const TrackPtr& trackPtr, int id) noexcept(false) + { + return trackPtr->_itemNCV(id); + } + + const ItemPtrRefs _items(const TrackPtr& trackPtr, bool recursive) const + { + return trackPtr->_items(recursive); + } + + ItemPtrNCVRefs _itemsNCV(const TrackPtr& trackPtr, bool recursive) + { + return trackPtr->_itemsNCV(recursive); + } + + int addItem(int parentTrackId, ItemPtr&& itemPtr, bool forceTheCompilerToUseMe = false) noexcept(false) + { + (void)forceTheCompilerToUseMe; + + int id = nextFreeItemId(); + + ItemPtr _itemPtr(std::move(itemPtr)); + + _itemPtr->m_id = id; + + _itemPtr->m_parentTrackId = parentTrackId; + + if (m_isSnapEnabled) + { + _itemPtr->m_startTime = _itemPtr->m_startTime - (_itemPtr->m_startTime % 1000); + _itemPtr->m_duration = _itemPtr->m_duration - (_itemPtr->m_duration % 1000); + } + Item* ptr = track(parentTrackId).addItem(std::move(_itemPtr)); + + m_itemCache.insert(std::pair(id, ptr)); + + QModelIndex idx = indexOfTrack(parentTrackId); + emit dataChanged(idx, idx); + + return id; + } + + void clearItems(); + int rowOfTrackId(int id) const noexcept(false); + + const Track& trackOfIndex(const QModelIndex& index) const; + int indexOf(int id) const; + + const QVector _itemIdsBetween(Track& t, qint64 start, qint64 end, bool strict, bool complete, bool recursive, + bool sorted, qint64 minimumDuration) const; + const QVector _copyItemIdsBetween(Track& t, qint64 start, qint64 end, bool strict, bool complete, + bool recursive, bool sorted, qint64 minimumDuration) const; + bool _isItemsBetween(const Track& t, qint64 start, qint64 end, const QVector& ignoreIds, bool strict, + bool complete, bool recursive, qint64 minimumDuration) const; + bool _isItemsBetween(const Track& t, qint64 start, qint64 end, int ignoreId, bool strict, bool complete, + bool recursive, qint64 minimumDuration) const; + + private: + int nextFreeTrackId() + { + return m_currentTrackId++; + } + + int nextFreeItemId() + { + return m_currentItemId++; + } + + QModelIndex indexOfTrackFromIndex(const QModelIndex& idx, int trackId) const; + QModelIndex indexOfTrackFromIndexSafe(const QModelIndex& idx, int trackId) const noexcept(false); + + public slots: + + virtual void onInsertTrack(const QModelIndex& index) + { + Q_UNUSED(index); + } + + virtual void onRemoveTrack(const QModelIndex& index) + { + Q_UNUSED(index); + } + + protected: + NGL::INGLLogger& m_logger; + TimelineView* m_view{nullptr}; + + Track m_rootTrack; + int m_currentTrackId{0}; + int m_currentItemId{0}; + bool m_isEditable{true}; + bool m_isSnapEnabled{false}; + int m_snapStep{500}; + int m_snapTol{1000}; + int m_minItemDuration{0}; + + bool m_itemCaching{true}; + bool m_trackCaching{true}; + std::map m_trackCache; + + std::map m_itemCache; + Items m_clipboard; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.cpp old mode 100755 new mode 100644 index db16f0ede..adf175b28 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.cpp @@ -1,11 +1,9 @@ #include "timeline_utils.h" -#include -#include - #include #include - +#include +#include namespace LtsTimeline { @@ -13,331 +11,324 @@ namespace LtsTimeline namespace DateTime { - - - int numberOfDateTimeFormats() { - return 6; + return 6; } QString toString(qint64 time, Format format) { - switch (format) - { - case Format::DTG: - return DTG::toStringMSec(time, DTG::DisplayFormat::Long); - case Format::ISODate: - return QDateTime::fromMSecsSinceEpoch(time).toString(Qt::ISODate); - case Format::Standard: - return QDateTime::fromMSecsSinceEpoch(time).toString(QStringLiteral("dd.MM.yyyy hh:mm:ss")); - case Format::DTGShort: - { - QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(time).toUTC().addSecs(DTG::timezone2Hours(DTG::timezone()) * 3600); - return dateTime.toString(QStringLiteral("hhmmss ")) + QStringLiteral("%1").arg(DTG::timezone()); - } - case Format::DTGVeryShort: - { - QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(time).toUTC().addSecs(DTG::timezone2Hours(DTG::timezone()) * 3600); - return dateTime.toString(QStringLiteral("hhmm")); - } - case Format::TimeOnly: - return QTime::fromMSecsSinceStartOfDay(time).toString(); - } - return {}; + switch (format) + { + case Format::DTG: + return DTG::toStringMSec(time, DTG::DisplayFormat::Long); + case Format::ISODate: + return QDateTime::fromMSecsSinceEpoch(time).toString(Qt::ISODate); + case Format::Standard: + return QDateTime::fromMSecsSinceEpoch(time).toString(QStringLiteral("dd.MM.yyyy hh:mm:ss")); + case Format::DTGShort: { + QDateTime dateTime = + QDateTime::fromMSecsSinceEpoch(time).toUTC().addSecs(DTG::timezone2Hours(DTG::timezone()) * 3600); + return dateTime.toString(QStringLiteral("hhmmss ")) + QStringLiteral("%1").arg(DTG::timezone()); + } + case Format::DTGVeryShort: { + QDateTime dateTime = + QDateTime::fromMSecsSinceEpoch(time).toUTC().addSecs(DTG::timezone2Hours(DTG::timezone()) * 3600); + return dateTime.toString(QStringLiteral("hhmm")); + } + case Format::TimeOnly: + return QTime::fromMSecsSinceStartOfDay(time).toString(); + } + return {}; } -} - - - - +} // namespace DateTime namespace Zoom { int numberOfZoomFactors() { - return 15; + return 15; } Factor LTSTIMELINE_EXPORT increment(Factor factor) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: - return ZoomFactor::ThirtySeconds; - case ZoomFactor::ThirtySeconds: - return ZoomFactor::SixtySeconds; - case ZoomFactor::SixtySeconds: - return ZoomFactor::TwoMinutes; - case ZoomFactor::TwoMinutes: - return ZoomFactor::ThreeMinutes; - case ZoomFactor::ThreeMinutes: - return ZoomFactor::FiveMinutes; - case ZoomFactor::FiveMinutes: - return ZoomFactor::TenMinutes; - case ZoomFactor::TenMinutes: - return ZoomFactor::FifteenMinutes; - case ZoomFactor::FifteenMinutes: - return ZoomFactor::ThirtyMinutes; - case ZoomFactor::ThirtyMinutes: - return ZoomFactor::SixtyMinutes; - case ZoomFactor::SixtyMinutes: - return ZoomFactor::TwoHours; - case ZoomFactor::TwoHours: - return ZoomFactor::FourHours; - case ZoomFactor::FourHours: - return ZoomFactor::EightHours; - case ZoomFactor::EightHours: - return ZoomFactor::TwelveHours; - case ZoomFactor::TwelveHours: - return ZoomFactor::OneDay; - case ZoomFactor::OneDay: - return ZoomFactor::OneDay; - } - return factor; + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return ZoomFactor::ThirtySeconds; + case ZoomFactor::ThirtySeconds: + return ZoomFactor::SixtySeconds; + case ZoomFactor::SixtySeconds: + return ZoomFactor::TwoMinutes; + case ZoomFactor::TwoMinutes: + return ZoomFactor::ThreeMinutes; + case ZoomFactor::ThreeMinutes: + return ZoomFactor::FiveMinutes; + case ZoomFactor::FiveMinutes: + return ZoomFactor::TenMinutes; + case ZoomFactor::TenMinutes: + return ZoomFactor::FifteenMinutes; + case ZoomFactor::FifteenMinutes: + return ZoomFactor::ThirtyMinutes; + case ZoomFactor::ThirtyMinutes: + return ZoomFactor::SixtyMinutes; + case ZoomFactor::SixtyMinutes: + return ZoomFactor::TwoHours; + case ZoomFactor::TwoHours: + return ZoomFactor::FourHours; + case ZoomFactor::FourHours: + return ZoomFactor::EightHours; + case ZoomFactor::EightHours: + return ZoomFactor::TwelveHours; + case ZoomFactor::TwelveHours: + return ZoomFactor::OneDay; + case ZoomFactor::OneDay: + return ZoomFactor::OneDay; + } + return factor; } Factor LTSTIMELINE_EXPORT decrement(Factor factor) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: - return ZoomFactor::FifteenSeconds; - case ZoomFactor::ThirtySeconds: - return ZoomFactor::FifteenSeconds; - case ZoomFactor::SixtySeconds: - return ZoomFactor::ThirtySeconds; - case ZoomFactor::TwoMinutes: - return ZoomFactor::SixtySeconds; - case ZoomFactor::ThreeMinutes: - return ZoomFactor::TwoMinutes; - case ZoomFactor::FiveMinutes: - return ZoomFactor::ThreeMinutes; - case ZoomFactor::TenMinutes: - return ZoomFactor::FiveMinutes; - case ZoomFactor::FifteenMinutes: - return ZoomFactor::TenMinutes; - case ZoomFactor::ThirtyMinutes: - return ZoomFactor::FifteenMinutes; - case ZoomFactor::SixtyMinutes: - return ZoomFactor::ThirtyMinutes; - case ZoomFactor::TwoHours: - return ZoomFactor::SixtyMinutes; - case ZoomFactor::FourHours: - return ZoomFactor::TwoHours; - case ZoomFactor::EightHours: - return ZoomFactor::FourHours; - case ZoomFactor::TwelveHours: - return ZoomFactor::EightHours; - case ZoomFactor::OneDay: - return ZoomFactor::TwelveHours; - } - return factor; + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return ZoomFactor::FifteenSeconds; + case ZoomFactor::ThirtySeconds: + return ZoomFactor::FifteenSeconds; + case ZoomFactor::SixtySeconds: + return ZoomFactor::ThirtySeconds; + case ZoomFactor::TwoMinutes: + return ZoomFactor::SixtySeconds; + case ZoomFactor::ThreeMinutes: + return ZoomFactor::TwoMinutes; + case ZoomFactor::FiveMinutes: + return ZoomFactor::ThreeMinutes; + case ZoomFactor::TenMinutes: + return ZoomFactor::FiveMinutes; + case ZoomFactor::FifteenMinutes: + return ZoomFactor::TenMinutes; + case ZoomFactor::ThirtyMinutes: + return ZoomFactor::FifteenMinutes; + case ZoomFactor::SixtyMinutes: + return ZoomFactor::ThirtyMinutes; + case ZoomFactor::TwoHours: + return ZoomFactor::SixtyMinutes; + case ZoomFactor::FourHours: + return ZoomFactor::TwoHours; + case ZoomFactor::EightHours: + return ZoomFactor::FourHours; + case ZoomFactor::TwelveHours: + return ZoomFactor::EightHours; + case ZoomFactor::OneDay: + return ZoomFactor::TwelveHours; + } + return factor; } Factor ceil(int value) { - if (value >= Factor::OneDay) - return Factor::OneDay; + if (value >= Factor::OneDay) + return Factor::OneDay; - Factor ret = Factor::FifteenSeconds; - while (static_cast(ret) < value) - { - ret = increment(ret); - } - return ret; + Factor ret = Factor::FifteenSeconds; + while (static_cast(ret) < value) + { + ret = increment(ret); + } + return ret; } Factor floor(int value) { - if (value <= Factor::FifteenSeconds) - return Factor::FifteenSeconds; + if (value <= Factor::FifteenSeconds) + return Factor::FifteenSeconds; - Factor ret = Factor::OneDay; - while (static_cast(ret) > value) - { - ret = decrement(ret); - } - return ret; + Factor ret = Factor::OneDay; + while (static_cast(ret) > value) + { + ret = decrement(ret); + } + return ret; } QVector availableZoomFactors(Factor min, Factor max) { - if (min > max) - return {}; + if (min > max) + return {}; - ZoomFactors ret; - ret.reserve(numberOfZoomFactors()); - Factor factor = min; - do - { - ret.append(factor); - if (factor == max) - break; - factor = increment(factor); - } while (increment(factor) > factor); - return ret; + ZoomFactors ret; + ret.reserve(numberOfZoomFactors()); + Factor factor = min; + do + { + ret.append(factor); + if (factor == max) + break; + factor = increment(factor); + } while (increment(factor) > factor); + return ret; } QString toString(ZoomFactor factor, bool useShort) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: - return useShort ? QApplication::tr("15 sec") : QApplication::tr("15 Seconds"); - case ZoomFactor::ThirtySeconds: - return useShort ? QApplication::tr("30 sec") : QApplication::tr("30 Seconds"); - case ZoomFactor::SixtySeconds: - return useShort ? QApplication::tr("1 min") : QApplication::tr("1 Minute"); - case ZoomFactor::TwoMinutes: - return useShort ? QApplication::tr("2 min") : QApplication::tr("2 Minutes"); - case ZoomFactor::ThreeMinutes: - return useShort ? QApplication::tr("3 min") : QApplication::tr("3 Minutes"); - case ZoomFactor::FiveMinutes: - return useShort ? QApplication::tr("5 min") : QApplication::tr("5 Minutes"); - case ZoomFactor::TenMinutes: - return useShort ? QApplication::tr("10 min") : QApplication::tr("10 Minutes"); - case ZoomFactor::FifteenMinutes: - return useShort ? QApplication::tr("15 min") : QApplication::tr("15 Minutes"); - case ZoomFactor::ThirtyMinutes: - return useShort ? QApplication::tr("30 min") : QApplication::tr("30 Minutes"); - case ZoomFactor::SixtyMinutes: - return useShort ? QApplication::tr("1 h") : QApplication::tr("1 Hour"); - case ZoomFactor::TwoHours: - return useShort ? QApplication::tr("2 h") : QApplication::tr("2 Hours"); - case ZoomFactor::FourHours: - return useShort ? QApplication::tr("4 h") : QApplication::tr("4 Hours"); - case ZoomFactor::EightHours: - return useShort ? QApplication::tr("8 h") : QApplication::tr("8 Hours"); - case ZoomFactor::TwelveHours: - return useShort ? QApplication::tr("12 h") : QApplication::tr("12 Hours"); - case ZoomFactor::OneDay: - return useShort ? QApplication::tr("1 d") : QApplication::tr("1 Day"); - } - return useShort ? QApplication::tr("N/A") : QApplication::tr("Unknown"); + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return useShort ? QApplication::tr("15 sec") : QApplication::tr("15 Seconds"); + case ZoomFactor::ThirtySeconds: + return useShort ? QApplication::tr("30 sec") : QApplication::tr("30 Seconds"); + case ZoomFactor::SixtySeconds: + return useShort ? QApplication::tr("1 min") : QApplication::tr("1 Minute"); + case ZoomFactor::TwoMinutes: + return useShort ? QApplication::tr("2 min") : QApplication::tr("2 Minutes"); + case ZoomFactor::ThreeMinutes: + return useShort ? QApplication::tr("3 min") : QApplication::tr("3 Minutes"); + case ZoomFactor::FiveMinutes: + return useShort ? QApplication::tr("5 min") : QApplication::tr("5 Minutes"); + case ZoomFactor::TenMinutes: + return useShort ? QApplication::tr("10 min") : QApplication::tr("10 Minutes"); + case ZoomFactor::FifteenMinutes: + return useShort ? QApplication::tr("15 min") : QApplication::tr("15 Minutes"); + case ZoomFactor::ThirtyMinutes: + return useShort ? QApplication::tr("30 min") : QApplication::tr("30 Minutes"); + case ZoomFactor::SixtyMinutes: + return useShort ? QApplication::tr("1 h") : QApplication::tr("1 Hour"); + case ZoomFactor::TwoHours: + return useShort ? QApplication::tr("2 h") : QApplication::tr("2 Hours"); + case ZoomFactor::FourHours: + return useShort ? QApplication::tr("4 h") : QApplication::tr("4 Hours"); + case ZoomFactor::EightHours: + return useShort ? QApplication::tr("8 h") : QApplication::tr("8 Hours"); + case ZoomFactor::TwelveHours: + return useShort ? QApplication::tr("12 h") : QApplication::tr("12 Hours"); + case ZoomFactor::OneDay: + return useShort ? QApplication::tr("1 d") : QApplication::tr("1 Day"); + } + return useShort ? QApplication::tr("N/A") : QApplication::tr("Unknown"); } QString toShortString(Factor factor) { - return toString(factor, true); + return toString(factor, true); } int majorInterval(ZoomFactor factor) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: - return 3000; - case ZoomFactor::ThirtySeconds: - return 5000; - case ZoomFactor::SixtySeconds: - return 10000; - case ZoomFactor::TwoMinutes: - return 15000; - case ZoomFactor::ThreeMinutes: - return 30000; - case ZoomFactor::FiveMinutes: - return 60000; - case ZoomFactor::TenMinutes: - return 60000; - case ZoomFactor::FifteenMinutes: - return 180000; - case ZoomFactor::ThirtyMinutes: - return 300000; - case ZoomFactor::SixtyMinutes: - return 600000; - case ZoomFactor::TwoHours: - return 900000; - case ZoomFactor::FourHours: - return 1800000; - case ZoomFactor::EightHours: - return 3600000; - case ZoomFactor::TwelveHours: - return 5400000; - case ZoomFactor::OneDay: - return 7200000; - } - return -1; + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return 3000; + case ZoomFactor::ThirtySeconds: + return 5000; + case ZoomFactor::SixtySeconds: + return 10000; + case ZoomFactor::TwoMinutes: + return 15000; + case ZoomFactor::ThreeMinutes: + return 30000; + case ZoomFactor::FiveMinutes: + return 60000; + case ZoomFactor::TenMinutes: + return 60000; + case ZoomFactor::FifteenMinutes: + return 180000; + case ZoomFactor::ThirtyMinutes: + return 300000; + case ZoomFactor::SixtyMinutes: + return 600000; + case ZoomFactor::TwoHours: + return 900000; + case ZoomFactor::FourHours: + return 1800000; + case ZoomFactor::EightHours: + return 3600000; + case ZoomFactor::TwelveHours: + return 5400000; + case ZoomFactor::OneDay: + return 7200000; + } + return -1; } int mediumInterval(ZoomFactor factor) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return -1; + case ZoomFactor::ThirtySeconds: + return -1; + case ZoomFactor::SixtySeconds: + return 5000; + case ZoomFactor::TwoMinutes: + return 6000; + case ZoomFactor::ThreeMinutes: + return 10000; + case ZoomFactor::FiveMinutes: + return 15000; + case ZoomFactor::TenMinutes: + return 20000; + case ZoomFactor::FifteenMinutes: + return 60000; + case ZoomFactor::ThirtyMinutes: + return 100000; + case ZoomFactor::SixtyMinutes: + return 150000; + case ZoomFactor::TwoHours: + return 300000; + case ZoomFactor::FourHours: + return 600000; + case ZoomFactor::EightHours: + return 900000; + case ZoomFactor::TwelveHours: + return 1800000; + case ZoomFactor::OneDay: + return 2400000; + } return -1; - case ZoomFactor::ThirtySeconds: - return -1; - case ZoomFactor::SixtySeconds: - return 5000; - case ZoomFactor::TwoMinutes: - return 6000; - case ZoomFactor::ThreeMinutes: - return 10000; - case ZoomFactor::FiveMinutes: - return 15000; - case ZoomFactor::TenMinutes: - return 20000; - case ZoomFactor::FifteenMinutes: - return 60000; - case ZoomFactor::ThirtyMinutes: - return 100000; - case ZoomFactor::SixtyMinutes: - return 150000; - case ZoomFactor::TwoHours: - return 300000; - case ZoomFactor::FourHours: - return 600000; - case ZoomFactor::EightHours: - return 900000; - case ZoomFactor::TwelveHours: - return 1800000; - case ZoomFactor::OneDay: - return 2400000; - } - return -1; } int minorInterval(ZoomFactor factor) { - switch (factor) - { - case ZoomFactor::FifteenSeconds: - return 1000; - case ZoomFactor::ThirtySeconds: - return 1000; - case ZoomFactor::SixtySeconds: - return 1000; - case ZoomFactor::TwoMinutes: - return 3000; - case ZoomFactor::ThreeMinutes: - return 5000; - case ZoomFactor::FiveMinutes: - return 5000; - case ZoomFactor::TenMinutes: - return 10000; - case ZoomFactor::FifteenMinutes: - return 20000; - case ZoomFactor::ThirtyMinutes: - return 25000; - case ZoomFactor::SixtyMinutes: - return 50000; - case ZoomFactor::TwoHours: - return 60000; - case ZoomFactor::FourHours: - return 150000; - case ZoomFactor::EightHours: - return 300000; - case ZoomFactor::TwelveHours: - return 600000; - case ZoomFactor::OneDay: - return 800000; - } - return -1; + switch (factor) + { + case ZoomFactor::FifteenSeconds: + return 1000; + case ZoomFactor::ThirtySeconds: + return 1000; + case ZoomFactor::SixtySeconds: + return 1000; + case ZoomFactor::TwoMinutes: + return 3000; + case ZoomFactor::ThreeMinutes: + return 5000; + case ZoomFactor::FiveMinutes: + return 5000; + case ZoomFactor::TenMinutes: + return 10000; + case ZoomFactor::FifteenMinutes: + return 20000; + case ZoomFactor::ThirtyMinutes: + return 25000; + case ZoomFactor::SixtyMinutes: + return 50000; + case ZoomFactor::TwoHours: + return 60000; + case ZoomFactor::FourHours: + return 150000; + case ZoomFactor::EightHours: + return 300000; + case ZoomFactor::TwelveHours: + return 600000; + case ZoomFactor::OneDay: + return 800000; + } + return -1; } -} +} // namespace Zoom -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.h old mode 100755 new mode 100644 index 9b1374eac..f95fa3a84 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_utils.h @@ -4,26 +4,24 @@ #include - namespace LtsTimeline { struct LTSTIMELINE_EXPORT Tick { - int pos{-1}; - qint64 time{0}; - QString label; - Tick() {} - explicit Tick(qint64 time) : time(time) {} - explicit Tick(int pos, qint64 time, const QString &label) : pos(pos), time(time), label(label) {} + int pos{-1}; + qint64 time{0}; + QString label; + + Tick() {} + + explicit Tick(qint64 time) : time(time) {} + + explicit Tick(int pos, qint64 time, const QString& label) : pos(pos), time(time), label(label) {} }; typedef QVector Ticks; - - - - namespace DateTime { @@ -33,24 +31,29 @@ extern int numberOfDateTimeFormats(); extern LTSTIMELINE_EXPORT QString toString(qint64 time, Format format); -} +} // namespace DateTime typedef DateTime::Format DateTimeFormat; - - - - namespace Zoom { -enum Factor : int -{ - FifteenSeconds = 15 * 1000, ThirtySeconds = 30 * 1000, SixtySeconds = 60 * 1000, - TwoMinutes = 2 * 60 * 1000, ThreeMinutes = 3 * 60 * 1000, FiveMinutes = 5 * 60 * 1000, - TenMinutes = 10 * 60 * 1000, FifteenMinutes = 15 * 60 * 1000, ThirtyMinutes = 30 * 60 * 1000, SixtyMinutes = 60 * 60 * 1000, - TwoHours = 2 * 60 * 60 * 1000, FourHours = 4 * 60 * 60 * 1000, EightHours = 8 * 60 * 60 * 1000, TwelveHours = 12 * 60 * 60 * 1000, - OneDay = 24 * 60 * 60 * 1000 +enum Factor : int { + FifteenSeconds = 15 * 1000, + ThirtySeconds = 30 * 1000, + SixtySeconds = 60 * 1000, + TwoMinutes = 2 * 60 * 1000, + ThreeMinutes = 3 * 60 * 1000, + FiveMinutes = 5 * 60 * 1000, + TenMinutes = 10 * 60 * 1000, + FifteenMinutes = 15 * 60 * 1000, + ThirtyMinutes = 30 * 60 * 1000, + SixtyMinutes = 60 * 60 * 1000, + TwoHours = 2 * 60 * 60 * 1000, + FourHours = 4 * 60 * 60 * 1000, + EightHours = 8 * 60 * 60 * 1000, + TwelveHours = 12 * 60 * 60 * 1000, + OneDay = 24 * 60 * 60 * 1000 }; extern LTSTIMELINE_EXPORT int numberOfZoomFactors(); @@ -75,9 +78,9 @@ extern LTSTIMELINE_EXPORT int mediumInterval(Factor factor); extern LTSTIMELINE_EXPORT int minorInterval(Factor factor); -} +} // namespace Zoom typedef Zoom::Factor ZoomFactor; typedef QVector ZoomFactors; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.cpp old mode 100755 new mode 100644 index 97426e356..f5cd5fe03 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.cpp @@ -1,12 +1,10 @@ - #include "timeline_view.h" -#include + #include "item_delegate.h" #include - #include #include #include @@ -18,14 +16,13 @@ #include #include #include - +#include namespace LtsTimeline { const int TimelineView::s_textHeight = 20; - TimelineView::TimelineView(QWidget *parent) : QTreeView(parent) , m_header(new TimelineHeaderView(this)) @@ -35,639 +32,603 @@ TimelineView::TimelineView(QWidget *parent) , m_trackHandler(new TimelineViewTrackHandler(this)) .getNGLLogger("Timeline.TimelineView")) { - setAlternatingRowColors(true); - setEditTriggers(QAbstractItemView::NoEditTriggers); - setSelectionBehavior(QAbstractItemView::SelectItems); - setSelectionMode(QAbstractItemView::NoSelection); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - setHeader(m_header); - setAcceptDrops(true); + setAlternatingRowColors(true); + setEditTriggers(QAbstractItemView::NoEditTriggers); + setSelectionBehavior(QAbstractItemView::SelectItems); + setSelectionMode(QAbstractItemView::NoSelection); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + setHeader(m_header); + setAcceptDrops(true); } - - - -void TimelineView::setHeader(QHeaderView *header) +void TimelineView::setHeader(QHeaderView* header) { - try - { - if (m_header && m_header != header) - delete m_header; - m_header = qobject_cast(header); - QTreeView::setHeader(m_header); - connect(m_header, &TimelineHeaderView::indicatorTimeChanged, this, [this]() + try { - viewport()->update(); - }); - connect(m_header, &TimelineHeaderView::indicatorVisibilityChanged, this, [this]() + if (m_header && m_header != header) + delete m_header; + m_header = qobject_cast(header); + QTreeView::setHeader(m_header); + connect(m_header, &TimelineHeaderView::indicatorTimeChanged, this, [this]() { viewport()->update(); }); + connect(m_header, &TimelineHeaderView::indicatorVisibilityChanged, this, [this]() { viewport()->update(); }); + connect(m_header, &TimelineHeaderView::hoverPositionChanged, this, [this]() { + if (m_model != nullptr) + emit m_model->layoutChanged(); + }); + connect(m_header, &TimelineHeaderView::hoverVisibilityChanged, this, [this]() { viewport()->update(); }); + } + catch (...) { - viewport()->update(); - }); - connect(m_header, &TimelineHeaderView::hoverPositionChanged, this, [this]() - { - if (m_model != nullptr) - emit m_model->layoutChanged(); - }); - connect(m_header, &TimelineHeaderView::hoverVisibilityChanged, this, [this]() - { - viewport()->update(); - }); - } - catch (...) - { - ERROR_LOG(m_logger) << "header view should be of type TimelineHeaderView"; - } + ERROR_LOG(m_logger) << "header view should be of type TimelineHeaderView"; + } } - -void TimelineView::setModel(QAbstractItemModel *model) +void TimelineView::setModel(QAbstractItemModel* model) { - m_model = model; - QTreeView::setModel(model); - setMouseTracking(true); + m_model = model; + QTreeView::setModel(model); + setMouseTracking(true); - - m_timelineModel = qobject_cast(model); + m_timelineModel = qobject_cast(model); - if (m_timelineModel != nullptr) - return; + if (m_timelineModel != nullptr) + return; - - m_proxyModel = qobject_cast(model); - if (m_proxyModel != nullptr) - m_timelineModel = qobject_cast(m_proxyModel->sourceModel()); + m_proxyModel = qobject_cast(model); + if (m_proxyModel != nullptr) + m_timelineModel = qobject_cast(m_proxyModel->sourceModel()); - if (m_timelineModel == nullptr) - qWarning() << "TimelineSelectHandler:c_tor: model is not a QAbstractItemModel!"; + if (m_timelineModel == nullptr) + qWarning() << "TimelineSelectHandler:c_tor: model is not a QAbstractItemModel!"; - Q_ASSERT(m_timelineModel != nullptr); + Q_ASSERT(m_timelineModel != nullptr); } - -void TimelineView::setProxyModel(QAbstractProxyModel *proxy) noexcept(false) +void TimelineView::setProxyModel(QAbstractProxyModel* proxy) noexcept(false) { - if (!qobject_cast(proxy->sourceModel())) - throw QStringLiteral("source model cannot be cast to TimelineModel"); + if (!qobject_cast(proxy->sourceModel())) + throw QStringLiteral("source model cannot be cast to TimelineModel"); - m_model = qobject_cast(proxy->sourceModel()); - m_proxyModel = proxy; - QTreeView::setModel(m_proxyModel); + m_model = qobject_cast(proxy->sourceModel()); + m_proxyModel = proxy; + QTreeView::setModel(m_proxyModel); } - -void TimelineView::setItemDelegate(QAbstractItemDelegate *delegate) +void TimelineView::setItemDelegate(QAbstractItemDelegate* delegate) { - try - { - m_delegate = static_cast(delegate); - QTreeView::setItemDelegate(m_delegate); - } - catch (...) - { - ERROR_LOG(m_logger) << "item delegate for TimelineView must be derived from ItemDelegate"; - } + try + { + m_delegate = static_cast(delegate); + QTreeView::setItemDelegate(m_delegate); + } + catch (...) + { + ERROR_LOG(m_logger) << "item delegate for TimelineView must be derived from ItemDelegate"; + } } - void TimelineView::setZoomFactor(ZoomFactor zoomFactor) { - if (zoomFactor == m_zoomFactor) - return; + if (zoomFactor == m_zoomFactor) + return; - if (m_minZoomFactor > zoomFactor) - { - setZoomFactor(m_minZoomFactor); - return; - } + if (m_minZoomFactor > zoomFactor) + { + setZoomFactor(m_minZoomFactor); + return; + } - if (m_upperZoomFactor < zoomFactor) - { - setZoomFactor(m_upperZoomFactor); - return; - } + if (m_upperZoomFactor < zoomFactor) + { + setZoomFactor(m_upperZoomFactor); + return; + } - m_zoomFactor = zoomFactor; - emit zoomChanged(m_zoomFactor); - if (m_currentTime + m_zoomFactor > endTime()) - setCurrentTime(endTime() - m_zoomFactor); - else - viewport()->update(); + m_zoomFactor = zoomFactor; + emit zoomChanged(m_zoomFactor); + if (m_currentTime + m_zoomFactor > endTime()) + setCurrentTime(endTime() - m_zoomFactor); + else + viewport()->update(); } void TimelineView::setMinimumZoomFactor(ZoomFactor zoomFactor) { - if (zoomFactor == m_minZoomFactor) - return; + if (zoomFactor == m_minZoomFactor) + return; - m_minZoomFactor = zoomFactor; - if (m_zoomFactor < m_minZoomFactor) - setZoomFactor(m_minZoomFactor); + m_minZoomFactor = zoomFactor; + if (m_zoomFactor < m_minZoomFactor) + setZoomFactor(m_minZoomFactor); } void TimelineView::setMaximumZoomFactor(ZoomFactor zoomFactor) { - if (zoomFactor == m_maxZoomFactor) - return; + if (zoomFactor == m_maxZoomFactor) + return; - m_maxZoomFactor = zoomFactor; - if (m_upperZoomFactor > m_maxZoomFactor) - m_upperZoomFactor = m_maxZoomFactor; - if (m_zoomFactor > m_maxZoomFactor) - setZoomFactor(m_maxZoomFactor); + m_maxZoomFactor = zoomFactor; + if (m_upperZoomFactor > m_maxZoomFactor) + m_upperZoomFactor = m_maxZoomFactor; + if (m_zoomFactor > m_maxZoomFactor) + setZoomFactor(m_maxZoomFactor); } - void TimelineView::setStartTime(qint64 time) { - if (time == m_startTime || time < 0) - return; + if (time == m_startTime || time < 0) + return; - m_startTime = time; - if (m_currentTime < m_startTime) - setCurrentTime(m_startTime); - if (m_duration > 0) - if (m_currentTime > endTime() - m_zoomFactor) - setCurrentTime(std::max(endTime() - m_zoomFactor, m_startTime)); - emit rangeChanged(m_startTime, endTime()); + m_startTime = time; + if (m_currentTime < m_startTime) + setCurrentTime(m_startTime); + if (m_duration > 0) + if (m_currentTime > endTime() - m_zoomFactor) + setCurrentTime(std::max(endTime() - m_zoomFactor, m_startTime)); + emit rangeChanged(m_startTime, endTime()); } void TimelineView::setCurrentTime(qint64 time) { - if (time == m_currentTime) - return; + if (time == m_currentTime) + return; - if (time < m_startTime) - time = m_startTime; - if (m_duration > 0) - if (time > endTime() - m_zoomFactor) - time = std::max(endTime() - m_zoomFactor, m_startTime); + if (time < m_startTime) + time = m_startTime; + if (m_duration > 0) + if (time > endTime() - m_zoomFactor) + time = std::max(endTime() - m_zoomFactor, m_startTime); - if (time == m_currentTime) - return; + if (time == m_currentTime) + return; - m_currentTime = time; - emit currentTimeChanged(m_currentTime); - viewport()->update(); + m_currentTime = time; + emit currentTimeChanged(m_currentTime); + viewport()->update(); } void TimelineView::setEndTime(qint64 time) { - if (time == m_startTime + m_duration) - return; + if (time == m_startTime + m_duration) + return; - if (time - m_startTime < m_minZoomFactor) - time = m_startTime + m_minZoomFactor; + if (time - m_startTime < m_minZoomFactor) + time = m_startTime + m_minZoomFactor; - setDuration(time - m_startTime); + setDuration(time - m_startTime); } void TimelineView::setDuration(int duration) { - if (duration == m_duration) - return; + if (duration == m_duration) + return; - if (duration <= m_minZoomFactor) - duration = m_minZoomFactor; - m_duration = duration; - emit rangeChanged(m_startTime, endTime()); - ZoomFactor upperZoomFactor = Zoom::floor(duration); - m_upperZoomFactor = std::min(upperZoomFactor, m_maxZoomFactor); - if (duration < m_zoomFactor) - setZoomFactor(m_upperZoomFactor); - if (m_currentTime > endTime()) - setCurrentTime(endTime() - m_zoomFactor); - viewport()->update(); + if (duration <= m_minZoomFactor) + duration = m_minZoomFactor; + m_duration = duration; + emit rangeChanged(m_startTime, endTime()); + ZoomFactor upperZoomFactor = Zoom::floor(duration); + m_upperZoomFactor = std::min(upperZoomFactor, m_maxZoomFactor); + if (duration < m_zoomFactor) + setZoomFactor(m_upperZoomFactor); + if (m_currentTime > endTime()) + setCurrentTime(endTime() - m_zoomFactor); + viewport()->update(); } void TimelineView::setRange(qint64 start, qint64 end) { - if (start == m_startTime && end - start == m_duration) - return; + if (start == m_startTime && end - start == m_duration) + return; - if (start > end) - { - m_startTime = end; - m_duration = std::max(start - m_startTime, static_cast(m_minZoomFactor)); - } - else - { - m_startTime = start; - m_duration = std::max(end - m_startTime, static_cast(m_minZoomFactor)); - } - if (m_currentTime < m_startTime) - m_currentTime = m_startTime; - if (m_duration > 0) - if (m_currentTime > endTime() - m_zoomFactor) - m_currentTime = std::max(endTime() - m_zoomFactor, m_startTime); - ZoomFactor upperZoomFactor = Zoom::floor(m_duration); - m_upperZoomFactor = upperZoomFactor > m_maxZoomFactor ? m_maxZoomFactor : upperZoomFactor; - emit rangeChanged(m_startTime, endTime()); - viewport()->update(); + if (start > end) + { + m_startTime = end; + m_duration = std::max(start - m_startTime, static_cast(m_minZoomFactor)); + } + else + { + m_startTime = start; + m_duration = std::max(end - m_startTime, static_cast(m_minZoomFactor)); + } + if (m_currentTime < m_startTime) + m_currentTime = m_startTime; + if (m_duration > 0) + if (m_currentTime > endTime() - m_zoomFactor) + m_currentTime = std::max(endTime() - m_zoomFactor, m_startTime); + ZoomFactor upperZoomFactor = Zoom::floor(m_duration); + m_upperZoomFactor = upperZoomFactor > m_maxZoomFactor ? m_maxZoomFactor : upperZoomFactor; + emit rangeChanged(m_startTime, endTime()); + viewport()->update(); } - void TimelineView::setCursorTextVisible(bool visible) { - m_isCursorTextVisible = visible; - viewport()->update(); + m_isCursorTextVisible = visible; + viewport()->update(); } -void TimelineView::setCursorText(const QString &text) +void TimelineView::setCursorText(const QString& text) { - m_cursorText = text; - viewport()->update(); + m_cursorText = text; + viewport()->update(); } - int TimelineView::toPixel(qint64 time) const { - return m_header ? m_header->toPixel(time) : -1; + return m_header ? m_header->toPixel(time) : -1; } qint64 TimelineView::toTime(int pixel) const { - return m_header ? m_header->toTime(pixel) : -1; + return m_header ? m_header->toTime(pixel) : -1; } qint64 TimelineView::toDuration(int pixel) const { - if (!m_header) - return -1; + if (!m_header) + return -1; - int pos = m_header->sectionPosition(Section::eItems); - return double(pixel - pos) / (geometry().width() - pos) * m_zoomFactor; + int pos = m_header->sectionPosition(Section::eItems); + return double(pixel - pos) / (geometry().width() - pos) * m_zoomFactor; } int TimelineView::fromDuration(qint64 time) const { - if (!m_header) - return -1; + if (!m_header) + return -1; - return (time - m_startTime) / m_zoomFactor * (geometry().width() - m_header->sectionPosition(Section::eItems)); + return (time - m_startTime) / m_zoomFactor * (geometry().width() - m_header->sectionPosition(Section::eItems)); } - void TimelineView::clearSelectedItems() { - m_selectedItemIds.clear(); - emit selectedItemsChanged(m_selectedItemIds); - viewport()->update(); + m_selectedItemIds.clear(); + emit selectedItemsChanged(m_selectedItemIds); + viewport()->update(); } void TimelineView::selectAllItems() { - if (m_model == nullptr) - return; + if (m_model == nullptr) + return; - m_selectedItemIds.clear(); - m_selectedItemIds = m_timelineModel->itemIds(); - emit selectedItemsChanged(m_selectedItemIds); - viewport()->update(); + m_selectedItemIds.clear(); + m_selectedItemIds = m_timelineModel->itemIds(); + emit selectedItemsChanged(m_selectedItemIds); + viewport()->update(); } void TimelineView::selectItem(int itemId, bool reset) { - if (reset) - m_selectedItemIds.clear(); - else if (m_selectedItemIds.contains(itemId)) - return; - m_selectedItemIds.append(itemId); - emit selectedItemsChanged(m_selectedItemIds); - viewport()->update(); + if (reset) + m_selectedItemIds.clear(); + else if (m_selectedItemIds.contains(itemId)) + return; + m_selectedItemIds.append(itemId); + emit selectedItemsChanged(m_selectedItemIds); + viewport()->update(); } -void TimelineView::selectItems(const QVector &itemIds, bool reset) +void TimelineView::selectItems(const QVector& itemIds, bool reset) { - if (reset) - m_selectedItemIds.clear(); - for (const int &itemId : std::as_const(itemIds)) - if (!m_selectedItemIds.contains(itemId)) - m_selectedItemIds.append(itemId); - emit selectedItemsChanged(m_selectedItemIds); - viewport()->update(); + if (reset) + m_selectedItemIds.clear(); + for (const int& itemId : std::as_const(itemIds)) + if (!m_selectedItemIds.contains(itemId)) + m_selectedItemIds.append(itemId); + emit selectedItemsChanged(m_selectedItemIds); + viewport()->update(); } void TimelineView::unselectItem(int itemId) { - const int iItem = m_selectedItemIds.indexOf(itemId); - if (iItem == -1) - return; - m_selectedItemIds.remove(iItem); - emit selectedItemsChanged(m_selectedItemIds); - viewport()->update(); + const int iItem = m_selectedItemIds.indexOf(itemId); + if (iItem == -1) + return; + m_selectedItemIds.remove(iItem); + emit selectedItemsChanged(m_selectedItemIds); + viewport()->update(); } - bool TimelineView::isCursorWithinRangeX(int x) const { - if (m_header) - return m_header->sectionPosition(Section::eItems) < x && x < geometry().right(); - return false; + if (m_header) + return m_header->sectionPosition(Section::eItems) < x && x < geometry().right(); + return false; } bool TimelineView::isCursorWithinRangeY(int y) const { - return 0 < y && y < geometry().bottom(); - + return 0 < y && y < geometry().bottom(); } - - - -void TimelineView::dragEnterEvent(QDragEnterEvent *event) +void TimelineView::dragEnterEvent(QDragEnterEvent* event) { - if (m_dragHandler) - m_dragHandler->dragEnterEvent(event); + if (m_dragHandler) + m_dragHandler->dragEnterEvent(event); } -void TimelineView::dragMoveEvent(QDragMoveEvent *event) +void TimelineView::dragMoveEvent(QDragMoveEvent* event) { - if (m_dragHandler) - m_dragHandler->dragMoveEvent(event); + if (m_dragHandler) + m_dragHandler->dragMoveEvent(event); } -void TimelineView::dragLeaveEvent(QDragLeaveEvent *event) +void TimelineView::dragLeaveEvent(QDragLeaveEvent* event) { - if (m_dragHandler) - m_dragHandler->dragLeaveEvent(event); + if (m_dragHandler) + m_dragHandler->dragLeaveEvent(event); } -void TimelineView::dropEvent(QDropEvent *event) +void TimelineView::dropEvent(QDropEvent* event) { - if (m_dragHandler) - m_dragHandler->dropEvent(event); + if (m_dragHandler) + m_dragHandler->dropEvent(event); } -void TimelineView::mouseDoubleClickEvent(QMouseEvent *event) +void TimelineView::mouseDoubleClickEvent(QMouseEvent* event) { - if (m_trackHandler) - m_trackHandler->mouseDoubleClickEvent(event); - if (m_selectHandler) - m_selectHandler->mouseDoubleClickEvent(event); -} - -void TimelineView::mouseMoveEvent(QMouseEvent *event) -{ - m_cursorPosition = event->pos(); - - - const QModelIndex index(indexAt(event->pos())); - - if (m_header) - { - m_header->setHoverPosition(isCursorWithinRange(event->pos()) ? event->pos().x() : -1); - if (m_header->mouseHandler()->isBusy()) - { - m_header->mouseHandler()->mouseMoveEvent(event); - return; - } - if (cursor() == Qt::SizeHorCursor) - { - if (m_resizeHandler) - { - if (!m_resizeHandler->isActive()) - setCursor(Qt::ArrowCursor); - } - else - setCursor(Qt::ArrowCursor); - } - } - - if (!m_model) - return; - - if (m_dragHandler && m_timelineModel->isEditable()) - if (cursor().shape() == Qt::ClosedHandCursor || cursor().shape() == Qt::ForbiddenCursor) - if (!m_dragHandler->m_dragItemIds.isEmpty() || !m_selectedItemIds.isEmpty()) - { - m_dragHandler->mouseMoveEvent(event); - return; - } - - if (m_resizeHandler && m_timelineModel->isEditable()) - if (cursor().shape() == Qt::SizeHorCursor) - if (m_resizeHandler->isActive()) - { - m_resizeHandler->mouseMoveEvent(event); - return; - } - - if (m_selectHandler) - m_selectHandler->mouseMoveEvent(event); - - if (!index.isValid() || index.column() == Section::eActuator) - { - if (m_resizeHandler && m_timelineModel->isEditable()) - if (!m_resizeHandler->isActive()) - setCursor(QCursor(Qt::ArrowCursor)); - - event->ignore(); - return; - } - - if (!m_timelineModel->isEditable()) - return; - - try - { - Track &track = m_timelineModel->track(index.data().toInt()); - Item &item = track.itemAt(toTime(event->pos().x())); - int startPos = toPixel(item.startTime()); - int endPos = toPixel(item.startTime() + item.duration()); - if (endPos - startPos < 15 || (startPos + 5 < event->pos().x() && event->pos().x() < endPos - 5)) - setCursor(QCursor(Qt::ArrowCursor)); - else - setCursor(QCursor(Qt::SizeHorCursor)); - } - catch (...) - { - setCursor(QCursor(Qt::ArrowCursor)); - } -} - -void TimelineView::mousePressEvent(QMouseEvent *event) -{ - if (!m_model) - return; - - if (m_header) - if (m_header->mouseHandler()->isBusy()) - { - m_header->mouseHandler()->mousePressEvent(event); - return; - } - - - const QModelIndex index = indexAt(event->pos()); - if (index.column() == Section::eActuator) - { - QTreeView::mousePressEvent(event); if (m_trackHandler) - m_trackHandler->mousePressEvent(event); - return; - } - - if (m_timelineModel->isEditable() && cursor().shape() == Qt::SizeHorCursor) - { - if (m_resizeHandler) - m_resizeHandler->mousePressEvent(event); - } - else - { + m_trackHandler->mouseDoubleClickEvent(event); if (m_selectHandler) - m_selectHandler->mousePressEvent(event); + m_selectHandler->mouseDoubleClickEvent(event); +} + +void TimelineView::mouseMoveEvent(QMouseEvent* event) +{ + m_cursorPosition = event->pos(); + + const QModelIndex index(indexAt(event->pos())); + + if (m_header) + { + m_header->setHoverPosition(isCursorWithinRange(event->pos()) ? event->pos().x() : -1); + if (m_header->mouseHandler()->isBusy()) + { + m_header->mouseHandler()->mouseMoveEvent(event); + return; + } + if (cursor() == Qt::SizeHorCursor) + { + if (m_resizeHandler) + { + if (!m_resizeHandler->isActive()) + setCursor(Qt::ArrowCursor); + } + else + setCursor(Qt::ArrowCursor); + } + } + + if (!m_model) + return; if (m_dragHandler && m_timelineModel->isEditable()) + if (cursor().shape() == Qt::ClosedHandCursor || cursor().shape() == Qt::ForbiddenCursor) + if (!m_dragHandler->m_dragItemIds.isEmpty() || !m_selectedItemIds.isEmpty()) + { + m_dragHandler->mouseMoveEvent(event); + return; + } + + if (m_resizeHandler && m_timelineModel->isEditable()) + if (cursor().shape() == Qt::SizeHorCursor) + if (m_resizeHandler->isActive()) + { + m_resizeHandler->mouseMoveEvent(event); + return; + } + + if (m_selectHandler) + m_selectHandler->mouseMoveEvent(event); + + if (!index.isValid() || index.column() == Section::eActuator) { - m_dragHandler->mousePressEvent(event); - if (m_dragHandler->isActive()) + if (m_resizeHandler && m_timelineModel->isEditable()) + if (!m_resizeHandler->isActive()) + setCursor(QCursor(Qt::ArrowCursor)); + + event->ignore(); return; } - if (event->button() == Qt::RightButton) - emit customContextMenuRequested(event->pos()); - } -} - -void TimelineView::mouseReleaseEvent(QMouseEvent *event) -{ - if (!m_model) - return; - - if (m_header) - if (m_header->mouseHandler()->isBusy()) - { - m_header->mouseHandler()->mouseReleaseEvent(event); - return; - } - - if (m_trackHandler) - m_trackHandler->mouseReleaseEvent(event); - - if (m_dragHandler && m_timelineModel->isEditable()) - if (m_dragHandler->isActive()) - { - m_dragHandler->mouseReleaseEvent(event); - viewport()->update(); - return; - } - - if (m_resizeHandler && m_timelineModel->isEditable()) - if (m_resizeHandler->isActive()) - { - m_resizeHandler->mouseReleaseEvent(event); - viewport()->update(); - return; - } - - if (m_selectHandler) - if (m_selectHandler->isActive() || !m_timelineModel->isEditable()) - m_selectHandler->mouseReleaseEvent(event); - - viewport()->update(); -} - -void TimelineView::keyPressEvent(QKeyEvent *event) -{ - if (m_model == nullptr) - return; - if (m_timelineModel->isEditable()) - { - if (m_resizeHandler) - if (m_resizeHandler->isActive()) + if (!m_timelineModel->isEditable()) return; - if (m_dragHandler) - m_dragHandler->keyPressEvent(event); - } - if (m_selectHandler) - m_selectHandler->keyPressEvent(event); - - viewport()->update(); + try + { + Track& track = m_timelineModel->track(index.data().toInt()); + Item& item = track.itemAt(toTime(event->pos().x())); + int startPos = toPixel(item.startTime()); + int endPos = toPixel(item.startTime() + item.duration()); + if (endPos - startPos < 15 || (startPos + 5 < event->pos().x() && event->pos().x() < endPos - 5)) + setCursor(QCursor(Qt::ArrowCursor)); + else + setCursor(QCursor(Qt::SizeHorCursor)); + } + catch (...) + { + setCursor(QCursor(Qt::ArrowCursor)); + } } -void TimelineView::wheelEvent(QWheelEvent *event) +void TimelineView::mousePressEvent(QMouseEvent* event) { - if (event->pos().y() <= m_header->geometry().bottom()) - m_header->wheelEvent(event); - else if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) - { - if (event->angleDelta().y() < 0) - setZoomFactor(Zoom::increment(m_zoomFactor)); + if (!m_model) + return; + + if (m_header) + if (m_header->mouseHandler()->isBusy()) + { + m_header->mouseHandler()->mousePressEvent(event); + return; + } + + const QModelIndex index = indexAt(event->pos()); + if (index.column() == Section::eActuator) + { + QTreeView::mousePressEvent(event); + if (m_trackHandler) + m_trackHandler->mousePressEvent(event); + return; + } + + if (m_timelineModel->isEditable() && cursor().shape() == Qt::SizeHorCursor) + { + if (m_resizeHandler) + m_resizeHandler->mousePressEvent(event); + } else - setZoomFactor(Zoom::decrement(m_zoomFactor)); - } - else - QTreeView::wheelEvent(event); + { + if (m_selectHandler) + m_selectHandler->mousePressEvent(event); + + if (m_dragHandler && m_timelineModel->isEditable()) + { + m_dragHandler->mousePressEvent(event); + if (m_dragHandler->isActive()) + return; + } + + if (event->button() == Qt::RightButton) + emit customContextMenuRequested(event->pos()); + } } -void TimelineView::paintEvent(QPaintEvent *event) +void TimelineView::mouseReleaseEvent(QMouseEvent* event) { - Q_UNUSED(event); + if (!m_model) + return; - QWidget *viewPort = viewport(); - QPainter painter(viewPort); + if (m_header) + if (m_header->mouseHandler()->isBusy()) + { + m_header->mouseHandler()->mouseReleaseEvent(event); + return; + } - painter.save(); - QTreeView::paintEvent(event); - if (m_dragHandler) - { - ItemDelegate *delegate = qobject_cast(itemDelegate()); - if (delegate) - delegate->paintDragItems(&painter); - } - painter.restore(); + if (m_trackHandler) + m_trackHandler->mouseReleaseEvent(event); - painter.save(); + if (m_dragHandler && m_timelineModel->isEditable()) + if (m_dragHandler->isActive()) + { + m_dragHandler->mouseReleaseEvent(event); + viewport()->update(); + return; + } - painter.setClipping(true); + if (m_resizeHandler && m_timelineModel->isEditable()) + if (m_resizeHandler->isActive()) + { + m_resizeHandler->mouseReleaseEvent(event); + viewport()->update(); + return; + } - - if (m_selectHandler) - if (m_selectHandler->isRubberBandActive()) - { - QColor color = TimelineHeaderView::highlightColor(); - painter.setPen(color); - color.setAlpha(100); - painter.setBrush(QBrush(color)); - painter.drawRect(m_selectHandler->m_rubberBand); - } + if (m_selectHandler) + if (m_selectHandler->isActive() || !m_timelineModel->isEditable()) + m_selectHandler->mouseReleaseEvent(event); - - if (m_header->isIndicatorVisible() && m_header->indicatorPosition() != -1 && - m_header->indicatorPosition() >= m_header->sectionPosition(Section::eItems)) - { - painter.setPen(TimelineHeaderView::highlightColor()); - painter.drawLine(m_header->indicatorPosition(), 0, m_header->indicatorPosition(), geometry().bottom()); - } - - - if (m_header->isHoverVisible() && m_header->hoverPosition() != -1) - { - painter.setPen(TimelineHeaderView::highlightColor()); - painter.drawLine(m_header->hoverPosition(), 0, m_header->hoverPosition(), geometry().bottom()); - if (m_isCursorTextVisible && !m_cursorText.isEmpty()) - { - painter.setBrush(QBrush(TimelineHeaderView::backgroundColor())); - QRect rect = QRect( - m_cursorPosition.x(), m_cursorPosition.y() - s_textHeight - 2, - painter.fontMetrics().horizontalAdvance(m_cursorText) + 2, s_textHeight + 2 - ); - painter.drawRect(rect); - painter.drawText(rect.adjusted(1, 1, -1, -1), Qt::AlignCenter, m_cursorText); - } - } - - - if (m_header->isLiveIndicatorVisible() && m_header->liveIndicatorTime() != -1 && - m_currentTime <= m_header->liveIndicatorTime() && m_header->liveIndicatorTime() <= m_currentTime + m_zoomFactor) - { - painter.setPen(m_header->liveIndicatorColor()); - painter.drawLine(m_header->liveIndicatorPosition(), 0, m_header->liveIndicatorPosition(), geometry().bottom()); - } - - painter.restore(); + viewport()->update(); } +void TimelineView::keyPressEvent(QKeyEvent* event) +{ + if (m_model == nullptr) + return; + if (m_timelineModel->isEditable()) + { + if (m_resizeHandler) + if (m_resizeHandler->isActive()) + return; + + if (m_dragHandler) + m_dragHandler->keyPressEvent(event); + } + if (m_selectHandler) + m_selectHandler->keyPressEvent(event); + + viewport()->update(); } + +void TimelineView::wheelEvent(QWheelEvent* event) +{ + if (event->pos().y() <= m_header->geometry().bottom()) + m_header->wheelEvent(event); + else if (QGuiApplication::queryKeyboardModifiers() == Qt::ControlModifier) + { + if (event->angleDelta().y() < 0) + setZoomFactor(Zoom::increment(m_zoomFactor)); + else + setZoomFactor(Zoom::decrement(m_zoomFactor)); + } + else + QTreeView::wheelEvent(event); +} + +void TimelineView::paintEvent(QPaintEvent* event) +{ + Q_UNUSED(event); + + QWidget* viewPort = viewport(); + QPainter painter(viewPort); + + painter.save(); + QTreeView::paintEvent(event); + if (m_dragHandler) + { + ItemDelegate* delegate = qobject_cast(itemDelegate()); + if (delegate) + delegate->paintDragItems(&painter); + } + painter.restore(); + + painter.save(); + + painter.setClipping(true); + + if (m_selectHandler) + if (m_selectHandler->isRubberBandActive()) + { + QColor color = TimelineHeaderView::highlightColor(); + painter.setPen(color); + color.setAlpha(100); + painter.setBrush(QBrush(color)); + painter.drawRect(m_selectHandler->m_rubberBand); + } + + if (m_header->isIndicatorVisible() && m_header->indicatorPosition() != -1 && + m_header->indicatorPosition() >= m_header->sectionPosition(Section::eItems)) + { + painter.setPen(TimelineHeaderView::highlightColor()); + painter.drawLine(m_header->indicatorPosition(), 0, m_header->indicatorPosition(), geometry().bottom()); + } + + if (m_header->isHoverVisible() && m_header->hoverPosition() != -1) + { + painter.setPen(TimelineHeaderView::highlightColor()); + painter.drawLine(m_header->hoverPosition(), 0, m_header->hoverPosition(), geometry().bottom()); + if (m_isCursorTextVisible && !m_cursorText.isEmpty()) + { + painter.setBrush(QBrush(TimelineHeaderView::backgroundColor())); + QRect rect = QRect(m_cursorPosition.x(), m_cursorPosition.y() - s_textHeight - 2, + painter.fontMetrics().horizontalAdvance(m_cursorText) + 2, s_textHeight + 2); + painter.drawRect(rect); + painter.drawText(rect.adjusted(1, 1, -1, -1), Qt::AlignCenter, m_cursorText); + } + } + + if (m_header->isLiveIndicatorVisible() && m_header->liveIndicatorTime() != -1 && + m_currentTime <= m_header->liveIndicatorTime() && m_header->liveIndicatorTime() <= m_currentTime + m_zoomFactor) + { + painter.setPen(m_header->liveIndicatorColor()); + painter.drawLine(m_header->liveIndicatorPosition(), 0, m_header->liveIndicatorPosition(), geometry().bottom()); + } + + painter.restore(); +} + +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.h old mode 100755 new mode 100644 index 4f51b2469..edb4c4511 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view.h @@ -1,27 +1,21 @@ - #pragma once -#include - +#include "ltstimeline_export.h" +#include "timeline_header_view.h" +#include "timeline_model.h" #include "timeline_view_drag_handler.h" #include "timeline_view_resize_handler.h" #include "timeline_view_selection_handler.h" #include "timeline_view_track_handler.h" -#include "timeline_header_view.h" -#include "timeline_model.h" - -#include "ltstimeline_export.h" - -#include #include +#include #include - +#include class QAbstractProxyModel; - namespace LtsTimeline { @@ -31,144 +25,237 @@ class TimelineViewSelectHandler; class TimelineViewTrackHandler; class TimelineWidget; - class LTSTIMELINE_EXPORT TimelineView : public QTreeView { - Q_OBJECT + Q_OBJECT - friend class ItemDelegate; - friend class TimelineHeaderView; - friend class TimelineViewDragHandler; - friend class TimelineViewResizeHandler; - friend class TimelineViewSelectHandler; - friend class TimelineViewTrackHandler; - friend class TimelineWidget; + friend class ItemDelegate; + friend class TimelineHeaderView; + friend class TimelineViewDragHandler; + friend class TimelineViewResizeHandler; + friend class TimelineViewSelectHandler; + friend class TimelineViewTrackHandler; + friend class TimelineWidget; -public: - static const int s_textHeight; + public: + static const int s_textHeight; - + explicit TimelineView(QWidget* parent = nullptr); - explicit TimelineView(QWidget *parent = nullptr); + TimelineHeaderView* header() + { + return m_header; + } - TimelineHeaderView *header() { return m_header; } - void setHeader(QHeaderView *header); + void setHeader(QHeaderView* header); - QAbstractItemModel *model() { return m_model; } - TimelineModel *timelineModel() { return m_timelineModel; } - void setModel(QAbstractItemModel *model) override; + QAbstractItemModel* model() + { + return m_model; + } - QAbstractProxyModel *proxyModel() { return m_proxyModel; } - void setProxyModel(QAbstractProxyModel *proxy) noexcept(false); + TimelineModel* timelineModel() + { + return m_timelineModel; + } - void setItemDelegate(QAbstractItemDelegate *delegate); - ItemDelegate *itemDelegate() const { return m_delegate; } + void setModel(QAbstractItemModel* model) override; - ZoomFactor zoomFactor() const { return m_zoomFactor; } - + QAbstractProxyModel* proxyModel() + { + return m_proxyModel; + } - void setZoomFactor(ZoomFactor zoomFactor); + void setProxyModel(QAbstractProxyModel* proxy) noexcept(false); - ZoomFactor minimumZoomFactor() const { return m_minZoomFactor; } - void setMinimumZoomFactor(ZoomFactor zoomFactor); + void setItemDelegate(QAbstractItemDelegate* delegate); - ZoomFactor maximumZoomFactor() const { return m_maxZoomFactor; } - void setMaximumZoomFactor(ZoomFactor zoomFactor); + ItemDelegate* itemDelegate() const + { + return m_delegate; + } - ZoomFactor upperZoomFactor() const { return m_upperZoomFactor; } + ZoomFactor zoomFactor() const + { + return m_zoomFactor; + } - qint64 startTime() const { return m_startTime; } - void setStartTime(qint64 time); + void setZoomFactor(ZoomFactor zoomFactor); - qint64 currentTime() const { return m_currentTime; } - void setCurrentTime(qint64 time); + ZoomFactor minimumZoomFactor() const + { + return m_minZoomFactor; + } - qint64 endTime() const { return m_startTime + m_duration; } - void setEndTime(qint64 time); + void setMinimumZoomFactor(ZoomFactor zoomFactor); - int duration() const { return m_duration; } - void setDuration(int duration); + ZoomFactor maximumZoomFactor() const + { + return m_maxZoomFactor; + } - void setRange(qint64 start, qint64 end); + void setMaximumZoomFactor(ZoomFactor zoomFactor); - bool isCursorTextVisible() const { return m_isCursorTextVisible; } - void setCursorTextVisible(bool visible); - void setCursorText(const QString &text); + ZoomFactor upperZoomFactor() const + { + return m_upperZoomFactor; + } - int toPixel(qint64 time) const; - qint64 toTime(int pixel) const; - qint64 toDuration(int pixel) const; - int fromDuration(qint64 time) const; + qint64 startTime() const + { + return m_startTime; + } - const QVector &selectedItemIds() const { return m_selectedItemIds; } - bool hasSelectedItems() const { return !m_selectedItemIds.isEmpty(); } - void clearSelectedItems(); - void selectAllItems(); - void selectItem(int itemId, bool reset = true); - void selectItems(const QVector &itemIds, bool reset = true); - void unselectItem(int itemId); + void setStartTime(qint64 time); - TimelineViewDragHandler *dragHandler() { return m_dragHandler; } - void setDragHandler(TimelineViewDragHandler *dragHandler) { m_dragHandler = dragHandler; } - TimelineViewResizeHandler *resizeHandler() { return m_resizeHandler; } - void setResizeHandler(TimelineViewResizeHandler *resizeHandler) { m_resizeHandler = resizeHandler; } - TimelineViewSelectHandler *selectHandler() { return m_selectHandler; } - void setSelectHandler(TimelineViewSelectHandler *selectHandler) { m_selectHandler = selectHandler; } - TimelineViewTrackHandler *trackHandler() { return m_trackHandler; } - void setTrackHandler(TimelineViewTrackHandler *trackHandler) { m_trackHandler = trackHandler; } + qint64 currentTime() const + { + return m_currentTime; + } - bool isCursorWithinRange(const QPoint &pos) const { return isCursorWithinRangeX(pos.x()) && isCursorWithinRangeY(pos.y()); } - bool isCursorWithinRangeX(int x) const; - bool isCursorWithinRangeY(int y) const; + void setCurrentTime(qint64 time); -protected: - NGL::INGLLogger &m_logger; - void dragEnterEvent(QDragEnterEvent *event) override; - void dragMoveEvent(QDragMoveEvent *event) override; - void dragLeaveEvent(QDragLeaveEvent *event) override; - void dropEvent(QDropEvent *event) override; - void mouseDoubleClickEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; - void wheelEvent(QWheelEvent *event) override; - virtual void paintEvent(QPaintEvent *event) override; + qint64 endTime() const + { + return m_startTime + m_duration; + } -signals: - void rangeChanged(qint64, qint64); - void currentTimeChanged(qint64); - void zoomChanged(ZoomFactor); - void trackActivated(int); - void selectedItemsChanged(const QVector &); - void itemActivated(int); - void currentItemTimeChanged(); + void setEndTime(qint64 time); -private: - TimelineHeaderView *m_header{nullptr}; - TimelineModel *m_timelineModel{nullptr}; - QAbstractItemModel *m_model{nullptr}; - QAbstractProxyModel *m_proxyModel{nullptr}; - ItemDelegate *m_delegate{nullptr}; - TimelineViewDragHandler *m_dragHandler{nullptr}; - TimelineViewResizeHandler *m_resizeHandler{nullptr}; - TimelineViewSelectHandler *m_selectHandler{nullptr}; - TimelineViewTrackHandler *m_trackHandler{nullptr}; + int duration() const + { + return m_duration; + } - ZoomFactor m_zoomFactor{ZoomFactor::ThirtyMinutes}; - ZoomFactor m_upperZoomFactor{ZoomFactor::OneDay}; - ZoomFactor m_minZoomFactor{ZoomFactor::FifteenSeconds}; - ZoomFactor m_maxZoomFactor{ZoomFactor::OneDay}; + void setDuration(int duration); - qint64 m_startTime{-1}; - qint64 m_currentTime{-1}; - int m_duration{-1}; + void setRange(qint64 start, qint64 end); - bool m_isCursorTextVisible{false}; - QString m_cursorText; - QPoint m_cursorPosition; + bool isCursorTextVisible() const + { + return m_isCursorTextVisible; + } - QVector m_selectedItemIds; + void setCursorTextVisible(bool visible); + void setCursorText(const QString& text); + + int toPixel(qint64 time) const; + qint64 toTime(int pixel) const; + qint64 toDuration(int pixel) const; + int fromDuration(qint64 time) const; + + const QVector& selectedItemIds() const + { + return m_selectedItemIds; + } + + bool hasSelectedItems() const + { + return !m_selectedItemIds.isEmpty(); + } + + void clearSelectedItems(); + void selectAllItems(); + void selectItem(int itemId, bool reset = true); + void selectItems(const QVector& itemIds, bool reset = true); + void unselectItem(int itemId); + + TimelineViewDragHandler* dragHandler() + { + return m_dragHandler; + } + + void setDragHandler(TimelineViewDragHandler* dragHandler) + { + m_dragHandler = dragHandler; + } + + TimelineViewResizeHandler* resizeHandler() + { + return m_resizeHandler; + } + + void setResizeHandler(TimelineViewResizeHandler* resizeHandler) + { + m_resizeHandler = resizeHandler; + } + + TimelineViewSelectHandler* selectHandler() + { + return m_selectHandler; + } + + void setSelectHandler(TimelineViewSelectHandler* selectHandler) + { + m_selectHandler = selectHandler; + } + + TimelineViewTrackHandler* trackHandler() + { + return m_trackHandler; + } + + void setTrackHandler(TimelineViewTrackHandler* trackHandler) + { + m_trackHandler = trackHandler; + } + + bool isCursorWithinRange(const QPoint& pos) const + { + return isCursorWithinRangeX(pos.x()) && isCursorWithinRangeY(pos.y()); + } + + bool isCursorWithinRangeX(int x) const; + bool isCursorWithinRangeY(int y) const; + + protected: + NGL::INGLLogger& m_logger; + void dragEnterEvent(QDragEnterEvent* event) override; + void dragMoveEvent(QDragMoveEvent* event) override; + void dragLeaveEvent(QDragLeaveEvent* event) override; + void dropEvent(QDropEvent* event) override; + void mouseDoubleClickEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; + void wheelEvent(QWheelEvent* event) override; + virtual void paintEvent(QPaintEvent* event) override; + + signals: + void rangeChanged(qint64, qint64); + void currentTimeChanged(qint64); + void zoomChanged(ZoomFactor); + void trackActivated(int); + void selectedItemsChanged(const QVector&); + void itemActivated(int); + void currentItemTimeChanged(); + + private: + TimelineHeaderView* m_header{nullptr}; + TimelineModel* m_timelineModel{nullptr}; + QAbstractItemModel* m_model{nullptr}; + QAbstractProxyModel* m_proxyModel{nullptr}; + ItemDelegate* m_delegate{nullptr}; + TimelineViewDragHandler* m_dragHandler{nullptr}; + TimelineViewResizeHandler* m_resizeHandler{nullptr}; + TimelineViewSelectHandler* m_selectHandler{nullptr}; + TimelineViewTrackHandler* m_trackHandler{nullptr}; + + ZoomFactor m_zoomFactor{ZoomFactor::ThirtyMinutes}; + ZoomFactor m_upperZoomFactor{ZoomFactor::OneDay}; + ZoomFactor m_minZoomFactor{ZoomFactor::FifteenSeconds}; + ZoomFactor m_maxZoomFactor{ZoomFactor::OneDay}; + + qint64 m_startTime{-1}; + qint64 m_currentTime{-1}; + int m_duration{-1}; + + bool m_isCursorTextVisible{false}; + QString m_cursorText; + QPoint m_cursorPosition; + + QVector m_selectedItemIds; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.cpp old mode 100755 new mode 100644 index a7021d793..82d494b13 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.cpp @@ -1,506 +1,515 @@ #include "timeline_view_drag_handler.h" + #include "item.h" -#include #include "track.h" #include -#include +#include #include #include -#include - +#include +#include namespace LtsTimeline { -TimelineViewDragHandler::TimelineViewDragHandler(TimelineView *view) - : m_view(view) -{} +TimelineViewDragHandler::TimelineViewDragHandler(TimelineView* view) : m_view(view) {} TimelineViewDragHandler::~TimelineViewDragHandler() { - m_view = nullptr; + m_view = nullptr; } - - - -void TimelineViewDragHandler::dragEnterEvent(QDragEnterEvent *e) +void TimelineViewDragHandler::dragEnterEvent(QDragEnterEvent* e) { - if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - { - e->ignore(); - return; - } - if (e->mimeData()->hasFormat(Item::mimetype)) - e->acceptProposedAction(); - else - e->ignore(); -} - -void TimelineViewDragHandler::dragMoveEvent(QDragMoveEvent *e) -{ - if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - { - e->ignore(); - return; - } - if (!e->mimeData()->hasFormat(Item::mimetype)) - return; - - m_dragPos = e->pos(); - m_view->m_header->setHoverPosition(m_dragPos.x()); - e->setAccepted(canDragItemsTo(e->pos())); - m_view->viewport()->update(); -} - -void TimelineViewDragHandler::dragLeaveEvent(QDragLeaveEvent *e) -{ - Q_UNUSED(e); - m_dragPos = {}; -} - -void TimelineViewDragHandler::dropEvent(QDropEvent *e) -{ - if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty()) - { - e->ignore(); - return; - } - if (!e->mimeData()->hasFormat(Item::mimetype)) - return; - - if (!canDragItemsTo(e->pos())) - { - clear(); - e->acceptProposedAction(); - return; - } - - qint64 dt = deltaTime(); - try - { - for (const int &itemId : std::as_const(m_dragItemIds)) + if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty() || + !m_dragStartIndex.isValid()) { - const Item &item = m_view->timelineModel()->item(itemId); - m_view->timelineModel()->moveItemToTrack(itemId, dragItemTrackId(item), item.startTime() + dt); + e->ignore(); + return; } - } - catch (const QString &str) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; } - clear(); - e->acceptProposedAction(); + if (e->mimeData()->hasFormat(Item::mimetype)) + e->acceptProposedAction(); + else + e->ignore(); } -void TimelineViewDragHandler::mouseMoveEvent(QMouseEvent *e) +void TimelineViewDragHandler::dragMoveEvent(QDragMoveEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; - - if (e->buttons() != Qt::LeftButton) - { - clear(); - return; - } - - if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - return; - - if ((e->pos() - m_dragStartPos).manhattanLength() < QApplication::startDragDistance()) - return; - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() == Section::eActuator) - { - m_view->setCursor(QCursor(Qt::ForbiddenCursor)); - return; - } - - m_dragPos = e->pos(); - m_view->setCursor(QCursor(canDragItemsTo(m_dragPos) ? Qt::ClosedHandCursor : Qt::ForbiddenCursor)); - if (index.data().toInt() == m_dragStartIndex.data().toInt()) - return; - - QMimeData *mimeData = new QMimeData(); - mimeData->setData(Item::mimetype, {}); - QDrag *drag = new QDrag(m_view); - drag->setMimeData(mimeData); - if (drag->exec(Qt::MoveAction) == Qt::MoveAction) - { - - } - else - { - - } -} - -void TimelineViewDragHandler::mousePressEvent(QMouseEvent *e) -{ - if (!m_view->timelineModel()->isEditable()) - return; - - if (e->button() != Qt::LeftButton) - return; - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() == Section::eActuator) - return; - - try - { - Track &track = m_view->timelineModel()->track(index.data().toInt()); - Item &item = track.itemAt(m_view->toTime(e->pos().x())); - m_dragItemIds = m_view->m_selectedItemIds; - if (!m_dragItemIds.contains(item.id())) - m_dragItemIds = { item.id() }; - - for (const int &itemId : m_dragItemIds) - if (!m_view->timelineModel()->item(itemId).isEditable()) + if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty() || + !m_dragStartIndex.isValid()) + { + e->ignore(); + return; + } + if (!e->mimeData()->hasFormat(Item::mimetype)) return; - m_dragStartIndex = index; - m_dragStartTime = m_view->toTime(e->pos().x()); - m_dragStartPos = e->pos(); - m_dragPos = m_dragStartPos; - m_view->setCursor(QCursor(Qt::ClosedHandCursor)); - } - catch (const QString &str) { DEBUG_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) {} + m_dragPos = e->pos(); + m_view->m_header->setHoverPosition(m_dragPos.x()); + e->setAccepted(canDragItemsTo(e->pos())); + m_view->viewport()->update(); } -void TimelineViewDragHandler::mouseReleaseEvent(QMouseEvent *e) +void TimelineViewDragHandler::dragLeaveEvent(QDragLeaveEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; - - if (e->button() != Qt::LeftButton) - return; - - if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - return; - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() == Section::eActuator) - return; - - if (index.data().toInt() != m_dragStartIndex.data().toInt()) - return; - - m_dragPos = e->pos(); - if (m_dragPos.x() == m_dragStartPos.x()) - { - clear(); - return; - } - if (!canMoveItemsTo(m_dragPos)) - { - clear(); - return; - } - - emit m_view->currentItemTimeChanged(); - qint64 dt = deltaTime(); - for (const int &itemId : m_dragItemIds) - { - Item &item = m_view->timelineModel()->item(itemId); - m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); - } - clear(); + Q_UNUSED(e); + m_dragPos = {}; } -void TimelineViewDragHandler::keyPressEvent(QKeyEvent *e) +void TimelineViewDragHandler::dropEvent(QDropEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; - if (m_view->m_selectedItemIds.isEmpty()) - return; + if (!m_view->timelineModel()->isEditable() || e->source() != m_view || m_dragItemIds.isEmpty()) + { + e->ignore(); + return; + } + if (!e->mimeData()->hasFormat(Item::mimetype)) + return; - if (e->key() == Qt::Key_Escape) - { + if (!canDragItemsTo(e->pos())) + { + clear(); + e->acceptProposedAction(); + return; + } + + qint64 dt = deltaTime(); + try + { + for (const int& itemId : std::as_const(m_dragItemIds)) + { + const Item& item = m_view->timelineModel()->item(itemId); + m_view->timelineModel()->moveItemToTrack(itemId, dragItemTrackId(item), item.startTime() + dt); + } + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + } clear(); - return; - } - - if (e->key() != Qt::Key_Left && e->key() != Qt::Key_Right) - return; - - int dt = m_view->timelineModel()->snapStep(); - if (e->key() == Qt::Key_Left) - moveItemsLeft(m_view->selectedItemIds(), QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? -dt : -10 * dt); - else - moveItemsRight(m_view->selectedItemIds(), QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? dt : 10 * dt); + e->acceptProposedAction(); } +void TimelineViewDragHandler::mouseMoveEvent(QMouseEvent* e) +{ + if (!m_view->timelineModel()->isEditable()) + return; + + if (e->buttons() != Qt::LeftButton) + { + clear(); + return; + } + + if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) + return; + + if ((e->pos() - m_dragStartPos).manhattanLength() < QApplication::startDragDistance()) + return; + + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() == Section::eActuator) + { + m_view->setCursor(QCursor(Qt::ForbiddenCursor)); + return; + } + + m_dragPos = e->pos(); + m_view->setCursor(QCursor(canDragItemsTo(m_dragPos) ? Qt::ClosedHandCursor : Qt::ForbiddenCursor)); + if (index.data().toInt() == m_dragStartIndex.data().toInt()) + return; + + QMimeData* mimeData = new QMimeData(); + mimeData->setData(Item::mimetype, {}); + QDrag* drag = new QDrag(m_view); + drag->setMimeData(mimeData); + if (drag->exec(Qt::MoveAction) == Qt::MoveAction) + { + } + else + { + } +} + +void TimelineViewDragHandler::mousePressEvent(QMouseEvent* e) +{ + if (!m_view->timelineModel()->isEditable()) + return; + + if (e->button() != Qt::LeftButton) + return; + + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() == Section::eActuator) + return; + + try + { + Track& track = m_view->timelineModel()->track(index.data().toInt()); + Item& item = track.itemAt(m_view->toTime(e->pos().x())); + m_dragItemIds = m_view->m_selectedItemIds; + if (!m_dragItemIds.contains(item.id())) + m_dragItemIds = {item.id()}; + + for (const int& itemId : m_dragItemIds) + if (!m_view->timelineModel()->item(itemId).isEditable()) + return; + + m_dragStartIndex = index; + m_dragStartTime = m_view->toTime(e->pos().x()); + m_dragStartPos = e->pos(); + m_dragPos = m_dragStartPos; + m_view->setCursor(QCursor(Qt::ClosedHandCursor)); + } + catch (const QString& str) + { + DEBUG_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; + } + catch (...) + { + } +} + +void TimelineViewDragHandler::mouseReleaseEvent(QMouseEvent* e) +{ + if (!m_view->timelineModel()->isEditable()) + return; + + if (e->button() != Qt::LeftButton) + return; + + if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) + return; + + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() == Section::eActuator) + return; + + if (index.data().toInt() != m_dragStartIndex.data().toInt()) + return; + + m_dragPos = e->pos(); + if (m_dragPos.x() == m_dragStartPos.x()) + { + clear(); + return; + } + if (!canMoveItemsTo(m_dragPos)) + { + clear(); + return; + } + + emit m_view->currentItemTimeChanged(); + qint64 dt = deltaTime(); + for (const int& itemId : m_dragItemIds) + { + Item& item = m_view->timelineModel()->item(itemId); + m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); + } + clear(); +} + +void TimelineViewDragHandler::keyPressEvent(QKeyEvent* e) +{ + if (!m_view->timelineModel()->isEditable()) + return; + if (m_view->m_selectedItemIds.isEmpty()) + return; + + if (e->key() == Qt::Key_Escape) + { + clear(); + return; + } + + if (e->key() != Qt::Key_Left && e->key() != Qt::Key_Right) + return; + + int dt = m_view->timelineModel()->snapStep(); + if (e->key() == Qt::Key_Left) + moveItemsLeft(m_view->selectedItemIds(), + QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? -dt : -10 * dt); + else + moveItemsRight(m_view->selectedItemIds(), + QApplication::keyboardModifiers().testFlag(Qt::ControlModifier) ? dt : 10 * dt); +} bool TimelineViewDragHandler::isActive() const { - return !m_dragItemIds.isEmpty() && (m_dragPos - m_dragStartPos).manhattanLength() >= QApplication::startDragDistance(); + return !m_dragItemIds.isEmpty() && + (m_dragPos - m_dragStartPos).manhattanLength() >= QApplication::startDragDistance(); } - int TimelineViewDragHandler::deltaX() const { - if (!m_view->timelineModel()->isSnapEnabled()) - return m_dragPos.x() - m_dragStartPos.x(); - return m_view->toPixel(m_dragStartTime + deltaTime()) - m_view->toPixel(m_dragStartTime); + if (!m_view->timelineModel()->isSnapEnabled()) + return m_dragPos.x() - m_dragStartPos.x(); + return m_view->toPixel(m_dragStartTime + deltaTime()) - m_view->toPixel(m_dragStartTime); } int TimelineViewDragHandler::deltaY() const { - const QModelIndex dragIndex = m_view->indexAt(m_dragPos); - if (!dragIndex.isValid()) - return m_dragPos.y() - m_dragStartPos.y(); - return m_view->visualRect(dragIndex).top() - m_view->visualRect(m_dragStartIndex).top(); + const QModelIndex dragIndex = m_view->indexAt(m_dragPos); + if (!dragIndex.isValid()) + return m_dragPos.y() - m_dragStartPos.y(); + return m_view->visualRect(dragIndex).top() - m_view->visualRect(m_dragStartIndex).top(); } qint64 TimelineViewDragHandler::deltaTime() const { - if (!m_view->timelineModel()->isSnapEnabled()) - return m_view->toTime(m_dragPos.x()) - m_view->toTime(m_dragStartPos.x()); + if (!m_view->timelineModel()->isSnapEnabled()) + return m_view->toTime(m_dragPos.x()) - m_view->toTime(m_dragStartPos.x()); - qint64 dt = ((m_view->toTime(m_dragPos.x()) - m_dragStartTime) / m_view->timelineModel()->snapStep()) * m_view->timelineModel()->snapStep(); - int dtAbsMin = 2 * m_view->timelineModel()->snapTolerance(); - int eps = m_view->timelineModel()->snapTolerance(); - for (const int &dragItemId : m_dragItemIds) - { - const Item &dragItem = m_view->timelineModel()->item(dragItemId); - qint64 start = dragItem.startTime() + dt; - qint64 end = start + dragItem.duration(); - for (int itemId : m_view->timelineModel()->itemIds()) + qint64 dt = ((m_view->toTime(m_dragPos.x()) - m_dragStartTime) / m_view->timelineModel()->snapStep()) * + m_view->timelineModel()->snapStep(); + int dtAbsMin = 2 * m_view->timelineModel()->snapTolerance(); + int eps = m_view->timelineModel()->snapTolerance(); + for (const int& dragItemId : m_dragItemIds) { - if (m_dragItemIds.contains(itemId)) - continue; + const Item& dragItem = m_view->timelineModel()->item(dragItemId); + qint64 start = dragItem.startTime() + dt; + qint64 end = start + dragItem.duration(); + for (int itemId : m_view->timelineModel()->itemIds()) + { + if (m_dragItemIds.contains(itemId)) + continue; - const Item &item = m_view->timelineModel()->item(itemId); - if (start - eps < item.startTime() + item.duration() && item.startTime() + item.duration() < start + eps) - { - qint64 dtCurrent = item.startTime() + item.duration() - dragItem.startTime(); - qint64 dtAbsCurrent = std::abs(dtCurrent); - if (dtAbsCurrent < dtAbsMin) - { - dtAbsMin = dtAbsCurrent; - dt = dtCurrent; + const Item& item = m_view->timelineModel()->item(itemId); + if (start - eps < item.startTime() + item.duration() && item.startTime() + item.duration() < start + eps) + { + qint64 dtCurrent = item.startTime() + item.duration() - dragItem.startTime(); + qint64 dtAbsCurrent = std::abs(dtCurrent); + if (dtAbsCurrent < dtAbsMin) + { + dtAbsMin = dtAbsCurrent; + dt = dtCurrent; + } + } + else if (end - eps < item.startTime() && item.startTime() < end + eps) + { + qint64 dtCurrent = item.startTime() - (dragItem.startTime() + dragItem.duration()); + qint64 dtAbsCurrent = std::abs(dtCurrent); + if (dtAbsCurrent < dtAbsMin) + { + dtAbsMin = dtAbsCurrent; + dt = dtCurrent; + } + } } - } - else if (end - eps < item.startTime() && item.startTime() < end + eps) - { - qint64 dtCurrent = item.startTime() - (dragItem.startTime() + dragItem.duration()); - qint64 dtAbsCurrent = std::abs(dtCurrent); - if (dtAbsCurrent < dtAbsMin) - { - dtAbsMin = dtAbsCurrent; - dt = dtCurrent; - } - } } - } - return dt; + return dt; } - - - -bool TimelineViewDragHandler::canDragItemsTo(const QPoint &point) const +bool TimelineViewDragHandler::canDragItemsTo(const QPoint& point) const { - if (!m_view->timelineModel()->isEditable()) - return false; + if (!m_view->timelineModel()->isEditable()) + return false; - if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - return false; + if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) + return false; + const QModelIndex index = m_view->indexAt(point); + if (!index.isValid() || index.column() == Section::eActuator) + return false; - const QModelIndex index = m_view->indexAt(point); - if (!index.isValid() || index.column() == Section::eActuator) - return false; + if (index.data().toInt() == m_dragStartIndex.data().toInt()) + return canMoveItemsTo(point); + else + { + try + { + qint64 dt = deltaTime(); + for (const int& itemId : m_dragItemIds) + { + const Item& item = m_view->timelineModel()->item(itemId); + int trackId = dragItemTrackId(item); + if (trackId == 0) + return false; - if (index.data().toInt() == m_dragStartIndex.data().toInt()) - return canMoveItemsTo(point); - else - { + const Track& track = m_view->timelineModel()->track(trackId); + qint64 startNew = item.startTime() + dt; + if (!m_view->timelineModel()->canDropItem(item, track.id(), startNew)) + return false; + + if (track.isItemsBetween(startNew, startNew + item.duration(), m_dragItemIds, true)) + return false; + } + } + catch (...) + { + return true; + } + } + return true; +} + +bool TimelineViewDragHandler::canMoveItemsTo(const QPoint& point) const +{ + if (!m_view->timelineModel()->isEditable()) + return false; + if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) + return false; + + const QModelIndex index = m_view->indexAt(point); + if (!index.isValid() || index.column() == Section::eActuator || + index.data().toInt() != m_dragStartIndex.data().toInt()) + return false; + + qint64 dt = deltaTime(); + for (const int& itemId : m_dragItemIds) + { + const Item& item = m_view->timelineModel()->item(itemId); + qint64 startNew = item.startTime() + dt; + if (!m_view->timelineModel()->canMoveItem(item, startNew)) + return false; + + const Track& track = m_view->timelineModel()->track(item.parentTrackId()); + if (track.isItemsBetween(startNew, startNew + item.duration(), m_dragItemIds, true)) + return false; + } + return true; +} + +void TimelineViewDragHandler::moveItemsLeft(const QVector& itemIds, int dt) +{ + Q_ASSERT(dt < 0); try { - qint64 dt = deltaTime(); - for (const int &itemId : m_dragItemIds) - { - const Item &item = m_view->timelineModel()->item(itemId); - int trackId = dragItemTrackId(item); - if (trackId == 0) - return false; + for (int itemId : itemIds) + { + const Item& item = m_view->timelineModel()->item(itemId); + const Track& track = m_view->timelineModel()->track(item.parentTrackId()); + if (track.isItemsBetween(item.startTime() + dt, item.startTime() + item.duration() + dt, itemIds, true)) + { + if (dt < -m_view->timelineModel()->snapStep()) + moveItemsLeft(itemIds, dt + m_view->timelineModel()->snapStep()); + return; + } + if (!m_view->timelineModel()->canMoveItem(item, item.startTime() + dt)) + { + if (dt < -m_view->timelineModel()->snapStep()) + moveItemsLeft(itemIds, dt + m_view->timelineModel()->snapStep()); + return; + } + } + } + catch (const QString& errMsg) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed: " << errMsg; + return; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + return; + } - const Track &track = m_view->timelineModel()->track(trackId); - qint64 startNew = item.startTime() + dt; - if (!m_view->timelineModel()->canDropItem(item, track.id(), startNew)) - return false; - - if (track.isItemsBetween(startNew, startNew + item.duration(), m_dragItemIds, true)) - return false; - } + try + { + for (int itemId : itemIds) + { + Item& item = m_view->timelineModel()->item(itemId); + m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); + } + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } catch (...) { - return true; } - } - return true; } -bool TimelineViewDragHandler::canMoveItemsTo(const QPoint &point) const +void TimelineViewDragHandler::moveItemsRight(const QVector& itemIds, int dt) { - if (!m_view->timelineModel()->isEditable()) - return false; - if (m_dragItemIds.isEmpty() || !m_dragStartIndex.isValid()) - return false; + Q_ASSERT(dt > 0); + try + { + for (int itemId : itemIds) + { + const Item& item = m_view->timelineModel()->item(itemId); + const Track& track = m_view->timelineModel()->track(item.parentTrackId()); + if (track.isItemsBetween(item.startTime() + dt, item.startTime() + item.duration() + dt, itemIds, true)) + { + if (dt > m_view->timelineModel()->snapStep()) + moveItemsRight(itemIds, dt - m_view->timelineModel()->snapStep()); + return; + } + if (!m_view->timelineModel()->canMoveItem(item, item.startTime() + dt)) + { + if (dt > m_view->timelineModel()->snapStep()) + moveItemsRight(itemIds, dt - m_view->timelineModel()->snapStep()); + return; + } + } + } + catch (const QString& errMsg) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed: " << errMsg; + return; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + return; + } - - const QModelIndex index = m_view->indexAt(point); - if (!index.isValid() || index.column() == Section::eActuator || index.data().toInt() != m_dragStartIndex.data().toInt()) - return false; - - qint64 dt = deltaTime(); - for (const int &itemId : m_dragItemIds) - { - const Item &item = m_view->timelineModel()->item(itemId); - qint64 startNew = item.startTime() + dt; - if (!m_view->timelineModel()->canMoveItem(item, startNew)) - return false; - - const Track &track = m_view->timelineModel()->track(item.parentTrackId()); - if (track.isItemsBetween(startNew, startNew + item.duration(), m_dragItemIds, true)) - return false; - } - return true; + try + { + for (int itemId : itemIds) + { + Item& item = m_view->timelineModel()->item(itemId); + m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); + } + } + catch (const QString& errMsg) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << errMsg; + } + catch (...) + { + } } - -void TimelineViewDragHandler::moveItemsLeft(const QVector &itemIds, int dt) +int TimelineViewDragHandler::dragItemTrackId(const Item& item) const { - Q_ASSERT(dt < 0); - try - { - for (int itemId : itemIds) + int dy = deltaY(); + + const QModelIndex index = m_view->indexAt(m_dragStartPos + QPoint(0, dy)); + if (index.data().toInt() == m_dragStartIndex.data().toInt()) + return item.parentTrackId(); + + try { - const Item &item = m_view->timelineModel()->item(itemId); - const Track &track = m_view->timelineModel()->track(item.parentTrackId()); - if (track.isItemsBetween(item.startTime() + dt, item.startTime() + item.duration() + dt, itemIds, true)) - { - if (dt < - m_view->timelineModel()->snapStep()) - moveItemsLeft(itemIds, dt + m_view->timelineModel()->snapStep()); - return; - } - if (!m_view->timelineModel()->canMoveItem(item, item.startTime() + dt)) - { - if (dt < - m_view->timelineModel()->snapStep()) - moveItemsLeft(itemIds, dt + m_view->timelineModel()->snapStep()); - return; - } - } - } - catch (const QString &errMsg) - { - ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed: " << errMsg; - return; - } - catch (...) - { - ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; - return; - } - try - { - for (int itemId : itemIds) + const QModelIndex originalIndex = m_view->timelineModel()->indexOfTrack(item.parentTrackId()); + + const QModelIndex newIndex = m_view->indexAt(m_view->visualRect(originalIndex).center() + QPoint(0, dy)); + return newIndex.data().toInt(); + } + catch (...) { - Item &item = m_view->timelineModel()->item(itemId); - m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); + return 0; } - } - catch (const QString &str) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) {} -} - -void TimelineViewDragHandler::moveItemsRight(const QVector &itemIds, int dt) -{ - Q_ASSERT(dt > 0); - try - { - for (int itemId : itemIds) - { - const Item &item = m_view->timelineModel()->item(itemId); - const Track &track = m_view->timelineModel()->track(item.parentTrackId()); - if (track.isItemsBetween(item.startTime() + dt, item.startTime() + item.duration() + dt, itemIds, true)) - { - if (dt > m_view->timelineModel()->snapStep()) - moveItemsRight(itemIds, dt - m_view->timelineModel()->snapStep()); - return; - } - if (!m_view->timelineModel()->canMoveItem(item, item.startTime() + dt)) - { - if (dt > m_view->timelineModel()->snapStep()) - moveItemsRight(itemIds, dt - m_view->timelineModel()->snapStep()); - return; - } - } - } - catch (const QString &errMsg) - { - ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed: " << errMsg; - return; - } - catch (...) - { - ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; - return; - } - - try - { - for (int itemId : itemIds) - { - Item &item = m_view->timelineModel()->item(itemId); - m_view->timelineModel()->setItemStartTime(item, item.startTime() + dt); - } - } - catch (const QString &errMsg) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << errMsg; } - catch (...) {} -} - - -int TimelineViewDragHandler::dragItemTrackId(const Item &item) const -{ - int dy = deltaY(); - - const QModelIndex index = m_view->indexAt(m_dragStartPos + QPoint(0, dy)); - if (index.data().toInt() == m_dragStartIndex.data().toInt()) - return item.parentTrackId(); - - try - { - - const QModelIndex originalIndex = m_view->timelineModel()->indexOfTrack(item.parentTrackId()); - - const QModelIndex newIndex = m_view->indexAt(m_view->visualRect(originalIndex).center() + QPoint(0, dy)); - return newIndex.data().toInt(); - } - catch (...) - { - return 0; - } } void TimelineViewDragHandler::clear() { - m_dragStartIndex = {}; - m_dragStartTime = -1; - m_dragStartPos = {}; - m_dragPos = {}; - m_dragItemIds.clear(); - m_view->setCursor(QCursor(Qt::ArrowCursor)); - m_view->viewport()->update(); + m_dragStartIndex = {}; + m_dragStartTime = -1; + m_dragStartPos = {}; + m_dragPos = {}; + m_dragItemIds.clear(); + m_view->setCursor(QCursor(Qt::ArrowCursor)); + m_view->viewport()->update(); } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.h old mode 100755 new mode 100644 index 9ba2cac01..831c07020 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_drag_handler.h @@ -1,13 +1,11 @@ #pragma once +#include "ltstimeline_export.h" #include "timeline_view.h" -#include "ltstimeline_export.h" - +#include #include #include -#include - class QDragEnterEvent; class QDragMoveEvent; @@ -16,7 +14,6 @@ class QDropEvent; class QMouseEvent; class QKeyEvent; - namespace LtsTimeline { @@ -25,58 +22,74 @@ class Track; class TimelineView; class ItemDelegate; - class LTSTIMELINE_EXPORT TimelineViewDragHandler { - friend class TimelineView; - friend class ItemDelegate; + friend class TimelineView; + friend class ItemDelegate; -public: - explicit TimelineViewDragHandler(TimelineView *view); - virtual ~TimelineViewDragHandler(); + public: + explicit TimelineViewDragHandler(TimelineView* view); + virtual ~TimelineViewDragHandler(); - virtual void dragEnterEvent(QDragEnterEvent *e); - virtual void dragMoveEvent(QDragMoveEvent *e); - virtual void dragLeaveEvent(QDragLeaveEvent *e); - virtual void dropEvent(QDropEvent *e); - virtual void mouseMoveEvent(QMouseEvent *e); - virtual void mousePressEvent(QMouseEvent *e); - virtual void mouseReleaseEvent(QMouseEvent *e); - virtual void keyPressEvent(QKeyEvent *e); + virtual void dragEnterEvent(QDragEnterEvent* e); + virtual void dragMoveEvent(QDragMoveEvent* e); + virtual void dragLeaveEvent(QDragLeaveEvent* e); + virtual void dropEvent(QDropEvent* e); + virtual void mouseMoveEvent(QMouseEvent* e); + virtual void mousePressEvent(QMouseEvent* e); + virtual void mouseReleaseEvent(QMouseEvent* e); + virtual void keyPressEvent(QKeyEvent* e); - virtual bool isActive() const; + virtual bool isActive() const; - virtual int deltaX() const; - virtual int deltaY() const; - virtual qint64 deltaTime() const; + virtual int deltaX() const; + virtual int deltaY() const; + virtual qint64 deltaTime() const; - - const QVector &dragItemIds() const { return m_dragItemIds; } - const QModelIndex &dragStartIndex() const { return m_dragStartIndex; } - qint64 dragStartTime() const { return m_dragStartTime; } - const QPoint &dragStartPos() const { return m_dragStartPos; } - const QPoint &dragPos() const { return m_dragPos; } + const QVector& dragItemIds() const + { + return m_dragItemIds; + } -protected: - virtual bool canDragItemsTo(const QPoint &point) const; - virtual bool canMoveItemsTo(const QPoint &point) const; + const QModelIndex& dragStartIndex() const + { + return m_dragStartIndex; + } - virtual void moveItemsLeft(const QVector &itemIds, int dt); - virtual void moveItemsRight(const QVector &itemIds, int dt); + qint64 dragStartTime() const + { + return m_dragStartTime; + } - int dragItemTrackId(const Item &item) const; - void clear(); + const QPoint& dragStartPos() const + { + return m_dragStartPos; + } -protected: - TimelineView *m_view{nullptr}; - QVector m_dragItemIds; - QModelIndex m_dragStartIndex; - qint64 m_dragStartTime{-1}; - QPoint m_dragStartPos; - QPoint m_dragPos; + const QPoint& dragPos() const + { + return m_dragPos; + } - int m_snapLinePos{-1}; + protected: + virtual bool canDragItemsTo(const QPoint& point) const; + virtual bool canMoveItemsTo(const QPoint& point) const; + virtual void moveItemsLeft(const QVector& itemIds, int dt); + virtual void moveItemsRight(const QVector& itemIds, int dt); + + int dragItemTrackId(const Item& item) const; + void clear(); + + protected: + TimelineView* m_view{nullptr}; + QVector m_dragItemIds; + QModelIndex m_dragStartIndex; + qint64 m_dragStartTime{-1}; + QPoint m_dragStartPos; + QPoint m_dragPos; + + int m_snapLinePos{-1}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.cpp old mode 100755 new mode 100644 index 9525b3f2f..3e94c3942 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.cpp @@ -1,279 +1,287 @@ #include "timeline_view_resize_handler.h" -#include "timeline_view.h" -#include "timeline_header_view.h" + #include "item.h" +#include "timeline_header_view.h" +#include "timeline_view.h" #include "track.h" #include -#include #include - +#include namespace LtsTimeline { -TimelineViewResizeHandler::TimelineViewResizeHandler(TimelineView *view) - : m_view(view) -{} +TimelineViewResizeHandler::TimelineViewResizeHandler(TimelineView* view) : m_view(view) {} TimelineViewResizeHandler::~TimelineViewResizeHandler() { - m_view = nullptr; + m_view = nullptr; } - - - -void TimelineViewResizeHandler::mouseMoveEvent(QMouseEvent *e) +void TimelineViewResizeHandler::mouseMoveEvent(QMouseEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; - if (m_currentTrackId == -1 || m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) - return; - if (!m_view->timelineModel()->item(m_currentItemId).isEditable()) - return; + if (!m_view->timelineModel()->isEditable()) + return; + if (m_currentTrackId == -1 || m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) + return; + if (!m_view->timelineModel()->item(m_currentItemId).isEditable()) + return; + const QModelIndex index(m_view->indexAt(e->pos())); + if (index.column() == Section::eActuator || !index.isValid()) + return; - const QModelIndex index(m_view->indexAt(e->pos())); - if (index.column() == Section::eActuator || !index.isValid()) - return; + Track& track = m_view->timelineModel()->track(index.data().toInt()); + if (track.id() != m_currentTrackId) + return; - Track &track = m_view->timelineModel()->track(index.data().toInt()); - if (track.id() != m_currentTrackId) - return; - - qint64 time = m_view->timelineModel()->isSnapEnabled() ? globalSnapTime(e->pos().x()) : localSnapTime(e->pos().x()); - try - { - Item &item = m_view->timelineModel()->item(m_currentItemId); - if (m_resizePos == ResizePosition::eStart) + qint64 time = m_view->timelineModel()->isSnapEnabled() ? globalSnapTime(e->pos().x()) : localSnapTime(e->pos().x()); + try { - if (item.startTime() == time) - return; + Item& item = m_view->timelineModel()->item(m_currentItemId); + if (m_resizePos == ResizePosition::eStart) + { + if (item.startTime() == time) + return; - if (!m_view->timelineModel()->canResizeItem(item, time, item.startTime() + item.duration() - time)) - return; + if (!m_view->timelineModel()->canResizeItem(item, time, item.startTime() + item.duration() - time)) + return; - m_view->timelineModel()->setItemDuration(track, item, item.startTime() + item.duration() - time); - m_view->timelineModel()->setItemStartTime(track, item, time); + m_view->timelineModel()->setItemDuration(track, item, item.startTime() + item.duration() - time); + m_view->timelineModel()->setItemStartTime(track, item, time); + } + else + { + if (item.duration() == time - item.startTime()) + return; + + if (!m_view->timelineModel()->canResizeItem(item, item.startTime(), time - item.startTime())) + return; + + m_view->timelineModel()->setItemDuration(track, item, time - item.startTime()); + } } - else + catch (...) { - if (item.duration() == time - item.startTime()) - return; - - if (!m_view->timelineModel()->canResizeItem(item, item.startTime(), time - item.startTime())) - return; - - m_view->timelineModel()->setItemDuration(track, item, time - item.startTime()); + mouseReleaseEvent(e); } - } - catch (...) - { - mouseReleaseEvent(e); - } } -void TimelineViewResizeHandler::mousePressEvent(QMouseEvent *e) +void TimelineViewResizeHandler::mousePressEvent(QMouseEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; + if (!m_view->timelineModel()->isEditable()) + return; - if (e->button() != Qt::LeftButton) - return; + if (e->button() != Qt::LeftButton) + return; + const QModelIndex index(m_view->indexAt(e->pos())); + if (!index.isValid() || index.column() == Section::eActuator) + return; - const QModelIndex index(m_view->indexAt(e->pos())); - if (!index.isValid() || index.column() == Section::eActuator) - return; + try + { + const Track& track = m_view->timelineModel()->track(index.data().toInt()); + const Item& item = track.itemAt(m_view->toTime(e->pos().x())); + if (!item.isEditable()) + return; - try - { - const Track &track = m_view->timelineModel()->track(index.data().toInt()); - const Item &item = track.itemAt(m_view->toTime(e->pos().x())); - if (!item.isEditable()) - return; + const int startPos = m_view->toPixel(item.startTime()); + const int endPos = m_view->toPixel(item.startTime() + item.duration()); + if (endPos - startPos < 15 || (startPos + 5 < e->pos().x() && e->pos().x() < endPos - 5)) + { + m_resizePos = ResizePosition::eNone; + return; + } + else if (startPos + 5 >= e->pos().x()) + m_resizePos = ResizePosition::eStart; + else + m_resizePos = ResizePosition::eEnd; - const int startPos = m_view->toPixel(item.startTime()); - const int endPos = m_view->toPixel(item.startTime() + item.duration()); - if (endPos - startPos < 15 || (startPos + 5 < e->pos().x() && e->pos().x() < endPos - 5)) + m_currentTrackId = track.id(); + m_currentItemId = item.id(); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) { - m_resizePos = ResizePosition::eNone; - return; } - else if (startPos + 5 >= e->pos().x()) - m_resizePos = ResizePosition::eStart; - else - m_resizePos = ResizePosition::eEnd; - - m_currentTrackId = track.id(); - m_currentItemId = item.id(); - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} } -void TimelineViewResizeHandler::mouseReleaseEvent(QMouseEvent *e) +void TimelineViewResizeHandler::mouseReleaseEvent(QMouseEvent* e) { - if (!m_view->timelineModel()->isEditable()) - return; + if (!m_view->timelineModel()->isEditable()) + return; - if (e->button() != Qt::LeftButton) - return; + if (e->button() != Qt::LeftButton) + return; - emit m_view->currentItemTimeChanged(); - m_view->setCursor(QCursor(Qt::ArrowCursor)); - m_currentTrackId = -1; - m_currentItemId = -1; - m_resizePos = ResizePosition::eNone; + emit m_view->currentItemTimeChanged(); + m_view->setCursor(QCursor(Qt::ArrowCursor)); + m_currentTrackId = -1; + m_currentItemId = -1; + m_resizePos = ResizePosition::eNone; } - - - qint64 TimelineViewResizeHandler::localSnapTime(int pos) const { - qint64 time = m_view->toTime(pos); - if (m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) - return time; + qint64 time = m_view->toTime(pos); + if (m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) + return time; - try - { - Track &track = m_view->timelineModel()->track(m_currentTrackId); - const Item ¤tItem = m_view->timelineModel()->item(m_currentItemId); - if (m_resizePos == ResizePosition::eStart) + try { - if (time >= currentItem.startTime() + currentItem.duration()) - time = currentItem.startTime() + currentItem.duration() - m_view->timelineModel()->minimumDuration(); - else - { - try + Track& track = m_view->timelineModel()->track(m_currentTrackId); + const Item& currentItem = m_view->timelineModel()->item(m_currentItemId); + if (m_resizePos == ResizePosition::eStart) { - const Item &previous = track.previous(m_currentItemId); - const qint64 endTime = previous.startTime() + previous.duration(); - if (time <= endTime) - time = endTime; + if (time >= currentItem.startTime() + currentItem.duration()) + time = currentItem.startTime() + currentItem.duration() - m_view->timelineModel()->minimumDuration(); + else + { + try + { + const Item& previous = track.previous(m_currentItemId); + const qint64 endTime = previous.startTime() + previous.duration(); + if (time <= endTime) + time = endTime; + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } + } } - catch (const QString &str) + else { - ERROR_LOG(m_view->m_logger) << str; + if (time <= currentItem.startTime()) + time = currentItem.startTime() + m_view->timelineModel()->minimumDuration(); + else + { + try + { + Item& next = track.next(m_currentItemId); + if (time >= next.startTime()) + time = next.startTime(); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } + } } - catch (...) {} - } } - else + catch (const QString& str) { - if (time <= currentItem.startTime()) - time = currentItem.startTime() + m_view->timelineModel()->minimumDuration(); - else - { - try - { - Item &next = track.next(m_currentItemId); - if (time >= next.startTime()) - time = next.startTime(); - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} - } + ERROR_LOG(m_view->m_logger) << str; } - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} - return time; + catch (...) + { + } + return time; } qint64 TimelineViewResizeHandler::globalSnapTime(int pos) const { - qint64 tPos = (m_view->toTime(pos) / m_view->timelineModel()->snapStep()) * m_view->timelineModel()->snapStep(); - if (m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) - return tPos; + qint64 tPos = (m_view->toTime(pos) / m_view->timelineModel()->snapStep()) * m_view->timelineModel()->snapStep(); + if (m_currentItemId == -1 || m_resizePos == ResizePosition::eNone) + return tPos; - qint64 tMin = m_view->m_startTime; - qint64 tMax = m_view->endTime(); - try - { - const Item &previous = m_view->timelineModel()->track(m_currentTrackId).previous(m_currentItemId); - tMin = previous.startTime() + previous.duration(); - } - catch (const QString &str) - { - DEBUG_LOG(m_view->m_logger) << str; - } - catch (...) {} - try - { - const Item &next = m_view->timelineModel()->track(m_currentTrackId).next(m_currentItemId); - tMax = next.startTime(); - } - catch (const QString &str) - { - DEBUG_LOG(m_view->m_logger) << str; - } - catch (...) {} - - qint64 time = tPos; - try - { - const Item ¤tItem = m_view->timelineModel()->item(m_currentItemId); - - int minDist = 2 * m_view->timelineModel()->snapTolerance(); - int eps = m_view->timelineModel()->snapTolerance(); - for (int itemId : m_view->timelineModel()->itemIds()) + qint64 tMin = m_view->m_startTime; + qint64 tMax = m_view->endTime(); + try + { + const Item& previous = m_view->timelineModel()->track(m_currentTrackId).previous(m_currentItemId); + tMin = previous.startTime() + previous.duration(); + } + catch (const QString& str) + { + DEBUG_LOG(m_view->m_logger) << str; + } + catch (...) + { + } + try + { + const Item& next = m_view->timelineModel()->track(m_currentTrackId).next(m_currentItemId); + tMax = next.startTime(); + } + catch (const QString& str) + { + DEBUG_LOG(m_view->m_logger) << str; + } + catch (...) { - if (itemId == m_currentItemId) - continue; - - try - { - const Item &item = m_view->timelineModel()->item(itemId); - qint64 t; - if (time - eps < item.startTime() && item.startTime() < time + eps) - t = item.startTime(); - else if (time - eps < item.startTime() + item.duration() && item.startTime() + item.duration() < time + eps) - t = item.startTime() + item.duration(); - else - continue; - - if (std::abs(t - tPos) < minDist) - { - if ((m_resizePos == ResizePosition::eStart && t >= currentItem.startTime() + currentItem.duration()) || - (m_resizePos == ResizePosition::eEnd && t <= currentItem.startTime())) - continue; - time = t; - minDist = time - tPos; - } - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} } - if (m_resizePos == ResizePosition::eStart && time >= currentItem.startTime() + currentItem.duration()) - return currentItem.startTime() + currentItem.duration() - m_view->timelineModel()->minimumDuration(); - else if (m_resizePos == ResizePosition::eEnd && time <= currentItem.startTime()) - return currentItem.startTime() + m_view->timelineModel()->minimumDuration(); - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} + qint64 time = tPos; + try + { + const Item& currentItem = m_view->timelineModel()->item(m_currentItemId); - time = std::max(tMin, time); - time = std::min(tMax, time); - return time; + int minDist = 2 * m_view->timelineModel()->snapTolerance(); + int eps = m_view->timelineModel()->snapTolerance(); + for (int itemId : m_view->timelineModel()->itemIds()) + { + if (itemId == m_currentItemId) + continue; + + try + { + const Item& item = m_view->timelineModel()->item(itemId); + qint64 t; + if (time - eps < item.startTime() && item.startTime() < time + eps) + t = item.startTime(); + else if (time - eps < item.startTime() + item.duration() && + item.startTime() + item.duration() < time + eps) + t = item.startTime() + item.duration(); + else + continue; + + if (std::abs(t - tPos) < minDist) + { + if ((m_resizePos == ResizePosition::eStart && + t >= currentItem.startTime() + currentItem.duration()) || + (m_resizePos == ResizePosition::eEnd && t <= currentItem.startTime())) + continue; + time = t; + minDist = time - tPos; + } + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } + } + + if (m_resizePos == ResizePosition::eStart && time >= currentItem.startTime() + currentItem.duration()) + return currentItem.startTime() + currentItem.duration() - m_view->timelineModel()->minimumDuration(); + else if (m_resizePos == ResizePosition::eEnd && time <= currentItem.startTime()) + return currentItem.startTime() + m_view->timelineModel()->minimumDuration(); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } + + time = std::max(tMin, time); + time = std::min(tMax, time); + return time; } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.h old mode 100755 new mode 100644 index e400fce44..1a84c0598 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_resize_handler.h @@ -4,39 +4,39 @@ #include - namespace LtsTimeline { class Track; class TimelineView; - class LTSTIMELINE_EXPORT TimelineViewResizeHandler { -public: - enum class ResizePosition { eNone, eStart, eEnd }; + public: + enum class ResizePosition { eNone, eStart, eEnd }; - explicit TimelineViewResizeHandler(TimelineView *view); - virtual ~TimelineViewResizeHandler(); + explicit TimelineViewResizeHandler(TimelineView* view); + virtual ~TimelineViewResizeHandler(); - virtual void mouseMoveEvent(QMouseEvent *e); - virtual void mousePressEvent(QMouseEvent *e); - virtual void mouseReleaseEvent(QMouseEvent *e); + virtual void mouseMoveEvent(QMouseEvent* e); + virtual void mousePressEvent(QMouseEvent* e); + virtual void mouseReleaseEvent(QMouseEvent* e); - virtual bool isActive() const { return m_currentTrackId != -1 && m_currentItemId != -1 && m_resizePos != ResizePosition::eNone; } + virtual bool isActive() const + { + return m_currentTrackId != -1 && m_currentItemId != -1 && m_resizePos != ResizePosition::eNone; + } -private: - virtual qint64 localSnapTime(int pos) const; - virtual qint64 globalSnapTime(int pos) const; - -protected: - TimelineView *m_view{nullptr}; - int m_currentTrackId{-1}; - int m_currentItemId{-1}; - ResizePosition m_resizePos{ResizePosition::eNone}; + private: + virtual qint64 localSnapTime(int pos) const; + virtual qint64 globalSnapTime(int pos) const; + protected: + TimelineView* m_view{nullptr}; + int m_currentTrackId{-1}; + int m_currentItemId{-1}; + ResizePosition m_resizePos{ResizePosition::eNone}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.cpp old mode 100755 new mode 100644 index 649f6e6c9..03cfccab4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.cpp @@ -1,321 +1,334 @@ #include "timeline_view_selection_handler.h" -#include + #include "item_delegate.h" #include +#include #include +#include #include #include -#include - -#include - +#include namespace LtsTimeline { -TimelineViewSelectHandler::TimelineViewSelectHandler(TimelineView *view) - : m_view(view) -{ -} +TimelineViewSelectHandler::TimelineViewSelectHandler(TimelineView* view) : m_view(view) {} TimelineViewSelectHandler::~TimelineViewSelectHandler() { - m_view = nullptr; + m_view = nullptr; } - - - -void TimelineViewSelectHandler::mouseDoubleClickEvent(QMouseEvent *e) +void TimelineViewSelectHandler::mouseDoubleClickEvent(QMouseEvent* e) { - if (e->button() != Qt::LeftButton) - return; - - m_view->clearSelectedItems(); - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() == Section::eActuator) - return; - - try - { - Track &track = m_view->timelineModel()->track(index.data().toInt()); - Item &item = track.itemAt(m_view->toTime(e->pos().x())); - emit m_view->itemActivated(item.id()); - } - catch (const QString &str) { DEBUG_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; } -} - -void TimelineViewSelectHandler::mouseMoveEvent(QMouseEvent *e) -{ - if (m_isRubberBandActive) - { - m_view->setCursor(QCursor(Qt::CrossCursor)); - if (!m_view->isCursorWithinRangeX(e->pos().x())) - m_rubberBand.setHeight(e->pos().y() - m_rubberBand.top()); - - - else - m_rubberBand.setRect( - m_rubberBand.left(), m_rubberBand.top(), e->pos().x() - m_rubberBand.left(), e->pos().y() - m_rubberBand.top() - ); - } - else - m_selectedItemId = -1; -} - -void TimelineViewSelectHandler::mousePressEvent(QMouseEvent *e) -{ - if (e->button() != Qt::LeftButton && e->button() != Qt::RightButton) - return; - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (index.isValid()) - { - if (index.column() == Section::eActuator) - { - qWarning() << "clicked on row with actuator" << index.data().toString(); - return; - } - - try - { - Track &track = m_view->timelineModel()->track(index.data().toInt()); - Item &item = track.itemAt(m_view->toTime(e->pos().x())); - if (e->button() == Qt::LeftButton) - m_selectedItemId = item.id(); - return; - } - catch (...) - { - if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + if (e->button() != Qt::LeftButton) return; - if (e->button() == Qt::RightButton) - { - emit m_view->customContextMenuRequested(e->pos()); - return; - } - - m_view->clearSelectedItems(); - m_rubberBand.setLeft(e->pos().x()); - m_rubberBand.setTop(e->pos().y()); - m_rubberBand.setSize(QSize(0, 0)); - m_isRubberBandActive = true; - return; - } - - return; - } - else - { - qWarning() << "TimelineViewSelectHandler::mousePressEvent: index invalid"; - } - - if (e->button() == Qt::RightButton) - return; - - if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - return; - - m_view->clearSelectedItems(); - - if (!m_view->isCursorWithinRangeX(e->pos().x())) - return; - - m_rubberBand.setLeft(e->pos().x()); - m_rubberBand.setTop(e->pos().y()); - m_rubberBand.setSize(QSize(0, 0)); - m_isRubberBandActive = true; -} - -void TimelineViewSelectHandler::mouseReleaseEvent(QMouseEvent *e) -{ - if (e->button() == Qt::RightButton) - { - - return; - } - - if (e->button() != Qt::LeftButton) - return; - - if (m_isRubberBandActive) - { - m_view->selectItems(getItemsWithinRubberBand()); - m_isRubberBandActive = false; - m_rubberBand.setSize(QSize(0, 0)); - m_view->setCursor(QCursor(Qt::ArrowCursor)); - return; - } - else - { + m_view->clearSelectedItems(); const QModelIndex index = m_view->indexAt(e->pos()); if (!index.isValid() || index.column() == Section::eActuator) - { - m_selectedItemId = -1; - return; - } + return; try { - Track &track = m_view->timelineModel()->track(index.data().toInt()); - Item &item = track.itemAt(m_view->toTime(e->pos().x())); - if (item.id() == m_selectedItemId) - { - if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - { - if (m_view->selectedItemIds().contains(m_selectedItemId)) - m_view->unselectItem(m_selectedItemId); - else - m_view->selectItem(m_selectedItemId, false); - } - else - { - if (m_view->m_selectedItemIds.size() > 1 || !m_view->m_selectedItemIds.contains(m_selectedItemId)) - m_view->selectItem(m_selectedItemId); - else - m_view->unselectItem(m_selectedItemId); - } - } - } catch (...) {} - m_selectedItemId = -1; - } + Track& track = m_view->timelineModel()->track(index.data().toInt()); + Item& item = track.itemAt(m_view->toTime(e->pos().x())); + emit m_view->itemActivated(item.id()); + } + catch (const QString& str) + { + DEBUG_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + } } -void TimelineViewSelectHandler::keyPressEvent(QKeyEvent *e) +void TimelineViewSelectHandler::mouseMoveEvent(QMouseEvent* e) { - if (e->key() == Qt::Key_Escape) - { - m_selectedItemId = -1; - m_view->clearSelectedItems(); - } - else if (e->key() == Qt::Key_Delete) - { - if (!m_view->m_selectedItemIds.isEmpty()) + if (m_isRubberBandActive) { - for (const int &itemId : std::as_const(m_view->m_selectedItemIds)) - { + m_view->setCursor(QCursor(Qt::CrossCursor)); + if (!m_view->isCursorWithinRangeX(e->pos().x())) + m_rubberBand.setHeight(e->pos().y() - m_rubberBand.top()); + + else + m_rubberBand.setRect(m_rubberBand.left(), m_rubberBand.top(), e->pos().x() - m_rubberBand.left(), + e->pos().y() - m_rubberBand.top()); + } + else + m_selectedItemId = -1; +} + +void TimelineViewSelectHandler::mousePressEvent(QMouseEvent* e) +{ + if (e->button() != Qt::LeftButton && e->button() != Qt::RightButton) + return; + + const QModelIndex index = m_view->indexAt(e->pos()); + if (index.isValid()) + { + if (index.column() == Section::eActuator) + { + qWarning() << "clicked on row with actuator" << index.data().toString(); + return; + } + try { - m_view->timelineModel()->removeItem(itemId); + Track& track = m_view->timelineModel()->track(index.data().toInt()); + Item& item = track.itemAt(m_view->toTime(e->pos().x())); + if (e->button() == Qt::LeftButton) + m_selectedItemId = item.id(); + return; } - catch (const QString &str) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; } - } - m_view->clearSelectedItems(); - m_selectedItemId = -1; + catch (...) + { + if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + return; + + if (e->button() == Qt::RightButton) + { + emit m_view->customContextMenuRequested(e->pos()); + return; + } + + m_view->clearSelectedItems(); + m_rubberBand.setLeft(e->pos().x()); + m_rubberBand.setTop(e->pos().y()); + m_rubberBand.setSize(QSize(0, 0)); + m_isRubberBandActive = true; + return; + } + + return; } - } - else if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - { - try + else { - switch (e->key()) - { - case Qt::Key_A: - m_view->selectAllItems(); - m_selectedItemId = -1; - break; - - case Qt::Key_C: - if (m_view->hasSelectedItems()) - m_view->timelineModel()->copyToClipboard(m_view->selectedItemIds()); - break; - - case Qt::Key_X: - if (m_view->hasSelectedItems()) - { - m_view->timelineModel()->cutToClipboard(m_view->selectedItemIds()); - m_view->clearSelectedItems(); - } - break; - - case Qt::Key_V: - if (!m_view->timelineModel()->m_clipboard.empty()) - { - qint64 time = m_view->currentTime(); - if (m_view->m_header->isIndicatorVisible() && m_view->m_header->indicatorTime() != -1) - time = m_view->m_header->indicatorTime(); - m_view->timelineModel()->pasteFromClipboard(time); - } - break; - - default: - break; - } + qWarning() << "TimelineViewSelectHandler::mousePressEvent: index invalid"; } - catch (const QString &str) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; } - catch (...) { ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; } - } + + if (e->button() == Qt::RightButton) + return; + + if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + return; + + m_view->clearSelectedItems(); + + if (!m_view->isCursorWithinRangeX(e->pos().x())) + return; + + m_rubberBand.setLeft(e->pos().x()); + m_rubberBand.setTop(e->pos().y()); + m_rubberBand.setSize(QSize(0, 0)); + m_isRubberBandActive = true; } +void TimelineViewSelectHandler::mouseReleaseEvent(QMouseEvent* e) +{ + if (e->button() == Qt::RightButton) + { + + return; + } + + if (e->button() != Qt::LeftButton) + return; + + if (m_isRubberBandActive) + { + m_view->selectItems(getItemsWithinRubberBand()); + m_isRubberBandActive = false; + m_rubberBand.setSize(QSize(0, 0)); + m_view->setCursor(QCursor(Qt::ArrowCursor)); + return; + } + else + { + + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() == Section::eActuator) + { + m_selectedItemId = -1; + return; + } + + try + { + Track& track = m_view->timelineModel()->track(index.data().toInt()); + Item& item = track.itemAt(m_view->toTime(e->pos().x())); + if (item.id() == m_selectedItemId) + { + if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + { + if (m_view->selectedItemIds().contains(m_selectedItemId)) + m_view->unselectItem(m_selectedItemId); + else + m_view->selectItem(m_selectedItemId, false); + } + else + { + if (m_view->m_selectedItemIds.size() > 1 || !m_view->m_selectedItemIds.contains(m_selectedItemId)) + m_view->selectItem(m_selectedItemId); + else + m_view->unselectItem(m_selectedItemId); + } + } + } + catch (...) + { + } + m_selectedItemId = -1; + } +} + +void TimelineViewSelectHandler::keyPressEvent(QKeyEvent* e) +{ + if (e->key() == Qt::Key_Escape) + { + m_selectedItemId = -1; + m_view->clearSelectedItems(); + } + else if (e->key() == Qt::Key_Delete) + { + if (!m_view->m_selectedItemIds.isEmpty()) + { + for (const int& itemId : std::as_const(m_view->m_selectedItemIds)) + { + try + { + m_view->timelineModel()->removeItem(itemId); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + } + } + m_view->clearSelectedItems(); + m_selectedItemId = -1; + } + } + else if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + { + try + { + switch (e->key()) + { + case Qt::Key_A: + m_view->selectAllItems(); + m_selectedItemId = -1; + break; + + case Qt::Key_C: + if (m_view->hasSelectedItems()) + m_view->timelineModel()->copyToClipboard(m_view->selectedItemIds()); + break; + + case Qt::Key_X: + if (m_view->hasSelectedItems()) + { + m_view->timelineModel()->cutToClipboard(m_view->selectedItemIds()); + m_view->clearSelectedItems(); + } + break; + + case Qt::Key_V: + if (!m_view->timelineModel()->m_clipboard.empty()) + { + qint64 time = m_view->currentTime(); + if (m_view->m_header->isIndicatorVisible() && m_view->m_header->indicatorTime() != -1) + time = m_view->m_header->indicatorTime(); + m_view->timelineModel()->pasteFromClipboard(time); + } + break; + + default: + break; + } + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " " << str; + } + catch (...) + { + ERROR_LOG(m_view->m_logger) << LOGFUNCTION << " failed"; + } + } +} bool TimelineViewSelectHandler::isActive() const { - if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - return true; - if (m_isRubberBandActive) - return true; - return m_selectedItemId != -1; + if (QApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + return true; + if (m_isRubberBandActive) + return true; + return m_selectedItemId != -1; } - - - QVector TimelineViewSelectHandler::getItemsWithinRubberBand() const { - const QPoint topLeft = { std::min(m_rubberBand.left(), m_rubberBand.right()), std::min(m_rubberBand.top(), m_rubberBand.bottom()) }; - const QPoint bottomRight = { std::max(m_rubberBand.left(), m_rubberBand.right()), std::max(m_rubberBand.top(), m_rubberBand.bottom()) }; - const qint64 start = m_view->toTime(topLeft.x()); - const qint64 end = m_view->toTime(bottomRight.x()); - if (start == end) - return {}; + const QPoint topLeft = {std::min(m_rubberBand.left(), m_rubberBand.right()), + std::min(m_rubberBand.top(), m_rubberBand.bottom())}; + const QPoint bottomRight = {std::max(m_rubberBand.left(), m_rubberBand.right()), + std::max(m_rubberBand.top(), m_rubberBand.bottom())}; + const qint64 start = m_view->toTime(topLeft.x()); + const qint64 end = m_view->toTime(bottomRight.x()); + if (start == end) + return {}; - QVector itemsWithinRubberBand; - const int h = m_view->itemDelegate()->sizeHint({}, {}).height(); - for (int y = topLeft.y(); y <= bottomRight.y(); y += h) - { - const QPoint point = { topLeft.x(), y }; - - const QModelIndex index = m_view->indexAt(point); - if (!index.isValid()) - continue; - - try + QVector itemsWithinRubberBand; + const int h = m_view->itemDelegate()->sizeHint({}, {}).height(); + for (int y = topLeft.y(); y <= bottomRight.y(); y += h) { - const Track &track = m_view->timelineModel()->track(index.data().toInt()); - itemsWithinRubberBand += track.itemIdsBetween(start, end); - } - catch (const QString &str) - { - ERROR_LOG(m_view->m_logger) << str; - } - catch (...) {} - } - if (topLeft.y() + h > bottomRight.y()) - { + const QPoint point = {topLeft.x(), y}; - const QModelIndex index = m_view->indexAt(bottomRight); - if (!index.isValid()) - return itemsWithinRubberBand; + const QModelIndex index = m_view->indexAt(point); + if (!index.isValid()) + continue; - try - { - const Track &track = m_view->timelineModel()->track(index.data().toInt()); - itemsWithinRubberBand += track.itemIdsBetween(start, end); + try + { + const Track& track = m_view->timelineModel()->track(index.data().toInt()); + itemsWithinRubberBand += track.itemIdsBetween(start, end); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } } - catch (const QString &str) + if (topLeft.y() + h > bottomRight.y()) { - ERROR_LOG(m_view->m_logger) << str; + + const QModelIndex index = m_view->indexAt(bottomRight); + if (!index.isValid()) + return itemsWithinRubberBand; + + try + { + const Track& track = m_view->timelineModel()->track(index.data().toInt()); + itemsWithinRubberBand += track.itemIdsBetween(start, end); + } + catch (const QString& str) + { + ERROR_LOG(m_view->m_logger) << str; + } + catch (...) + { + } } - catch (...) {} - } - return itemsWithinRubberBand; + return itemsWithinRubberBand; } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.h old mode 100755 new mode 100644 index d16deb15d..493c34975 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_selection_handler.h @@ -1,48 +1,47 @@ #pragma once -#include "timeline_view.h" - #include "ltstimeline_export.h" +#include "timeline_view.h" #include - class QMouseEvent; class QKeyEvent; - namespace LtsTimeline { class TimelineView; - class LTSTIMELINE_EXPORT TimelineViewSelectHandler { - friend class TimelineView; + friend class TimelineView; -public: - explicit TimelineViewSelectHandler(TimelineView *view); - virtual ~TimelineViewSelectHandler(); + public: + explicit TimelineViewSelectHandler(TimelineView* view); + virtual ~TimelineViewSelectHandler(); - virtual void mouseDoubleClickEvent(QMouseEvent *e); - virtual void mouseMoveEvent(QMouseEvent *e); - virtual void mousePressEvent(QMouseEvent *e); - virtual void mouseReleaseEvent(QMouseEvent *e); - virtual void keyPressEvent(QKeyEvent *e); + virtual void mouseDoubleClickEvent(QMouseEvent* e); + virtual void mouseMoveEvent(QMouseEvent* e); + virtual void mousePressEvent(QMouseEvent* e); + virtual void mouseReleaseEvent(QMouseEvent* e); + virtual void keyPressEvent(QKeyEvent* e); - virtual bool isActive() const; - virtual bool isRubberBandActive() const { return m_isRubberBandActive; } + virtual bool isActive() const; -protected: - virtual QVector getItemsWithinRubberBand() const; + virtual bool isRubberBandActive() const + { + return m_isRubberBandActive; + } -protected: - TimelineView *m_view{nullptr}; - int m_selectedItemId{-1}; - QRect m_rubberBand; - bool m_isRubberBandActive{false}; + protected: + virtual QVector getItemsWithinRubberBand() const; + protected: + TimelineView* m_view{nullptr}; + int m_selectedItemId{-1}; + QRect m_rubberBand; + bool m_isRubberBandActive{false}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.cpp old mode 100755 new mode 100644 index 4c2098e47..c40de768a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.cpp @@ -1,107 +1,98 @@ -#include "timeline_view_resize_handler.h" -#include "timeline_view.h" -#include "timeline_header_view.h" #include "item.h" +#include "timeline_header_view.h" +#include "timeline_view.h" +#include "timeline_view_resize_handler.h" #include "track.h" #include - #include -#include #include - +#include namespace LtsTimeline { -TimelineViewTrackHandler::TimelineViewTrackHandler(TimelineView *view) - : m_view(view) -{ -} +TimelineViewTrackHandler::TimelineViewTrackHandler(TimelineView* view) : m_view(view) {} TimelineViewTrackHandler::~TimelineViewTrackHandler() { - m_view = nullptr; + m_view = nullptr; } - - - -void TimelineViewTrackHandler::mouseDoubleClickEvent(QMouseEvent *e) +void TimelineViewTrackHandler::mouseDoubleClickEvent(QMouseEvent* e) { - if (e->button() != Qt::LeftButton) - return; - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() != Section::eActuator) - return; - - emit m_view->trackActivated(index.data().toInt()); -} - -void TimelineViewTrackHandler::mousePressEvent(QMouseEvent *e) -{ - if (e->button() != Qt::LeftButton) - { - if (e->button() == Qt::RightButton) - emit m_view->customContextMenuRequested(e->pos()); - return; - } - - - const QModelIndex index = m_view->indexAt(e->pos()); - if (!index.isValid() || index.column() != Section::eActuator) - return; - - try - { - if(!m_view->timelineModel()->isEditable()) - return; - - const Track &track = m_view->timelineModel()->track(index.data(Qt::UserRole).toInt()); - QRect visRect = m_view->visualRect(index); - int buttonLength = visRect.height() / 2; - if (track.hasInsertButton()) - { - QRect rect = QRect(visRect.right() - buttonLength, visRect.top(), buttonLength, buttonLength); - if (rect.contains(e->pos())) - { - m_pressedInsertButtonIndex = index; - - m_view->timelineModel()->onInsertTrack(index); + if (e->button() != Qt::LeftButton) return; - } - } - if (track.hasRemoveButton()) + + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() != Section::eActuator) + return; + + emit m_view->trackActivated(index.data().toInt()); +} + +void TimelineViewTrackHandler::mousePressEvent(QMouseEvent* e) +{ + if (e->button() != Qt::LeftButton) { - QRect rect = QRect(visRect.right() - buttonLength, visRect.center().y(), buttonLength, buttonLength); - if (rect.contains(e->pos())) - { - m_pressedRemoveButtonIndex = index; + if (e->button() == Qt::RightButton) + emit m_view->customContextMenuRequested(e->pos()); + return; + } - auto msg = new LtsWidgets::LtsMessageDialogNew(m_view, {}, QApplication::translate("LtsTimeline", "Do you really want to remove this filter track and all of its contents?"), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel); + const QModelIndex index = m_view->indexAt(e->pos()); + if (!index.isValid() || index.column() != Section::eActuator) + return; - QObject::connect(msg, &LtsWidgets::LtsMessageDialogNew::yes, - m_view, [this, index]() + try + { + if (!m_view->timelineModel()->isEditable()) + return; + + const Track& track = m_view->timelineModel()->track(index.data(Qt::UserRole).toInt()); + QRect visRect = m_view->visualRect(index); + int buttonLength = visRect.height() / 2; + if (track.hasInsertButton()) { + QRect rect = QRect(visRect.right() - buttonLength, visRect.top(), buttonLength, buttonLength); + if (rect.contains(e->pos())) + { + m_pressedInsertButtonIndex = index; - m_view->timelineModel()->onRemoveTrack(index); - }); + m_view->timelineModel()->onInsertTrack(index); + return; + } + } + if (track.hasRemoveButton()) + { + QRect rect = QRect(visRect.right() - buttonLength, visRect.center().y(), buttonLength, buttonLength); + if (rect.contains(e->pos())) + { + m_pressedRemoveButtonIndex = index; - return; - } + auto msg = new LtsWidgets::LtsMessageDialogNew( + m_view, {}, + QApplication::translate("LtsTimeline", + "Do you really want to remove this filter track and all of its contents?"), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel); + + QObject::connect(msg, &LtsWidgets::LtsMessageDialogNew::yes, m_view, + [this, index]() { m_view->timelineModel()->onRemoveTrack(index); }); + + return; + } + } + } + catch (...) + { } - } - catch (...) {} } -void TimelineViewTrackHandler::mouseReleaseEvent(QMouseEvent *e) +void TimelineViewTrackHandler::mouseReleaseEvent(QMouseEvent* e) { - Q_UNUSED(e); - m_pressedInsertButtonIndex = {}; - m_pressedRemoveButtonIndex = {}; + Q_UNUSED(e); + m_pressedInsertButtonIndex = {}; + m_pressedRemoveButtonIndex = {}; } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.h old mode 100755 new mode 100644 index 467fcd4fc..d72ec2b9b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_view_track_handler.h @@ -2,9 +2,8 @@ #include "ltstimeline_export.h" -#include #include - +#include namespace LtsTimeline { @@ -12,27 +11,32 @@ namespace LtsTimeline class Track; class TimelineView; - class LTSTIMELINE_EXPORT TimelineViewTrackHandler { -public: - explicit TimelineViewTrackHandler(TimelineView *view); - virtual ~TimelineViewTrackHandler(); + public: + explicit TimelineViewTrackHandler(TimelineView* view); + virtual ~TimelineViewTrackHandler(); - virtual void mouseDoubleClickEvent(QMouseEvent *e); - virtual void mousePressEvent(QMouseEvent *e); - virtual void mouseReleaseEvent(QMouseEvent *e); + virtual void mouseDoubleClickEvent(QMouseEvent* e); + virtual void mousePressEvent(QMouseEvent* e); + virtual void mouseReleaseEvent(QMouseEvent* e); - bool isInsertButtonPressed(const QModelIndex &index) const { return index == m_pressedInsertButtonIndex; } - bool isRemoveButtonPressed(const QModelIndex &index) const { return index == m_pressedRemoveButtonIndex; } + bool isInsertButtonPressed(const QModelIndex& index) const + { + return index == m_pressedInsertButtonIndex; + } -protected: - TimelineView *m_view{nullptr}; + bool isRemoveButtonPressed(const QModelIndex& index) const + { + return index == m_pressedRemoveButtonIndex; + } - QModelIndex m_pressedInsertButtonIndex; - QModelIndex m_pressedRemoveButtonIndex; + protected: + TimelineView* m_view{nullptr}; + QModelIndex m_pressedInsertButtonIndex; + QModelIndex m_pressedRemoveButtonIndex; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.cpp old mode 100755 new mode 100644 index 5ee464163..7d78effb1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.cpp @@ -1,23 +1,21 @@ - #include "timeline_widget.h" -#include -#include "ui_timeline_widget.h" -#include "timeline_view.h" + +#include "item_delegate.h" #include "timeline_header_view.h" #include "timeline_model.h" -#include "item_delegate.h" +#include "timeline_view.h" +#include "ui_timeline_widget.h" #include - -#include +#include #include #include +#include #include -#include #include - +#include namespace LtsTimeline { @@ -27,377 +25,345 @@ TimelineWidget::TimelineWidget(QWidget *parent) , m_ui(new Ui::Timeline) .getNGLLogger("Timeline.Widget")) { - m_ui->setupUi(this); - m_ui->debugWidget->hide(); - m_ui->wPlaceholder->hide(); - m_ui->pbZoomIn->setProperty("const", true); - m_ui->pbZoomOut->setProperty("const", true); - m_ui->cbZoom->setProperty("const", true); + m_ui->setupUi(this); + m_ui->debugWidget->hide(); + m_ui->wPlaceholder->hide(); + m_ui->pbZoomIn->setProperty("const", true); + m_ui->pbZoomOut->setProperty("const", true); + m_ui->cbZoom->setProperty("const", true); - connect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), - this, &TimelineWidget::onZoomSelected); - m_ui->pbZoomIn->setIcon(QIcon(QStringLiteral("icon:bgv_zoom_in.svg"))); - connect(m_ui->pbZoomIn, &QPushButton::clicked, - this, &TimelineWidget::onZoomIn); - m_ui->pbZoomOut->setIcon(QIcon(QStringLiteral("icon:bgv_zoom_out.svg"))); - connect(m_ui->pbZoomOut, &QPushButton::clicked, - this, &TimelineWidget::onZoomOut); + connect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), this, &TimelineWidget::onZoomSelected); + m_ui->pbZoomIn->setIcon(QIcon(QStringLiteral("icon:bgv_zoom_in.svg"))); + connect(m_ui->pbZoomIn, &QPushButton::clicked, this, &TimelineWidget::onZoomIn); + m_ui->pbZoomOut->setIcon(QIcon(QStringLiteral("icon:bgv_zoom_out.svg"))); + connect(m_ui->pbZoomOut, &QPushButton::clicked, this, &TimelineWidget::onZoomOut); - connect(m_ui->view, &TimelineView::rangeChanged, this, [this](qint64 min, qint64 max) - { - m_ui->slider->setRange(min / 1000, (max - m_ui->view->zoomFactor()) / 1000); - onUpdateZoomButtons(); - }); - connect(m_ui->view, &TimelineView::currentTimeChanged, this, [this](qint64 time) - { - m_ui->slider->setValue(time / 1000); - }); + connect(m_ui->view, &TimelineView::rangeChanged, this, [this](qint64 min, qint64 max) { + m_ui->slider->setRange(min / 1000, (max - m_ui->view->zoomFactor()) / 1000); + onUpdateZoomButtons(); + }); + connect(m_ui->view, &TimelineView::currentTimeChanged, this, + [this](qint64 time) { m_ui->slider->setValue(time / 1000); }); - connect(m_ui->view, &TimelineView::zoomChanged, - this, &TimelineWidget::onZoomChanged); + connect(m_ui->view, &TimelineView::zoomChanged, this, &TimelineWidget::onZoomChanged); - connect(m_ui->view->header(), &TimelineHeaderView::sectionResized, - this, &TimelineWidget::onSectionResized); + connect(m_ui->view->header(), &TimelineHeaderView::sectionResized, this, &TimelineWidget::onSectionResized); - connect(m_ui->slider, &QScrollBar::valueChanged, - this, &TimelineWidget::onSliderValueChanged); + connect(m_ui->slider, &QScrollBar::valueChanged, this, &TimelineWidget::onSliderValueChanged); - onZoomChanged(m_ui->view->zoomFactor()); + onZoomChanged(m_ui->view->zoomFactor()); } TimelineWidget::~TimelineWidget() { - delete m_ui; + delete m_ui; } - - - -TimelineView *TimelineWidget::view() +TimelineView* TimelineWidget::view() { - return m_ui->view; + return m_ui->view; } - -TimelineHeaderView *TimelineWidget::header() +TimelineHeaderView* TimelineWidget::header() { - return m_ui->view->header(); + return m_ui->view->header(); } - -TimelineModel *TimelineWidget::timelineModel() +TimelineModel* TimelineWidget::timelineModel() { - return m_ui->view->timelineModel(); + return m_ui->view->timelineModel(); } - -void TimelineWidget::setModel(QAbstractItemModel *model) +void TimelineWidget::setModel(QAbstractItemModel* model) { - m_ui->view->setModel(model); + m_ui->view->setModel(model); } - -QScrollBar *TimelineWidget::slider() +QScrollBar* TimelineWidget::slider() { - return m_ui->slider; + return m_ui->slider; } - ZoomFactor TimelineWidget::zoomFactor() const { - return m_ui->view->zoomFactor(); + return m_ui->view->zoomFactor(); } void TimelineWidget::setZoomFactor(ZoomFactor factor) { - m_ui->view->setZoomFactor(factor); + m_ui->view->setZoomFactor(factor); } - ZoomFactor TimelineWidget::minimumZoomFactor() const { - return m_ui->view->minimumZoomFactor(); + return m_ui->view->minimumZoomFactor(); } void TimelineWidget::setMinimumZoomFactor(ZoomFactor factor) { - m_ui->view->setMinimumZoomFactor(factor); - populateZoomFactorComboBox(); + m_ui->view->setMinimumZoomFactor(factor); + populateZoomFactorComboBox(); } - ZoomFactor TimelineWidget::maximumZoomFactor() const { - return m_ui->view->maximumZoomFactor(); + return m_ui->view->maximumZoomFactor(); } void TimelineWidget::setMaximumZoomFactor(ZoomFactor factor) { - m_ui->view->setMaximumZoomFactor(factor); - populateZoomFactorComboBox(); + m_ui->view->setMaximumZoomFactor(factor); + populateZoomFactorComboBox(); } - qint64 TimelineWidget::startTime() const { - return m_ui->view->startTime(); + return m_ui->view->startTime(); } void TimelineWidget::setStartTime(qint64 time) { - m_ui->view->setStartTime(time); + m_ui->view->setStartTime(time); } - qint64 TimelineWidget::currentTime() const { - return m_ui->view->currentTime(); + return m_ui->view->currentTime(); } void TimelineWidget::setCurrentTime(qint64 time) { - m_ui->view->setCurrentTime(time); + m_ui->view->setCurrentTime(time); } - qint64 TimelineWidget::endTime() const { - return m_ui->view->endTime(); + return m_ui->view->endTime(); } void TimelineWidget::setEndTime(qint64 time) { - m_ui->view->setEndTime(time); + m_ui->view->setEndTime(time); } - int TimelineWidget::duration() const { - return m_ui->view->duration(); + return m_ui->view->duration(); } void TimelineWidget::setDuration(int duration) { - m_ui->view->setDuration(duration); + m_ui->view->setDuration(duration); } - bool TimelineWidget::isCursorTextVisible() const { - return m_ui->view->isCursorTextVisible(); + return m_ui->view->isCursorTextVisible(); } void TimelineWidget::setCursorTextVisible(bool visible) { - m_ui->view->setCursorTextVisible(visible); + m_ui->view->setCursorTextVisible(visible); } -void TimelineWidget::setCursorText(const QString &text) +void TimelineWidget::setCursorText(const QString& text) { - m_ui->view->setCursorText(text); + m_ui->view->setCursorText(text); } - bool TimelineWidget::isSnapEnabled() const { - return m_ui->view->timelineModel()->isSnapEnabled(); + return m_ui->view->timelineModel()->isSnapEnabled(); } void TimelineWidget::setSnapEnabled(bool enabled) { - m_ui->view->timelineModel()->setSnapEnabled(enabled); + m_ui->view->timelineModel()->setSnapEnabled(enabled); } void TimelineWidget::enableSnap() { - m_ui->view->timelineModel()->setSnapEnabled(true); + m_ui->view->timelineModel()->setSnapEnabled(true); } void TimelineWidget::disableSnap() { - m_ui->view->timelineModel()->setSnapEnabled(false); + m_ui->view->timelineModel()->setSnapEnabled(false); } void TimelineWidget::triggerSnap() { - m_ui->view->timelineModel()->setSnapEnabled(!m_ui->view->timelineModel()->isSnapEnabled()); - if (m_ui->debugWidget->isVisible()) - m_ui->pbDebugTriggerSnap->setText(m_ui->view->timelineModel()->isSnapEnabled() ? QStringLiteral("Disable Snap") : - QStringLiteral("Enable Snap")); + m_ui->view->timelineModel()->setSnapEnabled(!m_ui->view->timelineModel()->isSnapEnabled()); + if (m_ui->debugWidget->isVisible()) + m_ui->pbDebugTriggerSnap->setText(m_ui->view->timelineModel()->isSnapEnabled() ? QStringLiteral("Disable Snap") + : QStringLiteral("Enable Snap")); } - void TimelineWidget::setZoomInIcon(QIcon icon) { - m_ui->pbZoomIn->setIcon(icon); + m_ui->pbZoomIn->setIcon(icon); } void TimelineWidget::setZoomOutIcon(QIcon icon) { - m_ui->pbZoomOut->setIcon(icon); + m_ui->pbZoomOut->setIcon(icon); } - -QWidget *TimelineWidget::placeholder() +QWidget* TimelineWidget::placeholder() { - if (m_ui->wPlaceholder->layout()->count() == 0) - return nullptr; - return m_ui->wPlaceholder->layout()->itemAt(0)->widget(); + if (m_ui->wPlaceholder->layout()->count() == 0) + return nullptr; + return m_ui->wPlaceholder->layout()->itemAt(0)->widget(); } -void TimelineWidget::setPlaceholder(QWidget *widget) +void TimelineWidget::setPlaceholder(QWidget* widget) { - QWidget *ptr = placeholder(); - if (ptr) - { - if (ptr == widget) - return; - m_ui->wPlaceholder->layout()->removeWidget(ptr); - delete ptr; - } - m_ui->wPlaceholder->layout()->addWidget(widget); + QWidget* ptr = placeholder(); + if (ptr) + { + if (ptr == widget) + return; + m_ui->wPlaceholder->layout()->removeWidget(ptr); + delete ptr; + } + m_ui->wPlaceholder->layout()->addWidget(widget); } - void TimelineWidget::showDebugWidget() { - m_ui->debugWidget->show(); + m_ui->debugWidget->show(); - m_ui->sbDebugSnapStep->setValue(m_ui->view->timelineModel()->snapStep()); - m_ui->sbDebugSnapTol->setValue(m_ui->view->timelineModel()->snapTolerance()); - m_ui->pbDebugTriggerSnap->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Snap") : - QStringLiteral("Enable Snap")); - m_ui->pbDebugTriggerIndicator->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Indicator") : - QStringLiteral("Enable Indicator")); - m_ui->pbDebugTriggerHover->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Hover") : - QStringLiteral("Enable Hover")); + m_ui->sbDebugSnapStep->setValue(m_ui->view->timelineModel()->snapStep()); + m_ui->sbDebugSnapTol->setValue(m_ui->view->timelineModel()->snapTolerance()); + m_ui->pbDebugTriggerSnap->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Snap") + : QStringLiteral("Enable Snap")); + m_ui->pbDebugTriggerIndicator->setText(m_ui->view->header()->isIndicatorVisible() + ? QStringLiteral("Disable Indicator") + : QStringLiteral("Enable Indicator")); + m_ui->pbDebugTriggerHover->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Hover") + : QStringLiteral("Enable Hover")); - connect(m_ui->view, &TimelineView::currentTimeChanged, this, &TimelineWidget::onUpdateDebugInfo); - connect(m_ui->view, &TimelineView::rangeChanged, this, &TimelineWidget::onUpdateDebugInfo); - connect(m_ui->view, &TimelineView::selectedItemsChanged, this, &TimelineWidget::onUpdateDebugInfo); - connect(m_ui->view, &TimelineView::zoomChanged, this, &TimelineWidget::onUpdateDebugInfo); - connect(m_ui->pbDebugTriggerSnap, &QPushButton::clicked, this, &TimelineWidget::triggerSnap); - connect(m_ui->sbDebugSnapStep, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), &TimelineModel::setSnapStep); - connect(m_ui->sbDebugSnapTol, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), &TimelineModel::setSnapTolerance); - connect(m_ui->pbDebugTriggerIndicator, &QPushButton::clicked, this, [this]() - { - m_ui->view->header()->setIndicatorVisible(!m_ui->view->header()->isIndicatorVisible()); - m_ui->pbDebugTriggerIndicator->setText(m_ui->view->header()->isIndicatorVisible() ? QStringLiteral("Disable Indicator") : - QStringLiteral("Enable Indicator")); - }); - connect(m_ui->pbDebugTriggerHover, &QPushButton::clicked, this, [this]() - { - m_ui->view->header()->setHoverVisible(!m_ui->view->header()->isHoverVisible()); - m_ui->pbDebugTriggerHover->setText(m_ui->view->header()->isHoverVisible() ? QStringLiteral("Disable Hover") : - QStringLiteral("Enable Hover")); - }); + connect(m_ui->view, &TimelineView::currentTimeChanged, this, &TimelineWidget::onUpdateDebugInfo); + connect(m_ui->view, &TimelineView::rangeChanged, this, &TimelineWidget::onUpdateDebugInfo); + connect(m_ui->view, &TimelineView::selectedItemsChanged, this, &TimelineWidget::onUpdateDebugInfo); + connect(m_ui->view, &TimelineView::zoomChanged, this, &TimelineWidget::onUpdateDebugInfo); + connect(m_ui->pbDebugTriggerSnap, &QPushButton::clicked, this, &TimelineWidget::triggerSnap); + connect(m_ui->sbDebugSnapStep, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), + &TimelineModel::setSnapStep); + connect(m_ui->sbDebugSnapTol, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), + &TimelineModel::setSnapTolerance); + connect(m_ui->pbDebugTriggerIndicator, &QPushButton::clicked, this, [this]() { + m_ui->view->header()->setIndicatorVisible(!m_ui->view->header()->isIndicatorVisible()); + m_ui->pbDebugTriggerIndicator->setText(m_ui->view->header()->isIndicatorVisible() + ? QStringLiteral("Disable Indicator") + : QStringLiteral("Enable Indicator")); + }); + connect(m_ui->pbDebugTriggerHover, &QPushButton::clicked, this, [this]() { + m_ui->view->header()->setHoverVisible(!m_ui->view->header()->isHoverVisible()); + m_ui->pbDebugTriggerHover->setText(m_ui->view->header()->isHoverVisible() ? QStringLiteral("Disable Hover") + : QStringLiteral("Enable Hover")); + }); - onUpdateDebugInfo(); + onUpdateDebugInfo(); } void TimelineWidget::hideDebugWidget() { - m_ui->debugWidget->hide(); - disconnect(m_ui->view, &TimelineView::currentTimeChanged, this, &TimelineWidget::onUpdateDebugInfo); - disconnect(m_ui->view, &TimelineView::rangeChanged, this, &TimelineWidget::onUpdateDebugInfo); - disconnect(m_ui->view, &TimelineView::selectedItemsChanged, this, &TimelineWidget::onUpdateDebugInfo); - disconnect(m_ui->view, &TimelineView::zoomChanged, this, &TimelineWidget::onUpdateDebugInfo); - disconnect(m_ui->pbDebugTriggerSnap, &QPushButton::clicked, this, &TimelineWidget::triggerSnap); - disconnect(m_ui->sbDebugSnapStep, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), &TimelineModel::setSnapStep); - disconnect(m_ui->sbDebugSnapTol, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), &TimelineModel::setSnapTolerance); - disconnect(m_ui->pbDebugTriggerIndicator); - disconnect(m_ui->pbDebugTriggerHover); + m_ui->debugWidget->hide(); + disconnect(m_ui->view, &TimelineView::currentTimeChanged, this, &TimelineWidget::onUpdateDebugInfo); + disconnect(m_ui->view, &TimelineView::rangeChanged, this, &TimelineWidget::onUpdateDebugInfo); + disconnect(m_ui->view, &TimelineView::selectedItemsChanged, this, &TimelineWidget::onUpdateDebugInfo); + disconnect(m_ui->view, &TimelineView::zoomChanged, this, &TimelineWidget::onUpdateDebugInfo); + disconnect(m_ui->pbDebugTriggerSnap, &QPushButton::clicked, this, &TimelineWidget::triggerSnap); + disconnect(m_ui->sbDebugSnapStep, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), + &TimelineModel::setSnapStep); + disconnect(m_ui->sbDebugSnapTol, qOverload(&QSpinBox::valueChanged), m_ui->view->timelineModel(), + &TimelineModel::setSnapTolerance); + disconnect(m_ui->pbDebugTriggerIndicator); + disconnect(m_ui->pbDebugTriggerHover); } - - - void TimelineWidget::populateZoomFactorComboBox() { - disconnect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), - this, &TimelineWidget::onZoomSelected); - m_ui->cbZoom->clear(); - QVector availableZooms = Zoom::availableZoomFactors(m_ui->view->minimumZoomFactor(), m_ui->view->upperZoomFactor()); - for (ZoomFactor factor : std::as_const(availableZooms)) - { - m_ui->cbZoom->addItem(Zoom::toString(factor), QVariant(factor)); - if (factor == zoomFactor()) - m_ui->cbZoom->setCurrentIndex(m_ui->cbZoom->findData(static_cast(zoomFactor()))); - } - connect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), - this, &TimelineWidget::onZoomSelected); + disconnect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), this, &TimelineWidget::onZoomSelected); + m_ui->cbZoom->clear(); + QVector availableZooms = + Zoom::availableZoomFactors(m_ui->view->minimumZoomFactor(), m_ui->view->upperZoomFactor()); + for (ZoomFactor factor : std::as_const(availableZooms)) + { + m_ui->cbZoom->addItem(Zoom::toString(factor), QVariant(factor)); + if (factor == zoomFactor()) + m_ui->cbZoom->setCurrentIndex(m_ui->cbZoom->findData(static_cast(zoomFactor()))); + } + connect(m_ui->cbZoom, qOverload(&QComboBox::currentIndexChanged), this, &TimelineWidget::onZoomSelected); } - - - void TimelineWidget::onSectionResized(int logicalIndex, int oldSize, int newSize) { - Q_UNUSED(oldSize); - if (logicalIndex == Section::eItems) - { - int width = m_ui->view->verticalScrollBar()->width(); - m_ui->slider->setMinimumHeight(width); - m_ui->slider->setMaximumHeight(width); - m_ui->slider->setMaximumWidth(newSize); - m_ui->slider->setMinimumWidth(newSize); - } + Q_UNUSED(oldSize); + if (logicalIndex == Section::eItems) + { + int width = m_ui->view->verticalScrollBar()->width(); + m_ui->slider->setMinimumHeight(width); + m_ui->slider->setMaximumHeight(width); + m_ui->slider->setMaximumWidth(newSize); + m_ui->slider->setMinimumWidth(newSize); + } } void TimelineWidget::onSliderValueChanged(int value) { - setCurrentTime(qint64(value) * 1000); + setCurrentTime(qint64(value) * 1000); } void TimelineWidget::onUpdateZoomButtons() { - m_ui->pbZoomIn->setEnabled(zoomFactor() > minimumZoomFactor()); - m_ui->pbZoomOut->setEnabled(zoomFactor() < m_ui->view->upperZoomFactor()); - populateZoomFactorComboBox(); + m_ui->pbZoomIn->setEnabled(zoomFactor() > minimumZoomFactor()); + m_ui->pbZoomOut->setEnabled(zoomFactor() < m_ui->view->upperZoomFactor()); + populateZoomFactorComboBox(); } void TimelineWidget::onZoomChanged(ZoomFactor factor) { - m_ui->slider->setMaximum((m_ui->view->endTime() - m_ui->view->zoomFactor()) / 1000); - m_ui->slider->setPageStep(factor / 1000); - m_ui->slider->setSingleStep(Zoom::minorInterval(factor)); - onUpdateZoomButtons(); - if (static_cast(m_ui->cbZoom->currentData().toInt()) != factor) - m_ui->cbZoom->setCurrentIndex(m_ui->cbZoom->findData(QVariant(factor))); + m_ui->slider->setMaximum((m_ui->view->endTime() - m_ui->view->zoomFactor()) / 1000); + m_ui->slider->setPageStep(factor / 1000); + m_ui->slider->setSingleStep(Zoom::minorInterval(factor)); + onUpdateZoomButtons(); + if (static_cast(m_ui->cbZoom->currentData().toInt()) != factor) + m_ui->cbZoom->setCurrentIndex(m_ui->cbZoom->findData(QVariant(factor))); } void TimelineWidget::onZoomSelected() { - ZoomFactor factor = static_cast(m_ui->cbZoom->currentData().toInt()); - if (factor != zoomFactor()) - setZoomFactor(factor); + ZoomFactor factor = static_cast(m_ui->cbZoom->currentData().toInt()); + if (factor != zoomFactor()) + setZoomFactor(factor); } void TimelineWidget::onZoomIn() { - setZoomFactor(Zoom::decrement(zoomFactor())); + setZoomFactor(Zoom::decrement(zoomFactor())); } void TimelineWidget::onZoomOut() { - setZoomFactor(Zoom::increment(zoomFactor())); + setZoomFactor(Zoom::increment(zoomFactor())); } - void TimelineWidget::onUpdateDebugInfo() { - m_ui->lblDebugStart->setText(DateTime::toString(startTime(), DateTimeFormat::DTG)); - m_ui->lblDebugEnd->setText(DateTime::toString(endTime(), DateTimeFormat::DTG)); - m_ui->lblDebugDuration->setText(QString::number(duration() / 1000) + QStringLiteral("s")); - m_ui->lblDebugCurrent->setText(DateTime::toString(currentTime(), DateTimeFormat::DTG)); - m_ui->lblDebugSlider->setText(DateTime::toString(qint64(m_ui->slider->value()) * 1000, DateTimeFormat::DTG)); - m_ui->lblDebugZoom->setText(Zoom::toString(m_ui->view->zoomFactor())); - QString selection; - for (int itemId : std::as_const(m_ui->view->selectedItemIds())) - selection += QString::number(itemId) + QStringLiteral(", "); - if (selection.size() > 1) - selection.chop(2); - m_ui->lblDebugSelection->setText(selection); + m_ui->lblDebugStart->setText(DateTime::toString(startTime(), DateTimeFormat::DTG)); + m_ui->lblDebugEnd->setText(DateTime::toString(endTime(), DateTimeFormat::DTG)); + m_ui->lblDebugDuration->setText(QString::number(duration() / 1000) + QStringLiteral("s")); + m_ui->lblDebugCurrent->setText(DateTime::toString(currentTime(), DateTimeFormat::DTG)); + m_ui->lblDebugSlider->setText(DateTime::toString(qint64(m_ui->slider->value()) * 1000, DateTimeFormat::DTG)); + m_ui->lblDebugZoom->setText(Zoom::toString(m_ui->view->zoomFactor())); + QString selection; + for (int itemId : std::as_const(m_ui->view->selectedItemIds())) + selection += QString::number(itemId) + QStringLiteral(", "); + if (selection.size() > 1) + selection.chop(2); + m_ui->lblDebugSelection->setText(selection); } -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.h old mode 100755 new mode 100644 index 514c87d55..d42b64736 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/timeline_widget.h @@ -1,27 +1,21 @@ - #pragma once -#include - +#include "ltstimeline_export.h" #include "timeline_utils.h" -#include "ltstimeline_export.h" #include - +#include #include - class QScrollBar; class QAbstractItemModel; - namespace Ui { class Timeline; } - namespace LtsTimeline { @@ -29,87 +23,85 @@ class TimelineView; class TimelineHeaderView; class TimelineModel; - class LTSTIMELINE_EXPORT TimelineWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TimelineWidget(QWidget *parent = nullptr); - ~TimelineWidget(); + public: + explicit TimelineWidget(QWidget* parent = nullptr); + ~TimelineWidget(); - TimelineView *view(); + TimelineView* view(); - TimelineHeaderView *header(); + TimelineHeaderView* header(); - TimelineModel *timelineModel(); - void setModel(QAbstractItemModel *model); + TimelineModel* timelineModel(); + void setModel(QAbstractItemModel* model); - QScrollBar *slider(); + QScrollBar* slider(); - ZoomFactor zoomFactor() const; - void setZoomFactor(ZoomFactor factor); + ZoomFactor zoomFactor() const; + void setZoomFactor(ZoomFactor factor); - ZoomFactor minimumZoomFactor() const; - void setMinimumZoomFactor(ZoomFactor factor); + ZoomFactor minimumZoomFactor() const; + void setMinimumZoomFactor(ZoomFactor factor); - ZoomFactor maximumZoomFactor() const; - void setMaximumZoomFactor(ZoomFactor factor); + ZoomFactor maximumZoomFactor() const; + void setMaximumZoomFactor(ZoomFactor factor); - qint64 startTime() const; - void setStartTime(qint64 time); + qint64 startTime() const; + void setStartTime(qint64 time); - qint64 currentTime() const; - void setCurrentTime(qint64 time); + qint64 currentTime() const; + void setCurrentTime(qint64 time); - qint64 endTime() const; - void setEndTime(qint64 time); + qint64 endTime() const; + void setEndTime(qint64 time); - int duration() const; - void setDuration(int duration); + int duration() const; + void setDuration(int duration); - bool isCursorTextVisible() const; - void setCursorTextVisible(bool visible); - void setCursorText(const QString &text); - void setCursorText(const QStringList &texts); + bool isCursorTextVisible() const; + void setCursorTextVisible(bool visible); + void setCursorText(const QString& text); + void setCursorText(const QStringList& texts); - bool isSnapEnabled() const; - void setSnapEnabled(bool enabled); - void enableSnap(); - void disableSnap(); - void triggerSnap(); + bool isSnapEnabled() const; + void setSnapEnabled(bool enabled); + void enableSnap(); + void disableSnap(); + void triggerSnap(); - void setZoomInIcon(QIcon icon); - void setZoomOutIcon(QIcon icon); + void setZoomInIcon(QIcon icon); + void setZoomOutIcon(QIcon icon); - QWidget *placeholder(); - void setPlaceholder(QWidget *widget); + QWidget* placeholder(); + void setPlaceholder(QWidget* widget); - void showDebugWidget(); - void hideDebugWidget(); + void showDebugWidget(); + void hideDebugWidget(); -private: + private: + NGL::INGLLogger& m_logger; + void populateZoomFactorComboBox(); -NGL::INGLLogger &m_logger; - void populateZoomFactorComboBox(); + public: + void onUpdateZoomButtons(); -public: - void onUpdateZoomButtons(); + private slots: + void onSectionResized(int logicalIndex, int oldSize, int newSize); + void onSliderValueChanged(int value); + void onZoomChanged(ZoomFactor factor); + void onZoomSelected(); + void onZoomIn(); + void onZoomOut(); -private slots: - void onSectionResized(int logicalIndex, int oldSize, int newSize); - void onSliderValueChanged(int value); - void onZoomChanged(ZoomFactor factor); - void onZoomSelected(); - void onZoomIn(); - void onZoomOut(); + void onUpdateDebugInfo(); - void onUpdateDebugInfo(); + signals: -signals: - -private: - Ui::Timeline *m_ui{nullptr}; + private: + Ui::Timeline* m_ui{nullptr}; }; -} +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.cpp old mode 100755 new mode 100644 index 59f845ff3..da29b6b71 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.cpp @@ -1,854 +1,623 @@ - #include "track.h" + #include namespace LtsTimeline { -const Track &Track::track(int id) const noexcept(false) +const Track& Track::track(int id) const noexcept(false) { - - auto const it = std::find_if(m_childrenTracks.cbegin(), m_childrenTracks.cend(), - [id](const TrackPtr &trackPtr) - { - return (trackPtr.get()->id() == id); - }); - if (it != m_childrenTracks.cend()) - return **it; + auto const it = std::find_if(m_childrenTracks.cbegin(), m_childrenTracks.cend(), + [id](const TrackPtr& trackPtr) { return (trackPtr.get()->id() == id); }); - - for (const TrackPtr &track : std::as_const(m_childrenTracks)) - { - try + if (it != m_childrenTracks.cend()) + return **it; + + for (const TrackPtr& track : std::as_const(m_childrenTracks)) { - return track->track(id); + try + { + return track->track(id); + } + catch (...) + { + } } - catch(...) - { - - } - } - - throw QStringLiteral("lookup failed!");; + throw QStringLiteral("lookup failed!"); + ; } - bool Track::hasTrack(int id, bool recursive) const { - if (std::find_if(m_childrenTracks.cbegin(), m_childrenTracks.cend(), - [id](const TrackPtr &trackPtr) - { - return (trackPtr.get()->id() == id); - }) != m_childrenTracks.cend()) - return true; + if (std::find_if(m_childrenTracks.cbegin(), m_childrenTracks.cend(), [id](const TrackPtr& trackPtr) { + return (trackPtr.get()->id() == id); + }) != m_childrenTracks.cend()) + return true; + + if (!recursive) + return false; + + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + { + if (trackPtr->hasTrack(id, true)) + return true; + } - if (!recursive) return false; - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - { - if (trackPtr->hasTrack(id, true)) - return true; - } - - return false; } - - - - - - - - - - - - - - - - - - - - - - - - -void Track::addCopyItemIds(const QSet &ids) +void Track::addCopyItemIds(const QSet& ids) { - m_copyItemIds += ids; + m_copyItemIds += ids; } - void Track::addCopyItemId(int id) { - m_copyItemIds += id; + m_copyItemIds += id; } - -const Track &Track::parentOf(int id) const noexcept(false) +const Track& Track::parentOf(int id) const noexcept(false) { - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - { - if (trackPtr->hasTrack(id)) - return *trackPtr; + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + { + if (trackPtr->hasTrack(id)) + return *trackPtr; - if (trackPtr->hasTrack(id, true)) - return trackPtr->parentOf(id); - } + if (trackPtr->hasTrack(id, true)) + return trackPtr->parentOf(id); + } - throw("not found"); + throw("not found"); } - -bool Track::isItemBetween(const Item &item, qint64 start, qint64 end, bool strict, bool complete, qint64 minimumDuration) +bool Track::isItemBetween(const Item& item, qint64 start, qint64 end, bool strict, bool complete, + qint64 minimumDuration) { - if (end - start == -1) - { + if (end - start == -1) + { + if (item.duration() == -1) + { + if (!complete) + return true; + + return strict ? item.startTime() > start : item.startTime() >= start; + } + + if (strict) + { + return (complete && item.startTime() > start) || (!complete && item.startTime() + item.duration() > start); + } + else + { + return (complete && item.startTime() >= start) || + (!complete && item.startTime() + item.duration() >= start); + } + } + if (item.duration() == -1) { - if (!complete) - return true; + if (complete) + return false; - return strict ? item.startTime() > start : item.startTime() >= start; + return strict ? item.startTime() < end : item.startTime() <= end; } + Q_ASSERT(end + 1 > start); + qint64 itemStart = item.startTime(), + itemEnd = item.startTime() + (std::max((qint64)item.duration(), minimumDuration)); + if (strict) - { - return (complete && item.startTime() > start) || - (!complete && item.startTime() + item.duration() > start); - } + return ((complete && (itemStart > start && itemEnd < end)) || + (!complete && (itemEnd > start && itemStart < end))); else - { - return (complete && item.startTime() >= start) || - (!complete && item.startTime() + item.duration() >= start); - } - } - - if (item.duration() == -1) - { - if (complete) - return false; - - return strict ? item.startTime() < end : item.startTime() <= end; - } - - Q_ASSERT(end+1 > start); - qint64 itemStart = item.startTime(), itemEnd = item.startTime() + (std::max((qint64)item.duration(), minimumDuration)); - - if (strict) - return ((complete && (itemStart > start && itemEnd < end)) || - (!complete && (itemEnd > start && itemStart < end))); - else - return ((complete && (itemStart >= start && itemEnd <= end)) || - (!complete && (itemEnd >= start && itemStart <= end))); + return ((complete && (itemStart >= start && itemEnd <= end)) || + (!complete && (itemEnd >= start && itemStart <= end))); } - void Track::removeCopyItem(int itemId) noexcept(false) { - m_copyItemIds.remove(itemId); + m_copyItemIds.remove(itemId); - for (TrackPtr &t : m_childrenTracks) - { - t->removeCopyItem(itemId); - } -} - - -const QVector Track::copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const -{ - auto itemPtrRefs = _copyItems(); - - - if (recursive) - { - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) + for (TrackPtr& t : m_childrenTracks) { - auto itemPtrRefs2 = trackPtr->_copyItems(); - itemPtrRefs.insert(itemPtrRefs.end(), itemPtrRefs2.begin(), itemPtrRefs2.end()); + t->removeCopyItem(itemId); } - } - - itemPtrRefs.erase(std::remove_if(itemPtrRefs.begin(), itemPtrRefs.end(), - [this, start, end, strict, complete](const ItemPtr &itemPtr) - { - return !isItemBetween(*itemPtr, start, end, strict, complete); - }), itemPtrRefs.end()); - - if (sorted) - { - sort(itemPtrRefs); - } - - - - return transformItemPtrsToIds(itemPtrRefs); } - -const QVector Track::itemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, bool sorted, qint64 minimumDuration) const +const QVector Track::copyItemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, + bool sorted, qint64 minimumDuration) const { - if (sorted) - { - auto itemPtrRefs = _items(recursive); - itemPtrRefs.erase(std::remove_if(itemPtrRefs.begin(), itemPtrRefs.end(), - [this, start, end, strict, complete, minimumDuration](const ItemPtr &itemPtr) - { - return !isItemBetween(*itemPtr, start, end, strict, complete, minimumDuration); - }), itemPtrRefs.end()); + auto itemPtrRefs = _copyItems(); - sort(itemPtrRefs); + if (recursive) + { + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + { + auto itemPtrRefs2 = trackPtr->_copyItems(); + itemPtrRefs.insert(itemPtrRefs.end(), itemPtrRefs2.begin(), itemPtrRefs2.end()); + } + } + + itemPtrRefs.erase(std::remove_if(itemPtrRefs.begin(), itemPtrRefs.end(), + [this, start, end, strict, complete](const ItemPtr& itemPtr) { + return !isItemBetween(*itemPtr, start, end, strict, complete); + }), + itemPtrRefs.end()); + + if (sorted) + { + sort(itemPtrRefs); + } return transformItemPtrsToIds(itemPtrRefs); - } - - - - QVector itemIds; - itemIds.reserve(m_items.size()); - - for (const ItemPtr &itemPtr : std::as_const(m_items)) - { - const Item &item = *itemPtr; - if (isItemBetween(item, start, end, strict, complete, minimumDuration)) - itemIds += item.id(); - } - - if (!recursive) - { - itemIds.squeeze(); - return itemIds; - } - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - itemIds += trackPtr->itemIdsBetween(start, end, strict, complete, true, minimumDuration); - - return itemIds; } - -bool Track::isItemsBetween(qint64 start, qint64 end, const QVector &ignoreIds, bool strict, bool complete, bool recursive, qint64 minimumDuration) const +const QVector Track::itemIdsBetween(qint64 start, qint64 end, bool strict, bool complete, bool recursive, + bool sorted, qint64 minimumDuration) const { - for (const ItemPtr &itemPtr : std::as_const(m_items)) - { - const Item &i = *itemPtr; - if (!ignoreIds.contains(i.id())) - if (isItemBetween(i, start, end, strict, complete, minimumDuration)) - return true; - } + if (sorted) + { + auto itemPtrRefs = _items(recursive); + itemPtrRefs.erase(std::remove_if(itemPtrRefs.begin(), itemPtrRefs.end(), + [this, start, end, strict, complete, minimumDuration](const ItemPtr& itemPtr) { + return !isItemBetween(*itemPtr, start, end, strict, complete, + minimumDuration); + }), + itemPtrRefs.end()); - - for (const int itemId : std::as_const(m_copyItemIds)) - { - const Item &i = item(itemId); - if (!ignoreIds.contains(i.id())) - if (isItemBetween(i, start, end, strict, complete, minimumDuration)) - return true; - } + sort(itemPtrRefs); + return transformItemPtrsToIds(itemPtrRefs); + } + + QVector itemIds; + itemIds.reserve(m_items.size()); + + for (const ItemPtr& itemPtr : std::as_const(m_items)) + { + const Item& item = *itemPtr; + if (isItemBetween(item, start, end, strict, complete, minimumDuration)) + itemIds += item.id(); + } + + if (!recursive) + { + itemIds.squeeze(); + return itemIds; + } + + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + itemIds += trackPtr->itemIdsBetween(start, end, strict, complete, true, minimumDuration); + + return itemIds; +} + +bool Track::isItemsBetween(qint64 start, qint64 end, const QVector& ignoreIds, bool strict, bool complete, + bool recursive, qint64 minimumDuration) const +{ + for (const ItemPtr& itemPtr : std::as_const(m_items)) + { + const Item& i = *itemPtr; + if (!ignoreIds.contains(i.id())) + if (isItemBetween(i, start, end, strict, complete, minimumDuration)) + return true; + } + + for (const int itemId : std::as_const(m_copyItemIds)) + { + const Item& i = item(itemId); + if (!ignoreIds.contains(i.id())) + if (isItemBetween(i, start, end, strict, complete, minimumDuration)) + return true; + } + + if (!recursive) + return false; + + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + if (trackPtr->isItemsBetween(start, end, ignoreIds, strict, complete, true, minimumDuration)) + return true; - if (!recursive) return false; - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - if (trackPtr->isItemsBetween(start, end, ignoreIds, strict, complete, true, minimumDuration)) - return true; - - return false; } - -bool Track::isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict, bool complete, bool recursive, qint64 minimumDuration) const +bool Track::isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict, bool complete, bool recursive, + qint64 minimumDuration) const { - return isItemsBetween(start, end, QVector({ ignoreId }), strict, complete, recursive, minimumDuration); + return isItemsBetween(start, end, QVector({ignoreId}), strict, complete, recursive, minimumDuration); } - -ItemPtrRefs Track::_items(bool recursive) const +ItemPtrRefs Track::_items(bool recursive) const { - - ItemPtrRefs x(m_items.cbegin(), m_items.cend()); - if (!m_copyItemIds.isEmpty()) - x.reserve(x.size() + m_copyItemIds.count()); + ItemPtrRefs x(m_items.cbegin(), m_items.cend()); - - for (const int itemId : std::as_const(m_copyItemIds)) - { - try + if (!m_copyItemIds.isEmpty()) + x.reserve(x.size() + m_copyItemIds.count()); + + for (const int itemId : std::as_const(m_copyItemIds)) { - x.push_back(std::cref(_item(itemId))); + try + { + x.push_back(std::cref(_item(itemId))); + } + catch (const QString& msg) + { + fprintf(stderr, "cannot add item ptr ref from copy item with copy item id %d: %s\n", itemId, + msg.toStdString().c_str()); + } + } + + if (!recursive) + return x; + + for (const TrackPtr& t : std::as_const(m_childrenTracks)) + { + const ItemPtrRefs x2(t->_items(true)); + x.insert(x.end(), x2.begin(), x2.end()); } - catch (const QString &msg) - { - fprintf(stderr, "cannot add item ptr ref from copy item with copy item id %d: %s\n", itemId, msg.toStdString().c_str()); - } - } - if (!recursive) return x; - - - for (const TrackPtr &t : std::as_const(m_childrenTracks)) - { - const ItemPtrRefs x2(t->_items(true)); - x.insert(x.end(), x2.begin(), x2.end()); - - } - - - - return x; } - -ItemPtrRefs Track::_copyItems() const +ItemPtrRefs Track::_copyItems() const { - - ItemPtrRefs x; - for (int id : std::as_const(m_copyItemIds)) - { - try + ItemPtrRefs x; + + for (int id : std::as_const(m_copyItemIds)) { - x.push_back(_item(id)); + try + { + x.push_back(_item(id)); + } + catch (...) + { + fprintf(stderr, "Track::_copyItems: cannot find item for item id %d\n", id); + continue; + } } - catch(...) - { - fprintf(stderr, "Track::_copyItems: cannot find item for item id %d\n", id); - continue; - } - } - return x; -} - - -ItemPtrNCVRefs Track::_itemsNCV(bool recursive) -{ - - ItemPtrNCVRefs x(m_items.begin(), m_items.end()); - - if (!recursive) return x; - - - for (TrackPtr &t : m_childrenTracks) - { - ItemPtrNCVRefs x2(t->_itemsNCV(true)); - x.insert(x.end(), x2.begin(), x2.end()); - - } - - return x; } - - -const QVector Track::_itemIds(bool recursive) const +ItemPtrNCVRefs Track::_itemsNCV(bool recursive) { - QVector itemIds(transformItemPtrsToIds(m_items)); - if (!recursive) + ItemPtrNCVRefs x(m_items.begin(), m_items.end()); + + if (!recursive) + return x; + + for (TrackPtr& t : m_childrenTracks) + { + ItemPtrNCVRefs x2(t->_itemsNCV(true)); + x.insert(x.end(), x2.begin(), x2.end()); + } + + return x; +} + +const QVector Track::_itemIds(bool recursive) const +{ + QVector itemIds(transformItemPtrsToIds(m_items)); + + if (!recursive) + return itemIds; + + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + itemIds += trackPtr->_itemIds(true); + return itemIds; - - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - itemIds += trackPtr->_itemIds(true); - - return itemIds; } - ItemPtrRef Track::_item(int id) const noexcept(false) { - - auto const it = std::find_if(m_items.cbegin(), m_items.cend(), - [id](const ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.cend()) - return *it; + auto const it = std::find_if(m_items.cbegin(), m_items.cend(), + [id](const ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - - for (const TrackPtr &track : std::as_const(m_childrenTracks)) - { - try + if (it != m_items.cend()) + return *it; + + for (const TrackPtr& track : std::as_const(m_childrenTracks)) { - return track->_item(id); + try + { + return track->_item(id); + } + catch (...) + { + } } - catch(...) - { - - } - } - - throw QStringLiteral("_item: item with id %1 not found!").arg(id); + throw QStringLiteral("_item: item with id %1 not found!").arg(id); } - void Track::printTrackIds(bool withItems, int level) const { - fprintf(stderr, "%*c Track %16.16s ", level * 2, '>', text().toStdString().c_str()); + fprintf(stderr, "%*c Track %16.16s ", level * 2, '>', text().toStdString().c_str()); - if (withItems) - { - fprintf(stderr, " ( "); - for (const ItemPtr &itemPtr : std::as_const(m_items)) + if (withItems) { - fprintf(stderr, "%d ", itemPtr->id()); + fprintf(stderr, " ( "); + for (const ItemPtr& itemPtr : std::as_const(m_items)) + { + fprintf(stderr, "%d ", itemPtr->id()); + } + fprintf(stderr, ")"); } - fprintf(stderr, ")"); - } - fprintf(stderr, "\n"); + fprintf(stderr, "\n"); - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - trackPtr->printTrackIds(level + 1); + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + trackPtr->printTrackIds(level + 1); } - QVector Track::itemIds(bool recursive, bool sorted) const { - if (sorted) - { - if (!recursive) - return transformItemPtrsToIds(m_items); + if (sorted) + { + if (!recursive) + return transformItemPtrsToIds(m_items); - - ItemPtrRefs is(_items(true)); + ItemPtrRefs is(_items(true)); - sort(is); + sort(is); - return transformItemPtrsToIds(is); - } + return transformItemPtrsToIds(is); + } + QVector itemIds; + itemIds.reserve(m_items.size()); - - QVector itemIds; - itemIds.reserve(m_items.size()); + itemIds += transformItemPtrsToIds(m_items); - itemIds += transformItemPtrsToIds(m_items); + if (!recursive) + return itemIds; + + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + itemIds += trackPtr->_itemIds(true); - if (!recursive) return itemIds; - - - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - itemIds += trackPtr->_itemIds(true); - - return itemIds; } - -void Track::addItemPtr(ItemPtr &&itemPtr) +void Track::addItemPtr(ItemPtr&& itemPtr) { - m_items.insert(std::upper_bound(m_items.begin(), m_items.end(), itemPtr->startTime(), - [](qint64 startTime, const ItemPtr &other) - { - return (other->startTime() > startTime); - }), std::move(itemPtr)); + m_items.insert( + std::upper_bound(m_items.begin(), m_items.end(), itemPtr->startTime(), + [](qint64 startTime, const ItemPtr& other) { return (other->startTime() > startTime); }), + std::move(itemPtr)); } - void Track::removeItem(int itemId) noexcept(false) { - auto it = std::find_if(m_items.begin(), m_items.end(), - [itemId](const ItemPtr &itemPtr) - { - return (itemPtr->id() == itemId); - }); + auto it = std::find_if(m_items.begin(), m_items.end(), + [itemId](const ItemPtr& itemPtr) { return (itemPtr->id() == itemId); }); - if (it == m_items.end()) - throw QStringLiteral("removeItem: item %1 not found").arg(itemId); + if (it == m_items.end()) + throw QStringLiteral("removeItem: item %1 not found").arg(itemId); - m_items.erase(it); + m_items.erase(it); } - -void Track::removeTrack(int trackId) noexcept(false) +void Track::removeTrack(int trackId) noexcept(false) { - auto it = std::find_if(m_childrenTracks.begin(), m_childrenTracks.end(), - [trackId](const TrackPtr &trackPtr) - { - return (trackPtr->id() == trackId); - }); + auto it = std::find_if(m_childrenTracks.begin(), m_childrenTracks.end(), + [trackId](const TrackPtr& trackPtr) { return (trackPtr->id() == trackId); }); - if (it == m_childrenTracks.end()) - throw QStringLiteral("removeTrack: track %1 not found on track %2").arg(trackId, id()); + if (it == m_childrenTracks.end()) + throw QStringLiteral("removeTrack: track %1 not found on track %2").arg(trackId, id()); - m_childrenTracks.erase(it); + m_childrenTracks.erase(it); } - ItemPtr Track::takeItem(int itemId) noexcept(false) { - auto it = std::find_if(m_items.begin(), m_items.end(), - [itemId](const ItemPtr &itemPtr) - { - return (itemPtr->id() == itemId); - }); + auto it = std::find_if(m_items.begin(), m_items.end(), + [itemId](const ItemPtr& itemPtr) { return (itemPtr->id() == itemId); }); - if (it == m_items.end()) - throw QStringLiteral("Track::takeItem: item with id %1 not found").arg(itemId); + if (it == m_items.end()) + throw QStringLiteral("Track::takeItem: item with id %1 not found").arg(itemId); - ItemPtr ptr = std::move(*it); + ItemPtr ptr = std::move(*it); - m_items.erase(it); + m_items.erase(it); - return ptr; + return ptr; } - - - - - - - - - - - - - - - - - - - - - - -Track &Track::track(int id) noexcept(false) +Track& Track::track(int id) noexcept(false) { - - auto it = std::find_if(m_childrenTracks.begin(), m_childrenTracks.end(), - [id](TrackPtr &trackPtr) - { - return (trackPtr.get()->id() == id); - }); - if (it != m_childrenTracks.end()) - { - Track &t = **it; - - return t; - } + auto it = std::find_if(m_childrenTracks.begin(), m_childrenTracks.end(), + [id](TrackPtr& trackPtr) { return (trackPtr.get()->id() == id); }); - - for (TrackPtr &track : m_childrenTracks) - { - try + if (it != m_childrenTracks.end()) { - return track->track(id); + Track& t = **it; + + return t; } - catch(...) + + for (TrackPtr& track : m_childrenTracks) { - - + try + { + return track->track(id); + } + catch (...) + { + } } - } - throw QStringLiteral("Track: track with id %1 not found").arg(id); + throw QStringLiteral("Track: track with id %1 not found").arg(id); } - ItemPtrNCVRef Track::_itemNCV(int id) noexcept(false) { - - auto const it = std::find_if(m_items.begin(), m_items.end(), - [id](ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.end()) - return *it; + auto const it = + std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - - for (TrackPtr &track : m_childrenTracks) - { - try + if (it != m_items.end()) + return *it; + + for (TrackPtr& track : m_childrenTracks) { - return track->_itemNCV(id); + try + { + return track->_itemNCV(id); + } + catch (...) + { + } } - catch(...) - { - - } - } - - throw QStringLiteral("lookup failed!");; + throw QStringLiteral("lookup failed!"); + ; } - -Item &Track::item(int id) noexcept(false) +Item& Track::item(int id) noexcept(false) { - - auto const it = std::find_if(m_items.begin(), m_items.end(), - [id](ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.end()) - return **it; + auto const it = + std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - - for (TrackPtr &track : m_childrenTracks) - { - try + if (it != m_items.end()) + return **it; + + for (TrackPtr& track : m_childrenTracks) { - return track->item(id); + try + { + return track->item(id); + } + catch (...) + { + } } - catch(...) - { - - } - } - - throw QStringLiteral("lookup failed!");; + throw QStringLiteral("lookup failed!"); + ; } - -const Item &Track::item(int id) const noexcept(false) +const Item& Track::item(int id) const noexcept(false) { - - auto const it = std::find_if(m_items.cbegin(), m_items.cend(), - [id](const ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.cend()) - return **it; + auto const it = std::find_if(m_items.cbegin(), m_items.cend(), + [id](const ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - - for (const TrackPtr &track : std::as_const(m_childrenTracks)) - { - try + if (it != m_items.cend()) + return **it; + + for (const TrackPtr& track : std::as_const(m_childrenTracks)) { - return track->item(id); + try + { + return track->item(id); + } + catch (...) + { + } } - catch(...) - { - - } - } - - throw QStringLiteral("lookup failed!");; + throw QStringLiteral("lookup failed!"); + ; } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Item &Track::previous(int id) noexcept(false) +Item& Track::previous(int id) noexcept(false) { - - auto it = std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.end() && (*it) != m_items.front()) - return **(--it); + auto it = + std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - throw QStringLiteral("Track::previous: previous item for id %1 not found").arg(id); + if (it != m_items.end() && (*it) != m_items.front()) + return **(--it); + + throw QStringLiteral("Track::previous: previous item for id %1 not found").arg(id); } - -Item &Track::next(int id) noexcept(false) +Item& Track::next(int id) noexcept(false) { - - auto it = std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr &itemPtr) - { - return (itemPtr.get()->id() == id); - }); - if (it != m_items.end() && (*it) != m_items.back()) - return **(++it); + auto it = + std::find_if(m_items.begin(), m_items.end(), [id](ItemPtr& itemPtr) { return (itemPtr.get()->id() == id); }); - throw QStringLiteral("lookup failed!");; + if (it != m_items.end() && (*it) != m_items.back()) + return **(++it); + + throw QStringLiteral("lookup failed!"); + ; } - - - - - - - - - - - - - - - - - - - int Track::rowOfTrack(int id) const noexcept(false) { - int row = 0; - for (const TrackPtr &trackPtr : std::as_const(m_childrenTracks)) - { - if (trackPtr->id() == id) - return row; - row++; - } + int row = 0; + for (const TrackPtr& trackPtr : std::as_const(m_childrenTracks)) + { + if (trackPtr->id() == id) + return row; + row++; + } - throw("not found"); + throw("not found"); } - -Track &Track::trackAt(int index) noexcept(false) +Track& Track::trackAt(int index) noexcept(false) { - return *m_childrenTracks.at(index); + return *m_childrenTracks.at(index); } - -const Track &Track::trackAt(int index) const noexcept(false) +const Track& Track::trackAt(int index) const noexcept(false) { - return *m_childrenTracks.at(index); + return *m_childrenTracks.at(index); } - -const Item &Track::copyItemAt(qint64 time) const noexcept(false) +const Item& Track::copyItemAt(qint64 time) const noexcept(false) { - auto const itemPtrRefs = _copyItems(); - const ItemPtrRefs::const_iterator it = - std::find_if(itemPtrRefs.cbegin(), itemPtrRefs.cend(), [time](const ItemPtr &itemPtr) - { - return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); - }); + auto const itemPtrRefs = _copyItems(); + const ItemPtrRefs::const_iterator it = + std::find_if(itemPtrRefs.cbegin(), itemPtrRefs.cend(), [time](const ItemPtr& itemPtr) { + return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); + }); - if (it != itemPtrRefs.cend()) - return *it->get(); + if (it != itemPtrRefs.cend()) + return *it->get(); - throw QStringLiteral("Track: can't find copy item at %1").arg(time); + throw QStringLiteral("Track: can't find copy item at %1").arg(time); } - -Item &Track::itemAt(qint64 time) noexcept(false) +Item& Track::itemAt(qint64 time) noexcept(false) { - - auto it = std::find_if(m_items.cbegin(), m_items.cend(), [time](const ItemPtr &itemPtr) - { - return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); - }); - if (it != m_items.cend()) - return **it; + auto it = std::find_if(m_items.cbegin(), m_items.cend(), [time](const ItemPtr& itemPtr) { + return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); + }); - throw QStringLiteral("lookup failed!");; + if (it != m_items.cend()) + return **it; + + throw QStringLiteral("lookup failed!"); + ; } - -const Item &Track::itemAt(qint64 time) const noexcept(false) +const Item& Track::itemAt(qint64 time) const noexcept(false) { - - auto const it = std::find_if(m_items.cbegin(), m_items.cend(), [time](const ItemPtr &itemPtr) - { - return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); - }); - if (it != m_items.cend()) - return **it; + auto const it = std::find_if(m_items.cbegin(), m_items.cend(), [time](const ItemPtr& itemPtr) { + return itemPtr.get()->startTime() <= time && time <= itemPtr.get()->startTime() + itemPtr.get()->duration(); + }); - throw QStringLiteral("lookup failed!");; + if (it != m_items.cend()) + return **it; + + throw QStringLiteral("lookup failed!"); + ; } -} - - - - - - - - - - - - - - - - - - - - +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.h old mode 100755 new mode 100644 index 07c91f8c9..b00cc550d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimeline/track.h @@ -1,20 +1,15 @@ - #pragma once #include "item.h" - #include "ltstimeline_export.h" #include #include #include - - #include - namespace LtsTimeline { class Track; @@ -26,238 +21,266 @@ typedef std::vector Tracks; typedef std::reference_wrapper TrackPtrRef; typedef std::vector TrackPtrRefs; - class LTSTIMELINE_EXPORT Track { -public: - Track(const QString &text = {}) - : m_text(text) - {} + public: + Track(const QString& text = {}) : m_text(text) {} - Track(const QString &text, int specialTrackType) - : m_text(text) - , m_userData(specialTrackType) - {} + Track(const QString& text, int specialTrackType) : m_text(text), m_userData(specialTrackType) {} - Track(const Track &) = delete; - Track &operator=(const Track &) = delete; - Track(Track &&t) noexcept = default; - virtual ~Track() = default; + Track(const Track&) = delete; + Track& operator=(const Track&) = delete; + Track(Track&& t) noexcept = default; + virtual ~Track() = default; - [[deprecated("Use model's track(int) instead.")]] const Track &track(int id) const noexcept(false); - [[deprecated("Use model's track(int) instead.")]] Track &track(int id) noexcept(false); - [[deprecated("Use model's item(int) instead.")]] Item &item(int id) noexcept(false); - [[deprecated("Use model's item(int) instead.")]] const Item &item(int id) const noexcept(false); - Item &previous(int id) noexcept(false); - Item &next(int id) noexcept(false); - - const Item ©ItemAt(qint64 time) const noexcept(false); - Item &itemAt(qint64 time) noexcept(false); - const Item &itemAt(qint64 time) const noexcept(false); - Track &trackAt(int index) noexcept(false); - const Track &trackAt(int index) const noexcept(false); - bool hasTrack(int id, bool recursive = false) const; - bool hasTracks() const { return !m_childrenTracks.empty(); } - int rowOfTrack(int id) const noexcept(false); - const Track &parentOf(int id) const noexcept(false); - - - const QSet ©ItemIds() const { return m_copyItemIds; } - void clearCopyItemIds() { m_copyItemIds.clear(); } - void addCopyItemIds(const QSet &ids); - void addCopyItemId(int id); - bool hasItems() const { return !m_items.empty(); } - bool hasCopyItems() const { return !m_copyItemIds.empty(); } - int itemCount() const { return m_items.size(); } - Items &items() { return m_items; } - const Items &items() const { return m_items; } - int trackCount() const { return m_childrenTracks.size(); } - Tracks &tracks() { return m_childrenTracks; } - const Tracks &tracks() const { return m_childrenTracks; } - QVector itemIds(bool recursive = false, bool sorted = false) const; - const QVector itemIdsBetween(qint64 start, qint64 end, bool strict = false, bool complete = false, bool recursive = false, bool sorted = false, qint64 minimumDuration = 0) const; - [[deprecated]] const QVector copyItemIdsBetween(qint64 start, qint64 end, bool strict = false, bool complete = false, bool recursive = false, bool sorted = false, qint64 minimumDuration = 0) const; - bool isItemsBetween(qint64 start, qint64 end, const QVector &ignoreIds, bool strict = false, bool complete = false, bool recursive = false, qint64 minimumDuration = 0) const; - bool isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict = false, bool complete = false, bool recursive = false, qint64 minimumDuration = 0) const; - - - int id() const { return m_id; } - virtual const QString text() const { return m_text; } - int parent() const { return m_parentId; } - int parentId() const { return m_parentId; } - void printTrackIds(bool withItems = false, int level = 0) const; - void removeCopyItem(int itemId) noexcept(false); - void removeItem(int itemId) noexcept(false); - ItemPtr takeItem(int itemId) noexcept(false); - QVariant userData() const { return m_userData; } - void setUserData(const QVariant &data) { m_userData = data; } + [[deprecated("Use model's track(int) instead.")]] const Track& track(int id) const noexcept(false); + [[deprecated("Use model's track(int) instead.")]] Track& track(int id) noexcept(false); + [[deprecated("Use model's item(int) instead.")]] Item& item(int id) noexcept(false); + [[deprecated("Use model's item(int) instead.")]] const Item& item(int id) const noexcept(false); + Item& previous(int id) noexcept(false); + Item& next(int id) noexcept(false); + const Item& copyItemAt(qint64 time) const noexcept(false); + Item& itemAt(qint64 time) noexcept(false); + const Item& itemAt(qint64 time) const noexcept(false); + Track& trackAt(int index) noexcept(false); + const Track& trackAt(int index) const noexcept(false); + bool hasTrack(int id, bool recursive = false) const; - inline static void sort(Items &items) - { - std::sort(items.begin(), items.end(), [](const ItemPtr &itemA, const ItemPtr &itemB) + bool hasTracks() const { - return itemA->startTime() < itemB->startTime(); - }); - } + return !m_childrenTracks.empty(); + } + int rowOfTrack(int id) const noexcept(false); + const Track& parentOf(int id) const noexcept(false); - inline static void sort(ItemPtrNCVRefs &items) - { - std::sort(items.begin(), items.end(), [](const ItemPtrNCVRef &itemA, const ItemPtrNCVRef &itemB) + const QSet& copyItemIds() const { - return itemA.get()->startTime() < itemB.get()->startTime(); - }); - } + return m_copyItemIds; + } - - inline static void sort(ItemPtrRefs &items) - { - std::sort(items.begin(), items.end(), [](const ItemPtrRef &itemA, const ItemPtrRef &itemB) + void clearCopyItemIds() { - return itemA.get()->startTime() < itemB.get()->startTime(); - }); - } + m_copyItemIds.clear(); + } - bool hasInsertButton() const { return m_hasInsertButton; } - void setInsertButton(bool hasButton) { m_hasInsertButton = hasButton; } - bool hasRemoveButton() const { return m_hasRemoveButton; } - void setRemoveButton(bool hasButton) { m_hasRemoveButton = hasButton; } + void addCopyItemIds(const QSet& ids); + void addCopyItemId(int id); - -protected: - QString m_text; - QVariant m_userData; - - -private: - void removeTrack(int trackId) noexcept(false); - void addItemPtr(ItemPtr &&itemPtr); - - static bool isItemBetween(const Item &item, qint64 start, qint64 end, bool strict, bool complete, qint64 minimumDuration = 0); - ItemPtrRefs _copyItems() const; - ItemPtrRefs _items(bool recursive) const; - ItemPtrNCVRefs _itemsNCV(bool recursive); - ItemPtrNCVRef _itemNCV(int id) noexcept(false); - ItemPtrRef _item(int id) const noexcept(false); - const QVector _itemIds(bool recursive) const; - - -public: - void clearItems() { m_items.clear(); } -private: - - friend class TimelineModel; - - - void sort() - { - sort(m_items); - } - - - template - Track *addTrack(TrackClass &&trackClass) - { - TrackClass _trackClass = std::move(trackClass); - m_childrenTracks.push_back(std::move(std::move(std::make_unique(std::move(_trackClass))))); - return m_childrenTracks.back().get(); - } - - - template - [[deprecated("Use model's track(...) and call addTrack(TrackClass) directly on that track.")]] - Track *addTrack(int parentTrackId, TrackClass &&trackClass) noexcept(false) - { - if (m_id == parentTrackId) - return addTrack(std::move(trackClass)); - - return track(parentTrackId).addTrack(std::move(trackClass)); - } - - - template - Item *addItem(ItemClass &&itemClass) - { - ItemClass _itemClass(std::move(itemClass)); - - auto it = m_items.insert(std::upper_bound(m_items.begin(), m_items.end(), _itemClass.startTime(), - [](qint64 startTime, const ItemPtr &other) + bool hasItems() const { - return (other->startTime() > startTime); - }), std::move(std::make_unique(std::move(_itemClass)))); + return !m_items.empty(); + } - return it->get(); - } - - - Item *addItem(ItemPtr &&itemPtr) - { - auto it = m_items.insert(std::upper_bound(m_items.begin(), m_items.end(), itemPtr->startTime(), - [](qint64 startTime, const ItemPtr &other) + bool hasCopyItems() const { - return (other->startTime() > startTime); - }), std::move(itemPtr)); + return !m_copyItemIds.empty(); + } - return it->get(); - } - - - template - [[deprecated]] - QVector transformItemPtrsToIds(const ItemContainer &itemContainer) const - { - QVector ids; - std::transform(itemContainer.cbegin(), itemContainer.cend(), std::back_inserter(ids), - [](const ItemPtr &itemPtr) -> int + int itemCount() const { - return itemPtr->id(); - }); - return ids; - } + return m_items.size(); + } + Items& items() + { + return m_items; + } - - - - - - - - - + const Items& items() const + { + return m_items; + } + int trackCount() const + { + return m_childrenTracks.size(); + } - int m_id { -1 }; - Tracks m_childrenTracks; - Items m_items; - int m_parentId { -1 }; - bool m_hasInsertButton { false }; - bool m_hasRemoveButton { false }; + Tracks& tracks() + { + return m_childrenTracks; + } + const Tracks& tracks() const + { + return m_childrenTracks; + } - QSet m_copyItemIds; + QVector itemIds(bool recursive = false, bool sorted = false) const; + const QVector itemIdsBetween(qint64 start, qint64 end, bool strict = false, bool complete = false, + bool recursive = false, bool sorted = false, qint64 minimumDuration = 0) const; + [[deprecated]] const QVector copyItemIdsBetween(qint64 start, qint64 end, bool strict = false, + bool complete = false, bool recursive = false, + bool sorted = false, qint64 minimumDuration = 0) const; + bool isItemsBetween(qint64 start, qint64 end, const QVector& ignoreIds, bool strict = false, + bool complete = false, bool recursive = false, qint64 minimumDuration = 0) const; + bool isItemsBetween(qint64 start, qint64 end, int ignoreId, bool strict = false, bool complete = false, + bool recursive = false, qint64 minimumDuration = 0) const; + + int id() const + { + return m_id; + } + + virtual const QString text() const + { + return m_text; + } + + int parent() const + { + return m_parentId; + } + + int parentId() const + { + return m_parentId; + } + + void printTrackIds(bool withItems = false, int level = 0) const; + void removeCopyItem(int itemId) noexcept(false); + void removeItem(int itemId) noexcept(false); + ItemPtr takeItem(int itemId) noexcept(false); + + QVariant userData() const + { + return m_userData; + } + + void setUserData(const QVariant& data) + { + m_userData = data; + } + + inline static void sort(Items& items) + { + std::sort(items.begin(), items.end(), + [](const ItemPtr& itemA, const ItemPtr& itemB) { return itemA->startTime() < itemB->startTime(); }); + } + + inline static void sort(ItemPtrNCVRefs& items) + { + std::sort(items.begin(), items.end(), [](const ItemPtrNCVRef& itemA, const ItemPtrNCVRef& itemB) { + return itemA.get()->startTime() < itemB.get()->startTime(); + }); + } + + inline static void sort(ItemPtrRefs& items) + { + std::sort(items.begin(), items.end(), [](const ItemPtrRef& itemA, const ItemPtrRef& itemB) { + return itemA.get()->startTime() < itemB.get()->startTime(); + }); + } + + bool hasInsertButton() const + { + return m_hasInsertButton; + } + + void setInsertButton(bool hasButton) + { + m_hasInsertButton = hasButton; + } + + bool hasRemoveButton() const + { + return m_hasRemoveButton; + } + + void setRemoveButton(bool hasButton) + { + m_hasRemoveButton = hasButton; + } + + protected: + QString m_text; + QVariant m_userData; + + private: + void removeTrack(int trackId) noexcept(false); + void addItemPtr(ItemPtr&& itemPtr); + + static bool isItemBetween(const Item& item, qint64 start, qint64 end, bool strict, bool complete, + qint64 minimumDuration = 0); + ItemPtrRefs _copyItems() const; + ItemPtrRefs _items(bool recursive) const; + ItemPtrNCVRefs _itemsNCV(bool recursive); + ItemPtrNCVRef _itemNCV(int id) noexcept(false); + ItemPtrRef _item(int id) const noexcept(false); + const QVector _itemIds(bool recursive) const; + + public: + void clearItems() + { + m_items.clear(); + } + + private: + friend class TimelineModel; + + void sort() + { + sort(m_items); + } + + template Track* addTrack(TrackClass&& trackClass) + { + TrackClass _trackClass = std::move(trackClass); + m_childrenTracks.push_back(std::move(std::move(std::make_unique(std::move(_trackClass))))); + return m_childrenTracks.back().get(); + } + + template + [[deprecated("Use model's track(...) and call addTrack(TrackClass) directly on that track.")]] Track* + addTrack(int parentTrackId, TrackClass&& trackClass) noexcept(false) + { + if (m_id == parentTrackId) + return addTrack(std::move(trackClass)); + + return track(parentTrackId).addTrack(std::move(trackClass)); + } + + template Item* addItem(ItemClass&& itemClass) + { + ItemClass _itemClass(std::move(itemClass)); + + auto it = m_items.insert( + std::upper_bound(m_items.begin(), m_items.end(), _itemClass.startTime(), + [](qint64 startTime, const ItemPtr& other) { return (other->startTime() > startTime); }), + std::move(std::make_unique(std::move(_itemClass)))); + + return it->get(); + } + + Item* addItem(ItemPtr&& itemPtr) + { + auto it = m_items.insert( + std::upper_bound(m_items.begin(), m_items.end(), itemPtr->startTime(), + [](qint64 startTime, const ItemPtr& other) { return (other->startTime() > startTime); }), + std::move(itemPtr)); + + return it->get(); + } + + template + [[deprecated]] QVector transformItemPtrsToIds(const ItemContainer& itemContainer) const + { + QVector ids; + std::transform(itemContainer.cbegin(), itemContainer.cend(), std::back_inserter(ids), + [](const ItemPtr& itemPtr) -> int { return itemPtr->id(); }); + return ids; + } + + int m_id{-1}; + Tracks m_childrenTracks; + Items m_items; + int m_parentId{-1}; + bool m_hasInsertButton{false}; + bool m_hasRemoveButton{false}; + + QSet m_copyItemIds; }; -} - - - - - - - - - - - - - - - - - - - - - +} // namespace LtsTimeline diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.cpp old mode 100755 new mode 100644 index dc9a99473..deba53613 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.cpp @@ -1,11 +1,9 @@ - #include "AbstractTimelineModel.h" -#include #include - +#include namespace LtsTimelineClassic { @@ -17,267 +15,216 @@ AbstractTimelineModel::AbstractTimelineModel(QObject *parent) : QAbstractItemMod , m_getEventListsRecursive(true) , m_rootItem(new Item(QLatin1String("#mwille/r00t/"))) , m_markersItem(new Item(tr("Markers"), QStringLiteral("Markers"))), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ - - m_rootItem->addItem(m_markersItem); + m_rootItem->addItem(m_markersItem); } - AbstractTimelineModel::~AbstractTimelineModel() { - delete m_rootItem; + delete m_rootItem; } - void AbstractTimelineModel::retranslate() { - m_markersItem->setName(tr("Markers")); + m_markersItem->setName(tr("Markers")); } - void AbstractTimelineModel::invalidateTimeline() { - const LtsTimelineClassic::ItemList il = m_rootItem->getFullItemList(true); - for (auto i = il.constBegin(); i != il.constEnd(); ++i) - { - LtsTimelineClassic::Item *item = *i; - - if (item != nullptr) - item->setEventListChanged(); - } -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Event *AbstractTimelineModel::getEvent(int uniqueId) -{ - const LtsTimelineClassic::ItemList il = m_rootItem->getFullItemList(true); - for (auto i = il.constBegin(); i != il.constEnd(); ++i) - { - LtsTimelineClassic::Item *item = *i; - - if (item != nullptr && item->getIdentifier() != QStringLiteral("Markers")) + const LtsTimelineClassic::ItemList il = m_rootItem->getFullItemList(true); + for (auto i = il.constBegin(); i != il.constEnd(); ++i) { - const LtsTimelineClassic::EventList el = item->getFullEventList(true, true); + LtsTimelineClassic::Item* item = *i; - for (LtsTimelineClassic::Event *event : el) - { - if (event->uniqueId() == uniqueId) - return event; - } + if (item != nullptr) + item->setEventListChanged(); } - } - - return nullptr; } - -void AbstractTimelineModel::addEvent(Event *event) +Event* AbstractTimelineModel::getEvent(int uniqueId) { - QStringList actuatorPath = event->getActuator(); - - - Item *currentItem = m_rootItem; - QModelIndex currentIndex = QModelIndex(); - - for (const QString &curPath : std::as_const(actuatorPath)) - { - Item *oldItem = currentItem; - const ItemList *itemList = currentItem->getChildren(); - - if (itemList != nullptr) + const LtsTimelineClassic::ItemList il = m_rootItem->getFullItemList(true); + for (auto i = il.constBegin(); i != il.constEnd(); ++i) { - for (int row = 0; row < itemList->count(); row++) - { - Item *childItem = itemList->at(row); - if (childItem->getName() == curPath) + LtsTimelineClassic::Item* item = *i; + + if (item != nullptr && item->getIdentifier() != QStringLiteral("Markers")) { - currentIndex = index(row, 0, currentIndex); - currentItem = childItem; - break; + const LtsTimelineClassic::EventList el = item->getFullEventList(true, true); + + for (LtsTimelineClassic::Event* event : el) + { + if (event->uniqueId() == uniqueId) + return event; + } } - } } - if (oldItem == currentItem) + return nullptr; +} + +void AbstractTimelineModel::addEvent(Event* event) +{ + QStringList actuatorPath = event->getActuator(); + + Item* currentItem = m_rootItem; + QModelIndex currentIndex = QModelIndex(); + + for (const QString& curPath : std::as_const(actuatorPath)) { - beginInsertRows(currentIndex, currentItem->childCount(), currentItem->childCount()); - Item *newItem = new Item(curPath); - currentItem->addItem(newItem); - endInsertRows(); + Item* oldItem = currentItem; + const ItemList* itemList = currentItem->getChildren(); - currentIndex = index(currentItem->childCount() - 1, 0, currentIndex); - currentItem = newItem; + if (itemList != nullptr) + { + for (int row = 0; row < itemList->count(); row++) + { + Item* childItem = itemList->at(row); + if (childItem->getName() == curPath) + { + currentIndex = index(row, 0, currentIndex); + currentItem = childItem; + break; + } + } + } + + if (oldItem == currentItem) + { + beginInsertRows(currentIndex, currentItem->childCount(), currentItem->childCount()); + Item* newItem = new Item(curPath); + currentItem->addItem(newItem); + endInsertRows(); + + currentIndex = index(currentItem->childCount() - 1, 0, currentIndex); + currentItem = newItem; + } } - } - currentItem->addEvent(event); + currentItem->addEvent(event); } - -Item *AbstractTimelineModel::getRootItem() +Item* AbstractTimelineModel::getRootItem() { - return m_rootItem; -} - - -Item *AbstractTimelineModel::itemFromIndex(const QModelIndex &idx) const -{ - if (!idx.isValid()) return m_rootItem; - return static_cast(idx.internalPointer()); } - -QVariant AbstractTimelineModel::data(const QModelIndex &index, int role) const +Item* AbstractTimelineModel::itemFromIndex(const QModelIndex& idx) const { - if (role != Qt::DisplayRole || !index.isValid()) - return QVariant(); - - Item *item = itemFromIndex(index); - if (!item) - return QVariant(); - - - - - - if (index.column() == 1) - { - PassiveEventContainer *pevcon = item->getPevcon(); - return QVariant::fromValue(pevcon); - } - - - QString name(item->getName()); - - if (name.isEmpty()) - name = tr("[unknown]"); - - return QVariant(name); + if (!idx.isValid()) + return m_rootItem; + return static_cast(idx.internalPointer()); } - -Qt::ItemFlags AbstractTimelineModel::flags(const QModelIndex &index) const +QVariant AbstractTimelineModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) - return {}; + if (role != Qt::DisplayRole || !index.isValid()) + return QVariant(); - return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; + Item* item = itemFromIndex(index); + if (!item) + return QVariant(); + + if (index.column() == 1) + { + PassiveEventContainer* pevcon = item->getPevcon(); + return QVariant::fromValue(pevcon); + } + + QString name(item->getName()); + + if (name.isEmpty()) + name = tr("[unknown]"); + + return QVariant(name); } +Qt::ItemFlags AbstractTimelineModel::flags(const QModelIndex& index) const +{ + if (!index.isValid()) + return {}; + + return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; +} QVariant AbstractTimelineModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation == Qt::Horizontal && role == Qt::DisplayRole) - { - - switch (section) - { - case 0: return QString(tr("Actuator") + QStringLiteral("\r\n")); - case 1: return QString(tr("Events") + QStringLiteral("\r\n")); - } - - - - - - - } + if (orientation == Qt::Horizontal && role == Qt::DisplayRole) + { - return QVariant(); + switch (section) + { + case 0: + return QString(tr("Actuator") + QStringLiteral("\r\n")); + case 1: + return QString(tr("Events") + QStringLiteral("\r\n")); + } + } + + return QVariant(); } - -QModelIndex AbstractTimelineModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex AbstractTimelineModel::index(int row, int column, const QModelIndex& parent) const { - if (!hasIndex(row, column, parent)) + if (!hasIndex(row, column, parent)) + return QModelIndex(); + + Item* item = itemFromIndex(parent); + Item* child = item ? item->child(row) : nullptr; + + if (child) + { + + return createIndex(row, column, child); + } + return QModelIndex(); - - Item *item = itemFromIndex(parent); - Item *child = item ? item->child(row) : nullptr; - - if (child) - { - - return createIndex(row, column, child); - } - - return QModelIndex(); } - -QModelIndex AbstractTimelineModel::parent(const QModelIndex &index) const +QModelIndex AbstractTimelineModel::parent(const QModelIndex& index) const { - if (!index.isValid()) - return QModelIndex(); + if (!index.isValid()) + return QModelIndex(); - Item *item = itemFromIndex(index); - Item *parent = item ? item->getParent() : nullptr; + Item* item = itemFromIndex(index); + Item* parent = item ? item->getParent() : nullptr; - if (parent == m_rootItem || parent == nullptr) - return QModelIndex(); + if (parent == m_rootItem || parent == nullptr) + return QModelIndex(); - int idx = parent->indexOfParent(); + int idx = parent->indexOfParent(); - if (idx == -1) - return QModelIndex(); + if (idx == -1) + return QModelIndex(); - return createIndex(idx, 0, parent); + return createIndex(idx, 0, parent); } - -int AbstractTimelineModel::rowCount(const QModelIndex &parent) const +int AbstractTimelineModel::rowCount(const QModelIndex& parent) const { - if (!parent.isValid()) - { - int r = m_rootItem->visibleChildCount(); - - return r; - } + if (!parent.isValid()) + { + int r = m_rootItem->visibleChildCount(); - Item *item = itemFromIndex(parent); - if (item) - { - int r = item->visibleChildCount(); - - return r; - } + return r; + } - return 0; + Item* item = itemFromIndex(parent); + if (item) + { + int r = item->visibleChildCount(); + + return r; + } + + return 0; } - -int AbstractTimelineModel::columnCount(const QModelIndex &) const +int AbstractTimelineModel::columnCount(const QModelIndex&) const { - return 2; + return 2; } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.h old mode 100755 new mode 100644 index bcdcc3aa8..78d954c0a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/AbstractTimelineModel.h @@ -1,113 +1,82 @@ - #pragma once -#include - #include "Event.h" #include "Item.h" #include "ltstimelineclassic_export.h" -#include #include - +#include +#include namespace LtsTimelineClassic { - - class LTSTIMELINECLASSIC_EXPORT AbstractTimelineModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT -public: - explicit AbstractTimelineModel( QObject *parent = nullptr); - ~AbstractTimelineModel(); + public: + explicit AbstractTimelineModel(QObject* parent = nullptr); + ~AbstractTimelineModel(); - void retranslate(); + void retranslate(); - + Item* getRootItem(); - Item *getRootItem(); + Event* getEvent(int uniqueId); - Event *getEvent(int uniqueId); + void invalidateTimeline(); - - void invalidateTimeline(); + void refreshData(); - + qint64 highestPositionedItem() const + { + return m_highestPositionedItem; + } - void refreshData(); + qint64 lowestPositionedItem() const + { + return m_lowestPositionedItem; + } - qint64 highestPositionedItem() const { return m_highestPositionedItem; } - qint64 lowestPositionedItem() const { return m_lowestPositionedItem; } + protected: + NGL::INGLLogger& m_logger; + protected: + void addEvent(Event* event); -protected: + QVariant data(const QModelIndex& index, int role) const; + Qt::ItemFlags flags(const QModelIndex& index) const; -NGL::INGLLogger &m_logger; -protected: - + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - void addEvent(Event *event); + Item* itemFromIndex(const QModelIndex& idx) const; - + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role) const; + QModelIndex parent(const QModelIndex& index) const; - + int rowCount(const QModelIndex& parent = QModelIndex()) const; - Qt::ItemFlags flags(const QModelIndex &index) const; + int columnCount(const QModelIndex& parent = QModelIndex()) const; - + virtual qint64 currentTime() const = 0; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + qint64 m_highestPositionedItem; + qint64 m_lowestPositionedItem; + bool m_getEventListsRecursive; + Item* m_rootItem; + Item* m_markersItem; - + signals: - Item *itemFromIndex(const QModelIndex &idx) const; + void signalContextMenu(const QPoint& position, Event* affectedEvent); - - - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - - - - QModelIndex parent(const QModelIndex &index) const; - - - - int rowCount(const QModelIndex &parent = QModelIndex()) const; - - - - int columnCount(const QModelIndex &parent = QModelIndex()) const; - - - virtual qint64 currentTime() const = 0; - - - qint64 m_highestPositionedItem; - qint64 m_lowestPositionedItem; - bool m_getEventListsRecursive; - Item *m_rootItem; - Item *m_markersItem; - - -signals: - - - void signalContextMenu(const QPoint &position, Event *affectedEvent); - - - - void signalClicked(Event *affectedEvent); - - - void signalToolTip(const QPoint &p, Event *e); + void signalClicked(Event* affectedEvent); + void signalToolTip(const QPoint& p, Event* e); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.cpp old mode 100755 new mode 100644 index 174dd8ca2..1455c4ef8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.cpp @@ -1,217 +1,162 @@ - #include "Event.h" #include - -#include #include #include - +#include #include namespace LtsTimelineClassic { -Event::Event(int uniqueId, int typeId, qint64 startTime, - qint64 endTime, int playerId, int partyId, int equipmentId, const QStringList &path, - const EventPaintFunc &paintFunc, const QColor &paintColor, const QJsonObject &detailData, int subEventId, - const LtsUtils::QPoint3D &pos, LtsSession::LtsSession *session) : m_path(path) - , m_detailData(detailData) - , m_position(pos) - , m_paintFunc(paintFunc) - , m_session(session) - , m_eventColor(paintColor) - , m_startTime(startTime) - , m_endTime(endTime) - , m_uniqueId(uniqueId) - , m_typeId(typeId) - , m_subEventId(subEventId) - , m_playerId(playerId) - , m_partyId(partyId) - , m_equipmentId(equipmentId) - , m_deleted(false) - , m_visible(true), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - checkDuration(); +Event::Event(int uniqueId, int typeId, qint64 startTime, qint64 endTime, int playerId, int partyId, int equipmentId, + const QStringList& path, const EventPaintFunc& paintFunc, const QColor& paintColor, + const QJsonObject& detailData, int subEventId, const LtsUtils::QPoint3D& pos, + LtsSession::LtsSession* session) + : m_path(path), m_detailData(detailData), m_position(pos), m_paintFunc(paintFunc), m_session(session), + m_eventColor(paintColor), m_startTime(startTime), m_endTime(endTime), m_uniqueId(uniqueId), m_typeId(typeId), + m_subEventId(subEventId), m_playerId(playerId), m_partyId(partyId), m_equipmentId(equipmentId), m_deleted(false), + m_visible(true), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + checkDuration(); } void Event::setVisible(bool visibility) { - if (visibility) - show(); - else - hide(); + if (visibility) + show(); + else + hide(); } - void Event::hide() { - this->m_visible = false; + this->m_visible = false; } - void Event::show() { - this->m_visible = true; + this->m_visible = true; } QString Event::getShortActuator() const { - return m_path.isEmpty() ? QString() : m_path.last(); + return m_path.isEmpty() ? QString() : m_path.last(); } - - - - - - - - - - - - - void Event::setEndT(qint64 newEnd) { - m_endTime = newEnd; + m_endTime = newEnd; - checkDuration(); + checkDuration(); } - bool Event::checkDuration() { - - - - - - - - - - - - - - - - - - - - return true; + return true; } - qint64 Event::duration(bool ignoreLiveEvents) const { - if (m_endTime > m_startTime) - { - if (m_duration == -1) - m_duration = m_endTime - m_startTime; + if (m_endTime > m_startTime) + { + if (m_duration == -1) + m_duration = m_endTime - m_startTime; - return m_duration; - } + return m_duration; + } - if (m_endTime < 0 && !ignoreLiveEvents) - { - qint64 currentTime = (m_session != nullptr) ? m_session->partitionTime() : time(nullptr) ; - qint64 duration = currentTime - m_startTime; + if (m_endTime < 0 && !ignoreLiveEvents) + { + qint64 currentTime = (m_session != nullptr) ? m_session->partitionTime() : time(nullptr); + qint64 duration = currentTime - m_startTime; - return duration; - } + return duration; + } - return 0; + return 0; } - -void Event::drawMultipleEventGraphic(QPainter *painter, const QRect &rect) +void Event::drawMultipleEventGraphic(QPainter* painter, const QRect& rect) { - painter->save(); - painter->setBrush(Qt::white); + painter->save(); + painter->setBrush(Qt::white); - int x = rect.x(); - int y = rect.y(); - int h = rect.height(); - int w = rect.width(); + int x = rect.x(); + int y = rect.y(); + int h = rect.height(); + int w = rect.width(); - - painter->drawRect(rect); + painter->drawRect(rect); - - int s1 = y + h - (h * 0.4); - int s2 = y + h - (h * 0.2); + int s1 = y + h - (h * 0.4); + int s2 = y + h - (h * 0.2); - painter->drawLine(QPoint(x, s1), - QPoint(x + w, s1)); - painter->drawLine(QPoint(x, s2), - QPoint(x + w, s2)); + painter->drawLine(QPoint(x, s1), QPoint(x + w, s1)); + painter->drawLine(QPoint(x, s2), QPoint(x + w, s2)); - painter->restore(); + painter->restore(); } -void Event::drawCustomEventGraphicTriangle(QPainter *painter, const QRect &rect) +void Event::drawCustomEventGraphicTriangle(QPainter* painter, const QRect& rect) { - int x = rect.x(); - int y = rect.y(); - int h = rect.height(); - int w = rect.width(); + int x = rect.x(); + int y = rect.y(); + int h = rect.height(); + int w = rect.width(); - QPolygon pol; - pol.append(QPoint(x + 0, y + h)); - pol.append(QPoint(x + (w / 2), y + 0)); - pol.append(QPoint(x + w, y + h)); - pol.append(QPoint(x + 0, y + h)); + QPolygon pol; + pol.append(QPoint(x + 0, y + h)); + pol.append(QPoint(x + (w / 2), y + 0)); + pol.append(QPoint(x + w, y + h)); + pol.append(QPoint(x + 0, y + h)); - QPainterPath path; - path.moveTo(x, y); - path.addPolygon(pol); + QPainterPath path; + path.moveTo(x, y); + path.addPolygon(pol); - painter->drawPath(path); + painter->drawPath(path); } -void Event::drawCustomEventGraphicInvertTriangle(QPainter *painter, const QRect &rect) +void Event::drawCustomEventGraphicInvertTriangle(QPainter* painter, const QRect& rect) { - int x = rect.x(); - int y = rect.y(); - int h = rect.height(); - int w = rect.width(); + int x = rect.x(); + int y = rect.y(); + int h = rect.height(); + int w = rect.width(); - QPolygon pol; - pol.append(QPoint( x + 0 , y + 0)); - pol.append(QPoint( x+ w , y + 0)); - pol.append(QPoint(x + ( w / 2 ), y + h)); - pol.append(QPoint( x + 0 , y + 0)); + QPolygon pol; + pol.append(QPoint(x + 0, y + 0)); + pol.append(QPoint(x + w, y + 0)); + pol.append(QPoint(x + (w / 2), y + h)); + pol.append(QPoint(x + 0, y + 0)); - QPainterPath path; - path.moveTo(x, y); - path.addPolygon(pol); + QPainterPath path; + path.moveTo(x, y); + path.addPolygon(pol); - painter->drawPath(path); + painter->drawPath(path); } -void Event::drawCustomEventGraphicEllipse(QPainter *painter, const QRect &rect) + +void Event::drawCustomEventGraphicEllipse(QPainter* painter, const QRect& rect) { - QPoint ellipsePos = rect.center(); - ellipsePos.rx()++; - ellipsePos.ry()++; + QPoint ellipsePos = rect.center(); + ellipsePos.rx()++; + ellipsePos.ry()++; - painter->drawEllipse(ellipsePos, rect.width() / 2, rect.height() / 2); + painter->drawEllipse(ellipsePos, rect.width() / 2, rect.height() / 2); } -void Event::drawCustomEventGraphicRect(QPainter *painter, const QRect &rect) +void Event::drawCustomEventGraphicRect(QPainter* painter, const QRect& rect) { - painter->drawRect(rect); + painter->drawRect(rect); } - -void Event::drawCustomEventGraphicRoundedRect(QPainter *painter, const QRect &rect) +void Event::drawCustomEventGraphicRoundedRect(QPainter* painter, const QRect& rect) { - painter->drawRoundedRect(rect, 50, 50, Qt::RelativeSize); + painter->drawRoundedRect(rect, 50, 50, Qt::RelativeSize); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.h old mode 100755 new mode 100644 index 78cf1b39b..53663a094 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Event.h @@ -1,14 +1,13 @@ - #pragma once #include "ltstimelineclassic_export.h" +#include #include #include #include -#include class QPainter; class QRect; @@ -21,138 +20,176 @@ class LtsSession; namespace LtsTimelineClassic { - - -class LTSTIMELINECLASSIC_EXPORT Event +class LTSTIMELINECLASSIC_EXPORT Event { -public: - enum ButtonType - { - ActiveEvent, - EventBlock, - }; + public: + enum ButtonType { + ActiveEvent, + EventBlock, + }; + typedef void (*EventPaintFunc)(QPainter*, const QRect&); + static void drawCustomEventGraphicTriangle(QPainter* painter, const QRect& rect); + static void drawCustomEventGraphicInvertTriangle(QPainter* painter, const QRect& rect); + static void drawCustomEventGraphicEllipse(QPainter* painter, const QRect& rect); + static void drawCustomEventGraphicRect(QPainter* painter, const QRect& rect); + static void drawCustomEventGraphicRoundedRect(QPainter* painter, const QRect& rect); + static void drawMultipleEventGraphic(QPainter* painter, const QRect& rect); - typedef void (*EventPaintFunc)(QPainter *, const QRect &); - static void drawCustomEventGraphicTriangle(QPainter *painter, const QRect &rect); - static void drawCustomEventGraphicInvertTriangle(QPainter *painter, const QRect &rect); - static void drawCustomEventGraphicEllipse(QPainter *painter, const QRect &rect); - static void drawCustomEventGraphicRect(QPainter *painter, const QRect &rect); - static void drawCustomEventGraphicRoundedRect(QPainter *painter, const QRect &rect); - static void drawMultipleEventGraphic(QPainter *painter, const QRect &rect); + Event() = default; + Event(int uniqueId, int typeId, qint64 startTime, qint64 endTime, int playerId, int partyId, int equipmentId, + const QStringList& path, const EventPaintFunc& paintFunc, const QColor& paintColor, + const QJsonObject& detailData, int subEventId = -1, const LtsUtils::QPoint3D& pos = LtsUtils::QPoint3D(), + LtsSession::LtsSession* session = nullptr); + QStringList getActuator() const + { + return m_path; + } - Event() = default; - Event(int uniqueId, int typeId, qint64 startTime, qint64 endTime, - int playerId, int partyId, int equipmentId, const QStringList &path, - const EventPaintFunc &paintFunc, const QColor &paintColor, - const QJsonObject &detailData, int subEventId = -1, - const LtsUtils::QPoint3D &pos = LtsUtils::QPoint3D(), - LtsSession::LtsSession *session = nullptr); + int typeId() const + { + return m_typeId; + } + int uniqueId() const + { + return m_uniqueId; + } - + int getSubEventID() const; - QStringList getActuator() const { return m_path; } + QColor getColor() const + { + return m_eventColor; + } - int typeId() const { return m_typeId; } - int uniqueId() const { return m_uniqueId; } + EventPaintFunc getPaintFunc() const + { + return m_paintFunc; + } - int getSubEventID() const; + qint64 startTime() const + { + return m_startTime; + } - QColor getColor() const { return m_eventColor; } + qint64 endTime() const + { + return m_endTime; + } - EventPaintFunc getPaintFunc() const { return m_paintFunc; } + const QJsonObject& detailData() const + { + return m_detailData; + } - + void setDetailData(const QJsonObject& detailData) + { + m_detailData = detailData; + } - qint64 startTime() const { return m_startTime; } - qint64 endTime() const { return m_endTime; } + void setEndT(qint64 newEnd); - + qint64 duration(bool ignoreLiveEvents = false) const; - + int playerId() const + { + return m_playerId; + } - + void setPlayerId(int playerId) + { + m_playerId = playerId; + } - + int partyId() const + { + return m_partyId; + } - const QJsonObject &detailData() const { return m_detailData; } - void setDetailData(const QJsonObject &detailData) { m_detailData = detailData; } + void setPartyId(int teamId) + { + m_partyId = teamId; + } - void setEndT(qint64 newEnd); + int equipmentId() const + { + return m_equipmentId; + } - + void setEquipmentId(int eqId) + { + m_equipmentId = eqId; + } - qint64 duration(bool ignoreLiveEvents = false) const; + QString getShortActuator() const; - int playerId() const { return m_playerId; } - void setPlayerId(int playerId) { m_playerId = playerId; } + bool positionValid() const + { + return !std::isnan(m_position.x()) && !std::isnan(m_position.y()); + } - int partyId() const { return m_partyId; } - void setPartyId(int teamId) { m_partyId = teamId; } + const LtsUtils::QPoint3D& position() const + { + return m_position; + } - int equipmentId() const { return m_equipmentId; } - void setEquipmentId(int eqId) { m_equipmentId = eqId; } + QPointF pos2d() const + { + return QPointF(m_position.x(), m_position.y()); + } - QString getShortActuator() const; + void setPosition(const LtsUtils::QPoint3D& pos) + { + m_position = pos; + } - bool positionValid() const { return !std::isnan(m_position.x()) && !std::isnan(m_position.y()); } - const LtsUtils::QPoint3D &position() const { return m_position; } - QPointF pos2d() const { return QPointF(m_position.x(), m_position.y()); } - void setPosition(const LtsUtils::QPoint3D &pos) { m_position = pos; } + void hide(); + void show(); - + bool isVisible() const + { + return m_visible; + } - void hide(); + void setVisible(bool visibility = true); - + void setDeleted() + { + m_deleted = true; + } - void show(); + bool isDeleted() const + { + return m_deleted; + } - + protected: + NGL::INGLLogger& m_logger; + QStringList m_path; + QJsonObject m_detailData; - bool isVisible() const { return m_visible; } + LtsUtils::QPoint3D m_position; + EventPaintFunc m_paintFunc = nullptr; + LtsSession::LtsSession* m_session = nullptr; + QColor m_eventColor; + qint64 m_startTime = -1; + qint64 m_endTime = -1; + mutable qint64 m_duration = -1; - + int m_uniqueId = -1; + int m_typeId = -1; + int m_subEventId = -1; + int m_playerId = -1; + int m_partyId = -1; + int m_equipmentId = -1; + bool m_deleted = false; + bool m_visible = false; - void setVisible(bool visibility = true); - - void setDeleted() { m_deleted = true; } - - bool isDeleted() const { return m_deleted; } - - -protected: - - -NGL::INGLLogger &m_logger; - QStringList m_path; - QJsonObject m_detailData; - - LtsUtils::QPoint3D m_position; - EventPaintFunc m_paintFunc = nullptr; - LtsSession::LtsSession *m_session = nullptr; - QColor m_eventColor; - qint64 m_startTime = -1; - qint64 m_endTime = -1; - mutable qint64 m_duration = -1; - - - int m_uniqueId = -1; - int m_typeId = -1; - int m_subEventId = -1; - int m_playerId = -1; - int m_partyId = -1; - int m_equipmentId = -1; - bool m_deleted = false; - bool m_visible = false; - -private: - - - static bool checkDuration(); + private: + static bool checkDuration(); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.cpp old mode 100755 new mode 100644 index 11929c6a2..63baa8f64 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.cpp @@ -1,62 +1,55 @@  - #include "EventDelegate.h" + #include "PassiveEventContainer.h" -#include - #include - +#include namespace LtsTimelineClassic { -EventDelegate::EventDelegate(QWidget *parent) - : QStyledItemDelegate(parent) - , m_liveTime(0) -{ +EventDelegate::EventDelegate(QWidget* parent) : QStyledItemDelegate(parent), m_liveTime(0) {} +QSize EventDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + (void)option; + (void)index; + + return QSize(50, 20); } -QSize EventDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +void EventDelegate::setKnownRanges(const QVector& knownRanges) { - (void)option; - (void)index; - - return QSize(50, 20); -} - -void EventDelegate::setKnownRanges(const QVector &knownRanges) -{ - m_knownRanges = knownRanges; + m_knownRanges = knownRanges; } void EventDelegate::setLiveTime(qint64 liveTime) { - m_liveTime = liveTime; + m_liveTime = liveTime; } -void EventDelegate::slotAddLine(int posX, qint64 time) +void EventDelegate::slotAddLine(int posX, qint64 time) { - m_lineMap.insert(posX, time); + m_lineMap.insert(posX, time); } void EventDelegate::slotResetLineList() { - m_lineMap.clear(); + m_lineMap.clear(); } -void EventDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +void EventDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { - if (index.data().canConvert()) - { - PassiveEventContainer *passiveEventContainer = qvariant_cast(index.data()); + if (index.data().canConvert()) + { + PassiveEventContainer* passiveEventContainer = qvariant_cast(index.data()); - passiveEventContainer->paint(painter, option, m_lineMap, m_knownRanges); - } - else - QStyledItemDelegate::paint(painter, option, index); + passiveEventContainer->paint(painter, option, m_lineMap, m_knownRanges); + } + else + QStyledItemDelegate::paint(painter, option, index); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.h old mode 100755 new mode 100644 index c79c2360d..ea52c56d5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventDelegate.h @@ -1,56 +1,40 @@ - #pragma once -#include - #include "AbstractTimelineModel.h" #include "Range.h" +#include #include - namespace LtsTimelineClassic { - - -class EventDelegate : public QStyledItemDelegate +class EventDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT -public: - + public: + EventDelegate(QWidget* parent = nullptr); + void setKnownRanges(const QVector& knownRanges); - EventDelegate(QWidget *parent = nullptr); - void setKnownRanges(const QVector &knownRanges); + QSize sizeHint(const QStyleOptionViewItem& option = QStyleOptionViewItem(), + const QModelIndex& index = QModelIndex()) const; - + void setLiveTime(qint64 liveTime); - QSize sizeHint(const QStyleOptionViewItem &option = QStyleOptionViewItem(), const QModelIndex &index = QModelIndex()) const; + private: + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; - void setLiveTime(qint64 liveTime); -private: - + LineMap m_lineMap; + QVector m_knownRanges; + qint64 m_liveTime; - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + public slots: - + void slotResetLineList(); - - - LineMap m_lineMap; - QVector m_knownRanges; - qint64 m_liveTime; - -public slots: - - - void slotResetLineList(); - - - - void slotAddLine(int posX, qint64 time); + void slotAddLine(int posX, qint64 time); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.cpp old mode 100755 new mode 100644 index a93a8cd71..696e589c5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.cpp @@ -1,176 +1,154 @@ - - #include "EventGraphic.h" -#include -#include -#include #include -#include -#include -#include - - #include - +#include +#include +#include +#include +#include +#include namespace LtsTimelineClassic { -EventGraphic::EventGraphic(Event *event) - : m_lowest(0) - , m_duration(-1) - , m_isMultipleEvent(false) +EventGraphic::EventGraphic(Event* event) : m_lowest(0), m_duration(-1), m_isMultipleEvent(false) { - m_eventList += event; + m_eventList += event; } - -void EventGraphic::addEvent(Event *event) +void EventGraphic::addEvent(Event* event) { - if (event == nullptr) - return; + if (event == nullptr) + return; - m_eventList += event; - m_isMultipleEvent = true; - m_lowest = 0; - m_duration = -1; + m_eventList += event; + m_isMultipleEvent = true; + m_lowest = 0; + m_duration = -1; } - -void EventGraphic::addEventList(const QVector &eventList) +void EventGraphic::addEventList(const QVector& eventList) { - if (eventList.isEmpty()) - return; + if (eventList.isEmpty()) + return; - m_eventList += eventList; - m_isMultipleEvent = true; - m_lowest = 0; - m_duration = -1; + m_eventList += eventList; + m_isMultipleEvent = true; + m_lowest = 0; + m_duration = -1; } - qint64 EventGraphic::getDuration() { - if (m_duration != -1) + if (m_duration != -1) + return m_duration; + + qint64 highestDuration = 0; + qint64 lowest = lowestTime(); + + for (Event* event : std::as_const(m_eventList)) + { + + qint64 duration = (event->startTime() - lowest) + event->duration(); + + if (duration > highestDuration) + highestDuration = duration; + } + + if (highestDuration < 0) + { + qWarning() << "duration < 0 !!" << highestDuration; + Q_ASSERT(false); + return 0; + } + + m_duration = highestDuration; return m_duration; - - qint64 highestDuration = 0; - qint64 lowest = lowestTime(); - - for (Event *event : std::as_const(m_eventList)) - { - - - - - - - qint64 duration = (event->startTime() - lowest) + event->duration(); - - if (duration > highestDuration) - highestDuration = duration; - } - - if (highestDuration < 0) - { - qWarning() << "duration < 0 !!" << highestDuration; - Q_ASSERT(false); - return 0; - } - - m_duration = highestDuration; - return m_duration; } - qint64 EventGraphic::lowestTime() const { - if (m_lowest != 0) - return m_lowest; + if (m_lowest != 0) + return m_lowest; - auto i = std::min_element(m_eventList.begin(), m_eventList.end(), [](const Event *a, const Event *b) - { - return a->startTime() < b->startTime(); - }); + auto i = std::min_element(m_eventList.begin(), m_eventList.end(), + [](const Event* a, const Event* b) { return a->startTime() < b->startTime(); }); - if (i == m_eventList.end()) - return 0; + if (i == m_eventList.end()) + return 0; - m_lowest = (*i)->startTime(); - return m_lowest; + m_lowest = (*i)->startTime(); + return m_lowest; } - bool EventGraphic::isMultipleEvent() const { - return m_isMultipleEvent; + return m_isMultipleEvent; } - -void EventGraphic::drawEventGraphic(QPainter *painter, const QRect &rect) const +void EventGraphic::drawEventGraphic(QPainter* painter, const QRect& rect) const { - painter->save(); + painter->save(); - painter->setPen(QPen(QBrush(QGuiApplication::palette().text()), 1.0)); + painter->setPen(QPen(QBrush(QGuiApplication::palette().text()), 1.0)); - if (isMultipleEvent()) - Event::drawMultipleEventGraphic(painter, rect); - else - { - Event *e = m_eventList.first(); - - if (e == nullptr) + if (isMultipleEvent()) + Event::drawMultipleEventGraphic(painter, rect); + else { - painter->restore(); - return; + Event* e = m_eventList.first(); + + if (e == nullptr) + { + painter->restore(); + return; + } + + painter->setBrush(QBrush(e->getColor())); + + if (e->getPaintFunc() == nullptr) + { + painter->restore(); + return; + } + + e->getPaintFunc()(painter, rect); } - painter->setBrush(QBrush(e->getColor())); - - if (e->getPaintFunc() == nullptr) - { - painter->restore(); - return; - } - - e->getPaintFunc()(painter, rect); - } - - painter->restore(); + painter->restore(); } - -void EventGraphic::drawDurationBackground(QPainter *painter, const QRect &rect) const +void EventGraphic::drawDurationBackground(QPainter* painter, const QRect& rect) const { - painter->save(); - if (!isMultipleEvent()) - { - Event *e = m_eventList.first(); - - if (e == nullptr) + painter->save(); + if (!isMultipleEvent()) { - painter->restore(); - return; + Event* e = m_eventList.first(); + + if (e == nullptr) + { + painter->restore(); + return; + } + + painter->setBrush(QBrush(e->getColor())); + painter->setPen(QPen(QBrush(e->getColor()), 0)); + } + else + { + painter->setBrush(QBrush(QColor("white"))); } - painter->setBrush(QBrush(e->getColor())); - painter->setPen(QPen(QBrush(e->getColor()), 0)); - } - else - { - painter->setBrush(QBrush(QColor("white"))); - } + painter->drawRect(rect.adjusted(0, 0, -2, 0)); - painter->drawRect(rect.adjusted(0, 0, -2, 0)); + painter->setPen(QPen(QBrush(QGuiApplication::palette().text()), 1.0)); - painter->setPen(QPen(QBrush(QGuiApplication::palette().text()), 1.0)); - - painter->drawLine(rect.topLeft(), rect.topRight()); - painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(1, 1)); - painter->restore(); + painter->drawLine(rect.topLeft(), rect.topRight()); + painter->drawLine(rect.bottomLeft() + QPoint(0, 1), rect.bottomRight() + QPoint(1, 1)); + painter->restore(); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.h old mode 100755 new mode 100644 index b92ef62bc..a7e62a1f2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventGraphic.h @@ -1,11 +1,9 @@ - - #pragma once -#include "EventList.h" #include "Event.h" +#include "EventList.h" #include "ltstimelineclassic_export.h" namespace LtsTimelineClassic @@ -13,36 +11,36 @@ namespace LtsTimelineClassic class LTSTIMELINECLASSIC_EXPORT EventGraphic { -public: + public: + enum Action { + ACTION_LEFT_CLICKED, + ACTION_RIGHT_CLICKED, + ACTION_TOOLTIP, + }; - enum Action - { - ACTION_LEFT_CLICKED, - ACTION_RIGHT_CLICKED, - ACTION_TOOLTIP, - }; + explicit EventGraphic(Event* event); - explicit EventGraphic(Event *event); + bool isMultipleEvent() const; - bool isMultipleEvent() const; + const QVector eventList() const + { + return m_eventList; + } - const QVector eventList() const { return m_eventList; } - void addEventList(const QVector &eventList); - void addEvent(Event *event); - qint64 lowestTime() const; - qint64 getDuration(); + void addEventList(const QVector& eventList); + void addEvent(Event* event); + qint64 lowestTime() const; + qint64 getDuration(); - void drawEventGraphic(QPainter *painter, const QRect &rect) const; - void drawDurationBackground(QPainter *painter, const QRect &rect) const; + void drawEventGraphic(QPainter* painter, const QRect& rect) const; + void drawDurationBackground(QPainter* painter, const QRect& rect) const; + private: + EventList m_eventList; -private: - EventList m_eventList; - - mutable qint64 m_lowest; - mutable qint64 m_duration; - bool m_isMultipleEvent; - + mutable qint64 m_lowest; + mutable qint64 m_duration; + bool m_isMultipleEvent; }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventList.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventList.h old mode 100755 new mode 100644 index bb76db606..492be33e1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventList.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventList.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,9 +8,9 @@ namespace LtsTimelineClassic { class Event; -using EventList = QVector; +using EventList = QVector; class EventGraphic; -using EventGraphicList = QVector; +using EventGraphicList = QVector; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.cpp old mode 100755 new mode 100644 index 61fd7415a..aa13cb8ab --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.cpp @@ -1,27 +1,26 @@ - #include "EventTools.h" -#include "EventGraphic.h" + #include "Event.h" +#include "EventGraphic.h" #include -#include -#include #include - +#include +#include namespace LtsTimelineClassic { -#define logger NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Timeline.EventTools") +#define logger NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Timeline.EventTools") #ifdef LTS_DEBUG #endif #ifdef VERBOSE - #define dbg_print(x) qWarning() << #x << x +#define dbg_print(x) qWarning() << #x << x #else - #define dbg_print(x) (void)x; +#define dbg_print(x) (void)x; #endif qint64 EventTools::s_minAdjusted = 0; @@ -30,391 +29,371 @@ qint64 EventTools::s_minTimeline = 0; qint64 EventTools::s_maxTimeline = 1; qint64 EventTools::s_sbPos = 0; qint64 EventTools::s_zoomFactor = 1; -int EventTools::s_paintMin = 0; -int EventTools::s_paintDiff = 0; -bool EventTools::s_isValid = false; +int EventTools::s_paintMin = 0; +int EventTools::s_paintDiff = 0; +bool EventTools::s_isValid = false; qint64 EventTools::s_diff = 0; -int EventTools::s_sectionHeight = 0; -int EventTools::s_test = 0; +int EventTools::s_sectionHeight = 0; +int EventTools::s_test = 0; qint64 EventTools::s_blockSizeTime = 0; -bool EventTools::s_inUse = false; - - - +bool EventTools::s_inUse = false; void EventTools::setValues(const qint64 min, const qint64 max, const qint64 sbPos, const qint64 zoomFactor) { - if (s_minTimeline == min && s_maxTimeline == max && s_sbPos == sbPos && s_zoomFactor == zoomFactor) - return; + if (s_minTimeline == min && s_maxTimeline == max && s_sbPos == sbPos && s_zoomFactor == zoomFactor) + return; - s_sbPos = sbPos; - s_zoomFactor = zoomFactor; + s_sbPos = sbPos; + s_zoomFactor = zoomFactor; - - + s_isValid = false; - s_isValid = false; + s_minAdjusted = s_sbPos; - s_minAdjusted = s_sbPos; + double d_max = s_minAdjusted; + d_max += s_zoomFactor; - double d_max = s_minAdjusted; - d_max += s_zoomFactor; + s_maxAdjusted = d_max; + s_diff = s_maxAdjusted - s_minAdjusted; - s_maxAdjusted = d_max; - s_diff = s_maxAdjusted - s_minAdjusted; + s_minTimeline = min; + s_maxTimeline = max - EventTools::s_diff + (EventTools::getBlockSizeTime() * 2); - s_minTimeline = min; - s_maxTimeline = max - EventTools::s_diff + (EventTools::getBlockSizeTime() * 2); + recalcBlockSizeTime(); - recalcBlockSizeTime(); - - if (min > 0 && max > 1) - { - s_isValid = true; - - - } - else - { - - } + if (min > 0 && max > 1) + { + s_isValid = true; + } + else + { + } #ifdef VERBOSE - qWarning() << "\r\n\r\nEventTools::setValues: " << "\r\n" - << "s_sbPos" << s_sbPos << "\r\n" - << "s_zoomFactor" << s_zoomFactor << "\r\n" - << "s_minTimeline" << s_minTimeline << "\r\n" - << "s_maxTimeline" << s_maxTimeline << "\r\n" - << "s_isValid" << s_isValid << "\r\n" - << "s_minAdjusted" << s_minAdjusted << "\r\n" - << "s_maxAdjusted" << (long)s_maxAdjusted << "\r\n" - << "s_diff" << s_diff << "\r\n" - ; + qWarning() << "\r\n\r\nEventTools::setValues: " + << "\r\n" + << "s_sbPos" << s_sbPos << "\r\n" + << "s_zoomFactor" << s_zoomFactor << "\r\n" + << "s_minTimeline" << s_minTimeline << "\r\n" + << "s_maxTimeline" << s_maxTimeline << "\r\n" + << "s_isValid" << s_isValid << "\r\n" + << "s_minAdjusted" << s_minAdjusted << "\r\n" + << "s_maxAdjusted" << (long)s_maxAdjusted << "\r\n" + << "s_diff" << s_diff << "\r\n"; #endif } - void EventTools::setSection(const int x, const int length) { - s_paintMin = x; - s_paintDiff = length; - + s_paintMin = x; + s_paintDiff = length; } - bool EventTools::isValid() { #ifdef VERBOSE - if (!s_isValid) - qWarning() << "<<<< INVALID EVENT TOOLS!!"; + if (!s_isValid) + qWarning() << "<<<< INVALID EVENT TOOLS!!"; - qWarning() << "\r\nEventTools::isValid: " << "\r\n" - << "s_isValid" << s_isValid << "\r\n" - ; + qWarning() << "\r\nEventTools::isValid: " + << "\r\n" + << "s_isValid" << s_isValid << "\r\n"; #endif - return s_isValid; + return s_isValid; } qint64 EventTools::getAdjustedMin() { - if (!isValid()) - return 0; + if (!isValid()) + return 0; - return s_minAdjusted; + return s_minAdjusted; } qint64 EventTools::getAdjustedMax() { - if (!isValid()) - return 1; + if (!isValid()) + return 1; - return s_maxAdjusted; + return s_maxAdjusted; } qint64 EventTools::getTimelineMin() { - if (!isValid()) - return 0; + if (!isValid()) + return 0; - return s_minTimeline; + return s_minTimeline; } qint64 EventTools::getScrollbarPosition() { - return s_sbPos; + return s_sbPos; } qint64 EventTools::getTimelineMax() { - if (!isValid()) - return 1; + if (!isValid()) + return 1; - return s_maxTimeline; + return s_maxTimeline; } -int EventTools::getEventPosition(qint64 eventTime) +int EventTools::getEventPosition(qint64 eventTime) { - qint64 min = s_minAdjusted; - - qint64 diff = s_diff; + qint64 min = s_minAdjusted; - - + qint64 diff = s_diff; - if (diff == 0) - { + if (diff == 0) + { #ifdef VERBOSE - qWarning() << "\n\ngetEventPosition: diff == 0\n"; + qWarning() << "\n\ngetEventPosition: diff == 0\n"; #endif - return 0; - } + return 0; + } - double pDiff = s_paintDiff; - double pMin = s_paintMin; + double pDiff = s_paintDiff; + double pMin = s_paintMin; - double x1 = eventTime; - x1 -= min; - x1 /= diff; + double x1 = eventTime; + x1 -= min; + x1 /= diff; - double x2 = x1; - x2 *= pDiff; - x2 += pMin; + double x2 = x1; + x2 *= pDiff; + x2 += pMin; #ifdef VERBOSE - qWarning() << "\r\n\r\nEventTools::getEventPosition: " << "\r\n" - << "min" << min << "\r\n" - << "diff" << diff << "\r\n" - << "pDiff" << pDiff << "\r\n" - << "pMin" << pMin << "\r\n" - << (long)x1 << "[x1]" << "= (" << eventTime << "[eventTime]" << "-" << min << "[min]" << ") /" << diff << "[diff]" << "\r\n" - << (long)x2 << "[x2]" << "= (" << (long)x1 << "[x1]" << "*" << pDiff << "[pDiff]" << ") +" << pMin << "[pMin]" << "\r\n" - ; + qWarning() << "\r\n\r\nEventTools::getEventPosition: " + << "\r\n" + << "min" << min << "\r\n" + << "diff" << diff << "\r\n" + << "pDiff" << pDiff << "\r\n" + << "pMin" << pMin << "\r\n" + << (long)x1 << "[x1]" + << "= (" << eventTime << "[eventTime]" + << "-" << min << "[min]" + << ") /" << diff << "[diff]" + << "\r\n" + << (long)x2 << "[x2]" + << "= (" << (long)x1 << "[x1]" + << "*" << pDiff << "[pDiff]" + << ") +" << pMin << "[pMin]" + << "\r\n"; - dbg_print(min); + dbg_print(min); #endif - return qRound(x2); + return qRound(x2); } -qint64 EventTools::getEventTime(double eventPosition) +qint64 EventTools::getEventTime(double eventPosition) { - if (!isValid()) - { - - return 0; - } + if (!isValid()) + { - if (eventPosition > 999999) - { - - WARNING_LOG(logger) << "getEventTime: pos > 999999 => returning 0" ; - return 0; - } + return 0; + } - double min = s_minAdjusted; - double diff = s_diff; - double pDiff = s_paintDiff; + if (eventPosition > 999999) + { - if (pDiff < 1) - { - - WARNING_LOG(logger) << "getEventTime: pDiff < 1" ; - return 0; - } + WARNING_LOG(logger) << "getEventTime: pos > 999999 => returning 0"; + return 0; + } - double pMin = s_paintMin; + double min = s_minAdjusted; + double diff = s_diff; + double pDiff = s_paintDiff; - double x1 = eventPosition; - x1 -= pMin; - x1 /= pDiff; + if (pDiff < 1) + { - double x2 = x1; - x2 *= diff; - x2 += min; + WARNING_LOG(logger) << "getEventTime: pDiff < 1"; + return 0; + } - return qRound64(x2); + double pMin = s_paintMin; + + double x1 = eventPosition; + x1 -= pMin; + x1 /= pDiff; + + double x2 = x1; + x2 *= diff; + x2 += min; + + return qRound64(x2); } - -void EventTools::drawMarkLines(QPainter *painter, const EventList &eventList, int viewHeight) +void EventTools::drawMarkLines(QPainter* painter, const EventList& eventList, int viewHeight) { - if (!isValid()) - return; + if (!isValid()) + return; - + for (int k = 0; k < eventList.count(); k++) + { + Event* e = eventList.at(k); + int pos = getEventPosition(e->startTime()); - for (int k = 0; k < eventList.count(); k++) - { - Event *e = eventList.at(k); - int pos = getEventPosition(e->startTime()); + if (pos < (s_paintMin) || pos > (s_paintMin + s_paintDiff)) + continue; - if (pos < (s_paintMin) || pos > (s_paintMin + s_paintDiff)) - continue; - - painter->drawLine(pos, 0, pos, viewHeight); - } + painter->drawLine(pos, 0, pos, viewHeight); + } } - void EventTools::recalcBlockSizeTime() { - s_blockSizeTime = _getBlockSizeTime(); + s_blockSizeTime = _getBlockSizeTime(); } - qint64 EventTools::_getBlockSizeTime() { - - int startPos = getEventPosition(s_minAdjusted); - int endPos = getEventPosition(s_maxAdjusted); - int posDiff = endPos - startPos; + int startPos = getEventPosition(s_minAdjusted); + int endPos = getEventPosition(s_maxAdjusted); - if (posDiff < 1) - { - - return 0; - } + int posDiff = endPos - startPos; - qint64 diff = s_maxAdjusted - s_minAdjusted; + if (posDiff < 1) + { - double pixelWidthInSeconds = diff; - pixelWidthInSeconds /= posDiff; + return 0; + } - int eventGraphicsWidth = eventWidth(); - qint64 result = eventGraphicsWidth; result *= pixelWidthInSeconds; + qint64 diff = s_maxAdjusted - s_minAdjusted; - #ifdef VERBOSE - qWarning() << "\r\n\r\nEventTools::recalcBlockSizeTime: " << "\r\n" - << "minAdj" << s_minAdjusted << "\r\n" - << "maxAdj" << s_maxAdjusted << "\r\n" - << "endPos" << endPos << "\r\n" - << "diff" << diff << "\r\n" - << "pixelWidthInSeconds" << pixelWidthInSeconds << "\r\n" - << "eventGraphicsWidth" << eventGraphicsWidth << "\r\n" - << "result" << result << "\r\n" - << "(duration > result) ?" << (duration > result) - ; - #endif + double pixelWidthInSeconds = diff; + pixelWidthInSeconds /= posDiff; - return result; + int eventGraphicsWidth = eventWidth(); + qint64 result = eventGraphicsWidth; + result *= pixelWidthInSeconds; + +#ifdef VERBOSE + qWarning() << "\r\n\r\nEventTools::recalcBlockSizeTime: " + << "\r\n" + << "minAdj" << s_minAdjusted << "\r\n" + << "maxAdj" << s_maxAdjusted << "\r\n" + << "endPos" << endPos << "\r\n" + << "diff" << diff << "\r\n" + << "pixelWidthInSeconds" << pixelWidthInSeconds << "\r\n" + << "eventGraphicsWidth" << eventGraphicsWidth << "\r\n" + << "result" << result << "\r\n" + << "(duration > result) ?" << (duration > result); +#endif + + return result; } - qint64 EventTools::getBlockSizeTime(qint64 duration) { - if (duration < s_blockSizeTime) - return s_blockSizeTime; - else - return duration; -} - - -void EventTools::drawEvents(QPainter *painter, const EventGraphicList &eventGraphicList, const int verticalPosition ) -{ - painter->save(); - - - painter->setClipping(true); - painter->setClipRect(QRect(s_paintMin, verticalPosition, s_paintDiff, s_sectionHeight)); - - - for (int i = 0; i < eventGraphicList.count(); i++) - { - EventGraphic *eg = eventGraphicList.at(i); - - if (!eg) - { - - - continue; - } - - qint64 eventStart = eg->lowestTime(); - - if (eventStart == 0) - continue; - - - -#ifdef VERBOSE - qWarning() << "\r\n\r\nEventTools::drawEvents" << "\r\n" - << "eventStart" << eventStart << "\r\n"; -#endif - - qint64 eventDuration = eg->getDuration(); - - int newEventPosition = getEventPosition(eventStart); - - int newEventEndPosition = 0; - int finalEventEndPos = 0; - - int eventGraphicsWidth = eventWidth(); - - if (eventDuration > 1) - { - qint64 eventPosition = eventStart; - eventPosition += eventDuration; - newEventEndPosition = getEventPosition(eventPosition); - finalEventEndPos = GetEndPos(newEventEndPosition, eventGraphicsWidth); - } + if (duration < s_blockSizeTime) + return s_blockSizeTime; else - { - newEventEndPosition = newEventPosition; - } - - - if (newEventPosition + (newEventEndPosition - newEventPosition) < ((-eventGraphicsWidth) + s_paintMin) || - newEventPosition > (s_paintMin + s_paintDiff)) - { -#ifdef VERBOSE - qWarning() << "\n\ndrawEvents: boundary check result was negative\n" << - " newEventPosition=" << newEventPosition << "\n" << - " newEventEndPosition=" << newEventPosition << "\n" << - " eventGraphicsWidth=" << eventGraphicsWidth << "\n" << - " s_paintMin=" << s_paintMin << "\n" << - " s_paintDiff=" << s_paintDiff << "\n"; -#endif - continue; - } - - - - int finalEventPos = newEventPosition; - - QRect eventGraphicRect(finalEventPos, verticalPosition + 2, eventGraphicsWidth, s_sectionHeight - 6); - - - - eg->drawEventGraphic(painter, eventGraphicRect); - -#ifdef VERBOSE - qWarning() << "drawEvents > actually draw an event at " - "x=" << eventGraphicRect.x() << " " - "y=" << eventGraphicRect.y() << " " - "eventStart=" << eventStart ; -#endif - - if (eventDuration > 1 && - (finalEventEndPos - 1) > finalEventPos) - { - QRect eventGraphicEndRect(finalEventEndPos, verticalPosition + 2, eventGraphicsWidth, s_sectionHeight - 6); - eg->drawEventGraphic(painter, eventGraphicEndRect); - - - - QRect eventWholeRect(newEventPosition + (eventGraphicsWidth / 2) - - , verticalPosition + 2 - , (newEventEndPosition - newEventPosition) - (eventGraphicsWidth) - , s_sectionHeight - 6); - - eg->drawDurationBackground(painter, eventWholeRect); - } - } - - painter->restore(); + return duration; } -} +void EventTools::drawEvents(QPainter* painter, const EventGraphicList& eventGraphicList, const int verticalPosition) +{ + painter->save(); + + painter->setClipping(true); + painter->setClipRect(QRect(s_paintMin, verticalPosition, s_paintDiff, s_sectionHeight)); + + for (int i = 0; i < eventGraphicList.count(); i++) + { + EventGraphic* eg = eventGraphicList.at(i); + + if (!eg) + { + + continue; + } + + qint64 eventStart = eg->lowestTime(); + + if (eventStart == 0) + continue; + +#ifdef VERBOSE + qWarning() << "\r\n\r\nEventTools::drawEvents" + << "\r\n" + << "eventStart" << eventStart << "\r\n"; +#endif + + qint64 eventDuration = eg->getDuration(); + + int newEventPosition = getEventPosition(eventStart); + + int newEventEndPosition = 0; + int finalEventEndPos = 0; + + int eventGraphicsWidth = eventWidth(); + + if (eventDuration > 1) + { + qint64 eventPosition = eventStart; + eventPosition += eventDuration; + newEventEndPosition = getEventPosition(eventPosition); + finalEventEndPos = GetEndPos(newEventEndPosition, eventGraphicsWidth); + } + else + { + newEventEndPosition = newEventPosition; + } + + if (newEventPosition + (newEventEndPosition - newEventPosition) < ((-eventGraphicsWidth) + s_paintMin) || + newEventPosition > (s_paintMin + s_paintDiff)) + { +#ifdef VERBOSE + qWarning() << "\n\ndrawEvents: boundary check result was negative\n" + << " newEventPosition=" << newEventPosition << "\n" + << " newEventEndPosition=" << newEventPosition << "\n" + << " eventGraphicsWidth=" << eventGraphicsWidth << "\n" + << " s_paintMin=" << s_paintMin << "\n" + << " s_paintDiff=" << s_paintDiff << "\n"; +#endif + continue; + } + + int finalEventPos = newEventPosition; + + QRect eventGraphicRect(finalEventPos, verticalPosition + 2, eventGraphicsWidth, s_sectionHeight - 6); + + eg->drawEventGraphic(painter, eventGraphicRect); + +#ifdef VERBOSE + qWarning() << "drawEvents > actually draw an event at " + "x=" + << eventGraphicRect.x() + << " " + "y=" + << eventGraphicRect.y() + << " " + "eventStart=" + << eventStart; +#endif + + if (eventDuration > 1 && (finalEventEndPos - 1) > finalEventPos) + { + QRect eventGraphicEndRect(finalEventEndPos, verticalPosition + 2, eventGraphicsWidth, s_sectionHeight - 6); + eg->drawEventGraphic(painter, eventGraphicEndRect); + + QRect eventWholeRect(newEventPosition + (eventGraphicsWidth / 2) + + , + verticalPosition + 2, (newEventEndPosition - newEventPosition) - (eventGraphicsWidth), + s_sectionHeight - 6); + + eg->drawDurationBackground(painter, eventWholeRect); + } + } + + painter->restore(); +} + +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.h old mode 100755 new mode 100644 index 3d32fcf39..70234be98 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/EventTools.h @@ -1,152 +1,108 @@ - #pragma once #include "EventList.h" - #include "ltstimelineclassic_export.h" -#include +#include #include - class QPainter; - namespace LtsTimelineClassic { - - class LTSTIMELINECLASSIC_EXPORT EventTools { - static const int s_EventTopPadding = 2; - static const int s_EventHeightPadding = -6; - static const int s_ButtonTopPadding = s_EventTopPadding + 2; - static const int s_ButtonHeightPadding = s_EventHeightPadding + 7; + static const int s_EventTopPadding = 2; + static const int s_EventHeightPadding = -6; + static const int s_ButtonTopPadding = s_EventTopPadding + 2; + static const int s_ButtonHeightPadding = s_EventHeightPadding + 7; -public: + public: + static int s_test; - static int s_test; + static qint64 fromMsecsToSeconds(qint64 msecs) + { + return (msecs / 1000); + } + static qint64 fromSecondsToMsecs(qint64 minutes) + { + return (minutes * 1000); + } - static qint64 fromMsecsToSeconds(qint64 msecs) - { - return (msecs / 1000); - } + static qint64 getBlockSizeTime(qint64 duration = 0); - static qint64 fromSecondsToMsecs(qint64 minutes) - { - return (minutes * 1000); - } + static void setValues(const qint64 min, const qint64 max, const qint64 sbPos, const qint64 zoomFactor); + static void setSection(const int x, const int length); - static qint64 getBlockSizeTime(qint64 duration = 0); + static bool isValid(); - + static bool isRelative(); - static void setValues(const qint64 min, const qint64 max, const qint64 sbPos, const qint64 zoomFactor); + static int getEventPosition(qint64 eventTime); - + static qint64 getAdjustedMin(); - + static qint64 getAdjustedMax(); + static qint64 getTimelineMin(); - static void setSection(const int x, const int length); + static qint64 getTimelineMax(); - + static qint64 getScrollbarPosition(); - static bool isValid(); + static void recalcBlockSizeTime(); - + static qint64 getEventTime(double eventPosition); - static bool isRelative(); + static void drawEvents(QPainter* painter, const EventGraphicList& eventGraphicList, const int verticalPosition); - + static void drawMarkLines(QPainter* painter, const EventList& eventList, int viewHeight); - static int getEventPosition(qint64 eventTime); + static inline int eventWidth() + { + return s_sectionHeight / 2; + } - + static inline int GetEndPos(int position, int graphicsWidth) + { - static qint64 getAdjustedMin(); + return position - graphicsWidth - 1; + } - + static inline float zoomFactor() + { + return s_zoomFactor; + } - static qint64 getAdjustedMax(); + static inline void setSectionHeight(int sectionHeight) + { + s_sectionHeight = sectionHeight; + } - + static bool s_inUse; - static qint64 getTimelineMin(); + private: + static qint64 _getBlockSizeTime(); - + static qint64 s_minAdjusted; + static qint64 s_maxAdjusted; + static qint64 s_minTimeline; + static qint64 s_maxTimeline; + static qint64 s_sbPos; + static qint64 s_zoomFactor; + static int s_paintMin; + static int s_paintDiff; + static bool s_isValid; + static int s_sectionHeight; + static qint64 s_blockSizeTime; - static qint64 getTimelineMax(); - - static qint64 getScrollbarPosition(); - - static void recalcBlockSizeTime(); - - - - static qint64 getEventTime(double eventPosition); - - - - static void drawEvents(QPainter *painter, const EventGraphicList &eventGraphicList, const int verticalPosition); - - - - static void drawMarkLines(QPainter *painter, const EventList &eventList, int viewHeight); - - - - - - - - - - - - static inline int eventWidth() - { - return s_sectionHeight / 2; - } - - - - static inline int GetEndPos(int position, int graphicsWidth) - { - - return position - graphicsWidth - 1; - } - - static inline float zoomFactor() { return s_zoomFactor; } - - static inline void setSectionHeight(int sectionHeight) { s_sectionHeight = sectionHeight; } - static bool s_inUse; - -private: - static qint64 _getBlockSizeTime(); - - - - - static qint64 s_minAdjusted; - static qint64 s_maxAdjusted; - static qint64 s_minTimeline; - static qint64 s_maxTimeline; - static qint64 s_sbPos; - static qint64 s_zoomFactor; - static int s_paintMin; - static int s_paintDiff; - static bool s_isValid; - static int s_sectionHeight; - static qint64 s_blockSizeTime; - -public: - static qint64 s_diff; + public: + static qint64 s_diff; }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.cpp old mode 100755 new mode 100644 index e28e30eba..f4ff0c41e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.cpp @@ -1,389 +1,337 @@ +#include "Item.h" + +#include "EventGraphic.h" +#include "EventTools.h" #include #include -#include "Item.h" -#include "EventTools.h" -#include "EventGraphic.h" - - #ifdef LTS_DEBUG #endif - namespace LtsTimelineClassic { -Item::Item(const QString &name, const QString &identifier) - : m_name(name) - , m_identifier(identifier) - , m_children(nullptr) - , m_parent(nullptr) - , m_pevcon(nullptr) - , m_eventListChanged(true) +Item::Item(const QString& name, const QString& identifier) + : m_name(name), m_identifier(identifier), m_children(nullptr), m_parent(nullptr), m_pevcon(nullptr), + m_eventListChanged(true) { - } - Item::~Item() { - delete m_pevcon; + delete m_pevcon; - if (m_children) - { - qDeleteAll(*m_children); - delete m_children; - } + if (m_children) + { + qDeleteAll(*m_children); + delete m_children; + } - qDeleteAll(m_eventList); + qDeleteAll(m_eventList); } - -PassiveEventContainer *Item::getPevcon() +PassiveEventContainer* Item::getPevcon() { - if (!m_pevcon) - m_pevcon = new PassiveEventContainer(m_name == QStringLiteral("Markers")); + if (!m_pevcon) + m_pevcon = new PassiveEventContainer(m_name == QStringLiteral("Markers")); - if (m_eventListChanged) - { - m_eventListChanged = false; - m_pevcon->setEventList(getEventGraphics()); - } + if (m_eventListChanged) + { + m_eventListChanged = false; + m_pevcon->setEventList(getEventGraphics()); + } - return m_pevcon; + return m_pevcon; } - const QString Item::path() const { - if (m_parent == nullptr) + if (m_parent == nullptr) + return m_name; + + return QStringLiteral("%1/%2").arg(m_parent->path(), m_name); +} + +const QString& Item::getName() const +{ return m_name; - - return QStringLiteral("%1/%2").arg(m_parent->path(), m_name); } - -const QString &Item::getName() const +Item* Item::getParent() const { - return m_name; + return m_parent; } - -Item *Item::getParent() const -{ - return m_parent; -} - - ItemList Item::getFullItemList(bool recursive) const { - ItemList il; + ItemList il; - if (m_children == nullptr) - return il; + if (m_children == nullptr) + return il; - il += *m_children; + il += *m_children; - if (!recursive) - return il; + if (!recursive) + return il; - auto end = m_children->constEnd(); - for (auto i = m_children->constBegin(); i != end; ++i) - { - il += (*i)->getFullItemList(recursive); - } - - return il; -} - - - - - - - - - - - - - - - - - -const EventGraphicList Item::getCurrentEGLFromPevcon() const -{ - if (m_pevcon == nullptr) - return EventGraphicList(); - return m_pevcon->getEventGraphicList(); -} - - -const EventGraphicList Item::getEventGraphics() const -{ - EventGraphicList egl; - EventList el = getFullEventList(true, false); - - std::sort(el.begin(), el.end(), [](const Event *a, const Event *b) - { - return a->startTime() < b->startTime(); - }); - - for (auto i1 = el.begin(); i1 != el.end(); ++i1) - { - Event *e1 = (*i1); - - if (e1->isDeleted()) - continue; - - qint64 egStart = e1->startTime(); - qint64 egEnd = egStart + EventTools::getBlockSizeTime(e1->duration()); - qint64 blockSizeTime = EventTools::getBlockSizeTime(); - bool egChanged = false; - - EventGraphic *eg = new EventGraphic(e1); - egl += eg; - - auto i2 = i1 + 1; - for (; i2 != el.end(); ++i2) + auto end = m_children->constEnd(); + for (auto i = m_children->constBegin(); i != end; ++i) { - if (egChanged) - { - egEnd = egStart + eg->getDuration(); + il += (*i)->getFullItemList(recursive); + } - if (egEnd - egStart < blockSizeTime) - egEnd = egStart + blockSizeTime; - - egChanged = false; - } - - Event *e2 = (*i2); - - if (e2->isDeleted()) - continue; - - qint64 start2 = e2->startTime(); - - if (start2 >= egStart && egEnd >= start2) - { - eg->addEvent(e2); - egChanged = true; - } - else - { - - --i2; - break; - } - } - - if (i2 == el.end()) - break; - i1 = i2; - - } - - return egl; + return il; } +const EventGraphicList Item::getCurrentEGLFromPevcon() const +{ + if (m_pevcon == nullptr) + return EventGraphicList(); + return m_pevcon->getEventGraphicList(); +} + +const EventGraphicList Item::getEventGraphics() const +{ + EventGraphicList egl; + EventList el = getFullEventList(true, false); + + std::sort(el.begin(), el.end(), [](const Event* a, const Event* b) { return a->startTime() < b->startTime(); }); + + for (auto i1 = el.begin(); i1 != el.end(); ++i1) + { + Event* e1 = (*i1); + + if (e1->isDeleted()) + continue; + + qint64 egStart = e1->startTime(); + qint64 egEnd = egStart + EventTools::getBlockSizeTime(e1->duration()); + qint64 blockSizeTime = EventTools::getBlockSizeTime(); + bool egChanged = false; + + EventGraphic* eg = new EventGraphic(e1); + egl += eg; + + auto i2 = i1 + 1; + for (; i2 != el.end(); ++i2) + { + if (egChanged) + { + egEnd = egStart + eg->getDuration(); + + if (egEnd - egStart < blockSizeTime) + egEnd = egStart + blockSizeTime; + + egChanged = false; + } + + Event* e2 = (*i2); + + if (e2->isDeleted()) + continue; + + qint64 start2 = e2->startTime(); + + if (start2 >= egStart && egEnd >= start2) + { + eg->addEvent(e2); + egChanged = true; + } + else + { + + --i2; + break; + } + } + + if (i2 == el.end()) + break; + i1 = i2; + } + + return egl; +} EventList Item::getFullEventList(bool recursive, bool getHiddenEvents) const { - EventList el; + EventList el; - if (getHiddenEvents) - { - el = m_eventList; - } - else - { - el.reserve(m_eventList.count()); - - for (Event *e : m_eventList) + if (getHiddenEvents) { - if (e == nullptr || !e->isVisible()) - continue; - - el.append(e); + el = m_eventList; } - } + else + { + el.reserve(m_eventList.count()); + + for (Event* e : m_eventList) + { + if (e == nullptr || !e->isVisible()) + continue; + + el.append(e); + } + } + + if (!m_children || !recursive) + return el; + + for (const Item* item : std::as_const(*m_children)) + el += item->getFullEventList(recursive, getHiddenEvents); - if (!m_children || !recursive) return el; - - for (const Item *item : std::as_const(*m_children)) - el += item->getFullEventList(recursive, getHiddenEvents); - - return el; } - -void Item::setParent(Item *parent) +void Item::setParent(Item* parent) { - m_parent = parent; + m_parent = parent; } - -void Item::addEvent(Event *event) +void Item::addEvent(Event* event) { - m_eventList.append(event); - setEventListChanged(); + m_eventList.append(event); + setEventListChanged(); } - void Item::setEventListChanged() { - m_eventListChanged = true; + m_eventListChanged = true; - if (m_parent != nullptr) - { - - m_parent->setEventListChanged(); - } + if (m_parent != nullptr) + { + + m_parent->setEventListChanged(); + } } - bool Item::removeEvent(int eventId) { - for (auto i = m_eventList.begin(); i != m_eventList.end(); ++i) - { - Event *event = *i; - - if (event->uniqueId() == eventId) + for (auto i = m_eventList.begin(); i != m_eventList.end(); ++i) { - m_eventList.erase(i); - setEventListChanged(); + Event* event = *i; - return true; + if (event->uniqueId() == eventId) + { + m_eventList.erase(i); + setEventListChanged(); + + return true; + } } - } - return false; + return false; } - -void Item::addItem(Item *item) +void Item::addItem(Item* item) { - if (!m_children) - m_children = new ItemList(); + if (!m_children) + m_children = new ItemList(); - item->setParent(this); - m_children->append(item); + item->setParent(this); + m_children->append(item); } - bool Item::hasVisibleEvents() const { - - if (!m_eventList.isEmpty() && - std::find_if(m_eventList.constBegin(), m_eventList.constEnd(), [](Event *e) { return e->isVisible(); }) != m_eventList.constEnd()) - return true; - - if (m_children == nullptr) - return false; + if (!m_eventList.isEmpty() && std::find_if(m_eventList.constBegin(), m_eventList.constEnd(), + [](Event* e) { return e->isVisible(); }) != m_eventList.constEnd()) + return true; - + if (m_children == nullptr) + return false; - for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) - { - Item *item = *i; - - if (item->hasVisibleEvents()) - return true; - } - - - return false; -} - - -Item *Item::child(int row) const -{ - if (m_children == nullptr) - return nullptr; - - int idx = 0; - - - for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) - { - Item *item = *i; - - if (item->hasVisibleEvents()) + for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) { - if (row == idx) - return item; - else - idx++; - } - } + Item* item = *i; - return nullptr; + if (item->hasVisibleEvents()) + return true; + } + + return false; } +Item* Item::child(int row) const +{ + if (m_children == nullptr) + return nullptr; + + int idx = 0; + + for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) + { + Item* item = *i; + + if (item->hasVisibleEvents()) + { + if (row == idx) + return item; + else + idx++; + } + } + + return nullptr; +} int Item::childCount() const { - if (m_children) - return m_children->count(); + if (m_children) + return m_children->count(); - return 0; + return 0; } - int Item::visibleChildCount() const { - if (m_children == nullptr) - return 0; + if (m_children == nullptr) + return 0; - int result = 0; + int result = 0; - for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) - { - Item *item = *i; + for (auto i = m_children->constBegin(); i != m_children->constEnd(); ++i) + { + Item* item = *i; - if (item->hasVisibleEvents()) - result++; - } + if (item->hasVisibleEvents()) + result++; + } - return result; + return result; } - -ItemList *Item::getChildren() +ItemList* Item::getChildren() { - return m_children; + return m_children; } - int Item::indexOfParent() const { - if (m_parent == nullptr || m_parent->getChildren() == nullptr) + if (m_parent == nullptr || m_parent->getChildren() == nullptr) + return -1; + + int idx = 0; + + ItemList* parentItemList = m_parent->getChildren(); + + for (auto i = parentItemList->constBegin(); i != parentItemList->constEnd(); ++i) + { + Item* item = *i; + + if (item == this) + return idx; + + idx++; + } + + Q_ASSERT(false); return -1; - - int idx = 0; - - ItemList *parentItemList = m_parent->getChildren(); - - - for (auto i = parentItemList->constBegin(); i != parentItemList->constEnd(); ++i) - { - Item *item = *i; - - if (item == this) - return idx; - - idx++; - } - - Q_ASSERT(false); - return -1; } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.h old mode 100755 new mode 100644 index e9df8c18f..f25949ba5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Item.h @@ -1,128 +1,84 @@ - #pragma once -#include "ltstimelineclassic_export.h" #include "EventList.h" #include "PassiveEventContainer.h" +#include "ltstimelineclassic_export.h" namespace LtsTimelineClassic { -class Item; -using ItemList = QList; - - +class Item; +using ItemList = QList; class LTSTIMELINECLASSIC_EXPORT Item { - -public: - - Item(const Item &) = delete; - Item &operator=(const Item &) = delete; - const EventGraphicList getEventGraphics() const; + public: + Item(const Item&) = delete; + Item& operator=(const Item&) = delete; + const EventGraphicList getEventGraphics() const; - + explicit Item(const QString& name, const QString& identifier = QString()); - explicit Item(const QString &name, const QString &identifier = QString()); + ~Item(); - + void addItem(Item* item); - ~Item(); + bool removeEvent(int eventId); - + void setEventListChanged(); - void addItem(Item *item); + const QString path() const; - bool removeEvent(int eventId); + PassiveEventContainer* getPevcon(); - void setEventListChanged(); + const EventGraphicList getCurrentEGLFromPevcon() const; - const QString path() const; + void setParent(Item* parent); - + const QString& getName() const; - + void setName(const QString& name) + { + m_name = name; + } - + const QString& getIdentifier() const + { + return m_identifier; + } - PassiveEventContainer *getPevcon(); + ItemList* getChildren(); - const EventGraphicList getCurrentEGLFromPevcon() const; + Item* getParent() const; - + void addEvent(Event* event); + EventList getFullEventList(bool recursive = true, bool getHiddenEvents = false) const; - + ItemList getFullItemList(bool recursive = true) const; - void setParent(Item *parent); + Item* child(int row) const; - + int indexOfParent() const; - const QString &getName() const; + int childCount() const; - void setName(const QString &name) { m_name = name; } + int visibleChildCount() const; - const QString &getIdentifier() const { return m_identifier; } + bool hasVisibleEvents() const; - + private: + QString m_name; + QString m_identifier; + ItemList* m_children; + Item* m_parent; + PassiveEventContainer* m_pevcon; + EventList m_eventList; - ItemList *getChildren(); - - - - - - - - Item *getParent() const; - - - - void addEvent(Event *event); - - - - EventList getFullEventList(bool recursive = true, bool getHiddenEvents = false) const; - - - - ItemList getFullItemList(bool recursive = true) const; - - - - Item *child(int row) const; - - - - int indexOfParent() const; - - - - - - - int childCount() const; - - int visibleChildCount() const; - - bool hasVisibleEvents() const; - - - -private: - QString m_name; - QString m_identifier; - ItemList *m_children; - Item *m_parent; - PassiveEventContainer *m_pevcon; - EventList m_eventList; - - - bool m_eventListChanged; + bool m_eventListChanged; }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/LineMap.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/LineMap.h old mode 100755 new mode 100644 index c97b47cd4..3e724a01b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/LineMap.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/LineMap.h @@ -1,6 +1,5 @@ - #pragma once #include diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.cpp old mode 100755 new mode 100644 index 428e0033c..ce37f2aa1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.cpp @@ -1,133 +1,99 @@ - #include "PassiveEventContainer.h" + #include "EventGraphic.h" #include "EventTools.h" +#include +#include #include #include #include #include -#include - #include #include -#include - - namespace LtsTimelineClassic { -PassiveEventContainer::PassiveEventContainer(bool ignoreKnownRanges, QObject *parent) - : QObject(parent) - , m_ignoreKnownRanges(ignoreKnownRanges) +PassiveEventContainer::PassiveEventContainer(bool ignoreKnownRanges, QObject* parent) + : QObject(parent), m_ignoreKnownRanges(ignoreKnownRanges) { - } - PassiveEventContainer::~PassiveEventContainer() { - qDeleteAll(m_eventGraphicList); + qDeleteAll(m_eventGraphicList); } - EventGraphicList PassiveEventContainer::getEventGraphicList() const { - return m_eventGraphicList; + return m_eventGraphicList; } - -void PassiveEventContainer::setEventList(const EventGraphicList &eventGraphicList) +void PassiveEventContainer::setEventList(const EventGraphicList& eventGraphicList) { - qDeleteAll(m_eventGraphicList); + qDeleteAll(m_eventGraphicList); - m_eventGraphicList = eventGraphicList; + m_eventGraphicList = eventGraphicList; } - -void PassiveEventContainer::paint(QPainter *painter, const QStyleOptionViewItem &option, const LineMap &lineMap, - const QVector &knownRanges) const +void PassiveEventContainer::paint(QPainter* painter, const QStyleOptionViewItem& option, const LineMap& lineMap, + const QVector& knownRanges) const { - EventTools::s_test++; + EventTools::s_test++; - bool alternate = option.features.testFlag(QStyleOptionViewItem::ViewItemFeature::Alternate); - const QColor bg = QColor(alternate ? QRgb(0xF6D8CE) : QRgb(0xFBF2EF)); + bool alternate = option.features.testFlag(QStyleOptionViewItem::ViewItemFeature::Alternate); + const QColor bg = QColor(alternate ? QRgb(0xF6D8CE) : QRgb(0xFBF2EF)); - QColor cachedBg(Qt::white); - if (alternate) - cachedBg = cachedBg.darker(110); + QColor cachedBg(Qt::white); + if (alternate) + cachedBg = cachedBg.darker(110); + painter->fillRect(option.rect, QBrush(bg)); - painter->fillRect(option.rect, QBrush(bg)); + int posX1 = option.rect.x(); + int posX2 = option.rect.right(); + int posY1 = option.rect.y(); + int posY2 = option.rect.bottom(); + int h = posY2 - posY1 + 1; - int posX1 = option.rect.x(); - int posX2 = option.rect.right(); - int posY1 = option.rect.y(); - int posY2 = option.rect.bottom(); - int h = posY2 - posY1 + 1; + painter->save(); + painter->setClipping(true); + painter->setClipRect(option.rect.adjusted(0, 0, 1, 1)); - painter->save(); - painter->setClipping(true); - painter->setClipRect(option.rect.adjusted(0, 0, 1, 1)); + int eventWidth = EventTools::eventWidth(); - int eventWidth = EventTools::eventWidth(); - - - if (m_ignoreKnownRanges) - { - painter->fillRect(QRect(posX1, posY1, posX2 - posX1, h), cachedBg); - } - else - { - for (const auto &range : knownRanges) + if (m_ignoreKnownRanges) { - int rangeStart = EventTools::getEventPosition(range.start); - int rangeEnd = EventTools::getEventPosition(range.end); - - - if (rangeEnd >= posX1 && rangeStart <= posX2) - painter->fillRect(QRect(rangeStart, posY1, rangeEnd - rangeStart + eventWidth + 1, h), cachedBg); + painter->fillRect(QRect(posX1, posY1, posX2 - posX1, h), cachedBg); } - } + else + { + for (const auto& range : knownRanges) + { + int rangeStart = EventTools::getEventPosition(range.start); + int rangeEnd = EventTools::getEventPosition(range.end); + if (rangeEnd >= posX1 && rangeStart <= posX2) + painter->fillRect(QRect(rangeStart, posY1, rangeEnd - rangeStart + eventWidth + 1, h), cachedBg); + } + } + painter->restore(); + for (auto i = lineMap.constBegin(); i != lineMap.constEnd(); ++i) + { + int posX = i.key(); + painter->setPen(QPen(QBrush(QGuiApplication::palette().shadow()), 1.0)); + if (posX > option.rect.x() && posX < (option.rect.x() + option.rect.width())) + painter->drawLine(posX, posY1, posX, posY2); + } - - - - - painter->restore(); - - - - - - for (auto i = lineMap.constBegin(); i != lineMap.constEnd(); ++i) - { - int posX = i.key(); - - painter->setPen(QPen(QBrush(QGuiApplication::palette().shadow()), 1.0)); - - if (posX > option.rect.x() && - posX < (option.rect.x() + option.rect.width())) - painter->drawLine(posX, posY1, posX, posY2); - } - - - - - - - - - EventTools::drawEvents(painter, m_eventGraphicList, option.rect.y()); - + EventTools::drawEvents(painter, m_eventGraphicList, option.rect.y()); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.h old mode 100755 new mode 100644 index 46dcf1fb8..8ce3973e4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/PassiveEventContainer.h @@ -1,6 +1,5 @@ - #pragma once #include "EventList.h" @@ -9,45 +8,33 @@ #include - class QPainter; class QStyleOptionViewItem; - namespace LtsTimelineClassic { - - -class PassiveEventContainer: public QObject +class PassiveEventContainer : public QObject { - Q_OBJECT + Q_OBJECT -public: - + public: + explicit PassiveEventContainer(bool ignoreKnownRanges, QObject* parent = nullptr); - explicit PassiveEventContainer(bool ignoreKnownRanges, QObject *parent = nullptr); + ~PassiveEventContainer(); - ~PassiveEventContainer(); + void paint(QPainter* painter, const QStyleOptionViewItem& option, const LineMap& lineMap, + const QVector& knownRanges) const; - + EventGraphicList getEventGraphicList() const; - void paint(QPainter *painter, const QStyleOptionViewItem &option, const LineMap &lineMap, const QVector &knownRanges) const; - - - - EventGraphicList getEventGraphicList() const; - - - - void setEventList(const EventGraphicList &eventGraphicList); - -private: - EventGraphicList m_eventGraphicList; - bool m_ignoreKnownRanges; + void setEventList(const EventGraphicList& eventGraphicList); + private: + EventGraphicList m_eventGraphicList; + bool m_ignoreKnownRanges; }; -} +} // namespace LtsTimelineClassic -Q_DECLARE_METATYPE(LtsTimelineClassic::PassiveEventContainer *) +Q_DECLARE_METATYPE(LtsTimelineClassic::PassiveEventContainer*) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Range.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Range.h old mode 100755 new mode 100644 index 8dab924a9..9635e6ee4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Range.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/Range.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,10 +8,11 @@ namespace LtsTimelineClassic { struct Range { - qint64 start = 0; - qint64 end = 0; - Range() = default; - Range(qint64 s, qint64 e) : start(s), end(e) {} + qint64 start = 0; + qint64 end = 0; + Range() = default; + + Range(qint64 s, qint64 e) : start(s), end(e) {} }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.cpp old mode 100755 new mode 100644 index 50069ed82..3af1abb88 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.cpp @@ -1,40 +1,33 @@ - - #include "TestTimelineModel.h" #include "EventGraphic.h" -#include #include - +#include namespace LtsTimelineClassic { -TestTimelineModel::TestTimelineModel() - : AbstractTimelineModel() +TestTimelineModel::TestTimelineModel() : AbstractTimelineModel() {} + +void TestTimelineModel::addTestEvent(Event* event) { - + AbstractTimelineModel::addEvent(event); } -void TestTimelineModel::addTestEvent(Event *event) +void TestTimelineModel::slotEventAction(EventGraphic* eg, int actionType) { - AbstractTimelineModel::addEvent(event); + (void)actionType; + + QString content = tr("Event count: %1").arg(QString::number(eg->eventList().count())); + + for (int i = 0; i < eg->eventList().count(); i++) + { + content += QLatin1String("\r\nTime: "); + content += QString::number(eg->eventList().at(i)->startTime()); + } } -void TestTimelineModel::slotEventAction(EventGraphic *eg, int actionType) -{ - (void)actionType; - - QString content = tr("Event count: %1").arg(QString::number(eg->eventList().count())); - - for (int i = 0; i < eg->eventList().count(); i++) - { - content += QLatin1String("\r\nTime: "); - content += QString::number(eg->eventList().at(i)->startTime()); - } -} - -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.h old mode 100755 new mode 100644 index 0ee5cd7f5..55b460000 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TestTimelineModel.h @@ -1,26 +1,23 @@ - #pragma once -#include - #include "AbstractTimelineModel.h" +#include namespace LtsTimelineClassic { class LTSTIMELINECLASSIC_EXPORT TestTimelineModel : public AbstractTimelineModel { - Q_OBJECT + Q_OBJECT -public: - TestTimelineModel(); - void addTestEvent(Event *event); + public: + TestTimelineModel(); + void addTestEvent(Event* event); - -private slots: - void slotEventAction(EventGraphic *, int); + private slots: + void slotEventAction(EventGraphic*, int); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.cpp old mode 100755 new mode 100644 index 5cb11e167..fa2393dad --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.cpp @@ -1,149 +1,138 @@ - -#include "TimelineWidget.h" #include "TimelineHeaderView.h" +#include "TimelineWidget.h" + +#include #include #include #include #include #include -#include - namespace LtsTimelineClassic { -TimelineHeaderView::TimelineHeaderView(QWidget *parent) - : QHeaderView(Qt::Horizontal, parent) - , m_posMarkTime(0) - , m_paintingRange(rect()) - , m_liveTime(0) +TimelineHeaderView::TimelineHeaderView(QWidget* parent) + : QHeaderView(Qt::Horizontal, parent), m_posMarkTime(0), m_paintingRange(rect()), m_liveTime(0) { - setSectionsClickable(true); + setSectionsClickable(true); - setStretchLastSection(true); + setStretchLastSection(true); - connect(this, &TimelineHeaderView::sectionResized, - this, &TimelineHeaderView::slotSectionResized); - + connect(this, &TimelineHeaderView::sectionResized, this, &TimelineHeaderView::slotSectionResized); } #define GET_LOGGER NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Timeline.HeaderView") void TimelineHeaderView::setPosMarkTime(qint64 time) { - m_posMarkTime = time; - refreshData(); + m_posMarkTime = time; + refreshData(); } void TimelineHeaderView::setLiveTime(qint64 time) { - m_liveTime = time; - refreshData(); + m_liveTime = time; + refreshData(); } void TimelineHeaderView::setPosMarkPos() { - - if (m_posMarkTime > 0) - { - int posMarkPos = EventTools::getEventPosition(m_posMarkTime); - emit signalSetPosMarkPos(posMarkPos); - refreshData(); - } + if (m_posMarkTime > 0) + { + int posMarkPos = EventTools::getEventPosition(m_posMarkTime); + emit signalSetPosMarkPos(posMarkPos); + refreshData(); + } } void TimelineHeaderView::refreshData() { - if (EventTools::getTimelineMin() > 0 && EventTools::getTimelineMax() > 1) - { - updateSection(1); - updateSection(0); - } + if (EventTools::getTimelineMin() > 0 && EventTools::getTimelineMax() > 1) + { + updateSection(1); + updateSection(0); + } } void TimelineHeaderView::slotSectionResized(int logicalIndex, int oldSize, int newSize) { - (void)oldSize; + (void)oldSize; - if (logicalIndex == 1) - m_paintingRange = QRect(0, 0, newSize, height()); + if (logicalIndex == 1) + m_paintingRange = QRect(0, 0, newSize, height()); - refreshData(); + refreshData(); } -void TimelineHeaderView::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const +void TimelineHeaderView::paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const { - painter->save(); - QHeaderView::paintSection(painter, rect, logicalIndex); - painter->restore(); - - - if (logicalIndex == 1) - { - int h = (rect.height() / 3); - int y = rect.height() - h; - int w = h; - - - painter->save(); - painter->setClipping(true); - - if (m_posMarkTime != 0) - { - double posMark = EventTools::getEventPosition(m_posMarkTime); - int x = + posMark; - - if (x >= sectionPosition(1)) - { - painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Inactive, QPalette::Highlight))); - painter->setBrush(QGuiApplication::palette().highlight()); - - QPolygon pol; - pol.append(QPoint(x + (-w / 2), y + 0)); - pol.append(QPoint(x + 0, y + h)); - pol.append(QPoint(x + (w / 2), y + 0)); - pol.append(QPoint(x + (-w / 2), y + 0)); - - QPainterPath path; - path.moveTo(x, y); - path.addPolygon(pol); - - painter->drawPath(path); - } - } - - - if (m_liveTime != 0) - { - int posLive = EventTools::getEventPosition(m_liveTime); - int x = posLive; - - if (x >= sectionPosition(1)) - { - painter->setPen(QPen(QColor("green"))); - painter->setBrush(QBrush(QColor("green"))); - - QPolygon pol; - pol.append(QPoint(x + (-w / 2), y + 0)); - pol.append(QPoint(x + 0, y + h)); - pol.append(QPoint(x + (w / 2), y + 0)); - pol.append(QPoint(x + (-w / 2), y + 0)); - - QPainterPath path; - path.moveTo(x, y); - path.addPolygon(pol); - - painter->drawPath(path); - } - } - + QHeaderView::paintSection(painter, rect, logicalIndex); painter->restore(); - } + + if (logicalIndex == 1) + { + int h = (rect.height() / 3); + int y = rect.height() - h; + int w = h; + + painter->save(); + painter->setClipping(true); + + if (m_posMarkTime != 0) + { + double posMark = EventTools::getEventPosition(m_posMarkTime); + int x = +posMark; + + if (x >= sectionPosition(1)) + { + painter->setPen(QPen(QGuiApplication::palette().color(QPalette::Inactive, QPalette::Highlight))); + painter->setBrush(QGuiApplication::palette().highlight()); + + QPolygon pol; + pol.append(QPoint(x + (-w / 2), y + 0)); + pol.append(QPoint(x + 0, y + h)); + pol.append(QPoint(x + (w / 2), y + 0)); + pol.append(QPoint(x + (-w / 2), y + 0)); + + QPainterPath path; + path.moveTo(x, y); + path.addPolygon(pol); + + painter->drawPath(path); + } + } + + if (m_liveTime != 0) + { + int posLive = EventTools::getEventPosition(m_liveTime); + int x = posLive; + + if (x >= sectionPosition(1)) + { + painter->setPen(QPen(QColor("green"))); + painter->setBrush(QBrush(QColor("green"))); + + QPolygon pol; + pol.append(QPoint(x + (-w / 2), y + 0)); + pol.append(QPoint(x + 0, y + h)); + pol.append(QPoint(x + (w / 2), y + 0)); + pol.append(QPoint(x + (-w / 2), y + 0)); + + QPainterPath path; + path.moveTo(x, y); + path.addPolygon(pol); + + painter->drawPath(path); + } + } + + painter->restore(); + } } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.h old mode 100755 new mode 100644 index ed9f7a695..1c8e8cdc7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineHeaderView.h @@ -1,64 +1,47 @@ - #pragma once -#include - #include "EventTools.h" #include - +#include class QPainter; namespace LtsTimelineClassic { - - class TimelineHeaderView : public QHeaderView { - Q_OBJECT + Q_OBJECT -public: - explicit TimelineHeaderView(QWidget *parent = nullptr); + public: + explicit TimelineHeaderView(QWidget* parent = nullptr); - + void refreshData(); + void setLiveTime(qint64 time); - void refreshData(); - void setLiveTime(qint64 time); + private: + qint64 m_posMarkTime; + QRect m_paintingRange; -private: - qint64 m_posMarkTime; - QRect m_paintingRange; - - qint64 m_liveTime; + qint64 m_liveTime; -protected: - + protected: + void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const; - void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const; + signals: -signals: - + void signalSetPosMarkPos(int pos); - void signalSetPosMarkPos(int pos); + public slots: -public slots: + void slotSectionResized(int logicalIndex, int oldSize, int newSize); - + void setPosMarkTime(qint64 time); - void slotSectionResized(int logicalIndex, int oldSize, int newSize); - - - - void setPosMarkTime(qint64 time); - -private: - - - - void setPosMarkPos(); + private: + void setPosMarkPos(); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.cpp old mode 100755 new mode 100644 index 1bafe2cce..1e20ecfc4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.cpp @@ -1,39 +1,34 @@ - -#include "TimelineWidget.h" #include "TimelineIndicator.h" + #include "EventTools.h" +#include "TimelineWidget.h" #include - -#include - -#include -#include +#include +#include +#include +#include #include #include +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include -#include -#include - -#include - - +#include +#include #ifdef LTS_DEBUG #endif #ifdef VERBOSE - #define dbg_print(x) qWarning() << #x << x +#define dbg_print(x) qWarning() << #x << x #else - #define dbg_print(x) (void)x; +#define dbg_print(x) (void)x; #endif namespace LtsTimelineClassic @@ -49,470 +44,410 @@ TimelineIndicator::TimelineIndicator(QWidget *parent) : QWidget(parent) , m_sectionPos(0) , m_sectionSize(0) .getNGLLogger("Timeline.Indicator")), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_timeArray.reserve(11 + 11 + 7 + 10); + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + m_timeArray.reserve(11 + 11 + 7 + 10); - m_timeArray << - - 1 << 2 << 3 << 4 << 5 << 6 << 12 << 15 << 20 << 30 << 60 << + m_timeArray << - - 1 * 60 << 2 * 60 << 3 * 60 << 4 * 60 << 5 * 60 << 6 * 60 << 12 * 60 << 15 * 60 << 20 * 60 << 30 * 60 << 60 * 60 << + 1 << 2 << 3 << 4 << 5 << 6 << 12 << 15 << 20 << 30 << 60 << - - 1 * 60 * 60 << 2 * 60 * 60 << 4 * 60 * 60 << 6 * 60 * 60 << 8 * 60 * 60 << 12 * 60 * 60 << 24 * 60 * 60 << + 1 * 60 << 2 * 60 << 3 * 60 << 4 * 60 << 5 * 60 << 6 * 60 << 12 * 60 << 15 * 60 << 20 * 60 << 30 * 60 << 60 * 60 + << - - 1 * 60 * 60 << 2 * 60 * 60 << 4 * 60 * 60 << 6 * 60 * 60 << 8 * 60 * 60 << 10 * 60 * 60 << 14 * 60 * 60 << 18 * 60 * 60 << 22 * 60 * 60 << 26 * 60 * 60 << 30 * 60 * 60; + 1 * 60 * 60 << 2 * 60 * 60 << 4 * 60 * 60 << 6 * 60 * 60 << 8 * 60 * 60 << 12 * 60 * 60 << 24 * 60 * 60 << - QHBoxLayout *centralLayout = new QHBoxLayout(); - centralLayout->setSpacing(0); + 1 * 60 * 60 << 2 * 60 * 60 << 4 * 60 * 60 << 6 * 60 * 60 << 8 * 60 * 60 << 10 * 60 * 60 << 14 * 60 * 60 + << 18 * 60 * 60 << 22 * 60 * 60 << 26 * 60 * 60 << 30 * 60 * 60; - setLayout(centralLayout); + QHBoxLayout* centralLayout = new QHBoxLayout(); + centralLayout->setSpacing(0); - m_pbZoom->setText(QLatin1String("+")); - m_pbZoom->setFixedSize(s_pbSize, s_pbSize); + setLayout(centralLayout); - m_pbUnzoom->setText(QLatin1String("-")); - m_pbUnzoom->setFixedSize(s_pbSize, s_pbSize); + m_pbZoom->setText(QLatin1String("+")); + m_pbZoom->setFixedSize(s_pbSize, s_pbSize); - - m_cbZoomLevel->addItem(tr("10 min"), 600); - m_cbZoomLevel->addItem(tr("30 min"), 1800); - m_cbZoomLevel->addItem(tr("1 h"), 3600); - m_cbZoomLevel->addItem(tr("2 h"), 7200); - m_cbZoomLevel->addItem(tr("4 h"), 14400); - m_cbZoomLevel->addItem(tr("8 h"), 28800); + m_pbUnzoom->setText(QLatin1String("-")); + m_pbUnzoom->setFixedSize(s_pbSize, s_pbSize); - m_cbZoomLevel->setCurrentIndex(0); - - m_cbZoomLevel->setFixedHeight(s_pbSize); - m_zoomFactorPoints = m_cbZoomLevel->currentData().toLongLong(); + m_cbZoomLevel->addItem(tr("10 min"), 600); + m_cbZoomLevel->addItem(tr("30 min"), 1800); + m_cbZoomLevel->addItem(tr("1 h"), 3600); + m_cbZoomLevel->addItem(tr("2 h"), 7200); + m_cbZoomLevel->addItem(tr("4 h"), 14400); + m_cbZoomLevel->addItem(tr("8 h"), 28800); - connect(m_cbZoomLevel, &QComboBox::currentTextChanged, - this, &TimelineIndicator::afterZoom); - connect(m_pbZoom, &QPushButton::clicked, - this, &TimelineIndicator::slotZoom); - connect(m_pbUnzoom, &QPushButton::clicked, - this, &TimelineIndicator::slotUnzoom); - connect(this, &TimelineIndicator::signalAddLine, - this, &TimelineIndicator::slotAddLine); - connect(this, &TimelineIndicator::signalResetLineList, - this, &TimelineIndicator::slotResetLineList); + m_cbZoomLevel->setCurrentIndex(0); - centralLayout->addWidget(m_pbZoom, 0, Qt::AlignLeft | Qt::AlignTop); - centralLayout->addWidget(m_pbUnzoom, 0, Qt::AlignLeft | Qt::AlignTop); - centralLayout->addWidget(m_cbZoomLevel, 1, Qt::AlignLeft | Qt::AlignTop); + m_cbZoomLevel->setFixedHeight(s_pbSize); + m_zoomFactorPoints = m_cbZoomLevel->currentData().toLongLong(); + connect(m_cbZoomLevel, &QComboBox::currentTextChanged, this, &TimelineIndicator::afterZoom); + connect(m_pbZoom, &QPushButton::clicked, this, &TimelineIndicator::slotZoom); + connect(m_pbUnzoom, &QPushButton::clicked, this, &TimelineIndicator::slotUnzoom); + connect(this, &TimelineIndicator::signalAddLine, this, &TimelineIndicator::slotAddLine); + connect(this, &TimelineIndicator::signalResetLineList, this, &TimelineIndicator::slotResetLineList); + centralLayout->addWidget(m_pbZoom, 0, Qt::AlignLeft | Qt::AlignTop); + centralLayout->addWidget(m_pbUnzoom, 0, Qt::AlignLeft | Qt::AlignTop); + centralLayout->addWidget(m_cbZoomLevel, 1, Qt::AlignLeft | Qt::AlignTop); - - - QFontMetrics fm(QApplication::font()); - m_currentTextHeight = fm.height(); + QFontMetrics fm(QApplication::font()); + m_currentTextHeight = fm.height(); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - m_currentTextWidth = fm.width(DTG::toString(QDateTime::currentDateTimeUtc(), DTG::Short)); + m_currentTextWidth = fm.width(DTG::toString(QDateTime::currentDateTimeUtc(), DTG::Short)); #else - m_currentTextWidth = fm.horizontalAdvance(DTG::toString(QDateTime::currentDateTimeUtc(), DTG::Short)); + m_currentTextWidth = fm.horizontalAdvance(DTG::toString(QDateTime::currentDateTimeUtc(), DTG::Short)); #endif - dbg_print(m_currentTextWidth); - - + dbg_print(m_currentTextWidth); } -TimelineIndicator::~TimelineIndicator() +TimelineIndicator::~TimelineIndicator() {} + +void TimelineIndicator::afterZoom() { - + m_zoomFactorPoints = m_cbZoomLevel->currentData().toLongLong() * 1000; + emit signalSetZoomFactor(m_zoomFactorPoints); + update(); } -void TimelineIndicator::afterZoom() -{ - m_zoomFactorPoints = m_cbZoomLevel->currentData().toLongLong() * 1000; - emit signalSetZoomFactor(m_zoomFactorPoints); - update(); -} - - void TimelineIndicator::slotZoom() { - int pos = m_cbZoomLevel->currentIndex(); + int pos = m_cbZoomLevel->currentIndex(); - if (pos == 0) - return; + if (pos == 0) + return; - m_cbZoomLevel->setCurrentIndex(pos - 1); - emit signalZoomChanged(); + m_cbZoomLevel->setCurrentIndex(pos - 1); + emit signalZoomChanged(); } void TimelineIndicator::slotUnzoom() { - int count = m_cbZoomLevel->count(); - int pos = m_cbZoomLevel->currentIndex(); + int count = m_cbZoomLevel->count(); + int pos = m_cbZoomLevel->currentIndex(); - if (pos >= count - 1) - return; + if (pos >= count - 1) + return; - m_cbZoomLevel->setCurrentIndex(pos + 1); - emit signalZoomChanged(); + m_cbZoomLevel->setCurrentIndex(pos + 1); + emit signalZoomChanged(); } -enum highestUnit -{ - HU_INVALID, - - HU_DAYS, - HU_HOURS, - HU_MINUTES, - HU_SECONDS +enum highestUnit { + HU_INVALID, + + HU_DAYS, + HU_HOURS, + HU_MINUTES, + HU_SECONDS }; void TimelineIndicator::refreshData() { #ifdef VERBOSE - qWarning() << ""; + qWarning() << ""; #endif - - - emit signalResetLineList(); + emit signalResetLineList(); #ifdef VERBOSE - qWarning() << "section x" << m_sectionPos << "length" << m_sectionSize; + qWarning() << "section x" << m_sectionPos << "length" << m_sectionSize; #endif - + double abstand = m_sectionPos + m_currentTextWidth + s_TimeTextDistanceTolerancePixels; + dbg_print(abstand); + qint64 eventTimeOfAbstand = EventTools::getEventTime(abstand); + dbg_print(eventTimeOfAbstand); + qint64 adjustedMin = EventTools::getAdjustedMin(); + dbg_print(adjustedMin); + qint64 textWidthTime = (eventTimeOfAbstand - adjustedMin); - + if (textWidthTime < 0) + { + qWarning() << "TimelineIndicator: paintEvent: textWidthTime invalid! (" << textWidthTime << ")"; + return; + } - - double abstand = m_sectionPos + m_currentTextWidth + s_TimeTextDistanceTolerancePixels; - dbg_print(abstand); + qint64 eventTime = EventTools::getEventTime(abstand); + dbg_print(eventTime); - + QDateTime textWidthDt = QDateTime::fromMSecsSinceEpoch(textWidthTime); - qint64 eventTimeOfAbstand = EventTools::getEventTime(abstand); - dbg_print(eventTimeOfAbstand); - qint64 adjustedMin = EventTools::getAdjustedMin(); - dbg_print(adjustedMin); - qint64 textWidthTime = (eventTimeOfAbstand - adjustedMin); + int days = textWidthDt.date().day() - 1; + int hours = textWidthDt.time().hour() - 1; + int minutes = textWidthDt.time().minute(); + int seconds = textWidthDt.time().second() - 1; - if (textWidthTime < 0) - { - qWarning() << "TimelineIndicator: paintEvent: textWidthTime invalid! (" << textWidthTime << ")"; - return; - } + highestUnit unit = HU_INVALID; - qint64 eventTime = EventTools::getEventTime(abstand); - dbg_print(eventTime); + if (days == 0) + if (hours == 0) + if (minutes == 0) + if (seconds == 0) + { +#ifdef VERBOSE + qWarning() << "refreshData: no lower time unit available"; +#endif + return; + } + else + { - - QDateTime textWidthDt = QDateTime::fromMSecsSinceEpoch(textWidthTime); + unit = HU_SECONDS; + } + else + { - - - int days = textWidthDt.date().day() - 1; - int hours = textWidthDt.time().hour() - 1; - int minutes = textWidthDt.time().minute(); - int seconds = textWidthDt.time().second() - 1; - - highestUnit unit = HU_INVALID; - - if (days == 0) - if (hours == 0) - if (minutes == 0) - if (seconds == 0) + unit = HU_MINUTES; + } + else { - #ifdef VERBOSE - qWarning() << "refreshData: no lower time unit available" ; - #endif - return; + + unit = HU_HOURS; + } + else + { + + unit = HU_DAYS; + } + + if (unit == HU_INVALID) + { +#ifdef VERBOSE + qWarning() << "unit == HU_INVALID"; +#endif + return; + } + + int higherValue = 0; + for (int i = 0; i < m_timeArray.size(); i++) + { + qint64 time = (m_timeArray[i] * 1000); + + if (time >= textWidthTime) + { + higherValue = time; + + break; } else { - - unit = HU_SECONDS; + continue; } - else - { - - unit = HU_MINUTES; - } - else - { - - unit = HU_HOURS; - } - else - { - - unit = HU_DAYS; - } - if (unit == HU_INVALID) - { #ifdef VERBOSE - qWarning() << "unit == HU_INVALID"; + qWarning() << "refreshData: no fitting highest unit found !"; #endif - return; - } - - int higherValue = 0; - for (int i = 0; i < m_timeArray.size(); i++) - { - qint64 time = (m_timeArray[i] * 1000); - - if (time >= textWidthTime) - { - higherValue = time; - - break; - } - else - { - continue; + return; } - - -#ifdef VERBOSE - qWarning() << "refreshData: no fitting highest unit found !" ; -#endif - return; - } - - - if (higherValue < 1) - { - - return; - } - - - - - - QDateTime minDt = QDateTime::fromMSecsSinceEpoch(adjustedMin); - dbg_print(minDt); - dbg_print(unit); - - switch (unit) - { - case HU_SECONDS: + if (higherValue < 1) { - minDt = minDt.addSecs(-(minDt.time().second())); + + return; + } + + QDateTime minDt = QDateTime::fromMSecsSinceEpoch(adjustedMin); + dbg_print(minDt); + dbg_print(unit); + + switch (unit) + { + case HU_SECONDS: { + minDt = minDt.addSecs(-(minDt.time().second())); #ifdef VERBOSE - qCritical() << "HU_SECONDS"; + qCritical() << "HU_SECONDS"; #endif - break; - } + break; + } - case HU_MINUTES: - { - minDt = minDt.addSecs(-(minDt.time().second())); - minDt = minDt.addSecs(-(minDt.time().minute() * 60)); + case HU_MINUTES: { + minDt = minDt.addSecs(-(minDt.time().second())); + minDt = minDt.addSecs(-(minDt.time().minute() * 60)); #ifdef VERBOSE - qCritical() << "HU_MINUTES"; + qCritical() << "HU_MINUTES"; #endif - break; - } + break; + } - case HU_HOURS: - { - minDt = minDt.addSecs(-(minDt.time().second())); - minDt = minDt.addSecs(-(minDt.time().minute() * 60)); - minDt = minDt.addSecs(-(minDt.time().hour() * 60 * 60)); + case HU_HOURS: { + minDt = minDt.addSecs(-(minDt.time().second())); + minDt = minDt.addSecs(-(minDt.time().minute() * 60)); + minDt = minDt.addSecs(-(minDt.time().hour() * 60 * 60)); #ifdef VERBOSE - qCritical() << "HU_HOURS"; + qCritical() << "HU_HOURS"; #endif - break; - } + break; + } - case HU_DAYS: - { - minDt = minDt.addSecs(-(minDt.time().second())); - minDt = minDt.addSecs(-(minDt.time().minute() * 60)); - minDt = minDt.addSecs(-(minDt.time().hour() * 60 * 60)); - minDt = minDt.addDays(-(minDt.date().day())); + case HU_DAYS: { + minDt = minDt.addSecs(-(minDt.time().second())); + minDt = minDt.addSecs(-(minDt.time().minute() * 60)); + minDt = minDt.addSecs(-(minDt.time().hour() * 60 * 60)); + minDt = minDt.addDays(-(minDt.date().day())); #ifdef VERBOSE - qCritical() << "HU_DAYS"; + qCritical() << "HU_DAYS"; #endif - break; - } + break; + } - default: - { + default: { #ifdef VERBOSE - qWarning() << "unit / scaling is off da charz !"; + qWarning() << "unit / scaling is off da charz !"; #endif - return; + return; + } } - } - dbg_print(minDt); + dbg_print(minDt); - - minDt = minDt.addMSecs(-higherValue); + minDt = minDt.addMSecs(-higherValue); - dbg_print(minDt); + dbg_print(minDt); - - qint64 maxTimelineView = EventTools::getAdjustedMax() + (higherValue ); - qint64 additional = textWidthTime / 2; - maxTimelineView += additional; + qint64 maxTimelineView = EventTools::getAdjustedMax() + (higherValue); + qint64 additional = textWidthTime / 2; + maxTimelineView += additional; - qint64 minTimeline = minDt.toMSecsSinceEpoch(); + qint64 minTimeline = minDt.toMSecsSinceEpoch(); - dbg_print(minTimeline); - dbg_print(maxTimelineView); - dbg_print(higherValue); + dbg_print(minTimeline); + dbg_print(maxTimelineView); + dbg_print(higherValue); - qint64 steps = (maxTimelineView - minTimeline) / higherValue; - if (steps < 0) - steps = steps * (-1); + qint64 steps = (maxTimelineView - minTimeline) / higherValue; + if (steps < 0) + steps = steps * (-1); - if (steps > 60000 || steps < 1) - { - ERROR_LOG(m_logger) << "More than 60000 ("< 60000) - break; - - currentStep++; - - int pos = EventTools::getEventPosition(indicatorTime); - dbg_print(indicatorTime); - - if (pos + (m_currentTextWidth / 4) + 1 < m_sectionPos) + if (steps > 60000 || steps < 1) { -#ifdef VERBOSE - qCritical() << "Indicator: pos" << pos << "invisible #1"; -#endif - continue; + ERROR_LOG(m_logger) << "More than 60000 (" << steps + << ") or less than 1 lines to draw. Loop will exit after 60000 lines."; } - else - if (pos - (m_currentTextWidth ) > (m_sectionPos + m_sectionSize)) + + if (steps < 1) + steps = 2; + + uint16_t currentStep = 0; + + dbg_print(steps); + + for (qint64 indicatorTime = minTimeline; indicatorTime < maxTimelineView + 1; indicatorTime += higherValue) + { + if (currentStep > 60000) + break; + + currentStep++; + + int pos = EventTools::getEventPosition(indicatorTime); + dbg_print(indicatorTime); + + if (pos + (m_currentTextWidth / 4) + 1 < m_sectionPos) + { #ifdef VERBOSE - qCritical() << "Indicator: pos" << pos << "invisible #2"; + qCritical() << "Indicator: pos" << pos << "invisible #1"; #endif - continue; - } - else - { + continue; + } + else if (pos - (m_currentTextWidth) > (m_sectionPos + m_sectionSize)) + { #ifdef VERBOSE - qCritical() << "Indicator: OKAY!! pos" << pos << "visible"; + qCritical() << "Indicator: pos" << pos << "invisible #2"; #endif + continue; + } + else + { +#ifdef VERBOSE + qCritical() << "Indicator: OKAY!! pos" << pos << "visible"; +#endif + } + + emit signalAddLine(pos, indicatorTime); } + dbg_print(currentStep); - - emit signalAddLine(pos, indicatorTime); - } + QFontMetrics fm(QApplication::font()); + m_currentTextHeight = fm.height(); - dbg_print(currentStep); - - QFontMetrics fm(QApplication::font()); - m_currentTextHeight = fm.height(); - - update(); + update(); } -void TimelineIndicator::paintEvent(QPaintEvent *) +void TimelineIndicator::paintEvent(QPaintEvent*) { - - QPainter painter(this); - painter.save(); - painter.setClipping(true); - painter.setClipRect(QRect(x() - 8 + m_sectionPos, 0, m_sectionSize, height())); + QPainter painter(this); + painter.save(); + painter.setClipping(true); + painter.setClipRect(QRect(x() - 8 + m_sectionPos, 0, m_sectionSize, height())); #ifdef VERBOSE - int textY = (height() - m_currentTextHeight - 5); + int textY = (height() - m_currentTextHeight - 5); #endif - int h = height(); + int h = height(); - for (auto i = m_lineMap.constBegin(); i != m_lineMap.constEnd(); ++i) - { - + for (auto i = m_lineMap.constBegin(); i != m_lineMap.constEnd(); ++i) + { - int pos = i.key(); - + int pos = i.key(); - painter.setPen(QPen(QColor("black"), 1.0)); - painter.drawLine(pos, m_currentTextHeight, pos, h); + painter.setPen(QPen(QColor("black"), 1.0)); + painter.drawLine(pos, m_currentTextHeight, pos, h); - int centeredPos = pos - (m_currentTextWidth / 2); - qint64 time = (*i); + int centeredPos = pos - (m_currentTextWidth / 2); + qint64 time = (*i); - - - - painter.drawText(centeredPos, (m_currentTextHeight / 2) + 4, - DTG::toStringMSec(time, DTG::Short)); + painter.drawText(centeredPos, (m_currentTextHeight / 2) + 4, DTG::toStringMSec(time, DTG::Short)); #ifdef VERBOSE - WARNING_LOG(m_logger) << "paintEvent: actual drawing position: x=" << centeredPos << " y=" << textY; + WARNING_LOG(m_logger) << "paintEvent: actual drawing position: x=" << centeredPos << " y=" << textY; #endif - } + } - painter.restore(); - - + painter.restore(); } void TimelineIndicator::slotSectionResized(int logicalIndex, int oldSize, int newSize) { - (void)oldSize; + (void)oldSize; - - QHeaderView *header = qobject_cast(QObject::sender()); + QHeaderView* header = qobject_cast(QObject::sender()); - if (!header) - return; + if (!header) + return; - if (logicalIndex == 1) - { - m_sectionPos = header->sectionPosition(1); - m_sectionSize = newSize; - - } + if (logicalIndex == 1) + { + m_sectionPos = header->sectionPosition(1); + m_sectionSize = newSize; + } - update(); + update(); } -void TimelineIndicator::slotAddLine(double posX, qint64 time) +void TimelineIndicator::slotAddLine(double posX, qint64 time) { #ifdef VERBOSE - qCritical() << "slotAddLine: posX" << posX << "time" << time; + qCritical() << "slotAddLine: posX" << posX << "time" << time; #endif - m_lineMap.insert(posX, time); + m_lineMap.insert(posX, time); } void TimelineIndicator::slotResetLineList() { - m_lineMap.clear(); + m_lineMap.clear(); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.h old mode 100755 new mode 100644 index ecbec61e0..4bc58f2bd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineIndicator.h @@ -1,15 +1,13 @@ - #pragma once -#include - #include "EventTools.h" #include "LineMap.h" -#include -#include -#include +#include +#include +#include +#include namespace NGL { @@ -20,92 +18,69 @@ class QPushButton; class QLabel; class QComboBox; - namespace LtsTimelineClassic { - - class TimelineIndicator : public QWidget { - Q_OBJECT + Q_OBJECT - - static const int s_TimeTextDistanceTolerancePixels = 10; - static const int s_pbSize = 18; + static const int s_TimeTextDistanceTolerancePixels = 10; + static const int s_pbSize = 18; -public: - explicit TimelineIndicator(QWidget *parent); - ~TimelineIndicator(); - qint64 zoomFactorPoints() const { return m_zoomFactorPoints * 1000; } + public: + explicit TimelineIndicator(QWidget* parent); + ~TimelineIndicator(); - + qint64 zoomFactorPoints() const + { + return m_zoomFactorPoints * 1000; + } - void refreshData(); + void refreshData(); -private: - QVector m_timeArray; - qint64 m_zoomFactorPoints; - QPushButton *m_pbZoom; - QPushButton *m_pbUnzoom; - QComboBox *m_cbZoomLevel; - int m_currentTextHeight; - int m_currentTextWidth; - LineMap m_lineMap; - int m_sectionPos; - int m_sectionSize; -protected: - + private: + QVector m_timeArray; + qint64 m_zoomFactorPoints; + QPushButton* m_pbZoom; + QPushButton* m_pbUnzoom; + QComboBox* m_cbZoomLevel; + int m_currentTextHeight; + int m_currentTextWidth; + LineMap m_lineMap; + int m_sectionPos; + int m_sectionSize; - NGL::INGLLogger &m_logger; - void paintEvent(QPaintEvent *); + protected: + NGL::INGLLogger& m_logger; + void paintEvent(QPaintEvent*); -signals: - + signals: - void signalSetTimelineRange(qint64 min, qint64 max); + void signalSetTimelineRange(qint64 min, qint64 max); - + void signalSetZoomFactor(qint64 zoomFactor); - void signalSetZoomFactor(qint64 zoomFactor); + void signalResetLineList(); - + void signalAddLine(int posX, qint64 time); - void signalResetLineList(); + void signalZoomChanged(); - + private slots: + void afterZoom(); - void signalAddLine(int posX, qint64 time); + public slots: - void signalZoomChanged(); + void slotSectionResized(int logicalIndex, int oldSize, int newSize); + void slotZoom(); -private slots: - void afterZoom(); + void slotUnzoom(); + void slotResetLineList(); -public slots: - - - - void slotSectionResized(int logicalIndex, int oldSize, int newSize); - - - - void slotZoom(); - - - - void slotUnzoom(); - - - - void slotResetLineList(); - - - - void slotAddLine(double posX, qint64 time); - + void slotAddLine(double posX, qint64 time); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.cpp old mode 100755 new mode 100644 index 935b5534b..f91cc96f8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.cpp @@ -1,393 +1,321 @@ - #include "TimelineView.h" -#include -#include "TimelineHeaderView.h" -#include "TimelineWidget.h" + #include "EventDelegate.h" #include "EventGraphic.h" +#include "TimelineHeaderView.h" +#include "TimelineWidget.h" -#include -#include #include +#include #include #include #include #include +#include +#include #include -#include - +#include namespace LtsTimelineClassic { +TimelineView::TimelineView(QWidget* parent) + : QTreeView(parent) -TimelineView::TimelineView(QWidget *parent) - : QTreeView(parent) - - , m_model(nullptr) - , m_drawCache(false) + , + m_model(nullptr), m_drawCache(false) { - m_posMarkTime = 0; + m_posMarkTime = 0; - - setAlternatingRowColors(true); - setEditTriggers(QAbstractItemView::NoEditTriggers); - setSelectionBehavior(QAbstractItemView::SelectItems); - setSelectionMode(QAbstractItemView::NoSelection); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); + setAlternatingRowColors(true); + setEditTriggers(QAbstractItemView::NoEditTriggers); + setSelectionBehavior(QAbstractItemView::SelectItems); + setSelectionMode(QAbstractItemView::NoSelection); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); } - -void TimelineView::setHeader(QHeaderView *header) +void TimelineView::setHeader(QHeaderView* header) { - if (header) - { - QTreeView::setHeader(header); - header->setMinimumSectionSize(150); - } - else - { - - } -} - - -AbstractTimelineModel *TimelineView::timelineModel() -{ - return m_model; -} - - -void TimelineView::setTimelineModel(AbstractTimelineModel *model) -{ - m_model = model; - setMouseTracking(true); - setModel(m_model); - - EventDelegate *ed = new EventDelegate(this); - - EventTools::setSectionHeight(ed->sizeHint().height()); - - setItemDelegate(ed); -} - - -EventGraphic *TimelineView::getEventOnPosition(QPoint position) -{ - position = viewport()->mapFromGlobal(position); - QModelIndex index = indexAt(position); - - if (index.isValid() && position.x() > header()->sectionSize(0)) - { - Item *item = static_cast(index.internalPointer()); - - if (!item) - return nullptr; - - qint64 curTime = EventTools::getEventTime(position.x()); - EventGraphicList egl = item->getCurrentEGLFromPevcon(); - - qint64 blockSizeTime = EventTools::getBlockSizeTime(); - - for (int i = 0; i < egl.count(); i++) + if (header) + { + QTreeView::setHeader(header); + header->setMinimumSectionSize(150); + } + else { - EventGraphic *eg = egl.at(i); - - if (!eg) - continue; - - qint64 eventStartTime = eg->lowestTime(); - - if (eventStartTime == 0) - continue; - - qint64 eventEndTime = eventStartTime; - - qint64 eglDuration = eg->getDuration(); - - if (eglDuration > blockSizeTime) - eventEndTime += eglDuration; - else - eventEndTime += blockSizeTime; - - if (curTime >= eventStartTime && curTime <= eventEndTime) - return eg; } - } - - return nullptr; } - -bool TimelineView::event(QEvent *event) +AbstractTimelineModel* TimelineView::timelineModel() { - switch (event->type()) - { - case QEvent::ToolTip: - { - + return m_model; +} - QHelpEvent *helpEvent = static_cast(event); +void TimelineView::setTimelineModel(AbstractTimelineModel* model) +{ + m_model = model; + setMouseTracking(true); + setModel(m_model); - if (!helpEvent) - return true; + EventDelegate* ed = new EventDelegate(this); - EventGraphic *eg = getEventOnPosition(helpEvent->globalPos()); + EventTools::setSectionHeight(ed->sizeHint().height()); + + setItemDelegate(ed); +} + +EventGraphic* TimelineView::getEventOnPosition(QPoint position) +{ + position = viewport()->mapFromGlobal(position); + QModelIndex index = indexAt(position); + + if (index.isValid() && position.x() > header()->sectionSize(0)) + { + Item* item = static_cast(index.internalPointer()); + + if (!item) + return nullptr; + + qint64 curTime = EventTools::getEventTime(position.x()); + EventGraphicList egl = item->getCurrentEGLFromPevcon(); + + qint64 blockSizeTime = EventTools::getBlockSizeTime(); + + for (int i = 0; i < egl.count(); i++) + { + EventGraphic* eg = egl.at(i); + + if (!eg) + continue; + + qint64 eventStartTime = eg->lowestTime(); + + if (eventStartTime == 0) + continue; + + qint64 eventEndTime = eventStartTime; + + qint64 eglDuration = eg->getDuration(); + + if (eglDuration > blockSizeTime) + eventEndTime += eglDuration; + else + eventEndTime += blockSizeTime; + + if (curTime >= eventStartTime && curTime <= eventEndTime) + return eg; + } + } + + return nullptr; +} + +bool TimelineView::event(QEvent* event) +{ + switch (event->type()) + { + case QEvent::ToolTip: { + + QHelpEvent* helpEvent = static_cast(event); + + if (!helpEvent) + return true; + + EventGraphic* eg = getEventOnPosition(helpEvent->globalPos()); + + if (!eg) + return true; + + emit signalEventAction(eg, EventGraphic::ACTION_TOOLTIP); + + return true; + } + + default: { + break; + } + } + + return QTreeView::event(event); +} + +void TimelineView::wheelEvent(QWheelEvent* event) +{ + QTreeView::wheelEvent(event); + + if (QGuiApplication::queryKeyboardModifiers() != Qt::ControlModifier) + return; + + int scrolls = event->delta() / 120; + + if (scrolls > 0) + { + for (int i = 0; i < scrolls; i++) + emit signalZoom(); + } + + if (scrolls < 0) + { + for (int i = 0; i > scrolls; i--) + emit signalUnzoom(); + } +} + +void TimelineView::mouseReleaseEvent(QMouseEvent* event) +{ + QTreeView::mouseReleaseEvent(event); + + QPoint position = event->globalPos(); + EventGraphic* eg = getEventOnPosition(position); if (!eg) - return true; + return; - emit signalEventAction(eg, EventGraphic::ACTION_TOOLTIP); + switch (event->button()) + { + case Qt::LeftButton: { + emit signalEventAction(eg, EventGraphic::ACTION_LEFT_CLICKED); + break; + } - return true; - } + case Qt::RightButton: { + emit signalEventAction(eg, EventGraphic::ACTION_RIGHT_CLICKED); + break; + } - default: - { - break; - } - } - - return QTreeView::event(event); + default: { + break; + } + } } - -void TimelineView::wheelEvent(QWheelEvent *event) +void TimelineView::slotAddLine(int posX, qint64 time) { - QTreeView::wheelEvent(event); - if (QGuiApplication::queryKeyboardModifiers() != Qt::ControlModifier) - return; - - int scrolls = event->delta() / 120; - - if (scrolls > 0) - { - for (int i = 0; i < scrolls; i++) - emit signalZoom(); - } - - if (scrolls < 0) - { - for (int i = 0; i > scrolls; i--) - emit signalUnzoom(); - } + m_lineMap.insert(posX, time); } - -void TimelineView::mouseReleaseEvent(QMouseEvent *event) -{ - QTreeView::mouseReleaseEvent(event); - - QPoint position = event->globalPos(); - EventGraphic *eg = getEventOnPosition(position); - - if (!eg) - return; - - switch (event->button()) - { - case Qt::LeftButton: - { - emit signalEventAction(eg, EventGraphic::ACTION_LEFT_CLICKED); - break; - } - - case Qt::RightButton: - { - emit signalEventAction(eg, EventGraphic::ACTION_RIGHT_CLICKED); - break; - } - - default: - { - break; - } - } -} - - -void TimelineView::slotAddLine(int posX, qint64 time) -{ - - m_lineMap.insert(posX, time); -} - - void TimelineView::slotResetLineList() { - m_lineMap.clear(); + m_lineMap.clear(); } - - - - - -void TimelineView::slotSetPosMarkTime(qint64 posMarkTime) +void TimelineView::slotSetPosMarkTime(qint64 posMarkTime) { - m_posMarkTime = posMarkTime; + m_posMarkTime = posMarkTime; - TimelineHeaderView *headerView = qobject_cast(header()); - if (headerView) - headerView->setPosMarkTime(posMarkTime); + TimelineHeaderView* headerView = qobject_cast(header()); + if (headerView) + headerView->setPosMarkTime(posMarkTime); - refreshData(); + refreshData(); } - void TimelineView::refreshData() { - update(); - viewport()->update(); + update(); + viewport()->update(); } - -void TimelineView::paintEvent(QPaintEvent *event) +void TimelineView::paintEvent(QPaintEvent* event) { - if (!m_model) - return; + if (!m_model) + return; - QWidget *viewp0rt = viewport(); + QWidget* viewp0rt = viewport(); - + QPainter painter(viewp0rt); - QPainter painter(viewp0rt); - - if (!painter.isActive()) - { - - } - - painter.save(); - - int viewPortHeight = viewp0rt->height(); - - QHeaderView *head0r = header(); - - - - int sectionPos = head0r->sectionPosition(1); - int sectionSize = head0r->sectionSize(1); - - int minSection = sectionPos; - int maxSection = minSection + sectionSize; - - - - - QRect paintRect(minSection, 0, - maxSection - minSection, height()); - painter.setClipping(true); - painter.setClipRect(paintRect); - - - - - - - - - - for (auto i = m_lineMap.constBegin(); i != m_lineMap.constEnd(); ++i) - { - int pos = i.key(); - - painter.setPen(QPen(QBrush(QGuiApplication::palette().shadow()), 1.0)); - - if (pos > minSection && - pos < maxSection) - painter.drawLine(pos, 0, pos, viewPortHeight); - else + if (!painter.isActive()) { + } + + painter.save(); + + int viewPortHeight = viewp0rt->height(); + + QHeaderView* head0r = header(); + + int sectionPos = head0r->sectionPosition(1); + int sectionSize = head0r->sectionSize(1); + + int minSection = sectionPos; + int maxSection = minSection + sectionSize; + + QRect paintRect(minSection, 0, maxSection - minSection, height()); + painter.setClipping(true); + painter.setClipRect(paintRect); + + for (auto i = m_lineMap.constBegin(); i != m_lineMap.constEnd(); ++i) + { + int pos = i.key(); + + painter.setPen(QPen(QBrush(QGuiApplication::palette().shadow()), 1.0)); + + if (pos > minSection && pos < maxSection) + painter.drawLine(pos, 0, pos, viewPortHeight); + else + { #ifdef VERBOSE - qCritical() << "out of view => pos" << pos << "min" << minSection << "max" << maxSection; + qCritical() << "out of view => pos" << pos << "min" << minSection << "max" << maxSection; #endif + } } - } + painter.restore(); + QTreeView::paintEvent(event); + painter.save(); - - painter.restore(); - QTreeView::paintEvent(event); - painter.save(); - - - - - - - - - - if (m_drawCache) - { - - painter.setPen(QPen(QBrush("gray"), 1)); - painter.setBrush(QBrush("gray")); - painter.drawRect(minSection, 0, maxSection, height()); - - - - painter.setPen(QPen(QBrush("white"), 1)); - painter.setBrush(QBrush("white")); - int h = height(); - - for (const auto &range : std::as_const(m_knownRanges)) + if (m_drawCache) { - int start = EventTools::getEventPosition(range.start); - if (start < minSection) - start = minSection; + painter.setPen(QPen(QBrush("gray"), 1)); + painter.setBrush(QBrush("gray")); + painter.drawRect(minSection, 0, maxSection, height()); - int end = EventTools::getEventPosition(range.end); + painter.setPen(QPen(QBrush("white"), 1)); + painter.setBrush(QBrush("white")); + int h = height(); - if (end > maxSection) - end = maxSection; + for (const auto& range : std::as_const(m_knownRanges)) + { + int start = EventTools::getEventPosition(range.start); - painter.drawRect(start, 0, end - start, h); + if (start < minSection) + start = minSection; + + int end = EventTools::getEventPosition(range.end); + + if (end > maxSection) + end = maxSection; + + painter.drawRect(start, 0, end - start, h); + } } - } - - - - - - - - - - - ItemList il = m_model->getRootItem()->getFullItemList(true); - for (int i = 0; i < il.count(); i++) - { - if (il.at(i)->getName() == tr("Markers")) - EventTools::drawMarkLines(&painter, il.at(i)->getFullEventList(true), height()); - } - - - - - if (m_posMarkTime > 0) - { - int posMarkPosition = EventTools::getEventPosition(m_posMarkTime); - - if (posMarkPosition > sectionPos && - posMarkPosition < sectionSize + sectionPos) + ItemList il = m_model->getRootItem()->getFullItemList(true); + for (int i = 0; i < il.count(); i++) { - painter.setPen(QPen(QGuiApplication::palette().highlight(), 1.0)); - int xpos = posMarkPosition; - painter.drawLine(xpos, 0, xpos, height()); + if (il.at(i)->getName() == tr("Markers")) + EventTools::drawMarkLines(&painter, il.at(i)->getFullEventList(true), height()); } - } - painter.restore(); + if (m_posMarkTime > 0) + { + int posMarkPosition = EventTools::getEventPosition(m_posMarkTime); - + if (posMarkPosition > sectionPos && posMarkPosition < sectionSize + sectionPos) + { + painter.setPen(QPen(QGuiApplication::palette().highlight(), 1.0)); + int xpos = posMarkPosition; + painter.drawLine(xpos, 0, xpos, height()); + } + } + + painter.restore(); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.h old mode 100755 new mode 100644 index 80b7f4678..7cd01873d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineView.h @@ -1,108 +1,72 @@ - #pragma once -#include - #include "AbstractTimelineModel.h" -#include "TimelineIndicator.h" -#include "TimelineHeaderView.h" #include "LineMap.h" #include "Range.h" +#include "TimelineHeaderView.h" +#include "TimelineIndicator.h" +#include #include - namespace LtsTimelineClassic { - class TimelineView : public QTreeView { - Q_OBJECT + Q_OBJECT -public: - + public: + explicit TimelineView(QWidget* parent); - explicit TimelineView(QWidget *parent); + EventGraphic* getEventOnPosition(QPoint position); - EventGraphic *getEventOnPosition(QPoint position); + void setTimelineModel(AbstractTimelineModel* model); - + AbstractTimelineModel* timelineModel(); - void setTimelineModel(AbstractTimelineModel *model); + void refreshData(); - + void setHeader(QHeaderView* header); - AbstractTimelineModel *timelineModel(); + void setKnownRanges(const QVector& newRanges) + { + m_knownRanges = newRanges; + } - + void setDrawCache(bool show) + { + m_drawCache = show; + } - void refreshData(); + private: + qint64 m_posMarkTime; + AbstractTimelineModel* m_model; + LineMap m_lineMap; + QVector m_knownRanges; + bool m_drawCache; - + protected: + bool event(QEvent* event) override; + void mouseReleaseEvent(QMouseEvent*) override; + void wheelEvent(QWheelEvent* event) override; - void setHeader(QHeaderView *header); + virtual void paintEvent(QPaintEvent* event) override; + public slots: - void setKnownRanges(const QVector &newRanges) - { - m_knownRanges = newRanges; - } + void slotResetLineList(); - void setDrawCache(bool show) - { - m_drawCache = show; - } + void slotAddLine(int posX, qint64 time); + void slotSetPosMarkTime(qint64 posMarkTime); -private: - qint64 m_posMarkTime; - AbstractTimelineModel *m_model; - LineMap m_lineMap; - QVector m_knownRanges; - bool m_drawCache; - - -protected: - bool event(QEvent *event) override; - void mouseReleaseEvent(QMouseEvent *) override; - void wheelEvent(QWheelEvent *event) override; - - - - - - - - - virtual void paintEvent(QPaintEvent *event) override; - - -public slots: - - - void slotResetLineList(); - - - - void slotAddLine(int posX, qint64 time); - - - - - - - - void slotSetPosMarkTime(qint64 posMarkTime); - - -signals: - - void signalEventAction(EventGraphic *eg, int); - void signalZoom(); - void signalUnzoom(); + signals: + void signalEventAction(EventGraphic* eg, int); + void signalZoom(); + void signalUnzoom(); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.cpp old mode 100755 new mode 100644 index 94eecb23f..d5f13c6be --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.cpp @@ -1,21 +1,18 @@ - #include "TimelineWidget.h" -#include "EventDelegate.h" -#include "ui_TimelineWidgetUi.h" + #include "AbstractTimelineModel.h" +#include "EventDelegate.h" #include "EventGraphic.h" +#include "ui_TimelineWidgetUi.h" #include - -#include +#include +#include #include #include -#include - -#include - +#include namespace LtsTimelineClassic { @@ -29,295 +26,251 @@ TimelineWidget::TimelineWidget(QWidget *parent) : QWidget(parent) , m_zoomFactor(1) , m_headerView(new TimelineHeaderView) , m_model(nullptr), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_timelineUi->setupUi(this); - m_timelineUi->view->setHeader(m_headerView); - m_headerView->setMinimumSectionSize(150); + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + m_timelineUi->setupUi(this); + m_timelineUi->view->setHeader(m_headerView); + m_headerView->setMinimumSectionSize(150); - m_timelineUi->scrollbar->setMouseTracking(true); - connect(m_timelineUi->scrollbar, &QScrollBar::sliderReleased, this, &TimelineWidget::scrollBarFilter2); - connect(m_timelineUi->scrollbar, &QScrollBar::actionTriggered, this, &TimelineWidget::scrollBarFilter1); + m_timelineUi->scrollbar->setMouseTracking(true); + connect(m_timelineUi->scrollbar, &QScrollBar::sliderReleased, this, &TimelineWidget::scrollBarFilter2); + connect(m_timelineUi->scrollbar, &QScrollBar::actionTriggered, this, &TimelineWidget::scrollBarFilter1); - connect(m_headerView, &QHeaderView::sectionResized, m_timelineUi->indicator, &TimelineIndicator::slotSectionResized); - connect(m_headerView, &QHeaderView::sectionResized, this, &TimelineWidget::slotSectionResized); - connect(m_timelineUi->view, &TimelineView::signalZoom, m_timelineUi->indicator, &TimelineIndicator::slotZoom); - connect(m_timelineUi->view, &TimelineView::signalUnzoom, m_timelineUi->indicator, &TimelineIndicator::slotUnzoom); + connect(m_headerView, &QHeaderView::sectionResized, m_timelineUi->indicator, + &TimelineIndicator::slotSectionResized); + connect(m_headerView, &QHeaderView::sectionResized, this, &TimelineWidget::slotSectionResized); + connect(m_timelineUi->view, &TimelineView::signalZoom, m_timelineUi->indicator, &TimelineIndicator::slotZoom); + connect(m_timelineUi->view, &TimelineView::signalUnzoom, m_timelineUi->indicator, &TimelineIndicator::slotUnzoom); - connect(m_timelineUi->view, &TimelineView::signalZoom, this, &TimelineWidget::signalZoomChanged); - connect(m_timelineUi->view, &TimelineView::signalUnzoom, this, &TimelineWidget::signalZoomChanged); + connect(m_timelineUi->view, &TimelineView::signalZoom, this, &TimelineWidget::signalZoomChanged); + connect(m_timelineUi->view, &TimelineView::signalUnzoom, this, &TimelineWidget::signalZoomChanged); - connect(m_timelineUi->indicator, &TimelineIndicator::signalZoomChanged, this, &TimelineWidget::signalZoomChanged); - connect(m_timelineUi->indicator, &TimelineIndicator::signalSetZoomFactor, this, &TimelineWidget::slotSetZoomFactor); + connect(m_timelineUi->indicator, &TimelineIndicator::signalZoomChanged, this, &TimelineWidget::signalZoomChanged); + connect(m_timelineUi->indicator, &TimelineIndicator::signalSetZoomFactor, this, &TimelineWidget::slotSetZoomFactor); - connect(m_timelineUi->view, &TimelineView::signalEventAction, - this, &TimelineWidget::signalEventAction); + connect(m_timelineUi->view, &TimelineView::signalEventAction, this, &TimelineWidget::signalEventAction); - connect(m_timelineUi->cbDrawCache, &QCheckBox::toggled, - this, [this](bool toggled) - { - m_timelineUi->view->setDrawCache(toggled); - update(); - }); + connect(m_timelineUi->cbDrawCache, &QCheckBox::toggled, this, [this](bool toggled) { + m_timelineUi->view->setDrawCache(toggled); + update(); + }); - connect(m_timelineUi->cbArm, &QCheckBox::toggled, - this, &TimelineWidget::signalArm); - connect(m_timelineUi->updateTimeline, &QPushButton::clicked, - this, &TimelineWidget::slotUpdateTimeline); + connect(m_timelineUi->cbArm, &QCheckBox::toggled, this, &TimelineWidget::signalArm); + connect(m_timelineUi->updateTimeline, &QPushButton::clicked, this, &TimelineWidget::slotUpdateTimeline); } - TimelineWidget::~TimelineWidget() { - delete m_timelineUi; + delete m_timelineUi; } - void TimelineWidget::setLiveTime(qint64 time) { - m_headerView->setLiveTime(time); + m_headerView->setLiveTime(time); - EventDelegate *ed = qobject_cast(m_timelineUi->view->itemDelegate()); - if (ed == nullptr) - { - qWarning() << "TimelineWidget::setLiveTime: ed == nullptr"; - return; - } + EventDelegate* ed = qobject_cast(m_timelineUi->view->itemDelegate()); + if (ed == nullptr) + { + qWarning() << "TimelineWidget::setLiveTime: ed == nullptr"; + return; + } - ed->setLiveTime(time); + ed->setLiveTime(time); } - void TimelineWidget::hideDebugWidget() { - m_timelineUi->debugWidget->hide(); - m_timelineUi->lbMinMax->hide(); + m_timelineUi->debugWidget->hide(); + m_timelineUi->lbMinMax->hide(); } -void TimelineWidget::knownRangesChanged(const QVector &newRanges) +void TimelineWidget::knownRangesChanged(const QVector& newRanges) { - EventDelegate *ed = qobject_cast(m_timelineUi->view->itemDelegate()); - if (ed == nullptr) - { - WARNING_LOG(m_logger) << "ed == nullptr"; - return; - } + EventDelegate* ed = qobject_cast(m_timelineUi->view->itemDelegate()); + if (ed == nullptr) + { + WARNING_LOG(m_logger) << "ed == nullptr"; + return; + } - m_timelineUi->view->setKnownRanges(newRanges); - ed->setKnownRanges(newRanges); - m_timelineUi->view->refreshData(); + m_timelineUi->view->setKnownRanges(newRanges); + ed->setKnownRanges(newRanges); + m_timelineUi->view->refreshData(); } - void TimelineWidget::setMaxPos() { - m_timelineUi->scrollbar->setValue(m_timelineUi->scrollbar->maximum()); + m_timelineUi->scrollbar->setValue(m_timelineUi->scrollbar->maximum()); } - int TimelineWidget::getMaxPos() const { - return m_timelineUi->scrollbar->maximum(); + return m_timelineUi->scrollbar->maximum(); } - int TimelineWidget::getPos() const { - return m_timelineUi->scrollbar->value(); + return m_timelineUi->scrollbar->value(); } - void TimelineWidget::setPos(qint64 pos) { - m_timelineUi->scrollbar->setValue(pos / 1000); + m_timelineUi->scrollbar->setValue(pos / 1000); } - void TimelineWidget::setPositionMarkerTime(const qint64 time) { - m_timelineUi->view->slotSetPosMarkTime(time); + m_timelineUi->view->slotSetPosMarkTime(time); } - -void TimelineWidget::slotUpdateTimeline() +void TimelineWidget::slotUpdateTimeline() { - qint64 min = m_model->lowestPositionedItem(); - qint64 max = m_model->highestPositionedItem(); + qint64 min = m_model->lowestPositionedItem(); + qint64 max = m_model->highestPositionedItem(); - if (m_timelineUi->cbMinMax->isChecked()) - { - QString minmax(QStringLiteral("%1 (%2) - %3 (%4)") - .arg(QDateTime::fromMSecsSinceEpoch(min).toString()) - .arg(min) - .arg(QDateTime::fromMSecsSinceEpoch(max).toString()) - .arg(max)); - m_timelineUi->lbMinMax->setText(minmax); - } + if (m_timelineUi->cbMinMax->isChecked()) + { + QString minmax(QStringLiteral("%1 (%2) - %3 (%4)") + .arg(QDateTime::fromMSecsSinceEpoch(min).toString()) + .arg(min) + .arg(QDateTime::fromMSecsSinceEpoch(max).toString()) + .arg(max)); + m_timelineUi->lbMinMax->setText(minmax); + } - setTimelineRange(min, max); - emit signalRangeChanged(); + setTimelineRange(min, max); + emit signalRangeChanged(); } - -void TimelineWidget::setTimelineModel(AbstractTimelineModel *model) +void TimelineWidget::setTimelineModel(AbstractTimelineModel* model) { - m_model = model; + m_model = model; - connect(m_model, &AbstractTimelineModel::dataChanged, - this, &TimelineWidget::slotRefreshData ); + connect(m_model, &AbstractTimelineModel::dataChanged, this, &TimelineWidget::slotRefreshData); - + m_timelineUi->view->setTimelineModel(m_model); - m_timelineUi->view->setTimelineModel(m_model); + connect(m_timelineUi->indicator, &TimelineIndicator::signalAddLine, m_timelineUi->view, &TimelineView::slotAddLine); + connect(m_timelineUi->indicator, &TimelineIndicator::signalResetLineList, m_timelineUi->view, + &TimelineView::slotResetLineList); - - connect(m_timelineUi->indicator, &TimelineIndicator::signalAddLine, - m_timelineUi->view, &TimelineView::slotAddLine); - connect(m_timelineUi->indicator, &TimelineIndicator::signalResetLineList, - m_timelineUi->view, &TimelineView::slotResetLineList); + EventDelegate* ed = qobject_cast(m_timelineUi->view->itemDelegate()); + if (ed != nullptr) + { + connect(m_timelineUi->indicator, &TimelineIndicator::signalAddLine, ed, &EventDelegate::slotAddLine); + connect(m_timelineUi->indicator, &TimelineIndicator::signalResetLineList, ed, + &EventDelegate::slotResetLineList); + } - EventDelegate *ed = qobject_cast(m_timelineUi->view->itemDelegate()); - if (ed != nullptr) - { - connect(m_timelineUi->indicator, &TimelineIndicator::signalAddLine, - ed, &EventDelegate::slotAddLine); - connect(m_timelineUi->indicator, &TimelineIndicator::signalResetLineList, - ed, &EventDelegate::slotResetLineList); - } + m_timelineUi->view->expandToDepth(1); - m_timelineUi->view->expandToDepth(1); + m_headerView->resizeSection(0, m_headerView->minimumSectionSize()); + m_headerView->resizeSection(1, m_headerView->minimumSectionSize()); - m_headerView->resizeSection(0, m_headerView->minimumSectionSize()); - m_headerView->resizeSection(1, m_headerView->minimumSectionSize()); - - slotSetZoomFactor(m_timelineUi->indicator->zoomFactorPoints()); + slotSetZoomFactor(m_timelineUi->indicator->zoomFactorPoints()); } - qint64 TimelineWidget::getRangeMinimum() const { - return EventTools::getAdjustedMin(); + return EventTools::getAdjustedMin(); } - qint64 TimelineWidget::getRangeMaximum() const { - return EventTools::getAdjustedMax(); + return EventTools::getAdjustedMax(); } - -void TimelineWidget::setTimelineRange(qint64 min, qint64 max) +void TimelineWidget::setTimelineRange(qint64 min, qint64 max) { - m_min = min; - m_max = max; + m_min = min; + m_max = max; - if (m_min > 0 && m_max > 2) - { - m_sbPos = EventTools::fromSecondsToMsecs(m_timelineUi->scrollbar->sliderPosition()); + if (m_min > 0 && m_max > 2) + { + m_sbPos = EventTools::fromSecondsToMsecs(m_timelineUi->scrollbar->sliderPosition()); - if (m_max <= m_min) - { - if (m_min > (10 * 60)) - m_min -= (10 * 60); - } - else - { - qint64 diff = m_max - m_min; - if (diff < (10 * 60)) - if (m_min > (10 * 60)) - m_min -= (10 * 60); + if (m_max <= m_min) + { + if (m_min > (10 * 60)) + m_min -= (10 * 60); + } + else + { + qint64 diff = m_max - m_min; + if (diff < (10 * 60)) + if (m_min > (10 * 60)) + m_min -= (10 * 60); + } + + EventTools::setValues(m_min, m_max, m_sbPos, m_zoomFactor); + + m_timelineUi->scrollbar->setRange(EventTools::fromMsecsToSeconds(EventTools::getTimelineMin()), + EventTools::fromMsecsToSeconds(EventTools::getTimelineMax())); + + if (m_sbPos < m_min) + { + m_sbPos = m_min; + + m_timelineUi->scrollbar->setSliderPosition(EventTools::fromMsecsToSeconds(m_sbPos)); + } + + int pagestep = EventTools::fromMsecsToSeconds(EventTools::s_diff); + if (pagestep < 0) + pagestep = 1; + + m_timelineUi->scrollbar->setPageStep(pagestep); + + m_timelineUi->bsz->setText(QString::number(EventTools::getBlockSizeTime())); } - - - - - - - EventTools::setValues(m_min, m_max, m_sbPos, m_zoomFactor); - - - - - m_timelineUi->scrollbar->setRange(EventTools::fromMsecsToSeconds(EventTools::getTimelineMin()), EventTools::fromMsecsToSeconds(EventTools::getTimelineMax())); - - if (m_sbPos < m_min) - { - m_sbPos = m_min; - - m_timelineUi->scrollbar->setSliderPosition(EventTools::fromMsecsToSeconds(m_sbPos)); - } - - - - int pagestep = EventTools::fromMsecsToSeconds(EventTools::s_diff); - if (pagestep < 0) - pagestep = 1; - - - m_timelineUi->scrollbar->setPageStep(pagestep); - - - - - m_timelineUi->bsz->setText(QString::number(EventTools::getBlockSizeTime())); - } - - - refreshData(); + refreshData(); } - void TimelineWidget::slotRefreshData() { - refreshData(); + refreshData(); } - void TimelineWidget::refreshData() { - m_headerView->refreshData(); - m_timelineUi->indicator->refreshData(); - m_timelineUi->view->refreshData(); + m_headerView->refreshData(); + m_timelineUi->indicator->refreshData(); + m_timelineUi->view->refreshData(); } - void TimelineWidget::slotSetZoomFactor(qint64 zoomFactor) { - m_zoomFactor = zoomFactor; - slotUpdateTimeline(); + m_zoomFactor = zoomFactor; + slotUpdateTimeline(); } - -void TimelineWidget::scrollBarFilter1(int ) +void TimelineWidget::scrollBarFilter1(int) { - scrollBarFilter2(); + scrollBarFilter2(); } - void TimelineWidget::scrollBarFilter2() { - slotUpdateTimeline(); + slotUpdateTimeline(); } - void TimelineWidget::slotSectionResized(int logicalIndex, int oldSize, int newSize) { - (void)oldSize; + (void)oldSize; - if (logicalIndex == 1) - { - int viewScrollbarWidth = m_timelineUi->view->verticalScrollBar()->width(); - m_timelineUi->scrollbar->setMinimumHeight(viewScrollbarWidth); - m_timelineUi->scrollbar->setMaximumHeight(viewScrollbarWidth); + if (logicalIndex == 1) + { + int viewScrollbarWidth = m_timelineUi->view->verticalScrollBar()->width(); + m_timelineUi->scrollbar->setMinimumHeight(viewScrollbarWidth); + m_timelineUi->scrollbar->setMaximumHeight(viewScrollbarWidth); - m_timelineUi->scrollbar->setMaximumWidth(newSize); - m_timelineUi->scrollbar->setMinimumWidth(newSize); + m_timelineUi->scrollbar->setMaximumWidth(newSize); + m_timelineUi->scrollbar->setMinimumWidth(newSize); - EventTools::setSection(m_headerView->sectionPosition(1), - newSize ); - } + EventTools::setSection(m_headerView->sectionPosition(1), newSize); + } - slotUpdateTimeline(); + slotUpdateTimeline(); } -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.h old mode 100755 new mode 100644 index c6cdc302a..0f2db920b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/TimelineWidget.h @@ -1,123 +1,86 @@ - #pragma once -#include - +#include "Range.h" #include "ltstimelineclassic_export.h" -#include "Range.h" #include - +#include #include - namespace Ui { class Timeline; } - namespace LtsTimelineClassic { class AbstractTimelineModel; class EventGraphic; class TimelineHeaderView; - - class LTSTIMELINECLASSIC_EXPORT TimelineWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - + public: + explicit TimelineWidget(QWidget* parent = nullptr); - explicit TimelineWidget(QWidget *parent = nullptr); + ~TimelineWidget(); - ~TimelineWidget(); + void setPositionMarkerTime(const qint64 time); - + qint64 getRangeMinimum() const; + qint64 getRangeMaximum() const; - void setPositionMarkerTime(const qint64 time); + void setPos(qint64 pos); + void setMaxPos(); + int getPos() const; + int getMaxPos() const; - qint64 getRangeMinimum() const; - qint64 getRangeMaximum() const; + void knownRangesChanged(const QVector& newRanges); + void hideDebugWidget(); + void setLiveTime(qint64 time); - void setPos(qint64 pos); - void setMaxPos(); - int getPos() const; - int getMaxPos() const; + private: + NGL::INGLLogger& m_logger; + void setTimelineRange(qint64 min, qint64 max); - void knownRangesChanged(const QVector &newRanges); - void hideDebugWidget(); - void setLiveTime(qint64 time); + void refreshData(); + Ui::Timeline* m_timelineUi; + qint64 m_min; + qint64 m_max; + qint64 m_sbPos; + qint64 m_zoomFactor; -private: - + TimelineHeaderView* m_headerView; + AbstractTimelineModel* m_model; - NGL::INGLLogger &m_logger; - void setTimelineRange(qint64 min, qint64 max); + signals: - void refreshData(); - Ui::Timeline *m_timelineUi; + void signalLoadNewEvents(qint64 from, qint64 to); - - qint64 m_min; - qint64 m_max; - qint64 m_sbPos; - qint64 m_zoomFactor; + void signalEventAction(EventGraphic* eg, int); + void signalRangeChanged(); + void signalArm(bool arm); + void signalZoomChanged(); - TimelineHeaderView *m_headerView; - AbstractTimelineModel *m_model; + public slots: + void scrollBarFilter1(int x); -signals: - + void scrollBarFilter2(); - void signalLoadNewEvents(qint64 from, qint64 to); + void slotSetZoomFactor(qint64 zoomFactor); - + void slotSectionResized(int logicalIndex, int oldSize, int newSize); - + void setTimelineModel(AbstractTimelineModel* model); - void signalEventAction(EventGraphic *eg, int); - void signalRangeChanged(); - void signalArm(bool arm); - void signalZoomChanged(); - - -public slots: - - - - void scrollBarFilter1(int x); - - - - void scrollBarFilter2(); - - - - void slotSetZoomFactor(qint64 zoomFactor); - - - - void slotSectionResized(int logicalIndex, int oldSize, int newSize); - - - - void setTimelineModel(AbstractTimelineModel *model); - - - - - void slotUpdateTimeline(); - - - void slotRefreshData(); + void slotUpdateTimeline(); + void slotRefreshData(); }; -} +} // namespace LtsTimelineClassic diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/main.cpp old mode 100755 new mode 100644 index 203b50ce5..05dd4bca0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsTimelineClassic/main.cpp @@ -1,82 +1,71 @@ - -#include "TimelineWidget.h" #include "TestTimelineModel.h" +#include "TimelineWidget.h" #include -#include +#include +#include +#include #include #include - +#include #include -#include -#include -#include - - -LtsTimelineClassic::TestTimelineModel *ttm; +LtsTimelineClassic::TestTimelineModel* ttm; void add(qint64 time_offset) { - qint64 time = 1505292189000; - time += time_offset; + qint64 time = 1505292189000; + time += time_offset; - ttm->addTestEvent(new LtsTimelineClassic::Event(0, (int)ProjectDataManagement::EventType_def::Hit, time, 0, 0, 0, 0, - QStringList() << QStringLiteral("Test"), - LtsTimelineClassic::Event::drawCustomEventGraphicEllipse, QColor("green"), QString())); + ttm->addTestEvent(new LtsTimelineClassic::Event( + 0, (int)ProjectDataManagement::EventType_def::Hit, time, 0, 0, 0, 0, QStringList() << QStringLiteral("Test"), + LtsTimelineClassic::Event::drawCustomEventGraphicEllipse, QColor("green"), QString())); } - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - qputenv("TDS_DEVEL", "yes, of course"); - qWarning() << "LtsTimelineClassicTest"; - NGLApplication app(argc, argv); - app.createLogger("Timeline", "log4cxx_timeline.props"); + qputenv("TDS_DEVEL", "yes, of course"); + qWarning() << "LtsTimelineClassicTest"; + NGLApplication app(argc, argv); + app.createLogger("Timeline", "log4cxx_timeline.props"); - STARTUP_LOG(app.baseLogger()); + STARTUP_LOG(app.baseLogger()); - int ret = 0; + int ret = 0; #if 1 - QWidget *widget = new QWidget(); - widget->setMinimumWidth(500); + QWidget* widget = new QWidget(); + widget->setMinimumWidth(500); - QVBoxLayout *layout = new QVBoxLayout(); - widget->setLayout(layout); + QVBoxLayout* layout = new QVBoxLayout(); + widget->setLayout(layout); - LtsTimelineClassic::TimelineWidget *timelineWidget = new LtsTimelineClassic::TimelineWidget(); - layout->addWidget(timelineWidget); + LtsTimelineClassic::TimelineWidget* timelineWidget = new LtsTimelineClassic::TimelineWidget(); + layout->addWidget(timelineWidget); - QHBoxLayout *btnLayout = new QHBoxLayout(); - QWidget *btnLayoutWidget = new QWidget(); - btnLayoutWidget->setLayout(btnLayout); - layout->addWidget(btnLayoutWidget); + QHBoxLayout* btnLayout = new QHBoxLayout(); + QWidget* btnLayoutWidget = new QWidget(); + btnLayoutWidget->setLayout(btnLayout); + layout->addWidget(btnLayoutWidget); - btnLayout->addWidget(new QPushButton(QStringLiteral("Filter"))); - btnLayout->addWidget(new QPushButton(QStringLiteral("CSV Export"))); - btnLayout->addStretch(1); + btnLayout->addWidget(new QPushButton(QStringLiteral("Filter"))); + btnLayout->addWidget(new QPushButton(QStringLiteral("CSV Export"))); + btnLayout->addStretch(1); - widget->show(); + widget->show(); - ttm = new LtsTimelineClassic::TestTimelineModel(); - timelineWidget->setTimelineModel(ttm); + ttm = new LtsTimelineClassic::TestTimelineModel(); + timelineWidget->setTimelineModel(ttm); - + add(0); + add(100 * 60 * 1000); + add(3000 * 60 * 1000); - - - add(0); - add(100 * 60 * 1000); - add(3000 * 60 * 1000); - - - - ret = app.exec(); - SHUTDOWN_LOG(app.baseLogger()); + ret = app.exec(); + SHUTDOWN_LOG(app.baseLogger()); #endif - return ret; + return ret; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp old mode 100755 new mode 100644 index 5cfd50391..fc55d9a24 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.cpp @@ -1,682 +1,652 @@ - -#include -#include -#include -#include -#include -#include -#include -#include - - #include "utils_test.h" -#include "pgarray.h" -#include "qpoint3d.h" + #include "connection.h" +#include "dds_vector.h" #include "json_object.h" -#include "sfm_bytemessage_converter.h" +#include "pgarray.h" #include "promise.h" #include "promise_examples.h" #include "qbytearray_byteaccess.h" -#include "dds_vector.h" +#include "qpoint3d.h" +#include "sfm_bytemessage_converter.h" + +#include +#include +#include +#include +#include +#include +#include +#include #define SUPPORT_QBITARRAY #include "dds_bitarray.h" -#include -#include -#include +#include #include #include - +#include +#include using namespace LtsUtils; + namespace QTest { -template <> -char *toString(const QVector &vec) +template <> char* toString(const QVector& vec) { - QStringList sl; - sl.reserve(vec.size()); - for (int i : vec) - sl += QString::number(i); - return qstrdup(sl.join(QLatin1Char(',')).toLatin1().constData()); + QStringList sl; + sl.reserve(vec.size()); + for (int i : vec) + sl += QString::number(i); + return qstrdup(sl.join(QLatin1Char(',')).toLatin1().constData()); } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) template -inline bool qCompare(const T1 &t1, const T2 &t2, const char *actual, const char *expected, - const char *file, int line) +inline bool qCompare(const T1& t1, const T2& t2, const char* actual, const char* expected, const char* file, int line) { - return compare_helper(t1 == t2, "Compared values are not the same", - toString(t1), toString(t2), actual, expected, file, line); + return compare_helper(t1 == t2, "Compared values are not the same", toString(t1), toString(t2), actual, expected, + file, line); } #endif -} +} // namespace QTest - - - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - QCoreApplication app(argc, argv); - LtsUtilsTest tc; - return QTest::qExec(&tc, argc, argv); + QCoreApplication app(argc, argv); + LtsUtilsTest tc; + return QTest::qExec(&tc, argc, argv); } - void LtsUtilsTest::test_promise() { - QVector results; + QVector results; - results.append(1); + results.append(1); - - LtsUtils::Promise p([&results](LtsUtils::ResultFunction resolve, LtsUtils::ResultFunction ) - { - results.append(4); - qDebug() << "LtsUtils Promise: Promise executed! Resolving now"; + LtsUtils::Promise p([&results](LtsUtils::ResultFunction resolve, LtsUtils::ResultFunction) { + results.append(4); + qDebug() << "LtsUtils Promise: Promise executed! Resolving now"; - resolve(QStringLiteral("hello world!")); - }); + resolve(QStringLiteral("hello world!")); + }); - results.append(2); - - bool resolved = false; - p.resolved([&resolved, &results](const QVariant &value) - { - results.append(5); - qDebug() << "LtsUtils Promise: Promise was resolved with value" << value; - resolved = true; - }); + results.append(2); - p.rejected([](const QVariant &val) - { - qCritical() << "rejected with val" << val; - QFAIL("Promise unexpectedly rejected"); - }); + bool resolved = false; + p.resolved([&resolved, &results](const QVariant& value) { + results.append(5); + qDebug() << "LtsUtils Promise: Promise was resolved with value" << value; + resolved = true; + }); - results.append(3); + p.rejected([](const QVariant& val) { + qCritical() << "rejected with val" << val; + QFAIL("Promise unexpectedly rejected"); + }); - QTRY_VERIFY2(resolved, "Promise was not resolved"); - QCOMPARE((QVector() << 1 << 2 << 3 << 4 << 5), results); + results.append(3); + + QTRY_VERIFY2(resolved, "Promise was not resolved"); + QCOMPARE((QVector() << 1 << 2 << 3 << 4 << 5), results); } - void LtsUtilsTest::test_promise_example1() { - qDebug("LtsUtils: test_promise_example1"); + qDebug("LtsUtils: test_promise_example1"); - LtsUtils::PromiseExample1 p; + LtsUtils::PromiseExample1 p; - QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); + QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); } - void LtsUtilsTest::test_promise_example2() { - qDebug("LtsUtils: test_promise_example2"); + qDebug("LtsUtils: test_promise_example2"); - LtsUtils::PromiseExample2 p; + LtsUtils::PromiseExample2 p; - QTRY_VERIFY2(p.isSuccess(), "Promise didn't reject as expected"); + QTRY_VERIFY2(p.isSuccess(), "Promise didn't reject as expected"); } - void LtsUtilsTest::test_promise_example3() { - qDebug("LtsUtils: test_promise_example3"); + qDebug("LtsUtils: test_promise_example3"); - LtsUtils::PromiseExample3 p; + LtsUtils::PromiseExample3 p; - qDebug() << "waiting for expected reject to happen, and wait 2 seconds to see if the timeout triggers even though it shouldn't, because the promise was already rejected"; + qDebug() << "waiting for expected reject to happen, and wait 2 seconds to see if the timeout triggers even though " + "it shouldn't, because the promise was already rejected"; - QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); + QTRY_VERIFY2(p.isSuccess(), "Promise was not resolved"); } - void LtsUtilsTest::test_toIntArray() { - qDebug("LtsUtils: test_toIntArray"); + qDebug("LtsUtils: test_toIntArray"); - QString str; - std::vector vec; + QString str; + std::vector vec; - str = QLatin1String("{0,1,2,3,4,999999999,-2147483647,2147483647}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 8, "Wrong size of QVector! (expected 8)"); + str = QLatin1String("{0,1,2,3,4,999999999,-2147483647,2147483647}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 8, "Wrong size of QVector! (expected 8)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == 1, "Wrong value on position 1"); - QVERIFY2(vec[2] == 2, "Wrong value on position 2"); - QVERIFY2(vec[3] == 3, "Wrong value on position 3"); - QVERIFY2(vec[4] == 4, "Wrong value on position 4"); - QVERIFY2(vec[5] == 999999999, "Wrong value on position 5"); - QVERIFY2(vec[6] == -2147483647, "Wrong vtest_fromIntArray2Dalue on position 6"); - QVERIFY2(vec[7] == 2147483647, "Wrong value on position 7"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == 1, "Wrong value on position 1"); + QVERIFY2(vec[2] == 2, "Wrong value on position 2"); + QVERIFY2(vec[3] == 3, "Wrong value on position 3"); + QVERIFY2(vec[4] == 4, "Wrong value on position 4"); + QVERIFY2(vec[5] == 999999999, "Wrong value on position 5"); + QVERIFY2(vec[6] == -2147483647, "Wrong vtest_fromIntArray2Dalue on position 6"); + QVERIFY2(vec[7] == 2147483647, "Wrong value on position 7"); - str = QLatin1String("1,2,3,"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); + str = QLatin1String("1,2,3,"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); - QVERIFY2(vec[0] == 1, "Wrong value on position 0"); - QVERIFY2(vec[1] == 2, "Wrong value on position 1"); - QVERIFY2(vec[2] == 3, "Wrong value on position 2"); + QVERIFY2(vec[0] == 1, "Wrong value on position 0"); + QVERIFY2(vec[1] == 2, "Wrong value on position 1"); + QVERIFY2(vec[2] == 3, "Wrong value on position 2"); - str = QLatin1String("{a,2,3}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); + str = QLatin1String("{a,2,3}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - str = QLatin1String("{abc}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray::fromPgString(str)(); - QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); + str = QLatin1String("{abc}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray::fromPgString(str)(); + QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); } - void LtsUtilsTest::test_fromIntArray() { - qDebug("LtsUtils: test_fromIntArray"); + qDebug("LtsUtils: test_fromIntArray"); - QString str = LtsUtils::IntArray({ 0, 1, 2, 3, 999999999, -2147483647, 2147483647 }).toPgString(); + QString str = LtsUtils::IntArray({0, 1, 2, 3, 999999999, -2147483647, 2147483647}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{0,1,2,3,999999999,-2147483647,2147483647}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{0,1,2,3,999999999,-2147483647,2147483647}")); - str = LtsUtils::IntArray(std::vector()).toPgString(); + str = LtsUtils::IntArray(std::vector()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } - void LtsUtilsTest::test_toBigintArray() { - qDebug("LtsUtils: test_toBigintArray"); + qDebug("LtsUtils: test_toBigintArray"); - QString str; - std::vector vec; + QString str; + std::vector vec; - str = QLatin1String("{0,1,2147483647,-2147483647,999999999999}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{0,1,2147483647,-2147483647,999999999999}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == 1, "Wrong value on position 1"); - QVERIFY2(vec[2] == 2147483647, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 999999999999, "Wrong value on position 4"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == 1, "Wrong value on position 1"); + QVERIFY2(vec[2] == 2147483647, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 999999999999, "Wrong value on position 4"); - str = QLatin1String("0,-2147483647,999999999999,"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); + str = QLatin1String("0,-2147483647,999999999999,"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 3, "Wrong size of QVector! (expected 3)"); - QVERIFY2(vec[0] == 0, "Wrong value on position 0"); - QVERIFY2(vec[1] == -2147483647, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); + QVERIFY2(vec[0] == 0, "Wrong value on position 0"); + QVERIFY2(vec[1] == -2147483647, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); - str = QLatin1String("{a,2,3}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); + str = QLatin1String("{a,2,3}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 2, "Wrong size of QVector! (expected 2)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - str = QLatin1String("{abc}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray::fromPgString(str)(); - QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); + str = QLatin1String("{abc}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray::fromPgString(str)(); + QVERIFY2(vec.size() == 0, "Wrong size of QVector! (expected 0)"); } - void LtsUtilsTest::test_fromBigintArray() { - qDebug("LtsUtils: test_fromBigintArray"); + qDebug("LtsUtils: test_fromBigintArray"); - QString str = LtsUtils::BigintArray({ 0, -2147483647, 2147483647, 999999999999, 123456789}).toPgString(); + QString str = LtsUtils::BigintArray({0, -2147483647, 2147483647, 999999999999, 123456789}).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{0,-2147483647,2147483647,999999999999,123456789}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{0,-2147483647,2147483647,999999999999,123456789}")); - str = LtsUtils::BigintArray(std::vector()).toPgString(); + str = LtsUtils::BigintArray(std::vector()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } - void LtsUtilsTest::test_toIntArray2D() { - qDebug("LtsUtils: test_toIntArray2D"); + qDebug("LtsUtils: test_toIntArray2D"); - QString str; - std::map vec; + QString str; + std::map vec; - str = QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647}}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::IntArray2D::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647}}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::IntArray2D::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); } - void LtsUtilsTest::test_fromIntArray2D() { - qDebug("LtsUtils: test_fromIntArray2D"); + qDebug("LtsUtils: test_fromIntArray2D"); - QString str = LtsUtils::IntArray2D({{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647},{5,123456}}).toPgString(); + QString str = LtsUtils::IntArray2D({{0, 2}, {1, 3}, {2, 999999999}, {3, -2147483647}, {4, 2147483647}, {5, 123456}}) + .toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647},{5,123456}}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{{0,2},{1,3},{2,999999999},{3,-2147483647},{4,2147483647},{5,123456}}")); - str = LtsUtils::IntArray2D(std::map()).toPgString(); + str = LtsUtils::IntArray2D(std::map()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } - void LtsUtilsTest::test_toBigintArray2D() { - qDebug("LtsUtils: test_toBigintArray2D"); + qDebug("LtsUtils: test_toBigintArray2D"); - QString str; - std::map vec; + QString str; + std::map vec; - str = QLatin1String("{{0,2},{1,3},{2,999999999999},{3,-2147483647},{4,2147483647}}"); - qDebug() << "LtsUtils: test " << str; - vec = LtsUtils::BigintArray2D::fromPgString(str)(); - QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); + str = QLatin1String("{{0,2},{1,3},{2,999999999999},{3,-2147483647},{4,2147483647}}"); + qDebug() << "LtsUtils: test " << str; + vec = LtsUtils::BigintArray2D::fromPgString(str)(); + QVERIFY2(vec.size() == 5, "Wrong size of QVector! (expected 5)"); - QVERIFY2(vec[0] == 2, "Wrong value on position 0"); - QVERIFY2(vec[1] == 3, "Wrong value on position 1"); - QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); - QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); - QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); + QVERIFY2(vec[0] == 2, "Wrong value on position 0"); + QVERIFY2(vec[1] == 3, "Wrong value on position 1"); + QVERIFY2(vec[2] == 999999999999, "Wrong value on position 2"); + QVERIFY2(vec[3] == -2147483647, "Wrong value on position 3"); + QVERIFY2(vec[4] == 2147483647, "Wrong value on position 4"); } - void LtsUtilsTest::test_fromBigintArray2D() { - qDebug("LtsUtils: test_fromBigintArray2D"); + qDebug("LtsUtils: test_fromBigintArray2D"); - QString str = LtsUtils::BigintArray2D({{0,-123456789},{1,-2147483647},{2,999999999999},{3,123456789},{4,2147483647}}).toPgString(); + QString str = + LtsUtils::BigintArray2D({{0, -123456789}, {1, -2147483647}, {2, 999999999999}, {3, 123456789}, {4, 2147483647}}) + .toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{{0,-123456789},{1,-2147483647},{2,999999999999},{3,123456789},{4,2147483647}}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{{0,-123456789},{1,-2147483647},{2,999999999999},{3,123456789},{4,2147483647}}")); - str = LtsUtils::BigintArray2D(std::map()).toPgString(); + str = LtsUtils::BigintArray2D(std::map()).toPgString(); - qDebug() << "LtsUtils: Result " << str; - QCOMPARE(str, QLatin1String("{}")); + qDebug() << "LtsUtils: Result " << str; + QCOMPARE(str, QLatin1String("{}")); } - void LtsUtilsTest::test_QPoint3D() { - qDebug("LtsUtils: test_QPoint3D"); + qDebug("LtsUtils: test_QPoint3D"); - LtsUtils::QPoint3D pos(0,0,0); + LtsUtils::QPoint3D pos(0, 0, 0); - qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; + qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; - QVERIFY2(pos.x() == 0, "Wrong position (X)"); - QVERIFY2(pos.y() == 0, "Wrong position (Y)"); - QVERIFY2(pos.z() == 0, "Wrong position (Z)"); + QVERIFY2(pos.x() == 0, "Wrong position (X)"); + QVERIFY2(pos.y() == 0, "Wrong position (Y)"); + QVERIFY2(pos.z() == 0, "Wrong position (Z)"); - pos.setX(92000); - pos.setY(77400); - pos.setZ(0); + pos.setX(92000); + pos.setY(77400); + pos.setZ(0); - qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; + qDebug() << "LstUtils: position (X,Y,Z) = (" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; - QVERIFY2(pos.x() == 92000, "Wrong position (X)"); - QVERIFY2(pos.y() == 77400, "Wrong position (Y)"); - QVERIFY2(pos.z() == 0, "Wrong position (Z)"); + QVERIFY2(pos.x() == 92000, "Wrong position (X)"); + QVERIFY2(pos.y() == 77400, "Wrong position (Y)"); + QVERIFY2(pos.z() == 0, "Wrong position (Z)"); } - - void LtsUtilsTest::test_bitArray() { - qDebug("LtsUtils: test_bitArray"); + qDebug("LtsUtils: test_bitArray"); - { - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(8)).size() == 1, " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(9)).size() == 2, " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(16)).size() == 2, " wrong size of underlying data"); - QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(17)).size() == 3, " wrong size of underlying data"); - } - - - - { - QBitArray ba(10); { - int i = 0; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; - - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; - ba[i++] = true; - ba[i++] = false; + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(8)).size() == 1, + " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(9)).size() == 2, + " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(16)).size() == 2, + " wrong size of underlying data"); + QVERIFY2(LtsUtils::BitArray::convert>(QBitArray(17)).size() == 3, + " wrong size of underlying data"); } - const std::vector bArray = LtsUtils::BitArray::convert>(ba); - - - for(int position=0; position<20;++position) - LtsUtils::BitArray::testBit(bArray, position); - - - { - QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); - QVERIFY2(ba == retrievedBd, " forward/backward failed"); + QBitArray ba(10); + { + int i = 0; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; + ba[i++] = true; + ba[i++] = false; + } + + const std::vector bArray = LtsUtils::BitArray::convert>(ba); + + for (int position = 0; position < 20; ++position) + LtsUtils::BitArray::testBit(bArray, position); + + { + QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); + QVERIFY2(ba == retrievedBd, " forward/backward failed"); + } + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); } - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - } - - - std::vector bArrayCopy; - { - QBitArray ba(10); + std::vector bArrayCopy; { - int i = 0; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; - ba[i++] = true; + QBitArray ba(10); + { + int i = 0; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; + ba[i++] = true; - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; - ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + ba[i++] = false; + } + + const std::vector bArray = LtsUtils::BitArray::convert>(ba); + + { + QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); + QVERIFY2(ba == retrievedBd, " forward/backward failed"); + } + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); + + bArrayCopy = bArray; } - const std::vector bArray = LtsUtils::BitArray::convert>(ba); - - { - QBitArray retrievedBd = LtsUtils::BitArray::convert(bArray, ba.size()); - QVERIFY2(ba == retrievedBd, " forward/backward failed"); + + LtsUtils::BitArray::clearBit(bArrayCopy, 0); + LtsUtils::BitArray::clearBit(bArrayCopy, 1); + LtsUtils::BitArray::clearBit(bArrayCopy, 2); + LtsUtils::BitArray::clearBit(bArrayCopy, 3); + LtsUtils::BitArray::clearBit(bArrayCopy, 4); + QVERIFY2(bArrayCopy[0] == 0, " clearBit failed"); + + LtsUtils::BitArray::setBit(bArrayCopy, 1); + LtsUtils::BitArray::setBit(bArrayCopy, 2); + LtsUtils::BitArray::setBit(bArrayCopy, 3); + LtsUtils::BitArray::setBit(bArrayCopy, 4); + LtsUtils::BitArray::setBit(bArrayCopy, 5); + + int i = 0; + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); + + { + QBitArray ba = LtsUtils::BitArray::convert(bArrayCopy, 10); + const std::vector retrievedVec = LtsUtils::BitArray::convert>(ba); + QVERIFY2(bArrayCopy == retrievedVec, " forward/backward failed"); + } } - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArray, i++) == false, " testBit failed"); - - - bArrayCopy = bArray; - } - - { - - - - LtsUtils::BitArray::clearBit(bArrayCopy, 0); - LtsUtils::BitArray::clearBit(bArrayCopy, 1); - LtsUtils::BitArray::clearBit(bArrayCopy, 2); - LtsUtils::BitArray::clearBit(bArrayCopy, 3); - LtsUtils::BitArray::clearBit(bArrayCopy, 4); - QVERIFY2(bArrayCopy[0] == 0, " clearBit failed"); - - - LtsUtils::BitArray::setBit(bArrayCopy, 1); - LtsUtils::BitArray::setBit(bArrayCopy, 2); - LtsUtils::BitArray::setBit(bArrayCopy, 3); - LtsUtils::BitArray::setBit(bArrayCopy, 4); - LtsUtils::BitArray::setBit(bArrayCopy, 5); - - int i = 0; - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == true, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - QVERIFY2(LtsUtils::BitArray::testBit(bArrayCopy, i++) == false, " testBit failed"); - - - { - QBitArray ba = LtsUtils::BitArray::convert(bArrayCopy, 10); - const std::vector retrievedVec = LtsUtils::BitArray::convert>(ba); - QVERIFY2(bArrayCopy == retrievedVec, " forward/backward failed"); - } - - } } - - void LtsUtilsTest::test_convert() { - constexpr int containerLen = 50; + constexpr int containerLen = 50; - - QByteArray ba(containerLen, Qt::Uninitialized); - for (int i = 0; i < containerLen; ++i) - ba[i] = i + 1; - const auto result = LtsUtils::convert>(ba); - const auto resultBA = LtsUtils::toQByteArray(result); - QCOMPARE(result.size(), containerLen); - QCOMPARE(resultBA.size(), containerLen); - for (int i = 0; i < containerLen; ++i) - QCOMPARE(resultBA.at(i), i + 1); - - - QVector> outer; - outer.reserve(containerLen); - for (int i = 0; i < containerLen; ++i) - outer.push_back(result); - const auto resultVec = LtsUtils::convert>>(outer); - const auto resultQVec = LtsUtils::convert>>(resultVec); - QCOMPARE(resultVec.size(), containerLen); - QCOMPARE(resultQVec.size(), containerLen); - for (const auto &inner : resultQVec) - { + QByteArray ba(containerLen, Qt::Uninitialized); for (int i = 0; i < containerLen; ++i) - QCOMPARE(inner.at(i), i + 1); - } + ba[i] = i + 1; + const auto result = LtsUtils::convert>(ba); + const auto resultBA = LtsUtils::toQByteArray(result); + QCOMPARE(result.size(), containerLen); + QCOMPARE(resultBA.size(), containerLen); + for (int i = 0; i < containerLen; ++i) + QCOMPARE(resultBA.at(i), i + 1); - - QVERIFY(!LtsUtils::isInVector(result, 0)); - QVERIFY(LtsUtils::isInVector(result, 1)); - QVERIFY(LtsUtils::isInVector(result, containerLen)); - QVERIFY(!LtsUtils::isInVector(result, containerLen + 1)); + QVector> outer; + outer.reserve(containerLen); + for (int i = 0; i < containerLen; ++i) + outer.push_back(result); + const auto resultVec = LtsUtils::convert>>(outer); + const auto resultQVec = LtsUtils::convert>>(resultVec); + QCOMPARE(resultVec.size(), containerLen); + QCOMPARE(resultQVec.size(), containerLen); + for (const auto& inner : resultQVec) + { + for (int i = 0; i < containerLen; ++i) + QCOMPARE(inner.at(i), i + 1); + } + + QVERIFY(!LtsUtils::isInVector(result, 0)); + QVERIFY(LtsUtils::isInVector(result, 1)); + QVERIFY(LtsUtils::isInVector(result, containerLen)); + QVERIFY(!LtsUtils::isInVector(result, containerLen + 1)); } - - class Emitter : public QObject { - Q_OBJECT + Q_OBJECT -signals: - void signal1(); - void signal2(int i); + signals: + void signal1(); + void signal2(int i); }; class Spy : public QObject { - Q_OBJECT + Q_OBJECT -public slots: - void slot1() { ++m_slot1Count; } + public slots: -public: - int m_slot1Count{0}; + void slot1() + { + ++m_slot1Count; + } + + public: + int m_slot1Count{0}; }; void LtsUtilsTest::test_connection() { - Emitter emitter; - Spy spy; - std::unique_ptr conn(LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 0); + Emitter emitter; + Spy spy; + std::unique_ptr conn( + LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 0); - conn->connect(); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 1); + conn->connect(); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 1); - conn->disconnect(); - emit emitter.signal1(); - QCOMPARE(spy.m_slot1Count, 1); + conn->disconnect(); + emit emitter.signal1(); + QCOMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_queuedConnection() { - Emitter emitter; - Spy spy; - std::unique_ptr conn(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 0); + Emitter emitter; + Spy spy; + std::unique_ptr conn( + LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 0); - conn->connect(Qt::QueuedConnection); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 0); + conn->connect(Qt::QueuedConnection); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 0); - QTRY_COMPARE(spy.m_slot1Count, 1); + QTRY_COMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_signalSignalConnection() { - Emitter emitter; - Spy spy; - std::unique_ptr signalSignalConn(LtsUtils::createConnection(&emitter, &Emitter::signal2, &emitter, &Emitter::signal1)); - std::unique_ptr signalSlotConn(LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); + Emitter emitter; + Spy spy; + std::unique_ptr signalSignalConn( + LtsUtils::createConnection(&emitter, &Emitter::signal2, &emitter, &Emitter::signal1)); + std::unique_ptr signalSlotConn( + LtsUtils::createConnection(&emitter, &Emitter::signal1, &spy, &Spy::slot1)); - signalSignalConn->connect(); - signalSlotConn->connect(); + signalSignalConn->connect(); + signalSlotConn->connect(); - emit emitter.signal2(42); - QCOMPARE(spy.m_slot1Count, 1); + emit emitter.signal2(42); + QCOMPARE(spy.m_slot1Count, 1); } void LtsUtilsTest::test_danglingConnection1() { - Spy spy; - std::unique_ptr conn; + Spy spy; + std::unique_ptr conn; - { - Emitter emitter; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - } + { + Emitter emitter; + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + } - conn->connect(); - conn->disconnect(); + conn->connect(); + conn->disconnect(); } void LtsUtilsTest::test_danglingConnection2() { - Emitter emitter; - std::unique_ptr conn; + Emitter emitter; + std::unique_ptr conn; - { - Spy spy; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); - } + { + Spy spy; + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, &spy, &Spy::slot1)); + } - conn->connect(); - conn->disconnect(); + conn->connect(); + conn->disconnect(); } void LtsUtilsTest::test_danglingConnection3() { - Emitter emitter; - std::unique_ptr spy(new Spy); - std::unique_ptr conn; + Emitter emitter; + std::unique_ptr spy(new Spy); + std::unique_ptr conn; - conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, spy.get(), &Spy::slot1)); + conn.reset(LtsUtils::createConnection(&emitter, &Emitter::signal2, spy.get(), &Spy::slot1)); - conn->connect(); - spy.reset(); - conn->disconnect(); + conn->connect(); + spy.reset(); + conn->disconnect(); } void LtsUtilsTest::test_jsonObject_fromJson() { - { - std::string json = R"({})"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = R"({})"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(obj.isValid()); + QVERIFY(obj.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": true})"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(obj.isValid()); - QVERIFY(!obj.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": true})"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(obj.isValid()); + QVERIFY(!obj.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": })"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(!obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": })"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(!obj.isValid()); + QVERIFY(obj.isEmpty()); + } - { - std::string json = "[1, 2, 3, 4]"; - const auto obj = JsonObject::fromJson(json); - QVERIFY(!obj.isValid()); - QVERIFY(obj.isEmpty()); - } + { + std::string json = "[1, 2, 3, 4]"; + const auto obj = JsonObject::fromJson(json); + QVERIFY(!obj.isValid()); + QVERIFY(obj.isEmpty()); + } } void LtsUtilsTest::test_jsonObject_contains() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {}, "int array": [1, 2, 3], "string array": ["hello", "json"], @@ -684,176 +654,173 @@ void LtsUtilsTest::test_jsonObject_contains() "int map": {"i": 1, "j": 2, "k": 3}, "mixed map": {"i": 1, "j": 2, "k": "3"} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QVERIFY(obj.contains("int")); - QVERIFY(obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("int")); + QVERIFY(obj.contains("int")); + QVERIFY(obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); + QVERIFY(!obj.contains("int")); - QVERIFY(!obj.contains("double")); - QVERIFY(obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); + QVERIFY(!obj.contains("double")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(obj.contains("string")); - QVERIFY(obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(obj.contains("string")); + QVERIFY(obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); + QVERIFY(!obj.contains("string")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); + QVERIFY(!obj.contains("bool")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(!obj.contains("null")); - QVERIFY(obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(!obj.contains("null")); + QVERIFY(obj.contains("null")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(obj.contains("object")); - QVERIFY(obj.contains("object")); - QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(obj.contains("object")); + QVERIFY(obj.contains("object")); + QVERIFY(!obj.contains("object")); + QVERIFY(!obj.contains("object")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(!obj.contains("int array")); - QVERIFY(obj.contains("int array")); - QVERIFY(obj.contains("int array")); - QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(!obj.contains("int array")); + QVERIFY(obj.contains("int array")); + QVERIFY(obj.contains("int array")); + QVERIFY(!obj.contains("int array")); - QVERIFY(obj.contains("mixed array")); - QVERIFY(obj.contains("mixed array")); + QVERIFY(obj.contains("mixed array")); + QVERIFY(obj.contains("mixed array")); + QVERIFY(obj.contains>("int array")); + QVERIFY(!obj.contains>("int array")); + QVERIFY(obj.contains>("int array")); + QVERIFY(!obj.contains>("int array")); - QVERIFY(obj.contains>("int array")); - QVERIFY(!obj.contains>("int array")); - QVERIFY(obj.contains>("int array")); - QVERIFY(!obj.contains>("int array")); - - QVERIFY((obj.contains>("int map"))); - QVERIFY(!(obj.contains>("mixed map"))); - QVERIFY((obj.contains>("int map"))); - QVERIFY(!(obj.contains>("mixed map"))); + QVERIFY((obj.contains>("int map"))); + QVERIFY(!(obj.contains>("mixed map"))); + QVERIFY((obj.contains>("int map"))); + QVERIFY(!(obj.contains>("mixed map"))); } void LtsUtilsTest::test_jsonObject_value() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {"a": 1, "b": 2, "c": 3}, "int array": [1, 2, 3], "string array": ["hello", "json"], "mixed array": ["hello", 42], "int map": {"i": 1, "j": 2, "k": 3} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QCOMPARE(obj.value("int"), 42); - QCOMPARE(obj.value("double"), 3.14); - QCOMPARE(obj.value("string").c_str(), "hello json"); - QCOMPARE(obj.value("string"), QStringLiteral("hello json")); - QCOMPARE(obj.value("bool"), true); + QCOMPARE(obj.value("int"), 42); + QCOMPARE(obj.value("double"), 3.14); + QCOMPARE(obj.value("string").c_str(), "hello json"); + QCOMPARE(obj.value("string"), QStringLiteral("hello json")); + QCOMPARE(obj.value("bool"), true); - QJsonObject expectedObject{ {QStringLiteral("a"), 1}, {QStringLiteral("b"), 2}, {QStringLiteral("c"), 3} }; - QCOMPARE(obj.value("object"), expectedObject); - QCOMPARE(obj.value("object"), JsonObject(expectedObject)); + QJsonObject expectedObject{{QStringLiteral("a"), 1}, {QStringLiteral("b"), 2}, {QStringLiteral("c"), 3}}; + QCOMPARE(obj.value("object"), expectedObject); + QCOMPARE(obj.value("object"), JsonObject(expectedObject)); - QJsonArray expectedMixedArray{QStringLiteral("hello"), 42}; - QCOMPARE(obj.value("mixed array"), expectedMixedArray); - QCOMPARE(obj.value("mixed array"), JsonArray(expectedMixedArray)); + QJsonArray expectedMixedArray{QStringLiteral("hello"), 42}; + QCOMPARE(obj.value("mixed array"), expectedMixedArray); + QCOMPARE(obj.value("mixed array"), JsonArray(expectedMixedArray)); - QVector expectedIntArray{1, 2, 3}; - QCOMPARE(obj.value>("int array"), expectedIntArray); + QVector expectedIntArray{1, 2, 3}; + QCOMPARE(obj.value>("int array"), expectedIntArray); - std::vector expectedStdIntArray{1, 2, 3}; - QCOMPARE(obj.value>("int array"), expectedStdIntArray); + std::vector expectedStdIntArray{1, 2, 3}; + QCOMPARE(obj.value>("int array"), expectedStdIntArray); - QVector expectedStringArray{QStringLiteral("hello"), QStringLiteral("json")}; - QCOMPARE(obj.value>("string array"), expectedStringArray); + QVector expectedStringArray{QStringLiteral("hello"), QStringLiteral("json")}; + QCOMPARE(obj.value>("string array"), expectedStringArray); - std::vector expectedStdStringArray{"hello", "json"}; - QCOMPARE(obj.value>("string array"), expectedStdStringArray); + std::vector expectedStdStringArray{"hello", "json"}; + QCOMPARE(obj.value>("string array"), expectedStdStringArray); - QMap expectedIntMap{ {QStringLiteral("i"), 1}, {QStringLiteral("j"), 2}, {QStringLiteral("k"), 3} }; - QCOMPARE((obj.value>("int map")), expectedIntMap); + QMap expectedIntMap{{QStringLiteral("i"), 1}, {QStringLiteral("j"), 2}, {QStringLiteral("k"), 3}}; + QCOMPARE((obj.value>("int map")), expectedIntMap); - std::map expectedStdIntMap{ {"i", 1}, {"j", 2}, {"k", 3} }; - QCOMPARE((obj.value>("int map")), expectedStdIntMap); + std::map expectedStdIntMap{{"i", 1}, {"j", 2}, {"k", 3}}; + QCOMPARE((obj.value>("int map")), expectedStdIntMap); - QVERIFY(obj.isNull("null")); + QVERIFY(obj.isNull("null")); } void LtsUtilsTest::test_jsonObject_valueWithError() { - std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, + std::string json = R"({ "int": 42, "double": 3.14, "string": "hello json", "bool": true, "null": null, "object": {"a": 1, "b": 2, "c": 3}, "int array": [1, 2, 3], "string array": ["hello", "json"], "mixed array": ["hello", 42], "mixed map": {"i": 1, "j": 2, "k": "3"} })"; - JsonObject obj = JsonObject::fromJson(json); + JsonObject obj = JsonObject::fromJson(json); - QVERIFY_EXCEPTION_THROWN(obj.value("unknown key"), JsonKeyError); + QVERIFY_EXCEPTION_THROWN(obj.value("unknown key"), JsonKeyError); - QVERIFY_EXCEPTION_THROWN(obj.value("double"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("string"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value("object"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(obj.value>("mixed array"), JsonTypeError); - QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); - QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("double"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("string"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("int"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value("object"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.value>("mixed array"), JsonTypeError); + QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); + QVERIFY_EXCEPTION_THROWN((obj.value>("mixed map")), JsonTypeError); } void LtsUtilsTest::test_jsonObject_valueOr() { - QJsonObject obj_{ {QStringLiteral("int"), 42} }; - JsonObject obj(obj_); + QJsonObject obj_{{QStringLiteral("int"), 42}}; + JsonObject obj(obj_); - QCOMPARE(obj.valueOr("int", -1), 42); + QCOMPARE(obj.valueOr("int", -1), 42); - - QCOMPARE(obj.valueOr("string", -1), -1); + QCOMPARE(obj.valueOr("string", -1), -1); - - QVERIFY_EXCEPTION_THROWN(obj.valueOr("int", QString()), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(obj.valueOr("int", QString()), JsonTypeError); } void LtsUtilsTest::test_jsonObject_integers() { - std::string json = R"({ + std::string json = R"({ "int16_min": -32768, "int16_max": 32767, "int16_min-1": -32769, @@ -880,323 +847,316 @@ void LtsUtilsTest::test_jsonObject_integers() "uint64_max": 9007199254740991, "uint64_max+1": 9007199254740992 })"; - JsonObject obj = JsonObject::fromJson(json); - QVERIFY(obj.contains("int16_min")); - QVERIFY(obj.contains("int16_max")); - QVERIFY(!obj.contains("int16_min-1")); - QVERIFY(!obj.contains("int16_max+1")); - QVERIFY(obj.contains("int16_min-1")); - QVERIFY(obj.contains("int16_max+1")); + JsonObject obj = JsonObject::fromJson(json); + QVERIFY(obj.contains("int16_min")); + QVERIFY(obj.contains("int16_max")); + QVERIFY(!obj.contains("int16_min-1")); + QVERIFY(!obj.contains("int16_max+1")); + QVERIFY(obj.contains("int16_min-1")); + QVERIFY(obj.contains("int16_max+1")); - QVERIFY(obj.contains("int32_min")); - QVERIFY(obj.contains("int32_max")); - QVERIFY(!obj.contains("int32_min-1")); - QVERIFY(!obj.contains("int32_max+1")); - QVERIFY(obj.contains("int32_min-1")); - QVERIFY(obj.contains("int32_max+1")); + QVERIFY(obj.contains("int32_min")); + QVERIFY(obj.contains("int32_max")); + QVERIFY(!obj.contains("int32_min-1")); + QVERIFY(!obj.contains("int32_max+1")); + QVERIFY(obj.contains("int32_min-1")); + QVERIFY(obj.contains("int32_max+1")); - QVERIFY(obj.contains("int64_min")); - QVERIFY(obj.contains("int64_max")); - QVERIFY(!obj.contains("int64_min-1")); - QVERIFY(!obj.contains("int64_max+1")); + QVERIFY(obj.contains("int64_min")); + QVERIFY(obj.contains("int64_max")); + QVERIFY(!obj.contains("int64_min-1")); + QVERIFY(!obj.contains("int64_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint16_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint16_max+1")); + QVERIFY(obj.contains("uint16_max+1")); - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint16_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint16_max+1")); - QVERIFY(obj.contains("uint16_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint32_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint32_max+1")); + QVERIFY(obj.contains("uint32_max+1")); - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint32_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint32_max+1")); - QVERIFY(obj.contains("uint32_max+1")); - - QVERIFY(obj.contains("uint_min")); - QVERIFY(obj.contains("uint64_max")); - QVERIFY(!obj.contains("uint_min-1")); - QVERIFY(!obj.contains("uint64_max+1")); + QVERIFY(obj.contains("uint_min")); + QVERIFY(obj.contains("uint64_max")); + QVERIFY(!obj.contains("uint_min-1")); + QVERIFY(!obj.contains("uint64_max+1")); } void LtsUtilsTest::test_jsonObject_nullValues() { - std::string jsonNullMap = R"( {"a": null, "b": null, "c": null} )"; - JsonObject obj = JsonObject::fromJson(jsonNullMap); - QVERIFY(obj.isMap()); + std::string jsonNullMap = R"( {"a": null, "b": null, "c": null} )"; + JsonObject obj = JsonObject::fromJson(jsonNullMap); + QVERIFY(obj.isMap()); } void LtsUtilsTest::test_jsonArray_fromJson() { - { - std::string json = "[]"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = "[]"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(arr.isValid()); + QVERIFY(arr.isEmpty()); + } - { - std::string json = R"([1, 2, true, false, null])"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(arr.isValid()); - QVERIFY(!arr.isEmpty()); - } + { + std::string json = R"([1, 2, true, false, null])"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(arr.isValid()); + QVERIFY(!arr.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": })"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(!arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": })"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(!arr.isValid()); + QVERIFY(arr.isEmpty()); + } - { - std::string json = R"({"a": 1, "b": true})"; - const auto arr = JsonArray::fromJson(json); - QVERIFY(!arr.isValid()); - QVERIFY(arr.isEmpty()); - } + { + std::string json = R"({"a": 1, "b": true})"; + const auto arr = JsonArray::fromJson(json); + QVERIFY(!arr.isValid()); + QVERIFY(arr.isEmpty()); + } } void LtsUtilsTest::test_jsonArray() { - std::string jsonIntArray = R"( [0, 1, 2, 3] )"; - JsonArray array = JsonArray::fromJson(jsonIntArray); - QCOMPARE(array.size(), 4); + std::string jsonIntArray = R"( [0, 1, 2, 3] )"; + JsonArray array = JsonArray::fromJson(jsonIntArray); + QCOMPARE(array.size(), 4); - QVERIFY(array.contains(0)); - QVERIFY(!array.contains(0)); - QCOMPARE(array.at(0), 0); + QVERIFY(array.contains(0)); + QVERIFY(!array.contains(0)); + QCOMPARE(array.at(0), 0); - QVERIFY_EXCEPTION_THROWN(array.at(0), JsonTypeError); + QVERIFY_EXCEPTION_THROWN(array.at(0), JsonTypeError); - QVERIFY_EXCEPTION_THROWN(array.contains(-1), JsonRangeError); - QVERIFY_EXCEPTION_THROWN(array.contains(4), JsonRangeError); - QVERIFY_EXCEPTION_THROWN(array.at(-1), JsonRangeError); - QVERIFY_EXCEPTION_THROWN(array.at(4), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.contains(-1), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.contains(4), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.at(-1), JsonRangeError); + QVERIFY_EXCEPTION_THROWN(array.at(4), JsonRangeError); - QVERIFY(array.isVector()); - QVERIFY(!array.isVector()); - QCOMPARE(array.toVector(), QVector({0, 1, 2, 3})); - QCOMPARE(array.toStdVector(), std::vector({0, 1, 2, 3})); + QVERIFY(array.isVector()); + QVERIFY(!array.isVector()); + QCOMPARE(array.toVector(), QVector({0, 1, 2, 3})); + QCOMPARE(array.toStdVector(), std::vector({0, 1, 2, 3})); } void LtsUtilsTest::test_jsonArray_nullArray() { - std::string jsonNullArray = R"( [null, null, null, null] )"; - JsonArray array = JsonArray::fromJson(jsonNullArray); - QVERIFY(array.isNull(0)); - QVERIFY(array.isVector()); + std::string jsonNullArray = R"( [null, null, null, null] )"; + JsonArray array = JsonArray::fromJson(jsonNullArray); + QVERIFY(array.isNull(0)); + QVERIFY(array.isVector()); } void LtsUtilsTest::test_byteStreamFromSfmMessage() { - SfmMessage msg; + SfmMessage msg; - msg.setId(16); - msg.setRtr(true); - const quint8 payloadArray [] = {0x11, 0x02, 0x03, 0x04, 0x50}; - msg.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); + msg.setId(16); + msg.setRtr(true); + const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50}; + msg.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); - const quint8 expectedResultArray [] = {0x02, 0x80, 0x00, 0x10, 0x05, - 0x80, 0x91, 0x80, 0x82, 0x80, - 0x83, 0x04, 0x50, 0x00, 0x03}; - QByteArray expectedResult = QByteArray(reinterpret_cast(expectedResultArray), sizeof(expectedResultArray)); + const quint8 expectedResultArray[] = {0x02, 0x80, 0x00, 0x10, 0x05, 0x80, 0x91, 0x80, + 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0x03}; + QByteArray expectedResult = + QByteArray(reinterpret_cast(expectedResultArray), sizeof(expectedResultArray)); - QByteArray byteMessage = byteStreamFromSfmMessage (msg); + QByteArray byteMessage = byteStreamFromSfmMessage(msg); - QCOMPARE(byteMessage, expectedResult); + QCOMPARE(byteMessage, expectedResult); } void LtsUtilsTest::test_byteStreamFromSfmMessage2() { - SfmMessage msg = LtsUtils::byteStreamToSfmMessage(QByteArray::fromHex("0280004f003003")); - QCOMPARE(msg.rtr(), true); - QVERIFY2(msg.id() == 0x4f, "Value not expected"); - QVERIFY2((msg.id() | (msg.rtr() << 15)) == 0x804f, "Value not expected"); + SfmMessage msg = LtsUtils::byteStreamToSfmMessage(QByteArray::fromHex("0280004f003003")); + QCOMPARE(msg.rtr(), true); + QVERIFY2(msg.id() == 0x4f, "Value not expected"); + QVERIFY2((msg.id() | (msg.rtr() << 15)) == 0x804f, "Value not expected"); } void LtsUtilsTest::test_byteStreamToSfmMessage() { - SfmMessage msgComplete; - msgComplete.setId(16); - msgComplete.setRtr(true); + SfmMessage msgComplete; + msgComplete.setId(16); + msgComplete.setRtr(true); - const quint8 payloadArray [] = {0x11, 0x02, 0x03, 0x04, 0x50, 0x00}; - msgComplete.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); + const quint8 payloadArray[] = {0x11, 0x02, 0x03, 0x04, 0x50, 0x00}; + msgComplete.setPayload(QByteArray(reinterpret_cast(payloadArray), sizeof(payloadArray))); - const quint8 dataArray [] = {0x02, 0x80, 0x00, 0x10, 0x06, - 0x80, 0x91, 0x80, 0x82, 0x80, - 0x83, 0x04, 0x50, 0x00, 0xFF, 0x03}; - QByteArray dataComplete = QByteArray(reinterpret_cast(dataArray), sizeof(dataArray)); + const quint8 dataArray[] = {0x02, 0x80, 0x00, 0x10, 0x06, 0x80, 0x91, 0x80, + 0x82, 0x80, 0x83, 0x04, 0x50, 0x00, 0xFF, 0x03}; + QByteArray dataComplete = QByteArray(reinterpret_cast(dataArray), sizeof(dataArray)); - SfmMessage result; - try - { - result = byteStreamToSfmMessage(dataComplete); - } - catch (const ConversionError &ex) - { - qDebug() << ex.what(); - } - QCOMPARE(result, msgComplete); + SfmMessage result; + try + { + result = byteStreamToSfmMessage(dataComplete); + } + catch (const ConversionError& ex) + { + qDebug() << ex.what(); + } + QCOMPARE(result, msgComplete); - - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(QByteArray()), ConversionError); + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(QByteArray()), ConversionError); - - QByteArray framingError = dataComplete; - framingError.chop(1); - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(framingError), ConversionError); + QByteArray framingError = dataComplete; + framingError.chop(1); + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(framingError), ConversionError); - - QByteArray checksumError = dataComplete; - checksumError[14] = 0x01; - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(checksumError), ConversionError); + QByteArray checksumError = dataComplete; + checksumError[14] = 0x01; + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(checksumError), ConversionError); - - QByteArray lengthError = dataComplete; - QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(lengthError.remove(13,1)), ConversionError); + QByteArray lengthError = dataComplete; + QVERIFY_EXCEPTION_THROWN(byteStreamToSfmMessage(lengthError.remove(13, 1)), ConversionError); } void LtsUtilsTest::byteAccess() { - QByteArray ba; - LtsUtils::set1Byte(0x67, ba); - LtsUtils::set1Byte(0xcb, ba); - LtsUtils::set2Byte(0x1234, ba); - LtsUtils::set2Byte(0x9876, ba); - LtsUtils::set3Byte(0x6263fb, ba); - LtsUtils::set3Byte(0x80e87b, ba); - LtsUtils::set4Byte(0x66b9dd15, ba); - LtsUtils::set4Byte(0xa254a715, ba); - LtsUtils::set8Byte(0x1234567812345678, ba); - LtsUtils::set8Byte(0x8234567812345678, ba); + QByteArray ba; + LtsUtils::set1Byte(0x67, ba); + LtsUtils::set1Byte(0xcb, ba); + LtsUtils::set2Byte(0x1234, ba); + LtsUtils::set2Byte(0x9876, ba); + LtsUtils::set3Byte(0x6263fb, ba); + LtsUtils::set3Byte(0x80e87b, ba); + LtsUtils::set4Byte(0x66b9dd15, ba); + LtsUtils::set4Byte(0xa254a715, ba); + LtsUtils::set8Byte(0x1234567812345678, ba); + LtsUtils::set8Byte(0x8234567812345678, ba); - { - int64_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, 6448123); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, -8329093); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, 1723456789); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, -1571510507); - LtsUtils::get8Byte(ba, pos, i); - QCOMPARE(i, 0x1234567812345678); - LtsUtils::get8Byte(ba, pos, i); - QCOMPARE(i, 0x8234567812345678); + { + int64_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, 6448123); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, -8329093); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, 1723456789); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, -1571510507); + LtsUtils::get8Byte(ba, pos, i); + QCOMPARE(i, 0x1234567812345678); + LtsUtils::get8Byte(ba, pos, i); + QCOMPARE(i, 0x8234567812345678); - uint64_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 6448123); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 8448123); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 1723456789); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 2723456789); - LtsUtils::get8Byte(ba, pos, u); - QCOMPARE(u, 0x1234567812345678); - LtsUtils::get8Byte(ba, pos, u); - QCOMPARE(u, 0x8234567812345678); - } - { - int32_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, 6448123); - LtsUtils::get3Byte(ba, pos, i); - QCOMPARE(i, -8329093); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, 1723456789); - LtsUtils::get4Byte(ba, pos, i); - QCOMPARE(i, -1571510507); + uint64_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 6448123); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 8448123); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 1723456789); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 2723456789); + LtsUtils::get8Byte(ba, pos, u); + QCOMPARE(u, 0x1234567812345678); + LtsUtils::get8Byte(ba, pos, u); + QCOMPARE(u, 0x8234567812345678); + } + { + int32_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, 6448123); + LtsUtils::get3Byte(ba, pos, i); + QCOMPARE(i, -8329093); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, 1723456789); + LtsUtils::get4Byte(ba, pos, i); + QCOMPARE(i, -1571510507); - uint32_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 6448123); - LtsUtils::get3Byte(ba, pos, u); - QCOMPARE(u, 8448123); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 1723456789); - LtsUtils::get4Byte(ba, pos, u); - QCOMPARE(u, 2723456789); - } - { - int16_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, 4660); - LtsUtils::get2Byte(ba, pos, i); - QCOMPARE(i, -26506); + uint32_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 6448123); + LtsUtils::get3Byte(ba, pos, u); + QCOMPARE(u, 8448123); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 1723456789); + LtsUtils::get4Byte(ba, pos, u); + QCOMPARE(u, 2723456789); + } + { + int16_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, 4660); + LtsUtils::get2Byte(ba, pos, i); + QCOMPARE(i, -26506); - uint16_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 4660); - LtsUtils::get2Byte(ba, pos, u); - QCOMPARE(u, 39030); - } - { - int8_t i = 0; - size_t pos = 0; - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, 103); - LtsUtils::get1Byte(ba, pos, i); - QCOMPARE(i, -53); + uint16_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 4660); + LtsUtils::get2Byte(ba, pos, u); + QCOMPARE(u, 39030); + } + { + int8_t i = 0; + size_t pos = 0; + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, 103); + LtsUtils::get1Byte(ba, pos, i); + QCOMPARE(i, -53); - uint8_t u = 0; - pos = 0; - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 103); - LtsUtils::get1Byte(ba, pos, u); - QCOMPARE(u, 203); - } + uint8_t u = 0; + pos = 0; + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 103); + LtsUtils::get1Byte(ba, pos, u); + QCOMPARE(u, 203); + } } - #include "utils_test.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h old mode 100755 new mode 100644 index e6a37453b..e0a247862 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/UnitTests/utils_test.h @@ -6,57 +6,50 @@ class LtsUtilsTest : public QObject { - Q_OBJECT -private Q_SLOTS: + Q_OBJECT + private Q_SLOTS: - void test_toIntArray(); - void test_fromIntArray(); - void test_toBigintArray(); - void test_fromBigintArray(); - void test_toIntArray2D(); - void test_fromIntArray2D(); - void test_toBigintArray2D(); - void test_fromBigintArray2D(); + void test_toIntArray(); + void test_fromIntArray(); + void test_toBigintArray(); + void test_fromBigintArray(); + void test_toIntArray2D(); + void test_fromIntArray2D(); + void test_toBigintArray2D(); + void test_fromBigintArray2D(); - void test_QPoint3D(); + void test_QPoint3D(); + void test_bitArray(); - void test_bitArray(); + void test_convert(); + void test_connection(); + void test_queuedConnection(); + void test_signalSignalConnection(); + void test_danglingConnection1(); + void test_danglingConnection2(); + void test_danglingConnection3(); - void test_convert(); + void test_jsonObject_fromJson(); + void test_jsonObject_contains(); + void test_jsonObject_value(); + void test_jsonObject_valueWithError(); + void test_jsonObject_valueOr(); + void test_jsonObject_integers(); + void test_jsonObject_nullValues(); + void test_jsonArray_fromJson(); + void test_jsonArray(); + void test_jsonArray_nullArray(); + void test_byteStreamFromSfmMessage(); + void test_byteStreamFromSfmMessage2(); + void test_byteStreamToSfmMessage(); - void test_connection(); - void test_queuedConnection(); - void test_signalSignalConnection(); - void test_danglingConnection1(); - void test_danglingConnection2(); - void test_danglingConnection3(); + void test_promise(); + void test_promise_example1(); + void test_promise_example2(); + void test_promise_example3(); - - void test_jsonObject_fromJson(); - void test_jsonObject_contains(); - void test_jsonObject_value(); - void test_jsonObject_valueWithError(); - void test_jsonObject_valueOr(); - void test_jsonObject_integers(); - void test_jsonObject_nullValues(); - void test_jsonArray_fromJson(); - void test_jsonArray(); - void test_jsonArray_nullArray(); - - - void test_byteStreamFromSfmMessage(); - void test_byteStreamFromSfmMessage2(); - void test_byteStreamToSfmMessage(); - - - void test_promise(); - void test_promise_example1(); - void test_promise_example2(); - void test_promise_example3(); - - - void byteAccess(); + void byteAccess(); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h old mode 100755 new mode 100644 index d48cbe915..5bd2136fe --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/await.h @@ -1,116 +1,84 @@ #pragma once - - - +#include #include #include -#include - #include - namespace LtsUtils { template -void addConnect(QEventLoop &x, bool &success, const typename QtPrivate::FunctionPointer::Object *sender, Func signal, bool isSuccess) +void addConnect(QEventLoop& x, bool& success, const typename QtPrivate::FunctionPointer::Object* sender, + Func signal, bool isSuccess) { - if (isSuccess) - { - QObject::connect(sender, signal, &x, [&success]() + if (isSuccess) { - - success = true; - }); - } + QObject::connect(sender, signal, &x, [&success]() { success = true; }); + } - QObject::connect(sender, signal, &x, &QEventLoop::quit, Qt::QueuedConnection); + QObject::connect(sender, signal, &x, &QEventLoop::quit, Qt::QueuedConnection); } - template -void addConnect(QEventLoop &x, bool &success, const typename QtPrivate::FunctionPointer::Object *sender, Func signal, bool isSuccess, Connect... connects) +void addConnect(QEventLoop& x, bool& success, const typename QtPrivate::FunctionPointer::Object* sender, + Func signal, bool isSuccess, Connect... connects) { - addConnect(x, success, sender, signal, isSuccess); - addConnect(x, success, connects...); + addConnect(x, success, sender, signal, isSuccess); + addConnect(x, success, connects...); } - -template -void await(Connect... connects) noexcept(false) +template void await(Connect... connects) noexcept(false) { - QEventLoop x; - bool success = false; + QEventLoop x; + bool success = false; - addConnect(x, success, connects...); + addConnect(x, success, connects...); - - x.exec(); - + x.exec(); - if (!success) - { - - throw std::runtime_error("Failed."); - } + if (!success) + { + + throw std::runtime_error("Failed."); + } } - -template -void awaitTimeout(const int timeoutMs, Connect... connects) noexcept(false) +template void awaitTimeout(const int timeoutMs, Connect... connects) noexcept(false) { - std::unique_ptr t(new QTimer); - bool timeout = false; + std::unique_ptr t(new QTimer); + bool timeout = false; - if (timeoutMs > -1) - { - t->setInterval(timeoutMs); - t->setSingleShot(true); - QObject::connect(t.get(), &QTimer::timeout, t.get(), [&timeout](){ fprintf(stderr, "awaitTimeout: timed out!\n"); timeout = true; }); - t->start(); - } + if (timeoutMs > -1) + { + t->setInterval(timeoutMs); + t->setSingleShot(true); + QObject::connect(t.get(), &QTimer::timeout, t.get(), [&timeout]() { + fprintf(stderr, "awaitTimeout: timed out!\n"); + timeout = true; + }); + t->start(); + } - await(t.get(), &QTimer::timeout, false, connects...); + await(t.get(), &QTimer::timeout, false, connects...); + if (timeout) + { - if (timeout) - { - - throw std::runtime_error("Timeout."); - } + throw std::runtime_error("Timeout."); + } } - - - - - - - - - - - - - - - - - template -void awaitWithCancelationSignal(const typename QtPrivate::FunctionPointer::Object *sender1, Func1 signal1, - const typename QtPrivate::FunctionPointer::Object *sender2, Func2 signal2, +void awaitWithCancelationSignal(const typename QtPrivate::FunctionPointer::Object* sender1, Func1 signal1, + const typename QtPrivate::FunctionPointer::Object* sender2, Func2 signal2, const int timeoutMs = 0) noexcept(false) { - if (timeoutMs > 0) - { - awaitTimeout(timeoutMs, - sender1, signal1, true, - sender2, signal2, false); - return; - } + if (timeoutMs > 0) + { + awaitTimeout(timeoutMs, sender1, signal1, true, sender2, signal2, false); + return; + } - await(sender1, signal1, true, - sender2, signal2, false); + await(sender1, signal1, true, sender2, signal2, false); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h index 21006cddd..5787cb8f3 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/connection.h @@ -8,92 +8,95 @@ #include #include -namespace LtsUtils { +namespace LtsUtils +{ -class IConnection { -public: - virtual ~IConnection() = default; - virtual void connect(Qt::ConnectionType = Qt::AutoConnection) = 0; - virtual void disconnect() = 0; +class IConnection +{ + public: + virtual ~IConnection() = default; + virtual void connect(Qt::ConnectionType = Qt::AutoConnection) = 0; + virtual void disconnect() = 0; }; -class DummyConnection : public IConnection { -public: - void connect(Qt::ConnectionType = Qt::AutoConnection) override {} - void disconnect() override {} +class DummyConnection : public IConnection +{ + public: + void connect(Qt::ConnectionType = Qt::AutoConnection) override {} + + void disconnect() override {} }; -namespace detail { +namespace detail +{ template struct ExtractClass; -template struct ExtractClass { - using type = T; +template struct ExtractClass +{ + using type = T; }; } // namespace detail -template class Connection : public IConnection { - static_assert(std::is_member_function_pointer_v, - "Must be a pointer to method"); - static_assert(std::is_member_function_pointer_v, - "Must be a pointer to method"); +template class Connection : public IConnection +{ + static_assert(std::is_member_function_pointer_v, "Must be a pointer to method"); + static_assert(std::is_member_function_pointer_v, "Must be a pointer to method"); - using Emitter = typename detail::ExtractClass::type; - using Target = typename detail::ExtractClass::type; + using Emitter = typename detail::ExtractClass::type; + using Target = typename detail::ExtractClass::type; - static_assert(std::is_base_of_v, - "Must be derived from QObject"); - static_assert(std::is_base_of_v, - "Must be derived from QObject"); + static_assert(std::is_base_of_v, "Must be derived from QObject"); + static_assert(std::is_base_of_v, "Must be derived from QObject"); -public: - Connection(Emitter *emitter, Signal signal, Target *target, Slot slot) - : m_emitter(emitter), m_signal(signal), m_target(target), m_slot(slot) { - Q_ASSERT(emitter); - Q_ASSERT(signal); - Q_ASSERT(target); - Q_ASSERT(slot); - } + public: + Connection(Emitter* emitter, Signal signal, Target* target, Slot slot) + : m_emitter(emitter), m_signal(signal), m_target(target), m_slot(slot) + { + Q_ASSERT(emitter); + Q_ASSERT(signal); + Q_ASSERT(target); + Q_ASSERT(slot); + } - void - connect(Qt::ConnectionType connectionType = Qt::AutoConnection) override { - Q_ASSERT(!m_connected); + void connect(Qt::ConnectionType connectionType = Qt::AutoConnection) override + { + Q_ASSERT(!m_connected); - m_connected = true; + m_connected = true; - if (!m_emitter || !m_target) - return; + if (!m_emitter || !m_target) + return; - m_conn = QObject::connect(m_emitter.data(), m_signal, m_target.data(), - m_slot, connectionType); - Q_ASSERT(m_conn); - } + m_conn = QObject::connect(m_emitter.data(), m_signal, m_target.data(), m_slot, connectionType); + Q_ASSERT(m_conn); + } - void disconnect() override { - Q_ASSERT(m_connected); + void disconnect() override + { + Q_ASSERT(m_connected); - if (m_conn) - QObject::disconnect(m_conn); + if (m_conn) + QObject::disconnect(m_conn); - m_connected = false; - } + m_connected = false; + } -private: - bool m_connected{false}; - QPointer m_emitter; - Signal m_signal; - QPointer m_target; - Slot m_slot; - QMetaObject::Connection m_conn; + private: + bool m_connected{false}; + QPointer m_emitter; + Signal m_signal; + QPointer m_target; + Slot m_slot; + QMetaObject::Connection m_conn; }; template -Connection * -createConnection(typename detail::ExtractClass::type *emitter, - Signal signal, - typename detail::ExtractClass::type *target, Slot slot) { - return new Connection(emitter, signal, target, slot); +Connection* createConnection(typename detail::ExtractClass::type* emitter, Signal signal, + typename detail::ExtractClass::type* target, Slot slot) +{ + return new Connection(emitter, signal, target, slot); } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h old mode 100755 new mode 100644 index c2a316a43..4d151b181 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/data_modification_enum.h @@ -1,30 +1,24 @@ - #pragma once #include -enum class DataModification -{ - eAdded, - eModified, - eRemoved -}; +enum class DataModification { eAdded, eModified, eRemoved }; -inline std::ostream &operator<<(std::ostream &str, DataModification mod) +inline std::ostream& operator<<(std::ostream& str, DataModification mod) { - switch(mod) - { - case DataModification::eAdded: - str << "DataModification::eAdded"; - break; - case DataModification::eModified: - str << "DataModification::eModified"; - break; - case DataModification::eRemoved: - str << "DataModification::eRemoved"; - break; - } - return str; + switch (mod) + { + case DataModification::eAdded: + str << "DataModification::eAdded"; + break; + case DataModification::eModified: + str << "DataModification::eModified"; + break; + case DataModification::eRemoved: + str << "DataModification::eRemoved"; + break; + } + return str; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h old mode 100755 new mode 100644 index a26a6c73a..f33f617ce --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_bitarray.h @@ -1,10 +1,9 @@ - #pragma once #ifdef SUPPORT_QBITARRAY -# include +#include #endif namespace LtsUtils @@ -14,85 +13,78 @@ namespace BitArray { constexpr inline int bitNumber(int position) { - return 7 - (position % 8); - + return 7 - (position % 8); } -template -inline bool testBit(const T &bitField, int position, bool *oob = nullptr) +template inline bool testBit(const T& bitField, int position, bool* oob = nullptr) { - const size_t byteNum = position / 8; - if (byteNum >= bitField.size()) - { + const size_t byteNum = position / 8; + if (byteNum >= bitField.size()) + { + if (oob) + *oob = true; + return false; + } if (oob) - *oob = true; - return false; - } - if (oob) - *oob = false; + *oob = false; - const typename T::value_type mask = 1 << bitNumber(position); - return ((bitField.at(byteNum) & mask) == mask); + const typename T::value_type mask = 1 << bitNumber(position); + return ((bitField.at(byteNum) & mask) == mask); } -template -inline bool setBit(T &bitField, int position, bool set = true) +template inline bool setBit(T& bitField, int position, bool set = true) { - const size_t byteNum = position / 8; - if (byteNum >= bitField.size()) - return false; + const size_t byteNum = position / 8; + if (byteNum >= bitField.size()) + return false; - const typename T::value_type mask = 1 << bitNumber(position); - if (set) - bitField[byteNum] |= mask; - else - bitField[byteNum] &= ~mask; + const typename T::value_type mask = 1 << bitNumber(position); + if (set) + bitField[byteNum] |= mask; + else + bitField[byteNum] &= ~mask; - return true; + return true; } -template -inline bool clearBit(T &bitField, int position) +template inline bool clearBit(T& bitField, int position) { - return setBit(bitField, position, false); + return setBit(bitField, position, false); } - #ifdef SUPPORT_QBITARRAY -template -inline T convert(const QBitArray &bitArray) +template inline T convert(const QBitArray& bitArray) { - T ret; - ret.resize((bitArray.size() + 7) / 8, 0); + T ret; + ret.resize((bitArray.size() + 7) / 8, 0); - for (int i = 0; i < bitArray.size(); ++i) - { - const size_t byteNum = i / 8; - const typename T::value_type mask = (1 << bitNumber(i)); - if (bitArray[i]) - ret[byteNum] |= mask; - else - ret[byteNum] &= ~mask; - } - return ret; + for (int i = 0; i < bitArray.size(); ++i) + { + const size_t byteNum = i / 8; + const typename T::value_type mask = (1 << bitNumber(i)); + if (bitArray[i]) + ret[byteNum] |= mask; + else + ret[byteNum] &= ~mask; + } + return ret; } -template -inline QBitArray convert(T &bitField, int realSize) +template inline QBitArray convert(T& bitField, int realSize) { - QBitArray ba(realSize); - for (int32_t i = 0; i < realSize; ++i) - { - const size_t byteNum = i / 8; - const typename T::value_type mask = (1 << bitNumber(i)); - bool bit = ((bitField[byteNum] & mask) == mask); - ba[i] = bit; - } - return ba; + QBitArray ba(realSize); + for (int32_t i = 0; i < realSize; ++i) + { + const size_t byteNum = i / 8; + const typename T::value_type mask = (1 << bitNumber(i)); + bool bit = ((bitField[byteNum] & mask) == mask); + ba[i] = bit; + } + return ba; } #endif -} +} // namespace BitArray -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h index 03be5b5ec..7c2ecfa1d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector.h @@ -5,31 +5,33 @@ #include #include -namespace LtsUtils { +namespace LtsUtils +{ -template inline void convert(const S &in, T &out) { - static_assert(!std::is_same_v, - "Try to convert a type to the same type - is useless"); - out.reserve(static_cast(in.size())); - std::copy(in.begin(), in.end(), std::back_inserter(out)); +template inline void convert(const S& in, T& out) +{ + static_assert(!std::is_same_v, "Try to convert a type to the same type - is useless"); + out.reserve(static_cast(in.size())); + std::copy(in.begin(), in.end(), std::back_inserter(out)); } -template inline T convert(const S &in) { - static_assert(!std::is_same_v, - "Try to convert a type to the same type - is useless"); - T out; - convert(in, out); - return out; +template inline T convert(const S& in) +{ + static_assert(!std::is_same_v, "Try to convert a type to the same type - is useless"); + T out; + convert(in, out); + return out; } -template inline QByteArray toQByteArray(const T &in) { - return convert(in); +template inline QByteArray toQByteArray(const T& in) +{ + return convert(in); } -template -bool isInVector(const T &vec, const V &valueToSearch) { - const auto end = vec.end(); - return std::find(vec.begin(), end, valueToSearch) != end; +template bool isInVector(const T& vec, const V& valueToSearch) +{ + const auto end = vec.end(); + return std::find(vec.begin(), end, valueToSearch) != end; } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h old mode 100755 new mode 100644 index 6684acf46..3c19be186 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/dds_vector_to_pixmap.h @@ -1,9 +1,9 @@ - #pragma once #include "ltsutilscore_export.h" + #include #include @@ -14,11 +14,11 @@ class QImage; namespace LtsUtils { -LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector &data); -LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray &data); -LTSUTILSCORE_EXPORT QImage getImage(const std::vector &data); -LTSUTILSCORE_EXPORT QImage getImage(const QByteArray &data); -LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng = nullptr); -LTSUTILSCORE_EXPORT std::vector fromImage(const QImage &image, bool *bIsPng = nullptr); +LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector& data); +LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray& data); +LTSUTILSCORE_EXPORT QImage getImage(const std::vector& data); +LTSUTILSCORE_EXPORT QImage getImage(const QByteArray& data); +LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng = nullptr); +LTSUTILSCORE_EXPORT std::vector fromImage(const QImage& image, bool* bIsPng = nullptr); -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json.h old mode 100755 new mode 100644 index c91ae03cc..8eef7f561 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json.h @@ -1 +1 @@ -#include +#include diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h index 7ceff4694..300bc9cee 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/json_object.h @@ -18,502 +18,671 @@ #include #include -namespace LtsUtils { +namespace LtsUtils +{ -class JsonParseError : public std::runtime_error { -public: - JsonParseError(const QJsonParseError &err) - : std::runtime_error( - "json parse error: " + err.errorString().toStdString() + - " - at offset " + std::to_string(err.offset)) {} -}; - -class JsonError : public std::runtime_error { -public: - using std::runtime_error::runtime_error; -}; - -class JsonKeyError : public JsonError { -public: - using JsonError::JsonError; -}; - -class JsonRangeError : public JsonError { -public: - using JsonError::JsonError; -}; - -class JsonTypeError : public JsonError { -public: - using JsonError::JsonError; -}; - -class JsonObject { -public: - class Key; - - JsonObject() = default; - explicit JsonObject(const QJsonObject &json) - : m_json(json), m_jsonIsSet(true) {} - - explicit JsonObject(QJsonObject &&json) - : m_json(std::move(json)), m_jsonIsSet(true) {} - - static inline JsonObject fromJson(const char *json, int len = -1); - static inline JsonObject fromJson(const QByteArray &json) { - return fromJson(json.data(), json.size()); - } - static inline JsonObject fromJson(const std::string &json) { - return fromJson(json.c_str(), json.size()); - } - - static inline JsonObject fromJsonSafe(const char *json, - int len = -1) noexcept(false); - static inline JsonObject - fromJsonSafe(const QByteArray &json) noexcept(false) { - return fromJsonSafe(json.data(), json.size()); - } - static inline JsonObject - fromJsonSafe(const std::string &json) noexcept(false) { - return fromJsonSafe(json.c_str(), json.size()); - } - - template [[nodiscard]] bool contains(const Key &key) const; - - [[nodiscard]] bool isNull(const Key &key) const { - return contains(key); - } - - [[nodiscard]] bool isEmpty() const { return m_json.isEmpty(); } - [[nodiscard]] bool isValid() const { return m_jsonIsSet; } - - template T value(const Key &key) const noexcept(false); - - template - T valueOr(const Key &key, const T &defaultValue) const noexcept(false); - - template [[nodiscard]] bool isMap() const; - - template QMap toMap() const noexcept(false); - - template std::map toStdMap() const; - - bool operator==(const JsonObject &other) const { - return m_json == other.m_json; - } - bool operator!=(const JsonObject &other) const { return !(*this == other); } - - class Key { +class JsonParseError : public std::runtime_error +{ public: - Key(QString s) : m_s(std::move(s)) {} + JsonParseError(const QJsonParseError& err) + : std::runtime_error("json parse error: " + err.errorString().toStdString() + " - at offset " + + std::to_string(err.offset)) + { + } +}; - Key(const std::string &s) : m_s(QString::fromStdString(s)) {} +class JsonError : public std::runtime_error +{ + public: + using std::runtime_error::runtime_error; +}; - Key(const char *s) : m_s(QString::fromUtf8(s)) {} +class JsonKeyError : public JsonError +{ + public: + using JsonError::JsonError; +}; - operator const QString &() const { return m_s; } +class JsonRangeError : public JsonError +{ + public: + using JsonError::JsonError; +}; + +class JsonTypeError : public JsonError +{ + public: + using JsonError::JsonError; +}; + +class JsonObject +{ + public: + class Key; + + JsonObject() = default; + + explicit JsonObject(const QJsonObject& json) : m_json(json), m_jsonIsSet(true) {} + + explicit JsonObject(QJsonObject&& json) : m_json(std::move(json)), m_jsonIsSet(true) {} + + static inline JsonObject fromJson(const char* json, int len = -1); + + static inline JsonObject fromJson(const QByteArray& json) + { + return fromJson(json.data(), json.size()); + } + + static inline JsonObject fromJson(const std::string& json) + { + return fromJson(json.c_str(), json.size()); + } + + static inline JsonObject fromJsonSafe(const char* json, int len = -1) noexcept(false); + + static inline JsonObject fromJsonSafe(const QByteArray& json) noexcept(false) + { + return fromJsonSafe(json.data(), json.size()); + } + + static inline JsonObject fromJsonSafe(const std::string& json) noexcept(false) + { + return fromJsonSafe(json.c_str(), json.size()); + } + + template [[nodiscard]] bool contains(const Key& key) const; + + [[nodiscard]] bool isNull(const Key& key) const + { + return contains(key); + } + + [[nodiscard]] bool isEmpty() const + { + return m_json.isEmpty(); + } + + [[nodiscard]] bool isValid() const + { + return m_jsonIsSet; + } + + template T value(const Key& key) const noexcept(false); + + template T valueOr(const Key& key, const T& defaultValue) const noexcept(false); + + template [[nodiscard]] bool isMap() const; + + template QMap toMap() const noexcept(false); + + template std::map toStdMap() const; + + bool operator==(const JsonObject& other) const + { + return m_json == other.m_json; + } + + bool operator!=(const JsonObject& other) const + { + return !(*this == other); + } + + class Key + { + public: + Key(QString s) : m_s(std::move(s)) {} + + Key(const std::string& s) : m_s(QString::fromStdString(s)) {} + + Key(const char* s) : m_s(QString::fromUtf8(s)) {} + + operator const QString&() const + { + return m_s; + } + + private: + const QString m_s; + }; + + operator const QJsonObject&() const + { + return m_json; + } + + [[nodiscard]] const QJsonObject& object() const + { + return m_json; + } private: - const QString m_s; - }; + [[nodiscard]] bool containsAny(const QString& key) const + { + return m_json.contains(key); + } - operator const QJsonObject &() const { return m_json; } - [[nodiscard]] const QJsonObject &object() const { return m_json; } - -private: - [[nodiscard]] bool containsAny(const QString &key) const { - return m_json.contains(key); - } - - QJsonObject m_json; - bool m_jsonIsSet = false; + QJsonObject m_json; + bool m_jsonIsSet = false; }; -JsonObject JsonObject::fromJson(const char *json, int len) { - if (len < 0) - len = strlen(json); - QJsonParseError error; - const auto doc = - QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); - if (error.error != QJsonParseError::NoError) - return {}; +JsonObject JsonObject::fromJson(const char* json, int len) +{ + if (len < 0) + len = strlen(json); + QJsonParseError error; + const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); + if (error.error != QJsonParseError::NoError) + return {}; - if (!doc.isObject()) - return {}; + if (!doc.isObject()) + return {}; - return JsonObject(doc.object()); + return JsonObject(doc.object()); } -JsonObject JsonObject::fromJsonSafe(const char *json, int len) noexcept(false) { - if (len < 0) - len = strlen(json); - QJsonParseError error; - const auto doc = - QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); - if (error.error != QJsonParseError::NoError) - throw JsonParseError(error); +JsonObject JsonObject::fromJsonSafe(const char* json, int len) noexcept(false) +{ + if (len < 0) + len = strlen(json); + QJsonParseError error; + const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); + if (error.error != QJsonParseError::NoError) + throw JsonParseError(error); - if (!doc.isObject()) - throw JsonTypeError("JSON root is not an object"); + if (!doc.isObject()) + throw JsonTypeError("JSON root is not an object"); - return JsonObject(doc.object()); + return JsonObject(doc.object()); } -class JsonArray { -public: - JsonArray() = default; - explicit JsonArray(const QJsonArray &json) - : m_json(json), m_jsonIsSet(true) {} +class JsonArray +{ + public: + JsonArray() = default; - explicit JsonArray(QJsonArray &&json) - : m_json(std::move(json)), m_jsonIsSet(true) {} + explicit JsonArray(const QJsonArray& json) : m_json(json), m_jsonIsSet(true) {} - static inline JsonArray fromJson(const char *json, int len = -1); - static inline JsonArray fromJson(const QByteArray &json) { - return fromJson(json.data(), json.size()); - } - static inline JsonArray fromJson(const std::string &json) { - return fromJson(json.c_str(), json.size()); - } + explicit JsonArray(QJsonArray&& json) : m_json(std::move(json)), m_jsonIsSet(true) {} - static inline JsonArray fromJsonSafe(const char *json, - int len = -1) noexcept(false); - static inline JsonArray fromJsonSafe(const QByteArray &json) noexcept(false) { - return fromJson(json.data(), json.size()); - } - static inline JsonArray - fromJsonSafe(const std::string &json) noexcept(false) { - return fromJson(json.c_str(), json.size()); - } + static inline JsonArray fromJson(const char* json, int len = -1); - [[nodiscard]] int size() const { return m_json.size(); } - [[nodiscard]] bool isEmpty() const { return m_json.isEmpty(); } - [[nodiscard]] bool isValid() const { return m_jsonIsSet; } + static inline JsonArray fromJson(const QByteArray& json) + { + return fromJson(json.data(), json.size()); + } - template - [[nodiscard]] bool contains(int index) const noexcept(false); + static inline JsonArray fromJson(const std::string& json) + { + return fromJson(json.c_str(), json.size()); + } - [[nodiscard]] bool isNull(int index) const noexcept(false) { - return contains(index); - } + static inline JsonArray fromJsonSafe(const char* json, int len = -1) noexcept(false); - template T at(int index) const noexcept(false); + static inline JsonArray fromJsonSafe(const QByteArray& json) noexcept(false) + { + return fromJson(json.data(), json.size()); + } - template [[nodiscard]] bool isVector() const; + static inline JsonArray fromJsonSafe(const std::string& json) noexcept(false) + { + return fromJson(json.c_str(), json.size()); + } - template QVector toVector() const noexcept(false); + [[nodiscard]] int size() const + { + return m_json.size(); + } - template std::vector toStdVector() const; + [[nodiscard]] bool isEmpty() const + { + return m_json.isEmpty(); + } - bool operator==(const JsonArray &other) const { - return m_json == other.m_json; - } - bool operator!=(const JsonArray &other) const { return !(*this == other); } + [[nodiscard]] bool isValid() const + { + return m_jsonIsSet; + } - const QJsonArray &operator()() const { return m_json; } + template [[nodiscard]] bool contains(int index) const noexcept(false); -private: - QJsonArray m_json; - bool m_jsonIsSet = false; + [[nodiscard]] bool isNull(int index) const noexcept(false) + { + return contains(index); + } + + template T at(int index) const noexcept(false); + + template [[nodiscard]] bool isVector() const; + + template QVector toVector() const noexcept(false); + + template std::vector toStdVector() const; + + bool operator==(const JsonArray& other) const + { + return m_json == other.m_json; + } + + bool operator!=(const JsonArray& other) const + { + return !(*this == other); + } + + const QJsonArray& operator()() const + { + return m_json; + } + + private: + QJsonArray m_json; + bool m_jsonIsSet = false; }; -JsonArray JsonArray::fromJson(const char *json, int len) { - if (len < 0) - len = strlen(json); - QJsonParseError error; - QJsonDocument doc = - QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); - if (error.error != QJsonParseError::NoError) - return {}; +JsonArray JsonArray::fromJson(const char* json, int len) +{ + if (len < 0) + len = strlen(json); + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); + if (error.error != QJsonParseError::NoError) + return {}; - if (!doc.isArray()) - return {}; + if (!doc.isArray()) + return {}; - return JsonArray(doc.array()); + return JsonArray(doc.array()); } -JsonArray JsonArray::fromJsonSafe(const char *json, int len) noexcept(false) { - if (len < 0) - len = strlen(json); - QJsonParseError error; - const auto doc = - QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); - if (error.error != QJsonParseError::NoError) - throw JsonParseError(error); +JsonArray JsonArray::fromJsonSafe(const char* json, int len) noexcept(false) +{ + if (len < 0) + len = strlen(json); + QJsonParseError error; + const auto doc = QJsonDocument::fromJson(QByteArray::fromRawData(json, len), &error); + if (error.error != QJsonParseError::NoError) + throw JsonParseError(error); - if (!doc.isArray()) - throw JsonTypeError("JSON root is not an array"); + if (!doc.isArray()) + throw JsonTypeError("JSON root is not an array"); - return JsonArray(doc.array()); + return JsonArray(doc.array()); } template struct JsonValue; -template struct JsonLimits { - static constexpr Int lowest() { return std::numeric_limits::lowest(); } - static constexpr Int max() { return std::numeric_limits::max(); } +template struct JsonLimits +{ + static constexpr Int lowest() + { + return std::numeric_limits::lowest(); + } + + static constexpr Int max() + { + return std::numeric_limits::max(); + } }; -template <> struct JsonLimits { - static constexpr int64_t lowest() { - return -(static_cast(1) << 53) + 1; - } - static constexpr int64_t max() { return (static_cast(1) << 53) - 1; } +template <> struct JsonLimits +{ + static constexpr int64_t lowest() + { + return -(static_cast(1) << 53) + 1; + } + + static constexpr int64_t max() + { + return (static_cast(1) << 53) - 1; + } }; -template <> struct JsonLimits { - static constexpr uint64_t lowest() { return 0; } - static constexpr uint64_t max() { return JsonLimits::max(); } +template <> struct JsonLimits +{ + static constexpr uint64_t lowest() + { + return 0; + } + + static constexpr uint64_t max() + { + return JsonLimits::max(); + } }; -template struct JsonIntValue { - static bool matchesType(const QJsonValue &value) { - if (!value.isDouble()) - return false; - double val = value.toDouble(); +template struct JsonIntValue +{ + static bool matchesType(const QJsonValue& value) + { + if (!value.isDouble()) + return false; + double val = value.toDouble(); - if (val < JsonLimits::lowest()) - return false; - if (val > JsonLimits::max()) - return false; + if (val < JsonLimits::lowest()) + return false; + if (val > JsonLimits::max()) + return false; - double wholeInt = static_cast(val); - return val == wholeInt; - } + double wholeInt = static_cast(val); + return val == wholeInt; + } - static Int value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Int"); - return static_cast(value.toDouble()); - } + static Int value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Int"); + return static_cast(value.toDouble()); + } }; -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue : JsonIntValue {}; - -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isDouble(); } - - static double value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Double"); - return value.toDouble(); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isBool(); } - - static bool value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Bool"); - return value.toBool(); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isString(); } - - static QString value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type String"); - return value.toString(); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isString(); } - - static std::string value(const QJsonValue &value) { - return JsonValue::value(value).toStdString(); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isObject(); } - - static QJsonObject value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Object"); - return value.toObject(); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isObject(); } - static JsonObject value(const QJsonValue &value) { - return JsonObject(JsonValue::value(value)); - } +template <> struct JsonValue : JsonIntValue +{ }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isNull(); } +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isDouble(); + } + + static double value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Double"); + return value.toDouble(); + } }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isArray(); } +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isBool(); + } - static QJsonArray value(const QJsonValue &value) noexcept(false) { - if (!matchesType(value)) - throw JsonTypeError("JSON value not of type Array"); - return value.toArray(); - } + static bool value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Bool"); + return value.toBool(); + } }; -template <> struct JsonValue { - static bool matchesType(const QJsonValue &value) { return value.isArray(); } - static JsonArray value(const QJsonValue &value) { - return JsonArray(JsonValue::value(value)); - } +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isString(); + } + + static QString value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type String"); + return value.toString(); + } }; -template struct JsonValue> { - static bool matchesType(const QJsonValue &value) { - if (!value.isArray()) - return false; +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isString(); + } - const JsonArray array(value.toArray()); - return array.isVector(); - } - - static QVector value(const QJsonValue &value) { - const JsonArray array(JsonValue::value(value)); - return array.toVector(); - } + static std::string value(const QJsonValue& value) + { + return JsonValue::value(value).toStdString(); + } }; -template struct JsonValue> { - static bool matchesType(const QJsonValue &value) { - return JsonValue>::matchesType(value); - } +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isObject(); + } - static std::vector value(const QJsonValue &value) { - const JsonArray array(JsonValue::value(value)); - return array.toStdVector(); - } + static QJsonObject value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Object"); + return value.toObject(); + } }; -template struct JsonValue> { - static bool matchesType(const QJsonValue &value) { - if (!value.isObject()) - return false; +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isObject(); + } - const JsonObject obj(JsonValue::value(value)); - return obj.isMap(); - } - - static QMap value(const QJsonValue &value) { - const JsonObject obj(JsonValue::value(value)); - return obj.toMap(); - } + static JsonObject value(const QJsonValue& value) + { + return JsonObject(JsonValue::value(value)); + } }; -template struct JsonValue> { - static bool matchesType(const QJsonValue &value) { - return JsonValue>::matchesType(value); - } - - static std::map value(const QJsonValue &value) { - const JsonObject obj(JsonValue::value(value)); - return obj.toStdMap(); - } +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isNull(); + } }; -template bool JsonObject::contains(const Key &key) const { - if (!m_json.contains(key)) - return false; - return JsonValue::matchesType(m_json.value(key)); +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isArray(); + } + + static QJsonArray value(const QJsonValue& value) noexcept(false) + { + if (!matchesType(value)) + throw JsonTypeError("JSON value not of type Array"); + return value.toArray(); + } +}; + +template <> struct JsonValue +{ + static bool matchesType(const QJsonValue& value) + { + return value.isArray(); + } + + static JsonArray value(const QJsonValue& value) + { + return JsonArray(JsonValue::value(value)); + } +}; + +template struct JsonValue> +{ + static bool matchesType(const QJsonValue& value) + { + if (!value.isArray()) + return false; + + const JsonArray array(value.toArray()); + return array.isVector(); + } + + static QVector value(const QJsonValue& value) + { + const JsonArray array(JsonValue::value(value)); + return array.toVector(); + } +}; + +template struct JsonValue> +{ + static bool matchesType(const QJsonValue& value) + { + return JsonValue>::matchesType(value); + } + + static std::vector value(const QJsonValue& value) + { + const JsonArray array(JsonValue::value(value)); + return array.toStdVector(); + } +}; + +template struct JsonValue> +{ + static bool matchesType(const QJsonValue& value) + { + if (!value.isObject()) + return false; + + const JsonObject obj(JsonValue::value(value)); + return obj.isMap(); + } + + static QMap value(const QJsonValue& value) + { + const JsonObject obj(JsonValue::value(value)); + return obj.toMap(); + } +}; + +template struct JsonValue> +{ + static bool matchesType(const QJsonValue& value) + { + return JsonValue>::matchesType(value); + } + + static std::map value(const QJsonValue& value) + { + const JsonObject obj(JsonValue::value(value)); + return obj.toStdMap(); + } +}; + +template bool JsonObject::contains(const Key& key) const +{ + if (!m_json.contains(key)) + return false; + return JsonValue::matchesType(m_json.value(key)); } -template T JsonObject::value(const Key &key) const noexcept(false) { - if (!containsAny(key)) - throw JsonKeyError("no element with key: " + - static_cast(key).toStdString()); - try { - return JsonValue::value(m_json.value(key)); - } catch (const JsonTypeError &typeError) { - throw JsonTypeError(std::string(typeError.what()) + " - key: " + - static_cast(key).toStdString()); - } +template T JsonObject::value(const Key& key) const noexcept(false) +{ + if (!containsAny(key)) + throw JsonKeyError("no element with key: " + static_cast(key).toStdString()); + try + { + return JsonValue::value(m_json.value(key)); + } + catch (const JsonTypeError& typeError) + { + throw JsonTypeError(std::string(typeError.what()) + + " - key: " + static_cast(key).toStdString()); + } } -template -T JsonObject::valueOr(const Key &key, const T &defaultValue) const { - try { - return value(key); - } +template T JsonObject::valueOr(const Key& key, const T& defaultValue) const +{ + try + { + return value(key); + } - catch (const JsonKeyError &) { - return defaultValue; - } + catch (const JsonKeyError&) + { + return defaultValue; + } } -template bool JsonObject::isMap() const { - const QStringList keys = m_json.keys(); - for (const auto &key : keys) - if (!JsonValue::matchesType(m_json.value(key))) - return false; +template bool JsonObject::isMap() const +{ + const QStringList keys = m_json.keys(); + for (const auto& key : keys) + if (!JsonValue::matchesType(m_json.value(key))) + return false; - return true; + return true; } -template QMap JsonObject::toMap() const { - QMap result; - for (auto current = m_json.begin(); current != m_json.end(); ++current) - result.insert(current.key(), JsonValue::value(current.value())); - return result; +template QMap JsonObject::toMap() const +{ + QMap result; + for (auto current = m_json.begin(); current != m_json.end(); ++current) + result.insert(current.key(), JsonValue::value(current.value())); + return result; } -template std::map JsonObject::toStdMap() const { - std::map result; - for (auto current = m_json.begin(); current != m_json.end(); ++current) - result.insert( - {current.key().toStdString(), JsonValue::value(current.value())}); - return result; +template std::map JsonObject::toStdMap() const +{ + std::map result; + for (auto current = m_json.begin(); current != m_json.end(); ++current) + result.insert({current.key().toStdString(), JsonValue::value(current.value())}); + return result; } -template bool JsonArray::contains(int index) const noexcept(false) { - if (index < 0 || index >= m_json.size()) - throw JsonRangeError("index out of range: " + std::to_string(index)); - return JsonValue::matchesType(m_json.at(index)); +template bool JsonArray::contains(int index) const noexcept(false) +{ + if (index < 0 || index >= m_json.size()) + throw JsonRangeError("index out of range: " + std::to_string(index)); + return JsonValue::matchesType(m_json.at(index)); } -template T JsonArray::at(int index) const noexcept(false) { - if (index < 0 || index >= m_json.size()) - throw JsonRangeError("index out of range: " + std::to_string(index)); - return JsonValue::value(m_json.at(index)); +template T JsonArray::at(int index) const noexcept(false) +{ + if (index < 0 || index >= m_json.size()) + throw JsonRangeError("index out of range: " + std::to_string(index)); + return JsonValue::value(m_json.at(index)); } -template bool JsonArray::isVector() const { - for (const QJsonValue &value : m_json) - if (!JsonValue::matchesType(value)) - return false; - return true; +template bool JsonArray::isVector() const +{ + for (const QJsonValue& value : m_json) + if (!JsonValue::matchesType(value)) + return false; + return true; } -template QVector JsonArray::toVector() const { - QVector result; - result.reserve(m_json.size()); - for (const QJsonValue &value : m_json) - result.push_back(JsonValue::value(value)); - return result; +template QVector JsonArray::toVector() const +{ + QVector result; + result.reserve(m_json.size()); + for (const QJsonValue& value : m_json) + result.push_back(JsonValue::value(value)); + return result; } -template std::vector JsonArray::toStdVector() const { - std::vector result; - result.reserve(m_json.size()); - for (const QJsonValue &value : m_json) - result.push_back(JsonValue::value(value)); - return result; +template std::vector JsonArray::toStdVector() const +{ + std::vector result; + result.reserve(m_json.size()); + for (const QJsonValue& value : m_json) + result.push_back(JsonValue::value(value)); + return result; } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp old mode 100755 new mode 100644 index 5bd5cb61d..9973dd562 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.cpp @@ -3,12 +3,12 @@ namespace LtsUtils { -LtsUtils::LtsPortRange fromQPoint(const QPoint &point) +LtsUtils::LtsPortRange fromQPoint(const QPoint& point) { - if (point.x() < 1025 || point.y() > 65535 || point.x() > point.y()) - return {}; + if (point.x() < 1025 || point.y() > 65535 || point.x() > point.y()) + return {}; - return {static_cast(point.x()), static_cast(point.y())}; + return {static_cast(point.x()), static_cast(point.y())}; } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h old mode 100755 new mode 100644 index 003990a53..681d1360f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_portrange.h @@ -7,9 +7,7 @@ namespace LtsUtils { - typedef QPair LtsPortRange; - - LTSUTILSCORE_EXPORT LtsPortRange fromQPoint(const QPoint &point); -} - +typedef QPair LtsPortRange; +LTSUTILSCORE_EXPORT LtsPortRange fromQPoint(const QPoint& point); +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp old mode 100755 new mode 100644 index 239a14cc4..042b7caf4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.cpp @@ -1,25 +1,22 @@ - #include "lts_translatable_identifier.h" #include - namespace LtsUtils { -LtsTranslatableIdentifier::LtsTranslatableIdentifier(const QString &identifier, const QObject *context, - const char *translatableText) - : m_identifier(identifier) - , m_translationContext(context->metaObject()->className()) - , m_translatableText(translatableText) -{} - - -const QString LtsTranslatableIdentifier::translatedText(const char *disambiguation, int n) const +LtsTranslatableIdentifier::LtsTranslatableIdentifier(const QString& identifier, const QObject* context, + const char* translatableText) + : m_identifier(identifier), m_translationContext(context->metaObject()->className()), + m_translatableText(translatableText) { - if (m_identifier.isEmpty() || m_translationContext == nullptr || m_translatableText == nullptr) - return {}; - return QCoreApplication::translate(m_translationContext, m_translatableText, disambiguation, n); } -} + +const QString LtsTranslatableIdentifier::translatedText(const char* disambiguation, int n) const +{ + if (m_identifier.isEmpty() || m_translationContext == nullptr || m_translatableText == nullptr) + return {}; + return QCoreApplication::translate(m_translationContext, m_translatableText, disambiguation, n); +} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h old mode 100755 new mode 100644 index 0f990dc2e..7ba3064b4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/lts_translatable_identifier.h @@ -1,33 +1,35 @@ #pragma once - - - #include "ltsutilscore_export.h" #include #include - namespace LtsUtils { class LTSUTILSCORE_EXPORT LtsTranslatableIdentifier { -public: - LtsTranslatableIdentifier() - : m_translationContext(nullptr) - , m_translatableText("") - {} + public: + LtsTranslatableIdentifier() : m_translationContext(nullptr), m_translatableText("") {} - LtsTranslatableIdentifier(const QString &identifier, const QObject *context, const char *translatableText); - const QString &identifier() const { return m_identifier; } - const QString translatedText(const char *disambiguation = nullptr, int n = -1) const; - const QString _context() const { return QString::fromUtf8(m_translationContext); } + LtsTranslatableIdentifier(const QString& identifier, const QObject* context, const char* translatableText); -private: - QString m_identifier; - const char *m_translationContext; - - const char *m_translatableText; + const QString& identifier() const + { + return m_identifier; + } + + const QString translatedText(const char* disambiguation = nullptr, int n = -1) const; + + const QString _context() const + { + return QString::fromUtf8(m_translationContext); + } + + private: + QString m_identifier; + const char* m_translationContext; + + const char* m_translatableText; }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h index 1667d8e27..0d1ad9ab8 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/ltsutilscore_export.h @@ -1,21 +1,21 @@ /** - * Export definitions for LtsUtilsCore - * $Id$ - * $HeadURL$ - * $Author$ - */ + * Export definitions for LtsUtilsCore + * $Id$ + * $HeadURL$ + * $Author$ + */ #pragma once #include #ifndef LTSUTILSCORE_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSUTILSCORE_EXPORT -# else -# if defined(MAKE_LTSUTILSCORE_LIB) -# define LTSUTILSCORE_EXPORT Q_DECL_EXPORT -# else -# define LTSUTILSCORE_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSUTILSCORE_EXPORT +#else +#if defined(MAKE_LTSUTILSCORE_LIB) +#define LTSUTILSCORE_EXPORT Q_DECL_EXPORT +#else +#define LTSUTILSCORE_EXPORT Q_DECL_IMPORT +#endif +#endif #endif \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h old mode 100755 new mode 100644 index 20f04b9f4..8ee74b67a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/outdated_position.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,7 +8,7 @@ namespace LtsUtils { inline bool isPositionTimeOutdated(qint64 curTime, qint64 posTime) { - - return curTime > posTime + 11 * 60 * 1000; -} + + return curTime > posTime + 11 * 60 * 1000; } +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp old mode 100755 new mode 100644 index d444982d6..71f01f649 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.cpp @@ -1,170 +1,151 @@ - #include "pgarray.h" -#include + #include #include - +#include #include #include namespace LtsUtils { -template -static inline QString convertToPgString(const std::vector &data) +template static inline QString convertToPgString(const std::vector& data) { - if (data.size() == 0) - return QLatin1String("{}"); - QString ret(QLatin1Char('{')); - for (T i : data) - ret += QString::number(i) + QLatin1Char(','); - ret.chop(1); - ret += QLatin1Char('}'); - return ret; + if (data.size() == 0) + return QLatin1String("{}"); + QString ret(QLatin1Char('{')); + for (T i : data) + ret += QString::number(i) + QLatin1Char(','); + ret.chop(1); + ret += QLatin1Char('}'); + return ret; } -template<> -LTSUTILSCORE_EXPORT QString IntArray::toPgString() const +template <> LTSUTILSCORE_EXPORT QString IntArray::toPgString() const { - return convertToPgString(m_data); + return convertToPgString(m_data); } -template<> -LTSUTILSCORE_EXPORT QString BigintArray::toPgString() const +template <> LTSUTILSCORE_EXPORT QString BigintArray::toPgString() const { - return convertToPgString(m_data); + return convertToPgString(m_data); } -template -static inline T convertFromPgString(const QString &str, const std::function &convertFunc) +template +static inline T convertFromPgString(const QString& str, + const std::function& convertFunc) { - typename T::ContainerType result; + typename T::ContainerType result; + + int idxStart = str.indexOf(QLatin1Char('{')); + int idxEnd = str.lastIndexOf(QLatin1Char('}')); + if (idxEnd < idxStart) + return T(result); + if (idxStart < 0 && idxEnd < 0) + { + + idxStart = -1; + idxEnd = str.length() + 1; + } + + const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); + const QVector vec = strRef.split(QLatin1Char(','), Qt::SkipEmptyParts); + result.reserve(vec.size()); + for (const QStringView& s : vec) + { + bool ok = false; + const typename T::Type i = convertFunc(s, &ok); + if (ok) + result.push_back(i); + } - int idxStart = str.indexOf(QLatin1Char('{')); - int idxEnd = str.lastIndexOf(QLatin1Char('}')); - if (idxEnd < idxStart) return T(result); - if (idxStart < 0 && idxEnd < 0) - { - - idxStart = -1; - idxEnd = str.length() + 1; - } - - const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); - const QVector vec = strRef.split(QLatin1Char(','), Qt::SkipEmptyParts); - result.reserve(vec.size()); - for (const QStringView &s : vec) - { - bool ok = false; - const typename T::Type i = convertFunc(s, &ok); - if (ok) - result.push_back(i); - } - - return T(result); } -template<> -LTSUTILSCORE_EXPORT IntArray IntArray::fromPgString(const QString &str) +template <> LTSUTILSCORE_EXPORT IntArray IntArray::fromPgString(const QString& str) { - return convertFromPgString(str, - [](QStringView val, bool * bOk) { return val.toString().toInt(bOk);}); + return convertFromPgString(str, [](QStringView val, bool* bOk) { return val.toString().toInt(bOk); }); } -template<> -LTSUTILSCORE_EXPORT BigintArray BigintArray::fromPgString(const QString &str) +template <> LTSUTILSCORE_EXPORT BigintArray BigintArray::fromPgString(const QString& str) { - return convertFromPgString(str, - [](QStringView val, bool * bOk) { return val.toString().toLongLong(bOk);}); + return convertFromPgString(str, + [](QStringView val, bool* bOk) { return val.toString().toLongLong(bOk); }); } - - - - - -template -static inline QString convertToPgString(const std::map &data) +template static inline QString convertToPgString(const std::map& data) { - if (data.size() == 0) - return QLatin1String("{}"); - QString ret(QLatin1Char('{')); - for (const auto &it : data) - { - ret += QLatin1Char('{') + QString::number(it.first) + - QLatin1Char(',') + QString::number(it.second) + QLatin1String("},"); - } - ret.chop(1); - ret += QLatin1Char('}'); - return ret; + if (data.size() == 0) + return QLatin1String("{}"); + QString ret(QLatin1Char('{')); + for (const auto& it : data) + { + ret += QLatin1Char('{') + QString::number(it.first) + QLatin1Char(',') + QString::number(it.second) + + QLatin1String("},"); + } + ret.chop(1); + ret += QLatin1Char('}'); + return ret; } -template<> -LTSUTILSCORE_EXPORT QString IntArray2D::toPgString() const +template <> LTSUTILSCORE_EXPORT QString IntArray2D::toPgString() const { - return convertToPgString(m_data); + return convertToPgString(m_data); } -template<> -LTSUTILSCORE_EXPORT QString BigintArray2D::toPgString() const +template <> LTSUTILSCORE_EXPORT QString BigintArray2D::toPgString() const { - return convertToPgString(m_data); + return convertToPgString(m_data); } - -template -static inline T convertFromPgString2D(const QString &str, const std::function &convertFunc) +template +static inline T convertFromPgString2D(const QString& str, + const std::function& convertFunc) { - typename T::ContainerType ret; - int idxStart = str.indexOf(QLatin1Char('{')); - int idxEnd = str.lastIndexOf(QLatin1Char('}')); - if (idxEnd < idxStart) + typename T::ContainerType ret; + int idxStart = str.indexOf(QLatin1Char('{')); + int idxEnd = str.lastIndexOf(QLatin1Char('}')); + if (idxEnd < idxStart) + return T(ret); + if (idxStart < 0 && idxEnd < 0) + { + + idxStart = -1; + idxEnd = str.length() + 1; + } + + const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); + idxStart = strRef.indexOf(QLatin1Char('{')); + while (idxStart >= 0) + { + idxEnd = strRef.indexOf(QLatin1Char('}'), idxStart); + if (idxEnd < 0) + break; + + const QStringView keyValueStr = strRef.mid(idxStart + 1, idxEnd - idxStart - 1); + const QVector keyValuePair = keyValueStr.split(QLatin1Char(','), Qt::SkipEmptyParts); + if (keyValuePair.size() != 2) + break; + const typename T::Type key = convertFunc(keyValuePair.at(0).trimmed()); + const typename T::Type value = convertFunc(keyValuePair.at(1).trimmed()); + ret.insert(std::make_pair(key, value)); + + idxStart = strRef.indexOf(QLatin1Char('{'), idxEnd + 1); + } + return T(ret); - if (idxStart < 0 && idxEnd < 0) - { - - idxStart = -1; - idxEnd = str.length() + 1; - } - - const QStringView strRef = QStringView(str).mid(idxStart + 1, idxEnd - idxStart - 1); - idxStart = strRef.indexOf(QLatin1Char('{')); - while (idxStart >= 0) - { - idxEnd = strRef.indexOf(QLatin1Char('}'), idxStart); - if (idxEnd < 0) - break; - - const QStringView keyValueStr = strRef.mid(idxStart + 1, idxEnd - idxStart - 1); - const QVector keyValuePair = keyValueStr.split(QLatin1Char(','), Qt::SkipEmptyParts); - if (keyValuePair.size() != 2) - break; - const typename T::Type key = convertFunc(keyValuePair.at(0).trimmed()); - const typename T::Type value = convertFunc(keyValuePair.at(1).trimmed()); - ret.insert(std::make_pair(key, value)); - - - idxStart = strRef.indexOf(QLatin1Char('{'), idxEnd + 1); - } - - return T(ret); } -template<> -LTSUTILSCORE_EXPORT IntArray2D IntArray2D::fromPgString(const QString &str) +template <> LTSUTILSCORE_EXPORT IntArray2D IntArray2D::fromPgString(const QString& str) { - return convertFromPgString2D(str, - [](QStringView val) { return val.toString().toInt();}); + return convertFromPgString2D(str, [](QStringView val) { return val.toString().toInt(); }); } -template<> -LTSUTILSCORE_EXPORT BigintArray2D BigintArray2D::fromPgString(const QString &str) +template <> LTSUTILSCORE_EXPORT BigintArray2D BigintArray2D::fromPgString(const QString& str) { - return convertFromPgString2D(str, - [](QStringView val) { return val.toString().toLongLong();}); + return convertFromPgString2D(str, [](QStringView val) { return val.toString().toLongLong(); }); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h index 4bd2900cd..c4549553d 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/pgarray.h @@ -6,23 +6,29 @@ #include #include -namespace LtsUtils { +namespace LtsUtils +{ -template class PgArray { -public: - using Type = T; - using ContainerType = C; +template class PgArray +{ + public: + using Type = T; + using ContainerType = C; - PgArray() = default; - Q_DECL_CONSTEXPR explicit PgArray(const C &data) : m_data(data) {} + PgArray() = default; - Q_DECL_CONSTEXPR C operator()() const { return m_data; } + Q_DECL_CONSTEXPR explicit PgArray(const C& data) : m_data(data) {} - [[nodiscard]] QString toPgString() const; - static PgArray fromPgString(const QString &str); + Q_DECL_CONSTEXPR C operator()() const + { + return m_data; + } -private: - C m_data; + [[nodiscard]] QString toPgString() const; + static PgArray fromPgString(const QString& str); + + private: + C m_data; }; using IntArray = PgArray>; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp old mode 100755 new mode 100644 index 0fc9bfd5c..9a3cebc10 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.cpp @@ -1,6 +1,5 @@ - #include "promise.h" #include @@ -8,96 +7,74 @@ namespace LtsUtils { -Promise::Promise(const std::function &function, QObject *parent) - : QObject(parent) - , m_functionAlreadySet(false) - , m_timeout(new QTimer(this)) - , m_resultSet(false) - , m_timeoutSet(false) +Promise::Promise(const std::function& function, QObject* parent) + : QObject(parent), m_functionAlreadySet(false), m_timeout(new QTimer(this)), m_resultSet(false), m_timeoutSet(false) { - m_timeout->setSingleShot(true); - connect(m_timeout, &QTimer::timeout, - this, &Promise::slotTimeout); - setFunction(function); + m_timeout->setSingleShot(true); + connect(m_timeout, &QTimer::timeout, this, &Promise::slotTimeout); + setFunction(function); } - -void Promise::setFunction(const std::function &function) +void Promise::setFunction(const std::function& function) { - if (!function || m_functionAlreadySet) - return; + if (!function || m_functionAlreadySet) + return; - m_functionAlreadySet = true; + m_functionAlreadySet = true; - if (m_timeoutSet) - m_timeout->start(); + if (m_timeoutSet) + m_timeout->start(); - - QTimer::singleShot(0, this, [this, function]() - { - - function([this](const QVariant &value) - { - resolve(value); - }, [this](const QVariant &value) - { - - reject(value); + QTimer::singleShot(0, this, [this, function]() { + function([this](const QVariant& value) { resolve(value); }, [this](const QVariant& value) { reject(value); }); }); - }); } - void Promise::setTimeout(int interval) { - m_timeout->stop(); - m_timeout->setInterval(interval); - m_timeoutSet = (interval != 0); + m_timeout->stop(); + m_timeout->setInterval(interval); + m_timeoutSet = (interval != 0); - if (interval != 0 && m_functionAlreadySet) - m_timeout->start(); + if (interval != 0 && m_functionAlreadySet) + m_timeout->start(); } - void Promise::slotTimeout() { - reject(QStringLiteral("timeout")); + reject(QStringLiteral("timeout")); } - -void Promise::resolve(const QVariant &value) +void Promise::resolve(const QVariant& value) { - if (m_resultSet) - return; - m_resultSet = true; + if (m_resultSet) + return; + m_resultSet = true; - m_timeout->stop(); - m_resolveFn(value); + m_timeout->stop(); + m_resolveFn(value); } - -void Promise::reject(const QVariant &value) +void Promise::reject(const QVariant& value) { - if (m_resultSet) - return; - m_resultSet = true; + if (m_resultSet) + return; + m_resultSet = true; - m_timeout->stop(); - m_rejectFn(value); + m_timeout->stop(); + m_rejectFn(value); } - -Promise &Promise::resolved(ResultFunction resolveFn) +Promise& Promise::resolved(ResultFunction resolveFn) { - m_resolveFn = resolveFn; - return *this; + m_resolveFn = resolveFn; + return *this; } - -Promise &Promise::rejected(ResultFunction rejectFn) +Promise& Promise::rejected(ResultFunction rejectFn) { - m_rejectFn = rejectFn; - return *this; + m_rejectFn = rejectFn; + return *this; } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h old mode 100755 new mode 100644 index f26084536..23d24a982 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise.h @@ -1,72 +1,48 @@ #pragma once - - - #include "ltsutilscore_export.h" #include #include - #include - class QTimer; - namespace LtsUtils { -typedef std::function RawResultFunction; -typedef const RawResultFunction &ResultFunction; - - - +typedef std::function RawResultFunction; +typedef const RawResultFunction& ResultFunction; class LTSUTILSCORE_EXPORT Promise : public QObject { - Q_OBJECT + Q_OBJECT -public: - + public: + Promise(const std::function& function, + QObject* parent = nullptr); - Promise(const std::function &function, QObject *parent = nullptr); + void setFunction(const std::function& function); - + void resolve(const QVariant& value = QVariant()); - void setFunction(const std::function &function); + void reject(const QVariant& value = QVariant()); - + void setTimeout(int interval); - void resolve(const QVariant &value = QVariant()); + Promise& resolved(ResultFunction resolveFn); - + Promise& rejected(ResultFunction rejectFn); - void reject(const QVariant &value = QVariant()); + private: + RawResultFunction m_resolveFn; + RawResultFunction m_rejectFn; + bool m_functionAlreadySet; + QTimer* m_timeout; + bool m_resultSet; + bool m_timeoutSet; - - - void setTimeout(int interval); - - - - Promise &resolved(ResultFunction resolveFn); - - - - Promise &rejected(ResultFunction rejectFn); - - -private: - RawResultFunction m_resolveFn; - RawResultFunction m_rejectFn; - bool m_functionAlreadySet; - QTimer *m_timeout; - bool m_resultSet; - bool m_timeoutSet; - - -private slots: - void slotTimeout(); + private slots: + void slotTimeout(); }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp old mode 100755 new mode 100644 index 4fa512d34..f83f98b70 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.cpp @@ -1,165 +1,100 @@ #include "promise_examples.h" + #include "promise.h" -#include -#include - - #include - +#include +#include namespace LtsUtils { - void PromiseExample1_Class::doSomethingAsync1() { - QTimer::singleShot(200, this, [this]() - { - emit signalDone1(true); - }); + QTimer::singleShot(200, this, [this]() { emit signalDone1(true); }); } - void PromiseExample1_Class::doSomethingAsync2() { - QTimer::singleShot(450, this, [this]() - { - emit signalDone2(true, 1234); - }); + QTimer::singleShot(450, this, [this]() { emit signalDone2(true, 1234); }); } - -PromiseExample1::PromiseExample1(QObject *parent) - : QObject(parent) - , m_success(false) +PromiseExample1::PromiseExample1(QObject* parent) : QObject(parent), m_success(false) { - + auto func = [this](ResultFunction resolve, ResultFunction reject) { + PromiseExample1_Class* c = new PromiseExample1_Class(this); - auto func = [this](ResultFunction resolve - , ResultFunction reject ) - { - - PromiseExample1_Class *c = new PromiseExample1_Class(this); + connect(c, &PromiseExample1_Class::signalDone1, this, [this, c, resolve, reject](bool didThisWork) { + if (!didThisWork) + { - - connect(c, &PromiseExample1_Class::signalDone1, - this, [this, c, resolve, reject](bool didThisWork) - { - - if (!didThisWork) - { - - reject(QStringLiteral("First Action did not succeed")); - return; - } - else - { - - + reject(QStringLiteral("First Action did not succeed")); + return; + } + else + { - connect(c, &PromiseExample1_Class::signalDone2, - this, [resolve, reject](bool didThisWork, int someNumberThatReturns) - { - if (didThisWork) - resolve(someNumberThatReturns); - else - reject(QStringLiteral("Second Action did not succeed")); + connect(c, &PromiseExample1_Class::signalDone2, this, + [resolve, reject](bool didThisWork, int someNumberThatReturns) { + if (didThisWork) + resolve(someNumberThatReturns); + else + reject(QStringLiteral("Second Action did not succeed")); + }); - + c->doSomethingAsync2(); + } }); - c->doSomethingAsync2(); - } + c->doSomethingAsync1(); + }; + Promise* p = new Promise(func, this); + + p->resolved([this](const QVariant& value) { + qDebug() << "example1 promise succeeded! 'someNumberThatReturns' was" << value; + + m_success = true; + }).rejected([](const QVariant& value) { qDebug() << "example1 promise failed.." << value; }); +} + +PromiseExample2::PromiseExample2(QObject* parent) : QObject(parent), m_success(false) +{ + + Promise* p = new Promise( + [](ResultFunction, ResultFunction) { + + }, + this); + + p->setTimeout(1000); + + p->resolved([](const QVariant&) { QFAIL("This test case's promise should never resolve"); }); + + p->rejected([this](const QVariant& val) { + QVERIFY2(val == QStringLiteral("timeout"), "Promise didn't reject with string \"timeout\""); + qDebug() << "Promise rejected as expected"; + m_success = true; }); - - c->doSomethingAsync1(); - }; - Promise *p = new Promise(func, this); - - - - - - p->resolved([this](const QVariant &value) - { - - qDebug() << "example1 promise succeeded! 'someNumberThatReturns' was" << value; - - m_success = true; - - }).rejected([](const QVariant &value) - { - - qDebug() << "example1 promise failed.." << value; - }); } - - - -PromiseExample2::PromiseExample2(QObject *parent) - : QObject(parent) - , m_success(false) +PromiseExample3::PromiseExample3(QObject* parent) : QObject(parent), m_success(true), m_alreadyRejected(false) { - + Promise* p = new Promise([](ResultFunction, ResultFunction reject) { reject(QString()); }, this); - Promise *p = new Promise([](ResultFunction , ResultFunction ) - { - - }, this); + p->setTimeout(1000); - p->setTimeout(1000); + p->resolved([](const QVariant&) { QFAIL("This test case's promise should never resolve"); }); - p->resolved([](const QVariant &) - { - QFAIL("This test case's promise should never resolve"); - }); + p->rejected([this](const QVariant& val) { + qDebug() << "rejected with val" << val; + QVERIFY2(val == QString(), "Promise didn't reject with an expected empty string."); + QVERIFY2(!m_alreadyRejected, "Promise rejected more than once"); - p->rejected([this](const QVariant &val) - { - QVERIFY2(val == QStringLiteral("timeout"), "Promise didn't reject with string \"timeout\""); - qDebug() << "Promise rejected as expected"; - m_success = true; - }); + m_alreadyRejected = true; + qDebug() << "Promise rejected as expected"; + }); } - - - -PromiseExample3::PromiseExample3(QObject *parent) - : QObject(parent) - , m_success(true) - , m_alreadyRejected(false) -{ - - - - Promise *p = new Promise([](ResultFunction , ResultFunction reject) - { - reject(QString()); - }, this); - - p->setTimeout(1000); - - p->resolved([](const QVariant &) - { - QFAIL("This test case's promise should never resolve"); - }); - - p->rejected([this](const QVariant &val) - { - qDebug() << "rejected with val" << val; - QVERIFY2(val == QString(), "Promise didn't reject with an expected empty string."); - QVERIFY2(!m_alreadyRejected, "Promise rejected more than once"); - - m_alreadyRejected = true; - qDebug() << "Promise rejected as expected"; - }); -} - - - -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h index 700c7238a..f5a8978f2 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/promise_examples.h @@ -2,53 +2,67 @@ #include -namespace LtsUtils { +namespace LtsUtils +{ -class PromiseExample1_Class : public QObject { - Q_OBJECT -public: - using QObject::QObject; +class PromiseExample1_Class : public QObject +{ + Q_OBJECT + public: + using QObject::QObject; - void doSomethingAsync1(); - void doSomethingAsync2(); + void doSomethingAsync1(); + void doSomethingAsync2(); -signals: - void signalDone1(bool didThisWork); - void signalDone2(bool didThisWork, int someNumberThatReturns); + signals: + void signalDone1(bool didThisWork); + void signalDone2(bool didThisWork, int someNumberThatReturns); }; -class PromiseExample1 : public QObject { - Q_OBJECT -public: - explicit PromiseExample1(QObject *parent = nullptr); +class PromiseExample1 : public QObject +{ + Q_OBJECT + public: + explicit PromiseExample1(QObject* parent = nullptr); - [[nodiscard]] bool isSuccess() const { return m_success; } + [[nodiscard]] bool isSuccess() const + { + return m_success; + } -private: - bool m_success; + private: + bool m_success; }; -class PromiseExample2 : public QObject { - Q_OBJECT -public: - explicit PromiseExample2(QObject *parent = nullptr); +class PromiseExample2 : public QObject +{ + Q_OBJECT + public: + explicit PromiseExample2(QObject* parent = nullptr); - [[nodiscard]] bool isSuccess() const { return m_success; } + [[nodiscard]] bool isSuccess() const + { + return m_success; + } -private: - bool m_success; + private: + bool m_success; }; -class PromiseExample3 : public QObject { - Q_OBJECT -public: - explicit PromiseExample3(QObject *parent = nullptr); +class PromiseExample3 : public QObject +{ + Q_OBJECT + public: + explicit PromiseExample3(QObject* parent = nullptr); - [[nodiscard]] bool isSuccess() const { return m_success; } + [[nodiscard]] bool isSuccess() const + { + return m_success; + } -private: - bool m_success; - bool m_alreadyRejected; + private: + bool m_success; + bool m_alreadyRejected; }; } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h index 8d8b5a6ee..80dddfd4f 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qbytearray_byteaccess.h @@ -5,237 +5,239 @@ #include #include -namespace LtsUtils { +namespace LtsUtils +{ -template void inline set8Byte(const T in, QByteArray &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - out += (in & 0xFF00000000000000UL) >> 56; - out += (in & 0x00FF000000000000UL) >> 48; - out += (in & 0x0000FF0000000000UL) >> 40; - out += (in & 0x000000FF00000000UL) >> 32; - out += (in & 0x00000000FF000000UL) >> 24; - out += (in & 0x0000000000FF0000UL) >> 16; - out += (in & 0x000000000000FF00UL) >> 8; - out += (in & 0x00000000000000FFUL); +template void inline set8Byte(const T in, QByteArray& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + out += (in & 0xFF00000000000000UL) >> 56; + out += (in & 0x00FF000000000000UL) >> 48; + out += (in & 0x0000FF0000000000UL) >> 40; + out += (in & 0x000000FF00000000UL) >> 32; + out += (in & 0x00000000FF000000UL) >> 24; + out += (in & 0x0000000000FF0000UL) >> 16; + out += (in & 0x000000000000FF00UL) >> 8; + out += (in & 0x00000000000000FFUL); } -template <> void inline set8Byte(const double in, QByteArray &out) { - union hack { - double d; - int64_t i; - } h; - h.d = in; - set8Byte(h.i, out); +template <> void inline set8Byte(const double in, QByteArray& out) +{ + union hack { + double d; + int64_t i; + } h; + + h.d = in; + set8Byte(h.i, out); } -template -bool inline get8Byte(const QByteArray &baData, size_t &pos, T &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - static_assert(sizeof(T) >= 8, - "sizeof(out) is smaller than 8 bytes - will not fit"); - out = T(); +template bool inline get8Byte(const QByteArray& baData, size_t& pos, T& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + static_assert(sizeof(T) >= 8, "sizeof(out) is smaller than 8 bytes - will not fit"); + out = T(); - if (size_t(baData.size()) < pos + 8) - return false; + if (size_t(baData.size()) < pos + 8) + return false; - const char *data = baData.data() + pos; + const char* data = baData.data() + pos; - if (std::numeric_limits::is_signed) - out |= static_cast(data[0]) << 56; - else - out |= (data[0] & 0xFFULL) << 56; - out |= (data[1] & 0xFFULL) << 48; - out |= (data[2] & 0xFFULL) << 40; - out |= (data[3] & 0xFFULL) << 32; - out |= (data[4] & 0xFFULL) << 24; - out |= (data[5] & 0xFFULL) << 16; - out |= (data[6] & 0xFFULL) << 8; - out |= (data[7] & 0xFFULL); + if (std::numeric_limits::is_signed) + out |= static_cast(data[0]) << 56; + else + out |= (data[0] & 0xFFULL) << 56; + out |= (data[1] & 0xFFULL) << 48; + out |= (data[2] & 0xFFULL) << 40; + out |= (data[3] & 0xFFULL) << 32; + out |= (data[4] & 0xFFULL) << 24; + out |= (data[5] & 0xFFULL) << 16; + out |= (data[6] & 0xFFULL) << 8; + out |= (data[7] & 0xFFULL); - pos += 8; + pos += 8; - return true; + return true; } -template <> -bool inline get8Byte(const QByteArray &baData, size_t &pos, double &out) { - out = 0.; - union hack { - double d; - int64_t i; - } h; - if (!get8Byte(baData, pos, h.i)) - return false; - out = h.d; - return true; +template <> bool inline get8Byte(const QByteArray& baData, size_t& pos, double& out) +{ + out = 0.; + + union hack { + double d; + int64_t i; + } h; + + if (!get8Byte(baData, pos, h.i)) + return false; + out = h.d; + return true; } -template bool inline get8Byte(const QByteArray &data, T &out) { - size_t pos = 0; - return get8Byte(data, pos, out); +template bool inline get8Byte(const QByteArray& data, T& out) +{ + size_t pos = 0; + return get8Byte(data, pos, out); } -template void inline set4Byte(const T in, QByteArray &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - out += (in & 0xFF000000) >> 24; - out += (in & 0x00FF0000) >> 16; - out += (in & 0x0000FF00) >> 8; - out += (in & 0x000000FF); +template void inline set4Byte(const T in, QByteArray& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + out += (in & 0xFF000000) >> 24; + out += (in & 0x00FF0000) >> 16; + out += (in & 0x0000FF00) >> 8; + out += (in & 0x000000FF); } -template <> void inline set4Byte(const double in, QByteArray &out) { - int tmp = qRound(in); - return set4Byte(tmp, out); +template <> void inline set4Byte(const double in, QByteArray& out) +{ + int tmp = qRound(in); + return set4Byte(tmp, out); } -template -bool inline get4Byte(const QByteArray &baData, size_t &pos, T &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - static_assert(sizeof(T) >= 4, - "sizeof(out) is smaller than 4 bytes - will not fit"); - out = T(); +template bool inline get4Byte(const QByteArray& baData, size_t& pos, T& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + static_assert(sizeof(T) >= 4, "sizeof(out) is smaller than 4 bytes - will not fit"); + out = T(); - if (size_t(baData.size()) < pos + 4) - return false; + if (size_t(baData.size()) < pos + 4) + return false; - const char *data = baData.data() + pos; + const char* data = baData.data() + pos; - if (std::numeric_limits::is_signed) - out |= data[0] << 24; - else - out |= (data[0] & 0xFFU) << 24; - out |= (data[1] & 0xFFU) << 16; - out |= (data[2] & 0xFFU) << 8; - out |= (data[3] & 0xFFU); + if (std::numeric_limits::is_signed) + out |= data[0] << 24; + else + out |= (data[0] & 0xFFU) << 24; + out |= (data[1] & 0xFFU) << 16; + out |= (data[2] & 0xFFU) << 8; + out |= (data[3] & 0xFFU); - pos += 4; + pos += 4; - return true; + return true; } -template <> -bool inline get4Byte(const QByteArray &baData, size_t &pos, double &out) { - out = 0.; - int tmp; - if (!get4Byte(baData, pos, tmp)) - return false; - out = tmp; - return true; +template <> bool inline get4Byte(const QByteArray& baData, size_t& pos, double& out) +{ + out = 0.; + int tmp; + if (!get4Byte(baData, pos, tmp)) + return false; + out = tmp; + return true; } -template bool inline get4Byte(const QByteArray &data, T &out) { - size_t pos = 0; - return get4Byte(data, pos, out); +template bool inline get4Byte(const QByteArray& data, T& out) +{ + size_t pos = 0; + return get4Byte(data, pos, out); } -template void inline set3Byte(const T in, QByteArray &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - out += (in & 0x00FF0000) >> 16; - out += (in & 0x0000FF00) >> 8; - out += (in & 0x000000FF); +template void inline set3Byte(const T in, QByteArray& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + out += (in & 0x00FF0000) >> 16; + out += (in & 0x0000FF00) >> 8; + out += (in & 0x000000FF); } -template -bool inline get3Byte(const QByteArray &baData, size_t &pos, T &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - static_assert(sizeof(T) >= 3, - "sizeof(out) is smaller than 3 bytes - will not fit"); - out = T(); +template bool inline get3Byte(const QByteArray& baData, size_t& pos, T& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + static_assert(sizeof(T) >= 3, "sizeof(out) is smaller than 3 bytes - will not fit"); + out = T(); - if (size_t(baData.size()) < pos + 3) - return false; + if (size_t(baData.size()) < pos + 3) + return false; - const char *data = baData.data() + pos; + const char* data = baData.data() + pos; - if (std::numeric_limits::is_signed) - out |= data[0] << 16; - else - out |= (data[0] & 0xFFU) << 16; - out |= (data[1] & 0xFFU) << 8; - out |= (data[2] & 0xFFU); + if (std::numeric_limits::is_signed) + out |= data[0] << 16; + else + out |= (data[0] & 0xFFU) << 16; + out |= (data[1] & 0xFFU) << 8; + out |= (data[2] & 0xFFU); - pos += 3; + pos += 3; - return true; + return true; } -template bool inline get3Byte(const QByteArray &data, T &out) { - size_t pos = 0; - return get3Byte(data, pos, out); +template bool inline get3Byte(const QByteArray& data, T& out) +{ + size_t pos = 0; + return get3Byte(data, pos, out); } -template void inline set2Byte(const T in, QByteArray &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - out += (in & 0x0000FF00) >> 8; - out += (in & 0x000000FF); +template void inline set2Byte(const T in, QByteArray& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + out += (in & 0x0000FF00) >> 8; + out += (in & 0x000000FF); } -template -bool inline get2Byte(const QByteArray &baData, size_t &pos, T &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - static_assert(sizeof(T) >= 2, - "sizeof(out) is smaller than 2 bytes - will not fit"); - out = T(); +template bool inline get2Byte(const QByteArray& baData, size_t& pos, T& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + static_assert(sizeof(T) >= 2, "sizeof(out) is smaller than 2 bytes - will not fit"); + out = T(); - if (size_t(baData.size()) < pos + 2) - return false; + if (size_t(baData.size()) < pos + 2) + return false; - const char *data = baData.data() + pos; + const char* data = baData.data() + pos; - if (std::numeric_limits::is_signed) - out |= data[0] << 8; - else - out |= (data[0] & 0xFFU) << 8; - out |= data[1] & 0xFFU; + if (std::numeric_limits::is_signed) + out |= data[0] << 8; + else + out |= (data[0] & 0xFFU) << 8; + out |= data[1] & 0xFFU; - pos += 2; + pos += 2; - return true; + return true; } -template bool inline get2Byte(const QByteArray &data, T &out) { - size_t pos = 0; - return get2Byte(data, pos, out); +template bool inline get2Byte(const QByteArray& data, T& out) +{ + size_t pos = 0; + return get2Byte(data, pos, out); } -template void inline set1Byte(const T in, QByteArray &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - unsigned char c = in; - out += c; +template void inline set1Byte(const T in, QByteArray& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + unsigned char c = in; + out += c; } -template -bool inline get1Byte(const QByteArray &baData, size_t &pos, T &out) { - static_assert(std::is_integral_v || std::is_enum_v, - "Only integrals allowed for raw byte accessd"); - out = T(); +template bool inline get1Byte(const QByteArray& baData, size_t& pos, T& out) +{ + static_assert(std::is_integral_v || std::is_enum_v, "Only integrals allowed for raw byte accessd"); + out = T(); - if (size_t(baData.size()) < pos + 1) - return false; + if (size_t(baData.size()) < pos + 1) + return false; - const char *data = baData.data() + pos; + const char* data = baData.data() + pos; - if (std::numeric_limits::is_signed) - out = (T)(data[0]); - else - out = (T)(data[0] & 0xFF); + if (std::numeric_limits::is_signed) + out = (T)(data[0]); + else + out = (T)(data[0] & 0xFF); - pos += 1; + pos += 1; - return true; + return true; } -template bool inline get1Byte(const QByteArray &data, T &out) { - size_t pos = 0; - return get1Byte(data, pos, out); +template bool inline get1Byte(const QByteArray& data, T& out) +{ + size_t pos = 0; + return get1Byte(data, pos, out); } } // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp old mode 100755 new mode 100644 index 2e2435096..963c1de0d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.cpp @@ -2,87 +2,72 @@ #include - namespace LtsUtils { - - - - -QPlane3D::QPlane3D(const QPoint3D &pos, const QPoint3D &vec1, const QPoint3D &vec2) - : m_pos(pos) - , m_vec1(vec1) - , m_vec2(vec2) +QPlane3D::QPlane3D(const QPoint3D& pos, const QPoint3D& vec1, const QPoint3D& vec2) + : m_pos(pos), m_vec1(vec1), m_vec2(vec2) { - m_normal = QPoint3D::crossProduct(m_vec1, m_vec2); - m_planeC = QPoint3D::dotProduct(m_pos, m_normal); + m_normal = QPoint3D::crossProduct(m_vec1, m_vec2); + m_planeC = QPoint3D::dotProduct(m_pos, m_normal); } - -QPoint3D QPlane3D::intersection(const QPoint3D &point, const QPoint3D &direction) const +QPoint3D QPlane3D::intersection(const QPoint3D& point, const QPoint3D& direction) const { - const double dotProduct = QPoint3D::dotProduct(direction, m_normal); - if (qFuzzyIsNull(dotProduct)) - return inPlane(point) ? point : QPoint3D(); - const double distance = distanceTo(point) / std::abs(dotProduct); - return point + distance * direction; + const double dotProduct = QPoint3D::dotProduct(direction, m_normal); + if (qFuzzyIsNull(dotProduct)) + return inPlane(point) ? point : QPoint3D(); + const double distance = distanceTo(point) / std::abs(dotProduct); + return point + distance * direction; } -bool QPlane3D::intersects(const QPoint3D &direction) const +bool QPlane3D::intersects(const QPoint3D& direction) const { - return !isParallel(direction); + return !isParallel(direction); } -bool QPlane3D::isParallel(const QPoint3D &direction) const +bool QPlane3D::isParallel(const QPoint3D& direction) const { - return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, direction)); + return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, direction)); } -bool QPlane3D::inPlane(const QPoint3D &point) const +bool QPlane3D::inPlane(const QPoint3D& point) const { - if (point == m_pos) - return true; - return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, point - m_pos)); + if (point == m_pos) + return true; + return qFuzzyIsNull(QPoint3D::dotProduct(m_normal, point - m_pos)); } -double QPlane3D::distanceTo(const QPoint3D &point) const +double QPlane3D::distanceTo(const QPoint3D& point) const { - return QPoint3D::dotProduct(point - m_pos, m_normal); + return QPoint3D::dotProduct(point - m_pos, m_normal); } - - - - - -QPolygon3D::QPolygon3D(const QVector &vertices) - : QPlane3D(vertices[0], vertices[1], vertices[2]) - , m_vertices(vertices) +QPolygon3D::QPolygon3D(const QVector& vertices) + : QPlane3D(vertices[0], vertices[1], vertices[2]), m_vertices(vertices) { } - -bool QPolygon3D::containsPoint(const QPoint3D &point) const +bool QPolygon3D::containsPoint(const QPoint3D& point) const { - if (!inPlane(point)) - return false; + if (!inPlane(point)) + return false; - if (contains(point)) - return true; + if (contains(point)) + return true; - double angleSum = 0.; - double cosTheta = 0.; - const int numberOfVertices = m_vertices.size(); - for (int i = 0; i < m_vertices.size(); ++i) - { - const QPoint3D &first = m_vertices[i % numberOfVertices] - point; - const QPoint3D &second = m_vertices[(i + 1) % numberOfVertices] - point; + double angleSum = 0.; + double cosTheta = 0.; + const int numberOfVertices = m_vertices.size(); + for (int i = 0; i < m_vertices.size(); ++i) + { + const QPoint3D& first = m_vertices[i % numberOfVertices] - point; + const QPoint3D& second = m_vertices[(i + 1) % numberOfVertices] - point; - cosTheta = QPoint3D::dotProduct(first, second) / (first.length() * second.length()); - angleSum += acos(cosTheta); - } - return qFuzzyIsNull(M_2_PI - angleSum); + cosTheta = QPoint3D::dotProduct(first, second) / (first.length() * second.length()); + angleSum += acos(cosTheta); + } + return qFuzzyIsNull(M_2_PI - angleSum); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h old mode 100755 new mode 100644 index 12478a8fe..cc5127362 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qplane3d.h @@ -1,15 +1,12 @@ - #pragma once +#include "ltsutilscore_export.h" #include "qpoint3d.h" -#include "ltsutilscore_export.h" - -#include #include - +#include namespace LtsUtils { @@ -17,43 +14,63 @@ namespace LtsUtils class LTSUTILSCORE_EXPORT QPlane3D { -public: - QPlane3D(const QPoint3D &pos, const QPoint3D &vec1, const QPoint3D &vec2); + public: + QPlane3D(const QPoint3D& pos, const QPoint3D& vec1, const QPoint3D& vec2); - QPoint3D intersection(const QPoint3D &point, const QPoint3D &direction) const; - bool intersects(const QPoint3D &direction) const; - bool isParallel(const QPoint3D &direction) const; - bool inPlane(const QPoint3D &point) const; - double distanceTo(const QPoint3D &point) const; + QPoint3D intersection(const QPoint3D& point, const QPoint3D& direction) const; + bool intersects(const QPoint3D& direction) const; + bool isParallel(const QPoint3D& direction) const; + bool inPlane(const QPoint3D& point) const; + double distanceTo(const QPoint3D& point) const; - const QPoint3D &pos() const { return m_pos; } - const QPoint3D &vec1() const { return m_vec1; } - const QPoint3D &vec2() const { return m_vec2; } - const QPoint3D &normal() const { return m_normal; } - double planeC() const { return m_planeC; } + const QPoint3D& pos() const + { + return m_pos; + } -protected: - QPoint3D m_pos; - QPoint3D m_vec1; - QPoint3D m_vec2; - QPoint3D m_normal; - double m_planeC; + const QPoint3D& vec1() const + { + return m_vec1; + } + const QPoint3D& vec2() const + { + return m_vec2; + } + + const QPoint3D& normal() const + { + return m_normal; + } + + double planeC() const + { + return m_planeC; + } + + protected: + QPoint3D m_pos; + QPoint3D m_vec1; + QPoint3D m_vec2; + QPoint3D m_normal; + double m_planeC; }; - class LTSUTILSCORE_EXPORT QPolygon3D : public QPlane3D { -public: - QPolygon3D(const QVector &vertices); + public: + QPolygon3D(const QVector& vertices); - bool contains(const QPoint3D &point) const { return m_vertices.contains(point); } - bool containsPoint(const QPoint3D &point) const; + bool contains(const QPoint3D& point) const + { + return m_vertices.contains(point); + } -private: - QVector m_vertices; + bool containsPoint(const QPoint3D& point) const; + private: + QVector m_vertices; }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp old mode 100755 new mode 100644 index dc4fc26c6..6b875508b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.cpp @@ -1,48 +1,49 @@ - #include "qpoint3d.h" + #include using namespace LtsUtils; +double QPoint3D::distanceToLine(const QPoint3D& point, const QPoint3D& direction) const +{ + if (direction.isNull()) + return (*this - point).length(); + QPoint3D p = point + dotProduct(*this - point, direction) * direction; + return (*this - p).length(); +} -double QPoint3D::distanceToLine(const QPoint3D &point, const QPoint3D &direction) const +double QPoint3D::distanceToPlane(const QPoint3D& plane, const QPoint3D& normal) const +{ + return dotProduct(*this - plane, normal); +} + +double QPoint3D::distanceToPlane(const QPoint3D& plane1, const QPoint3D& plane2, const QPoint3D& plane3) const +{ + QPoint3D n = normal(plane2 - plane1, plane3 - plane1); + return dotProduct(*this - plane1, n); +} + +double QPoint3D::distanceToPoint(const QPoint3D& point) const { - if (direction.isNull()) return (*this - point).length(); - QPoint3D p = point + dotProduct(*this - point, direction) * direction; - return (*this - p).length(); } -double QPoint3D::distanceToPlane(const QPoint3D &plane, const QPoint3D &normal) const +QDataStream& operator<<(QDataStream& s, const QPoint3D& p) { - return dotProduct(*this - plane, normal); + s << p.x() << p.y() << p.z(); + return s; } -double QPoint3D::distanceToPlane(const QPoint3D &plane1, const QPoint3D &plane2, const QPoint3D &plane3) const +QDataStream& operator>>(QDataStream& s, QPoint3D& p) { - QPoint3D n = normal(plane2 - plane1, plane3 - plane1); - return dotProduct(*this - plane1, n); -} - -double QPoint3D::distanceToPoint(const QPoint3D &point) const -{ - return (*this - point).length(); -} - - -QDataStream &operator<<(QDataStream &s, const QPoint3D &p) -{ - s << p.x() << p.y() << p.z(); - return s; -} - -QDataStream &operator>>(QDataStream &s, QPoint3D &p) -{ - double x, y, z; - s >> x; p.rx() = x; - s >> y; p.ry() = y; - s >> z; p.rz() = z; - return s; + double x, y, z; + s >> x; + p.rx() = x; + s >> y; + p.ry() = y; + s >> z; + p.rz() = z; + return s; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h old mode 100755 new mode 100644 index 6d461a339..2a6783607 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/qpoint3d.h @@ -1,296 +1,294 @@ - #pragma once -#include -#include - #include "ltsutilscore_export.h" #include -#include - +#include +#include +#include namespace LtsUtils { class QPoint3D { -public: - enum class Axis { X, Y, Z }; + public: + enum class Axis { X, Y, Z }; - Q_DECL_CONSTEXPR QPoint3D() = default; - Q_DECL_CONSTEXPR QPoint3D(double xpos, double ypos, double zpos); - template - explicit QPoint3D(const T &data) - : xp(data.offsetX()) - , yp(data.offsetY()) - , zp(data.offsetZ()) - {} + Q_DECL_CONSTEXPR QPoint3D() = default; + Q_DECL_CONSTEXPR QPoint3D(double xpos, double ypos, double zpos); - inline bool isNull() const; - - Q_DECL_CONSTEXPR inline double x() const; - Q_DECL_CONSTEXPR inline double y() const; - Q_DECL_CONSTEXPR inline double z() const; - Q_DECL_RELAXED_CONSTEXPR inline void setX(double xpos); - Q_DECL_RELAXED_CONSTEXPR inline void setY(double ypos); - Q_DECL_RELAXED_CONSTEXPR inline void setZ(double zpos); - - Q_DECL_RELAXED_CONSTEXPR inline double &rx(); - Q_DECL_RELAXED_CONSTEXPR inline double &ry(); - Q_DECL_RELAXED_CONSTEXPR inline double &rz(); - - Q_DECL_CONSTEXPR inline QPointF toPointF() const; - static QPoint3D fromQPointF(const QPointF &p) - { - return QPoint3D(p.x(), p.y(), .0); - } - - inline double lengthSquared() const { return (xp * xp) + (yp * yp) + (zp * zp); } - inline double length() const { return std::sqrt(lengthSquared()); } - inline void normalize() - { - double len = xp * xp + yp * yp + zp * zp; - if (qFuzzyIsNull(len - 1.0f) || qFuzzyIsNull(len)) - return; - - len = std::sqrt(len); - - xp /= len; - yp /= len; - zp /= len; - } - inline QPoint3D normalized() const - { - double len = xp * xp + yp * yp + zp * zp; - if (qFuzzyIsNull(len - 1.0f)) - return *this; - else if (!qFuzzyIsNull(len)) - return *this / std::sqrt(len); - else - return QPoint3D(*this); - } - - inline void rotate(const double &phi, const Axis &axis) - { - const double sin = std::sin(phi); - const double cos = std::cos(phi); - switch (axis) + template explicit QPoint3D(const T& data) : xp(data.offsetX()), yp(data.offsetY()), zp(data.offsetZ()) { - case Axis::X: + } + + inline bool isNull() const; + + Q_DECL_CONSTEXPR inline double x() const; + Q_DECL_CONSTEXPR inline double y() const; + Q_DECL_CONSTEXPR inline double z() const; + Q_DECL_RELAXED_CONSTEXPR inline void setX(double xpos); + Q_DECL_RELAXED_CONSTEXPR inline void setY(double ypos); + Q_DECL_RELAXED_CONSTEXPR inline void setZ(double zpos); + + Q_DECL_RELAXED_CONSTEXPR inline double& rx(); + Q_DECL_RELAXED_CONSTEXPR inline double& ry(); + Q_DECL_RELAXED_CONSTEXPR inline double& rz(); + + Q_DECL_CONSTEXPR inline QPointF toPointF() const; + + static QPoint3D fromQPointF(const QPointF& p) { - const double _yp = (cos * yp) - (sin * zp); - const double _zp = (sin * yp) + (cos * zp); - yp = _yp; - zp = _zp; - break; + return QPoint3D(p.x(), p.y(), .0); } - case Axis::Y: + + inline double lengthSquared() const { - const double _xp = (cos * xp) + (sin * zp); - const double _zp = (-sin * xp) + (cos * zp); - xp = _xp; - zp = _zp; - break; + return (xp * xp) + (yp * yp) + (zp * zp); } - case Axis::Z: + + inline double length() const { - const double _xp = (cos * xp) - (sin * yp); - const double _yp = (sin * xp) + (cos * yp); - xp = _xp; - yp = _yp; - break; + return std::sqrt(lengthSquared()); } + + inline void normalize() + { + double len = xp * xp + yp * yp + zp * zp; + if (qFuzzyIsNull(len - 1.0f) || qFuzzyIsNull(len)) + return; + + len = std::sqrt(len); + + xp /= len; + yp /= len; + zp /= len; } - } - inline QPoint3D rotated(const double &phi, const Axis &axis) const - { - QPoint3D p(*this); - p.rotate(phi, axis); - return p; - } - inline double distanceToLine(const QPoint3D &point, const QPoint3D &direction) const; - inline double distanceToPlane(const QPoint3D &plane, const QPoint3D &normal) const; - inline double distanceToPlane(const QPoint3D &plane1, const QPoint3D &plane2, const QPoint3D &plane3) const; - inline double distanceToPoint(const QPoint3D &point) const; + inline QPoint3D normalized() const + { + double len = xp * xp + yp * yp + zp * zp; + if (qFuzzyIsNull(len - 1.0f)) + return *this; + else if (!qFuzzyIsNull(len)) + return *this / std::sqrt(len); + else + return QPoint3D(*this); + } - friend Q_DECL_CONSTEXPR inline bool operator==(const QPoint3D &p1, const QPoint3D &p2); - friend Q_DECL_CONSTEXPR inline bool operator!=(const QPoint3D &p1, const QPoint3D &p2); - friend Q_DECL_CONSTEXPR inline QPoint3D operator +(const QPoint3D &p1, const QPoint3D &p2) - { - return QPoint3D(p1.xp + p2.xp, p1.yp + p2.yp, p1.zp + p2.zp); - } + inline void rotate(const double& phi, const Axis& axis) + { + const double sin = std::sin(phi); + const double cos = std::cos(phi); + switch (axis) + { + case Axis::X: { + const double _yp = (cos * yp) - (sin * zp); + const double _zp = (sin * yp) + (cos * zp); + yp = _yp; + zp = _zp; + break; + } + case Axis::Y: { + const double _xp = (cos * xp) + (sin * zp); + const double _zp = (-sin * xp) + (cos * zp); + xp = _xp; + zp = _zp; + break; + } + case Axis::Z: { + const double _xp = (cos * xp) - (sin * yp); + const double _yp = (sin * xp) + (cos * yp); + xp = _xp; + yp = _yp; + break; + } + } + } - friend Q_DECL_CONSTEXPR inline QPoint3D operator -(const QPoint3D &p1, const QPoint3D &p2) - { - return QPoint3D(p1.xp - p2.xp, p1.yp - p2.yp, p1.zp - p2.zp); - } + inline QPoint3D rotated(const double& phi, const Axis& axis) const + { + QPoint3D p(*this); + p.rotate(phi, axis); + return p; + } - friend Q_DECL_CONSTEXPR inline QPoint3D operator *(const QPoint3D &p1, double factor) - { - return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); - } - friend Q_DECL_CONSTEXPR inline QPoint3D operator *(double factor, const QPoint3D &p1) - { - return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); - } + inline double distanceToLine(const QPoint3D& point, const QPoint3D& direction) const; + inline double distanceToPlane(const QPoint3D& plane, const QPoint3D& normal) const; + inline double distanceToPlane(const QPoint3D& plane1, const QPoint3D& plane2, const QPoint3D& plane3) const; + inline double distanceToPoint(const QPoint3D& point) const; - friend Q_DECL_CONSTEXPR inline QPoint3D operator /(const QPoint3D &p1, double factor) - { - return QPoint3D(p1.xp / factor, p1.yp / factor, p1.zp / factor); - } + friend Q_DECL_CONSTEXPR inline bool operator==(const QPoint3D& p1, const QPoint3D& p2); + friend Q_DECL_CONSTEXPR inline bool operator!=(const QPoint3D& p1, const QPoint3D& p2); - Q_DECL_RELAXED_CONSTEXPR inline QPoint3D &operator +=(const QPoint3D &o) - { - xp += o.xp; - yp += o.yp; - zp += o.zp; - return *this; - } - Q_DECL_RELAXED_CONSTEXPR inline QPoint3D &operator -=(const QPoint3D &o) - { - xp -= o.xp; - yp -= o.yp; - zp -= o.zp; - return *this; - } - Q_DECL_RELAXED_CONSTEXPR inline QPoint3D &operator *=(double factor) - { - xp *= factor; - yp *= factor; - zp *= factor; - return *this; - } - Q_DECL_RELAXED_CONSTEXPR inline QPoint3D &operator /=(double divisor) - { - xp /= divisor; - yp /= divisor; - zp /= divisor; - return *this; - } + friend Q_DECL_CONSTEXPR inline QPoint3D operator+(const QPoint3D& p1, const QPoint3D& p2) + { + return QPoint3D(p1.xp + p2.xp, p1.yp + p2.yp, p1.zp + p2.zp); + } - Q_DECL_CONSTEXPR static inline double dotProduct(const QPoint3D& v1, const QPoint3D& v2) - { - return v1.xp * v2.xp + v1.yp * v2.yp + v1.zp * v2.zp; - } + friend Q_DECL_CONSTEXPR inline QPoint3D operator-(const QPoint3D& p1, const QPoint3D& p2) + { + return QPoint3D(p1.xp - p2.xp, p1.yp - p2.yp, p1.zp - p2.zp); + } - Q_DECL_CONSTEXPR static inline QPoint3D crossProduct(const QPoint3D& v1, const QPoint3D& v2) - { - return QPoint3D(v1.yp * v2.zp - v1.zp * v2.yp, - v1.zp * v2.xp - v1.xp * v2.zp, - v1.xp * v2.yp - v1.yp * v2.xp); - } + friend Q_DECL_CONSTEXPR inline QPoint3D operator*(const QPoint3D& p1, double factor) + { + return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); + } - static inline QPoint3D normal(const QPoint3D &v1, const QPoint3D &v2) - { - return crossProduct(v1, v2).normalized(); - } - static inline QPoint3D normal(const QPoint3D &v1, const QPoint3D &v2, const QPoint3D &v3) - { - return crossProduct((v2 - v1), (v3 - v1)).normalized(); - } + friend Q_DECL_CONSTEXPR inline QPoint3D operator*(double factor, const QPoint3D& p1) + { + return QPoint3D(p1.xp * factor, p1.yp * factor, p1.zp * factor); + } - Q_DECL_CONSTEXPR friend inline bool qFuzzyCompare(const QPoint3D& v1, const QPoint3D& v2); + friend Q_DECL_CONSTEXPR inline QPoint3D operator/(const QPoint3D& p1, double factor) + { + return QPoint3D(p1.xp / factor, p1.yp / factor, p1.zp / factor); + } -private: - double xp = 0; - double yp = 0; - double zp = 0; + Q_DECL_RELAXED_CONSTEXPR inline QPoint3D& operator+=(const QPoint3D& o) + { + xp += o.xp; + yp += o.yp; + zp += o.zp; + return *this; + } + + Q_DECL_RELAXED_CONSTEXPR inline QPoint3D& operator-=(const QPoint3D& o) + { + xp -= o.xp; + yp -= o.yp; + zp -= o.zp; + return *this; + } + + Q_DECL_RELAXED_CONSTEXPR inline QPoint3D& operator*=(double factor) + { + xp *= factor; + yp *= factor; + zp *= factor; + return *this; + } + + Q_DECL_RELAXED_CONSTEXPR inline QPoint3D& operator/=(double divisor) + { + xp /= divisor; + yp /= divisor; + zp /= divisor; + return *this; + } + + Q_DECL_CONSTEXPR static inline double dotProduct(const QPoint3D& v1, const QPoint3D& v2) + { + return v1.xp * v2.xp + v1.yp * v2.yp + v1.zp * v2.zp; + } + + Q_DECL_CONSTEXPR static inline QPoint3D crossProduct(const QPoint3D& v1, const QPoint3D& v2) + { + return QPoint3D(v1.yp * v2.zp - v1.zp * v2.yp, v1.zp * v2.xp - v1.xp * v2.zp, v1.xp * v2.yp - v1.yp * v2.xp); + } + + static inline QPoint3D normal(const QPoint3D& v1, const QPoint3D& v2) + { + return crossProduct(v1, v2).normalized(); + } + + static inline QPoint3D normal(const QPoint3D& v1, const QPoint3D& v2, const QPoint3D& v3) + { + return crossProduct((v2 - v1), (v3 - v1)).normalized(); + } + + Q_DECL_CONSTEXPR friend inline bool qFuzzyCompare(const QPoint3D& v1, const QPoint3D& v2); + + private: + double xp = 0; + double yp = 0; + double zp = 0; }; +LTSUTILSCORE_EXPORT QDataStream& operator<<(QDataStream& s, const QPoint3D& p); +LTSUTILSCORE_EXPORT QDataStream& operator>>(QDataStream& s, QPoint3D& p); - -LTSUTILSCORE_EXPORT QDataStream &operator<<(QDataStream &s, const QPoint3D &p); -LTSUTILSCORE_EXPORT QDataStream &operator>>(QDataStream &s, QPoint3D &p); - - - - -Q_DECL_CONSTEXPR inline QPoint3D::QPoint3D(double xpos, double ypos, double zpos) : xp(xpos), yp(ypos), zp(zpos) { } +Q_DECL_CONSTEXPR inline QPoint3D::QPoint3D(double xpos, double ypos, double zpos) : xp(xpos), yp(ypos), zp(zpos) {} inline bool QPoint3D::isNull() const { - return qIsNull(xp) && qIsNull(yp) && qIsNull(zp); + return qIsNull(xp) && qIsNull(yp) && qIsNull(zp); } Q_DECL_CONSTEXPR inline double QPoint3D::x() const { - return xp; + return xp; } Q_DECL_CONSTEXPR inline double QPoint3D::y() const { - return yp; + return yp; } Q_DECL_CONSTEXPR inline double QPoint3D::z() const { - return zp; + return zp; } Q_DECL_RELAXED_CONSTEXPR inline void QPoint3D::setX(double xpos) { - xp = xpos; + xp = xpos; } Q_DECL_RELAXED_CONSTEXPR inline void QPoint3D::setY(double ypos) { - yp = ypos; + yp = ypos; } Q_DECL_RELAXED_CONSTEXPR inline void QPoint3D::setZ(double zpos) { - zp = zpos; + zp = zpos; } -Q_DECL_RELAXED_CONSTEXPR inline double &QPoint3D::rx() +Q_DECL_RELAXED_CONSTEXPR inline double& QPoint3D::rx() { - return xp; + return xp; } -Q_DECL_RELAXED_CONSTEXPR inline double &QPoint3D::ry() +Q_DECL_RELAXED_CONSTEXPR inline double& QPoint3D::ry() { - return yp; + return yp; } -Q_DECL_RELAXED_CONSTEXPR inline double &QPoint3D::rz() +Q_DECL_RELAXED_CONSTEXPR inline double& QPoint3D::rz() { - return zp; + return zp; } - Q_DECL_CONSTEXPR inline QPointF QPoint3D::toPointF() const { - return QPointF(xp, yp); + return QPointF(xp, yp); } - -Q_DECL_CONSTEXPR inline bool operator==(const QPoint3D &p1, const QPoint3D &p2) +Q_DECL_CONSTEXPR inline bool operator==(const QPoint3D& p1, const QPoint3D& p2) { - return p1.xp == p2.xp && p1.yp == p2.yp && p1.zp == p2.zp; + return p1.xp == p2.xp && p1.yp == p2.yp && p1.zp == p2.zp; } -Q_DECL_CONSTEXPR inline bool operator!=(const QPoint3D &p1, const QPoint3D &p2) +Q_DECL_CONSTEXPR inline bool operator!=(const QPoint3D& p1, const QPoint3D& p2) { - return p1.xp != p2.xp || p1.yp != p2.yp || p1.zp != p2.zp; + return p1.xp != p2.xp || p1.yp != p2.yp || p1.zp != p2.zp; } Q_DECL_CONSTEXPR inline bool qFuzzyCompare(const QPoint3D& v1, const QPoint3D& v2) { - return ::qFuzzyCompare(v1.xp, v2.xp) && - ::qFuzzyCompare(v1.yp, v2.yp) && - ::qFuzzyCompare(v1.zp, v2.zp); + return ::qFuzzyCompare(v1.xp, v2.xp) && ::qFuzzyCompare(v1.yp, v2.yp) && ::qFuzzyCompare(v1.zp, v2.zp); } -inline std::ostream& operator<< (std::ostream& stream, const QPoint3D& pos) +inline std::ostream& operator<<(std::ostream& stream, const QPoint3D& pos) { - stream << "(" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; - return stream; + stream << "(" << pos.x() << "," << pos.y() << "," << pos.z() << ")"; + return stream; } -} +} // namespace LtsUtils Q_DECLARE_TYPEINFO(LtsUtils::QPoint3D, Q_MOVABLE_TYPE); diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp old mode 100755 new mode 100644 index a8d543e3d..560111eb3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.cpp @@ -1,22 +1,21 @@ - #include "scoped_connection.h" + #include "connection.h" namespace LtsUtils { -ScopedConnection::ScopedConnection(IConnection *connection, Qt::ConnectionType connType) - : m_conn(connection) +ScopedConnection::ScopedConnection(IConnection* connection, Qt::ConnectionType connType) : m_conn(connection) { - Q_ASSERT(connection); - m_conn->connect(connType); + Q_ASSERT(connection); + m_conn->connect(connType); } ScopedConnection::~ScopedConnection() { - m_conn->disconnect(); + m_conn->disconnect(); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h old mode 100755 new mode 100644 index ecd8fd3e6..329b52712 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/scoped_connection.h @@ -1,9 +1,9 @@ - #pragma once #include "ltsutilscore_export.h" + #include namespace LtsUtils @@ -11,16 +11,14 @@ namespace LtsUtils class IConnection; - - class LTSUTILSCORE_EXPORT ScopedConnection { -public: - explicit ScopedConnection(IConnection *connection, Qt::ConnectionType = Qt::AutoConnection); - ~ScopedConnection(); + public: + explicit ScopedConnection(IConnection* connection, Qt::ConnectionType = Qt::AutoConnection); + ~ScopedConnection(); -private: - IConnection *m_conn; + private: + IConnection* m_conn; }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp old mode 100755 new mode 100644 index a5876f216..c6530d694 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.cpp @@ -1,13 +1,10 @@ - #include "sfm_bytemessage_converter.h" namespace LtsUtils { - - static constexpr unsigned char XON = 0x11; static constexpr unsigned char XOFF = 0x13; static constexpr unsigned char STX = 0x02; @@ -22,280 +19,265 @@ static constexpr unsigned char SUB_SUBST = 0x00; static constexpr int HEADER_SIZE = 3; static constexpr int CHECKSUM_SIZE = 1; -static constexpr int MINIMUM_BYTE_SIZE = 1 + HEADER_SIZE + CHECKSUM_SIZE + 1; +static constexpr int MINIMUM_BYTE_SIZE = 1 + HEADER_SIZE + CHECKSUM_SIZE + 1; - - -static SfmMessage getSfmMessage(const QByteArray &p_data) +static SfmMessage getSfmMessage(const QByteArray& p_data) { - - unsigned short id = 0; - id |= (((unsigned short)p_data[0]) & 0x7F) << 8; - id |= (((unsigned short)p_data[1]) & 0xFF) << 0; - SfmMessage msg; - msg.setId(id); - msg.setRtr(p_data[0]&0x80); - msg.setPayload(p_data.right(p_data.size() - HEADER_SIZE)); + unsigned short id = 0; + id |= (((unsigned short)p_data[0]) & 0x7F) << 8; + id |= (((unsigned short)p_data[1]) & 0xFF) << 0; - return msg; + SfmMessage msg; + msg.setId(id); + msg.setRtr(p_data[0] & 0x80); + msg.setPayload(p_data.right(p_data.size() - HEADER_SIZE)); + + return msg; } - - -static QByteArray getHeader(const SfmMessage &p_msg) +static QByteArray getHeader(const SfmMessage& p_msg) { - QByteArray header(2, Qt::Uninitialized); - - header[0] = ((p_msg.id() >> 8) & 0x7f) | (p_msg.rtr() << 7); - - header[1] = (p_msg.id() >> 0) & 0xff; + QByteArray header(2, Qt::Uninitialized); - return header; + header[0] = ((p_msg.id() >> 8) & 0x7f) | (p_msg.rtr() << 7); + + header[1] = (p_msg.id() >> 0) & 0xff; + + return header; } - - -static inline char getChecksum(const QByteArray &p_data) +static inline char getChecksum(const QByteArray& p_data) { - char sum = 0; + char sum = 0; - - for (const char c : p_data) - sum += c; + for (const char c : p_data) + sum += c; - - return sum ^ 0xff; + return sum ^ 0xff; } - - -static QByteArray removeChecksum(const QByteArray &p_data) +static QByteArray removeChecksum(const QByteArray& p_data) { - QByteArray withoutChecksum(p_data); - ConversionError error ("Checksum error"); + QByteArray withoutChecksum(p_data); + ConversionError error("Checksum error"); - if (p_data.size() >= CHECKSUM_SIZE) - { - withoutChecksum.chop(1); - - - if (p_data.at(p_data.size() - 1) != getChecksum(withoutChecksum)) - throw error; - } - else - throw error; - - return withoutChecksum; -} - - - -static QByteArray maskData(const QByteArray &p_data) -{ - QByteArray maskData; - maskData.reserve(p_data.size() * 8 / 6); - - for (const unsigned char byte : p_data) - { - switch (byte) + if (p_data.size() >= CHECKSUM_SIZE) { - case XON: - maskData.append(SUBST); - maskData.append(SUB_XON); - break; - case XOFF: - maskData.append(SUBST); - maskData.append(SUB_XOFF); - break; - case STX: - maskData.append(SUBST); - maskData.append(SUB_STX); - break; - case ETX: - maskData.append(SUBST); - maskData.append(SUB_ETX); - break; - case SUBST: - maskData.append(SUBST); - maskData.append(static_cast(SUB_SUBST)); - break; - default: - maskData.append(byte); - break; - } - } + withoutChecksum.chop(1); - return maskData; + if (p_data.at(p_data.size() - 1) != getChecksum(withoutChecksum)) + throw error; + } + else + throw error; + + return withoutChecksum; +} + +static QByteArray maskData(const QByteArray& p_data) +{ + QByteArray maskData; + maskData.reserve(p_data.size() * 8 / 6); + + for (const unsigned char byte : p_data) + { + switch (byte) + { + case XON: + maskData.append(SUBST); + maskData.append(SUB_XON); + break; + case XOFF: + maskData.append(SUBST); + maskData.append(SUB_XOFF); + break; + case STX: + maskData.append(SUBST); + maskData.append(SUB_STX); + break; + case ETX: + maskData.append(SUBST); + maskData.append(SUB_ETX); + break; + case SUBST: + maskData.append(SUBST); + maskData.append(static_cast(SUB_SUBST)); + break; + default: + maskData.append(byte); + break; + } + } + + return maskData; } static bool mustBeMasked(const unsigned char byte) { - switch (byte) - { - case XON: - case XOFF: - case STX: - case ETX: - case SUBST: - return true; - default: - break; - } - return false; -} - -int lenMaskedData(const QByteArray &data) -{ - int ret = data.length(); - const unsigned char upperLen = ((data.length() & 0xff00) >> 8); - const unsigned char lowerLen = ((data.length() & 0x00ff) >> 0); - if (mustBeMasked(upperLen)) - ++ret; - if (mustBeMasked(lowerLen)) - ++ret; - for (const unsigned char byte : data) - { - if (mustBeMasked(byte)) - ++ret; - } - if (mustBeMasked(getChecksum(data))) - ++ret; - - return ret; -} - - - - -static QByteArray unmaskData(const QByteArray &p_data) -{ - QByteArray unmaskData; - unmaskData.reserve(p_data.size()); - - for (int position = 0; position < p_data.size(); ++position) - { - unsigned char byte = p_data.at(position); - if (byte == SUBST) + switch (byte) { - ++position; - byte = p_data.at(position); + case XON: + case XOFF: + case STX: + case ETX: + case SUBST: + return true; + default: + break; + } + return false; +} - switch (byte) - { - case SUB_XON: unmaskData.append(XON); break; - case SUB_XOFF: unmaskData.append(XOFF); break; - case SUB_STX: unmaskData.append(STX); break; - case SUB_ETX: unmaskData.append(ETX); break; - case SUB_SUBST: unmaskData.append(SUBST); break; - default: break; - } +int lenMaskedData(const QByteArray& data) +{ + int ret = data.length(); + const unsigned char upperLen = ((data.length() & 0xff00) >> 8); + const unsigned char lowerLen = ((data.length() & 0x00ff) >> 0); + if (mustBeMasked(upperLen)) + ++ret; + if (mustBeMasked(lowerLen)) + ++ret; + for (const unsigned char byte : data) + { + if (mustBeMasked(byte)) + ++ret; + } + if (mustBeMasked(getChecksum(data))) + ++ret; + + return ret; +} + +static QByteArray unmaskData(const QByteArray& p_data) +{ + QByteArray unmaskData; + unmaskData.reserve(p_data.size()); + + for (int position = 0; position < p_data.size(); ++position) + { + unsigned char byte = p_data.at(position); + if (byte == SUBST) + { + ++position; + byte = p_data.at(position); + + switch (byte) + { + case SUB_XON: + unmaskData.append(XON); + break; + case SUB_XOFF: + unmaskData.append(XOFF); + break; + case SUB_STX: + unmaskData.append(STX); + break; + case SUB_ETX: + unmaskData.append(ETX); + break; + case SUB_SUBST: + unmaskData.append(SUBST); + break; + default: + break; + } + } + else + unmaskData.append(byte); + } + return unmaskData; +} + +static QByteArray addFrame(const QByteArray& p_data) +{ + QByteArray ret; + ret.reserve(2 + p_data.size()); + ret.append(STX); + ret.append(p_data); + ret.append(ETX); + return ret; +} + +static QByteArray removeFrame(const QByteArray& p_data) +{ + + if (p_data[0] == STX && p_data[p_data.size() - 1] == ETX) + { + + return p_data.mid(1, p_data.size() - 2); } else - unmaskData.append(byte); - } - return unmaskData; + throw ConversionError("Framing Error"); } - - -static QByteArray addFrame(const QByteArray &p_data) +static void checkLength(const QByteArray& p_data) { - QByteArray ret; - ret.reserve(2 + p_data.size()); - ret.append(STX); - ret.append(p_data); - ret.append(ETX); - return ret; + if (p_data.size() < HEADER_SIZE) + throw ConversionError("Telegram too short"); + + unsigned char length = p_data[HEADER_SIZE - 1]; + if (length != p_data.size() - HEADER_SIZE) + throw ConversionError("Telegram length does not match"); } - - -static QByteArray removeFrame(const QByteArray &p_data) +QByteArray byteStreamFromSfmMessage(const SfmMessage& message) { - - if (p_data[0] == STX && p_data[p_data.size() - 1] == ETX) - { - - return p_data.mid(1, p_data.size() - 2); - } - else - throw ConversionError("Framing Error"); -} + QByteArray byteData(getHeader(message)); - - -static void checkLength(const QByteArray &p_data) -{ - if (p_data.size() < HEADER_SIZE) - throw ConversionError("Telegram too short"); - - unsigned char length = p_data[HEADER_SIZE - 1]; - if (length != p_data.size() - HEADER_SIZE) - throw ConversionError("Telegram length does not match"); -} - -QByteArray byteStreamFromSfmMessage(const SfmMessage &message) -{ - QByteArray byteData(getHeader(message)); - - byteData.append(message.payload().size()); - byteData.append(message.payload()); - byteData.append(getChecksum(byteData)); - - return addFrame(maskData(byteData)); -} - -SfmMessage byteStreamToSfmMessage(const QByteArray &datastream) -{ - if (datastream.size() < MINIMUM_BYTE_SIZE) - throw ConversionError("Can't convert an QByteArray that hasn't the minimum size!"); - - QByteArray checkMsg; - - - checkMsg = removeFrame(datastream); - checkMsg = unmaskData(checkMsg); - - checkMsg = removeChecksum(checkMsg); - - checkLength(checkMsg); - - - return getSfmMessage(checkMsg); -} - -QByteArray byteStreamFromEscMessage(const QByteArray &message) -{ - QByteArray byteData = message; - if (message.size() == 1) - { - - byteData.append(message); - } - else + byteData.append(message.payload().size()); + byteData.append(message.payload()); byteData.append(getChecksum(byteData)); - byteData = maskData(byteData); - byteData = addFrame(byteData); - - return byteData; + return addFrame(maskData(byteData)); } -QByteArray byteStreamToEscMessage(const QByteArray &datastream) +SfmMessage byteStreamToSfmMessage(const QByteArray& datastream) { - if (datastream.size() < 2) - return QByteArray("ERROR"); + if (datastream.size() < MINIMUM_BYTE_SIZE) + throw ConversionError("Can't convert an QByteArray that hasn't the minimum size!"); - QByteArray checkMsg; + QByteArray checkMsg; - - checkMsg = removeFrame(datastream); - checkMsg = unmaskData(checkMsg); - - - checkMsg.chop(1); - return checkMsg; + checkMsg = removeFrame(datastream); + checkMsg = unmaskData(checkMsg); + + checkMsg = removeChecksum(checkMsg); + + checkLength(checkMsg); + + return getSfmMessage(checkMsg); } -} +QByteArray byteStreamFromEscMessage(const QByteArray& message) +{ + QByteArray byteData = message; + if (message.size() == 1) + { + + byteData.append(message); + } + else + byteData.append(getChecksum(byteData)); + + byteData = maskData(byteData); + byteData = addFrame(byteData); + + return byteData; +} + +QByteArray byteStreamToEscMessage(const QByteArray& datastream) +{ + if (datastream.size() < 2) + return QByteArray("ERROR"); + + QByteArray checkMsg; + + checkMsg = removeFrame(datastream); + checkMsg = unmaskData(checkMsg); + + checkMsg.chop(1); + return checkMsg; +} + +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h old mode 100755 new mode 100644 index 9ff01ae4c..541202fb2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/sfm_bytemessage_converter.h @@ -1,9 +1,9 @@ - #pragma once #include "ltsutilscore_export.h" + #include namespace LtsUtils @@ -11,54 +11,62 @@ namespace LtsUtils class LTSUTILSCORE_EXPORT SfmMessage { -public: - unsigned int id() const { return m_id; } - void setId(unsigned int id) { m_id = id; } + public: + unsigned int id() const + { + return m_id; + } - bool rtr() const { return m_rtr; } - void setRtr(bool rtr) { m_rtr = rtr; } + void setId(unsigned int id) + { + m_id = id; + } - QByteArray payload() const { return m_payload; } - void setPayload(const QByteArray &payload) { m_payload = payload; } + bool rtr() const + { + return m_rtr; + } - bool operator==(const SfmMessage &msg) const - { - return (m_id == msg.id() && - m_rtr == msg.rtr() && - m_payload == msg.payload()); - } + void setRtr(bool rtr) + { + m_rtr = rtr; + } -protected: - unsigned int m_id = 0; - bool m_rtr = false; - QByteArray m_payload; + QByteArray payload() const + { + return m_payload; + } + + void setPayload(const QByteArray& payload) + { + m_payload = payload; + } + + bool operator==(const SfmMessage& msg) const + { + return (m_id == msg.id() && m_rtr == msg.rtr() && m_payload == msg.payload()); + } + + protected: + unsigned int m_id = 0; + bool m_rtr = false; + QByteArray m_payload; }; - class ConversionError : public std::runtime_error { -public: - using std::runtime_error::runtime_error; + public: + using std::runtime_error::runtime_error; }; +LTSUTILSCORE_EXPORT QByteArray byteStreamFromSfmMessage(const SfmMessage& message); +LTSUTILSCORE_EXPORT SfmMessage byteStreamToSfmMessage(const QByteArray& datastream); -LTSUTILSCORE_EXPORT QByteArray byteStreamFromSfmMessage(const SfmMessage &message); +LTSUTILSCORE_EXPORT QByteArray byteStreamFromEscMessage(const QByteArray& message); +LTSUTILSCORE_EXPORT QByteArray byteStreamToEscMessage(const QByteArray& datastream); +LTSUTILSCORE_EXPORT int lenMaskedData(const QByteArray& data); -LTSUTILSCORE_EXPORT SfmMessage byteStreamToSfmMessage(const QByteArray &datastream); - - - -LTSUTILSCORE_EXPORT QByteArray byteStreamFromEscMessage(const QByteArray &message); - - - -LTSUTILSCORE_EXPORT QByteArray byteStreamToEscMessage(const QByteArray &datastream); - - - -LTSUTILSCORE_EXPORT int lenMaskedData(const QByteArray &data); - -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h old mode 100755 new mode 100644 index 0be695230..24dbc221b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsCore/variant_operators.h @@ -1,39 +1,37 @@ #pragma once -#include #include - +#include #include - namespace LtsUtils { -inline bool lessThan(const QVariant &var1, const QVariant &var2) +inline bool lessThan(const QVariant& var1, const QVariant& var2) { - if (var1.canConvert(QMetaType::QString) && var2.canConvert(QMetaType::QString)) - { - QString str1(var1.toString()); - QString str2(var2.toString()); + if (var1.canConvert(QMetaType::QString) && var2.canConvert(QMetaType::QString)) + { + QString str1(var1.toString()); + QString str2(var2.toString()); - bool k1 = false; - double d1 = str1.toDouble(&k1); + bool k1 = false; + double d1 = str1.toDouble(&k1); - if (!k1) - return str1 < str2; + if (!k1) + return str1 < str2; - bool k2 = false; - double d2 = str2.toDouble(&k2); + bool k2 = false; + double d2 = str2.toDouble(&k2); - if (!k2) - return str1 < str2; + if (!k2) + return str1 < str2; - return d1 < d2; - } - else if (var1.canConvert(QMetaType::Double) && var2.canConvert(QMetaType::Double)) - return var1.toDouble() < var2.toDouble(); + return d1 < d2; + } + else if (var1.canConvert(QMetaType::Double) && var2.canConvert(QMetaType::Double)) + return var1.toDouble() < var2.toDouble(); - return false; + return false; } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp old mode 100755 new mode 100644 index f16856c1d..a253f437d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.cpp @@ -1,73 +1,59 @@ - #include "connect_dialog.h" + #include "ui_connect_dialog.h" #include - namespace LtsUtils { int ConnectingDialog::s_waitForHistoricalDataWaitTime = 10000; - void ConnectingDialog::reset() { - m_ui->label->setText(QStringLiteral("%1").arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); + m_ui->label->setText(QStringLiteral("%1") + .arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); } - void ConnectingDialog::setup() { - m_ui = new Ui::ConnectingDialog; - m_ui->setupUi(this); - reset(); - setMinimumSize(sizeHint()); - connect(m_ui->pbRetry, &QPushButton::clicked, - this, [this]() - { - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setEnabled(false); - + m_ui = new Ui::ConnectingDialog; + m_ui->setupUi(this); reset(); - emit signalStopLoop(); - }); + setMinimumSize(sizeHint()); + connect(m_ui->pbRetry, &QPushButton::clicked, this, [this]() { + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setEnabled(false); - connect(m_ui->pbIgnore, &QPushButton::clicked, - this, [this]() - { - m_ui->pbIgnore->setEnabled(false); - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setText(tr("continuing..")); + reset(); + emit signalStopLoop(); + }); - deleteLater(); - return; + connect(m_ui->pbIgnore, &QPushButton::clicked, this, [this]() { + m_ui->pbIgnore->setEnabled(false); + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setText(tr("continuing..")); - - - - - - - }); + deleteLater(); + return; + }); } - ConnectingDialog::~ConnectingDialog() { - delete m_ui; + delete m_ui; } - void ConnectingDialog::failed() { - m_ui->label->setText(QStringLiteral("%1").arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); + m_ui->label->setText(QStringLiteral("%1") + .arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); - m_ui->pbRetry->setEnabled(true); - m_ui->pbIgnore->setEnabled(true); + m_ui->pbRetry->setEnabled(true); + m_ui->pbIgnore->setEnabled(true); - raise(); + raise(); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h old mode 100755 new mode 100644 index 78efa3967..f888519f7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog.h @@ -1,18 +1,14 @@ - #pragma once -#include - #include "ltsutilsguiconnectdialog_export.h" + #include - -#include +#include #include - +#include #include - namespace Ui { class ConnectingDialog; @@ -23,61 +19,55 @@ namespace LtsUtils class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialog : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - static int s_waitForHistoricalDataWaitTime; + public: + static int s_waitForHistoricalDataWaitTime; - template - explicit ConnectingDialog(DtcType dtc, - WaitForHistoricalDataFunction waitForHistoricalDataFunction, - const QString &serviceName, - const QString &exerciseName, - QWidget *parent = nullptr) - : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) - , m_serviceName(serviceName) - , m_exerciseName(exerciseName) - , m_ui(nullptr) - { - setWindowTitle(tr("Connecting ..")); - setup(); - show(); - - while (true) + template + explicit ConnectingDialog(DtcType dtc, WaitForHistoricalDataFunction waitForHistoricalDataFunction, + const QString& serviceName, const QString& exerciseName, QWidget* parent = nullptr) + : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_serviceName(serviceName), + m_exerciseName(exerciseName), m_ui(nullptr) { - if ((dtc.get()->*waitForHistoricalDataFunction)(s_waitForHistoricalDataWaitTime)) - { - deleteLater(); - return; - } + setWindowTitle(tr("Connecting ..")); + setup(); + show(); - if (s_waitForHistoricalDataWaitTime >= 999999) - { - deleteLater(); - return; - } - else - { - failed(); - } + while (true) + { + if ((dtc.get()->*waitForHistoricalDataFunction)(s_waitForHistoricalDataWaitTime)) + { + deleteLater(); + return; + } + + if (s_waitForHistoricalDataWaitTime >= 999999) + { + deleteLater(); + return; + } + else + { + failed(); + } + } } - } - ~ConnectingDialog(); + ~ConnectingDialog(); - void failed(); + void failed(); -private: - QString m_serviceName; - QString m_exerciseName; - Ui::ConnectingDialog *m_ui; + private: + QString m_serviceName; + QString m_exerciseName; + Ui::ConnectingDialog* m_ui; - void reset(); - void setup(); - -signals: - void signalStopLoop(); + void reset(); + void setup(); + signals: + void signalStopLoop(); }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp old mode 100755 new mode 100644 index 3d35ee492..1c0f8322e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.cpp @@ -1,157 +1,129 @@ +#include "connect_dialog_nt.h" #include "connect_dialog.h" -#include "connect_dialog_nt.h" #include "ui_connect_dialog.h" #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) #include #endif - namespace LtsUtils { - -ConnectingDialogNT::ConnectingDialogNT(const std::function &checkFn, - const QString &serviceName, - const QString &exerciseName, - QWidget *parent) - : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) - , m_serviceName(serviceName) - , m_exerciseName(exerciseName) - , m_checkFn(checkFn) - , m_go(false) - , m_autoRetryTimer(new QTimer(this)) - , m_ui(new Ui::ConnectingDialog ) +ConnectingDialogNT::ConnectingDialogNT(const std::function& checkFn, const QString& serviceName, + const QString& exerciseName, QWidget* parent) + : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), m_serviceName(serviceName), + m_exerciseName(exerciseName), m_checkFn(checkFn), m_go(false), m_autoRetryTimer(new QTimer(this)), + m_ui(new Ui::ConnectingDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_autoRetryTimer->setInterval(1000); - connect(m_autoRetryTimer, &QTimer::timeout, - this, [this]() - { - if (m_autoRetryTick < 1) - { - slotRetry(); - return; - } + m_autoRetryTimer->setInterval(1000); + connect(m_autoRetryTimer, &QTimer::timeout, this, [this]() { + if (m_autoRetryTick < 1) + { + slotRetry(); + return; + } - m_ui->pbRetry->setText(QStringLiteral("%1 [%2]").arg(tr("Retry")).arg(m_autoRetryTick)); - m_autoRetryTick--; - }); + m_ui->pbRetry->setText(QStringLiteral("%1 [%2]").arg(tr("Retry")).arg(m_autoRetryTick)); + m_autoRetryTick--; + }); - reset(); - setMinimumSize(sizeHint()); - connect(m_ui->pbRetry, &QPushButton::clicked, - this, &ConnectingDialogNT::slotRetry); + reset(); + setMinimumSize(sizeHint()); + connect(m_ui->pbRetry, &QPushButton::clicked, this, &ConnectingDialogNT::slotRetry); - connect(m_ui->pbIgnore, &QPushButton::clicked, - this, [this]() - { - m_ui->pbIgnore->setEnabled(false); + connect(m_ui->pbIgnore, &QPushButton::clicked, this, [this]() { + m_ui->pbIgnore->setEnabled(false); + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setText(tr("continuing..")); + + emit signalFailed(); + deleteLater(); + return; + }); + + show(); + + connect(this, &ConnectingDialogNT::signalGo, this, &ConnectingDialogNT::slotGo, Qt::QueuedConnection); + + m_go = true; m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setText(tr("continuing..")); - - emit signalFailed(); - deleteLater(); - return; - - - - - - - - }); - - show(); - - connect(this, &ConnectingDialogNT::signalGo, - this, &ConnectingDialogNT::slotGo, Qt::QueuedConnection); - - m_go = true; - m_ui->pbRetry->setEnabled(false); } - int ConnectingDialogNT::random(int min, int max) { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) - return QRandomGenerator::global()->bounded(min, max); + return QRandomGenerator::global()->bounded(min, max); #else - return (qrand() % (((max + 1) - min) + min)); + return (qrand() % (((max + 1) - min) + min)); #endif } - - -bool ConnectingDialogNT::event(QEvent *event) +bool ConnectingDialogNT::event(QEvent* event) { - bool result = LtsWidgets::LtsFramelessDialog::event(event); + bool result = LtsWidgets::LtsFramelessDialog::event(event); - if (event->type() == QEvent::Paint && m_go) - { - m_go = false; - QTimer::singleShot(0, this, &ConnectingDialogNT::signalGo); - } + if (event->type() == QEvent::Paint && m_go) + { + m_go = false; + QTimer::singleShot(0, this, &ConnectingDialogNT::signalGo); + } - return result; + return result; } - void ConnectingDialogNT::slotRetry() { - m_autoRetryTimer->stop(); + m_autoRetryTimer->stop(); - m_ui->pbRetry->setText(tr("Retry")); - m_ui->pbRetry->setEnabled(false); - m_ui->pbIgnore->setEnabled(false); + m_ui->pbRetry->setText(tr("Retry")); + m_ui->pbRetry->setEnabled(false); + m_ui->pbIgnore->setEnabled(false); - reset(); - QTimer::singleShot(1, this, &ConnectingDialogNT::slotGo); + reset(); + QTimer::singleShot(1, this, &ConnectingDialogNT::slotGo); } - void ConnectingDialogNT::slotGo() { - - if (m_checkFn(ConnectingDialog::s_waitForHistoricalDataWaitTime)) - { - emit signalSuccess(); - deleteLater(); - return; - } - - failed(); + if (m_checkFn(ConnectingDialog::s_waitForHistoricalDataWaitTime)) + { + emit signalSuccess(); + deleteLater(); + return; + } + + failed(); } - void ConnectingDialogNT::reset() { - m_ui->label->setText(QStringLiteral("%1").arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); + m_ui->label->setText(QStringLiteral("%1") + .arg(tr("Connecting to %1 on %2 ...").arg(m_serviceName, m_exerciseName))); } - ConnectingDialogNT::~ConnectingDialogNT() { - delete m_ui; + delete m_ui; } - void ConnectingDialogNT::failed() { - m_ui->label->setText(QStringLiteral("%1").arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); + m_ui->label->setText(QStringLiteral("%1") + .arg(tr("Could not connect to %1 on %2 !").arg(m_serviceName, m_exerciseName))); - m_ui->pbRetry->setEnabled(true); - m_ui->pbIgnore->setEnabled(true); + m_ui->pbRetry->setEnabled(true); + m_ui->pbIgnore->setEnabled(true); - m_autoRetryTick = random(5, 20); - m_autoRetryTimer->start(); + m_autoRetryTick = random(5, 20); + m_autoRetryTimer->start(); - raise(); + raise(); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h old mode 100755 new mode 100644 index 91bc75a68..f3785c373 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/ConnectDialog/connect_dialog_nt.h @@ -1,15 +1,12 @@ - #pragma once -#include - #include "ltsutilsguiconnectdialog_export.h" + #include - +#include #include - class QTimer; namespace Ui @@ -22,43 +19,38 @@ namespace LtsUtils class LTSUTILSGUICONNECTDIALOG_EXPORT ConnectingDialogNT : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - + public: + explicit ConnectingDialogNT(const std::function& checkFn, const QString& serviceName, + const QString& exerciseName, QWidget* parent); + ~ConnectingDialogNT(); - explicit ConnectingDialogNT(const std::function &checkFn, - const QString &serviceName, - const QString &exerciseName, - QWidget *parent); - ~ConnectingDialogNT(); + void failed(); + private slots: + void slotGo(); + void slotRetry(); - void failed(); + signals: + void signalGo(); + void signalFailed(); + void signalSuccess(); -private slots: - void slotGo(); - void slotRetry(); + private: + QString m_serviceName; + QString m_exerciseName; + std::function m_checkFn; + bool m_go; -signals: - void signalGo(); - void signalFailed(); - void signalSuccess(); + QTimer* m_autoRetryTimer; + int m_autoRetryTick{0}; -private: - QString m_serviceName; - QString m_exerciseName; - std::function m_checkFn; - bool m_go; + Ui::ConnectingDialog* m_ui; - QTimer *m_autoRetryTimer; - int m_autoRetryTick { 0 }; - - Ui::ConnectingDialog *m_ui; - - int random(int min, int max); - bool event(QEvent *event) override; - void reset(); + int random(int min, int max); + bool event(QEvent* event) override; + void reset(); }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp old mode 100755 new mode 100644 index f5872c3bc..3eaa456a3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.cpp @@ -1,9 +1,7 @@ - -#include #include - +#include #include #include #include @@ -12,123 +10,120 @@ #include #include - namespace LtsUtils { -QIcon iconFromSvg(const QByteArray &svgData, QSize iconSize) +QIcon iconFromSvg(const QByteArray& svgData, QSize iconSize) { - QSvgRenderer renderer(svgData); - QPixmap p(iconSize); - p.fill(Qt::transparent); - QPainter painter(&p); - renderer.render(&painter); - painter.end(); + QSvgRenderer renderer(svgData); + QPixmap p(iconSize); + p.fill(Qt::transparent); + QPainter painter(&p); + renderer.render(&painter); + painter.end(); - return {p}; + return {p}; } -QIcon iconFromSvg(const QString &svgFilename, QSize iconSize) +QIcon iconFromSvg(const QString& svgFilename, QSize iconSize) { - QFile f(svgFilename); - if (!f.open(QIODevice::ReadOnly)) - return {}; - return iconFromSvg(f.readAll(), iconSize); + QFile f(svgFilename); + if (!f.open(QIODevice::ReadOnly)) + return {}; + return iconFromSvg(f.readAll(), iconSize); } -QPixmap pixmapFromIcon(const QIcon &icon, QSize iconSize) +QPixmap pixmapFromIcon(const QIcon& icon, QSize iconSize) { - return icon.pixmap(iconSize).scaled(100, 100, Qt::AspectRatioMode::IgnoreAspectRatio); + return icon.pixmap(iconSize).scaled(100, 100, Qt::AspectRatioMode::IgnoreAspectRatio); } -QPixmap pixmapFromSvg(const QString &svgFilename, QSize iconSize) +QPixmap pixmapFromSvg(const QString& svgFilename, QSize iconSize) { - return pixmapFromIcon(iconFromSvg(svgFilename, iconSize), iconSize); + return pixmapFromIcon(iconFromSvg(svgFilename, iconSize), iconSize); } -QPixmap getPixmap(const std::vector &data) +QPixmap getPixmap(const std::vector& data) { - if (data.size() == 0) - return QPixmap(); - - return getPixmap(QByteArray(reinterpret_cast(&data.at(0)), data.size())); + if (data.size() == 0) + return QPixmap(); + + return getPixmap(QByteArray(reinterpret_cast(&data.at(0)), data.size())); } -QPixmap getPixmap(const QByteArray &data) +QPixmap getPixmap(const QByteArray& data) { - return QPixmap::fromImage(QImage::fromData(data)); + return QPixmap::fromImage(QImage::fromData(data)); } -QImage getImage(const std::vector &data) +QImage getImage(const std::vector& data) { - if (data.size() == 0) - return QImage(); - - return getImage(QByteArray(reinterpret_cast(&data.at(0)), data.size())); + if (data.size() == 0) + return QImage(); + + return getImage(QByteArray(reinterpret_cast(&data.at(0)), data.size())); } -QImage getImage(const QByteArray &data) +QImage getImage(const QByteArray& data) { - return QImage::fromData(data); + return QImage::fromData(data); } -static inline void setIf(bool *boolPtr, bool val) +static inline void setIf(bool* boolPtr, bool val) { - if (boolPtr) - *boolPtr = val; + if (boolPtr) + *boolPtr = val; } -std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng) +std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng) { - QBuffer buf; - buf.open(QIODevice::WriteOnly); - pixmap.save(&buf, "PNG"); - buf.close(); - QByteArray ba = buf.buffer(); + QBuffer buf; + buf.open(QIODevice::WriteOnly); + pixmap.save(&buf, "PNG"); + buf.close(); + QByteArray ba = buf.buffer(); - setIf(bIsPng, true); - - if (ba.size() > 10240 && !pixmap.hasAlpha() && !pixmap.hasAlphaChannel()) - { - QBuffer buf2; - buf2.open(QIODevice::WriteOnly); - pixmap.save(&buf2, "JPG"); - buf2.close(); - if (buf2.buffer().size() < buf.buffer().size()) + setIf(bIsPng, true); + + if (ba.size() > 10240 && !pixmap.hasAlpha() && !pixmap.hasAlphaChannel()) { - setIf(bIsPng, false); - ba = buf2.buffer(); + QBuffer buf2; + buf2.open(QIODevice::WriteOnly); + pixmap.save(&buf2, "JPG"); + buf2.close(); + if (buf2.buffer().size() < buf.buffer().size()) + { + setIf(bIsPng, false); + ba = buf2.buffer(); + } } - } - return convert>(ba); + return convert>(ba); } -std::vector fromImage(const QImage &image, bool *bIsPng) +std::vector fromImage(const QImage& image, bool* bIsPng) { - QBuffer buf; - buf.open(QIODevice::WriteOnly); - image.save(&buf, "PNG"); - buf.close(); - QByteArray ba = buf.buffer(); + QBuffer buf; + buf.open(QIODevice::WriteOnly); + image.save(&buf, "PNG"); + buf.close(); + QByteArray ba = buf.buffer(); - - setIf(bIsPng, true); - if ((ba.size() > 10240 && !image.hasAlphaChannel()) || - ba.size() > 1024 * 1024) - { - QBuffer buf2; - buf2.open(QIODevice::WriteOnly); - image.save(&buf2, "JPG"); - buf2.close(); - if (buf2.buffer().size() < buf.buffer().size()) + setIf(bIsPng, true); + if ((ba.size() > 10240 && !image.hasAlphaChannel()) || ba.size() > 1024 * 1024) { - setIf(bIsPng, false); - ba = buf2.buffer(); + QBuffer buf2; + buf2.open(QIODevice::WriteOnly); + image.save(&buf2, "JPG"); + buf2.close(); + if (buf2.buffer().size() < buf.buffer().size()) + { + setIf(bIsPng, false); + ba = buf2.buffer(); + } } - } - return convert>(ba); + return convert>(ba); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h old mode 100755 new mode 100644 index a0c225416..da819aac5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/dds_vector_to_pixmap.h @@ -1,13 +1,11 @@ - #pragma once #include "ltsutilsguidds_export.h" #include #include - #include #include @@ -19,15 +17,15 @@ class QIcon; namespace LtsUtils { -LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector &data); -LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray &data); -LTSUTILSCORE_EXPORT QImage getImage(const std::vector &data); -LTSUTILSCORE_EXPORT QImage getImage(const QByteArray &data); -LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QByteArray &svgData, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QString &svgFilename, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QPixmap pixmapFromIcon(const QIcon &icon, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT QPixmap pixmapFromSvg(const QString &svgFilename, QSize iconSize = QSize(100, 100)); -LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap &pixmap, bool *bIsPng = nullptr); -LTSUTILSCORE_EXPORT std::vector fromImage(const QImage &image, bool *bIsPng = nullptr); +LTSUTILSCORE_EXPORT QPixmap getPixmap(const std::vector& data); +LTSUTILSCORE_EXPORT QPixmap getPixmap(const QByteArray& data); +LTSUTILSCORE_EXPORT QImage getImage(const std::vector& data); +LTSUTILSCORE_EXPORT QImage getImage(const QByteArray& data); +LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QByteArray& svgData, QSize iconSize = QSize(100, 100)); +LTSUTILSCORE_EXPORT QIcon iconFromSvg(const QString& svgFilename, QSize iconSize = QSize(100, 100)); +LTSUTILSCORE_EXPORT QPixmap pixmapFromIcon(const QIcon& icon, QSize iconSize = QSize(100, 100)); +LTSUTILSCORE_EXPORT QPixmap pixmapFromSvg(const QString& svgFilename, QSize iconSize = QSize(100, 100)); +LTSUTILSCORE_EXPORT std::vector fromPixmap(const QPixmap& pixmap, bool* bIsPng = nullptr); +LTSUTILSCORE_EXPORT std::vector fromImage(const QImage& image, bool* bIsPng = nullptr); -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp old mode 100755 new mode 100644 index ec92f01df..e9574f6ea --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.cpp @@ -1,6 +1,5 @@ - #include "request_helper.h" #ifdef REQUEST_HELPER_WITH_GUI @@ -9,268 +8,239 @@ #include #endif - #include -#include -#include #include #include +#include +#include #define DEBUG - namespace LtsUtils { bool RequestHelper::s_debug = false; -RequestHelper::RequestHelper(QObject *parent, bool quiet, - - const std::function &success, - const std::function &failure) - : QObject(parent) - , m_failed(false) - , m_repliedId(-1) - , m_quiet(quiet) - , m_blockingCall(true) - , m_successFn(success) - , m_failureFn(failure) -{ - connect(this, &RequestHelper::signalSuccess, this, m_successFn, Qt::QueuedConnection); - connect(this, &RequestHelper::signalFailed, this, m_failureFn, Qt::QueuedConnection); +RequestHelper::RequestHelper(QObject* parent, bool quiet, - if (s_debug) - { - QTimer *t = new QTimer(this); - t->setInterval(2000); - t->setSingleShot(true); - connect(this, &RequestHelper::signalNextRequest, t, static_cast(&QTimer::start)); - connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); - } - else - { - connect(this, &RequestHelper::signalNextRequest, - this, &RequestHelper::slotNextRequest, - Qt::QueuedConnection - -); - } + const std::function& success, const std::function& failure) + : QObject(parent), m_failed(false), m_repliedId(-1), m_quiet(quiet), m_blockingCall(true), m_successFn(success), + m_failureFn(failure) +{ + connect(this, &RequestHelper::signalSuccess, this, m_successFn, Qt::QueuedConnection); + connect(this, &RequestHelper::signalFailed, this, m_failureFn, Qt::QueuedConnection); + + if (s_debug) + { + QTimer* t = new QTimer(this); + t->setInterval(2000); + t->setSingleShot(true); + connect(this, &RequestHelper::signalNextRequest, t, static_cast(&QTimer::start)); + connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); + } + else + { + connect(this, &RequestHelper::signalNextRequest, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection + + ); + } } - -void RequestHelper::addRequest(const std::function &requestFunction, - const std::function &baseReplyHandler) +void RequestHelper::addRequest(const std::function& requestFunction, + const std::function& baseReplyHandler) { - m_requestFunctions.append(RequestFunctionContainer(requestFunction, baseReplyHandler)); + m_requestFunctions.append(RequestFunctionContainer(requestFunction, baseReplyHandler)); } -bool RequestHelper::requestReply(const Core::FunctionReply &baseReply) +bool RequestHelper::requestReply(const Core::FunctionReply& baseReply) { - const Core::FunctionReplyObject fro(baseReply.id(), - baseReply.errorString(), - baseReply.errorParams()); - return _requestReply(fro, &baseReply); + const Core::FunctionReplyObject fro(baseReply.id(), baseReply.errorString(), baseReply.errorParams()); + return _requestReply(fro, &baseReply); } -bool RequestHelper::requestReply(const Core::FunctionReplyObject &replyObject) +bool RequestHelper::requestReply(const Core::FunctionReplyObject& replyObject) { - return _requestReply(replyObject, nullptr); + return _requestReply(replyObject, nullptr); } - -bool RequestHelper::_requestReply(const Core::FunctionReplyObject &fro, const Core::FunctionReply *baseReply) +bool RequestHelper::_requestReply(const Core::FunctionReplyObject& fro, const Core::FunctionReply* baseReply) { - m_errorString = fro.translated(); + m_errorString = fro.translated(); #ifdef REQUEST_HELPER_WITH_GUI - if (fro.error()) - { - - if (!m_quiet) + if (fro.error()) { - if (m_blockingCall) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), - m_errorString, - tr("Request failed")); - } - else - { - new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), - m_errorString, - tr("Request failed")); - } + + if (!m_quiet) + { + if (m_blockingCall) + { + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), m_errorString, + tr("Request failed")); + } + else + { + new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), m_errorString, + tr("Request failed")); + } + } } - } #endif - m_repliedId = fro.id(); + m_repliedId = fro.id(); - if (m_singleRequestCustomFunctionReply != nullptr) - { - if (baseReply) - m_singleRequestCustomFunctionReply(*baseReply); - else - m_singleRequestCustomFunctionReply(Core::FunctionReply(fro.id(), fro.str(), fro.args(), fro.additionalInfo())); - } + if (m_singleRequestCustomFunctionReply != nullptr) + { + if (baseReply) + m_singleRequestCustomFunctionReply(*baseReply); + else + m_singleRequestCustomFunctionReply( + Core::FunctionReply(fro.id(), fro.str(), fro.args(), fro.additionalInfo())); + } - if (fro.error()) - { - failure(); - return false; - } + if (fro.error()) + { + failure(); + return false; + } - emit signalNextRequest(); - return true; + emit signalNextRequest(); + return true; } - -bool RequestHelper::startSingleRequest(const std::function &requestFunction, - const std::function &baseReplyHandler) +bool RequestHelper::startSingleRequest( + const std::function& requestFunction, + const std::function& baseReplyHandler) { - addRequest(requestFunction, baseReplyHandler); - return startRequests(); + addRequest(requestFunction, baseReplyHandler); + return startRequests(); } - void RequestHelper::failure() { - m_failed = true; - emit signalFailed(); - done(); + m_failed = true; + emit signalFailed(); + done(); } - void RequestHelper::done() { #ifdef REQUEST_HELPER_WITH_GUI - if (!m_quiet) - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); + if (!m_quiet) + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); #endif - m_requestFunctions.clear(); - m_singleRequestCustomFunctionReply = nullptr; + m_requestFunctions.clear(); + m_singleRequestCustomFunctionReply = nullptr; - if (m_blockingCall) - emit signalQuitLoop(); + if (m_blockingCall) + emit signalQuitLoop(); - m_blockingCall = true; + m_blockingCall = true; - if (!m_blockingCall) - deleteLater(); + if (!m_blockingCall) + deleteLater(); } - void RequestHelper::slotNextRequest() { - if (m_requestFunctions.isEmpty()) - { - if (!m_blockingCall) - emit signalSuccess(); - - done(); - - return; - } - - const RequestFunctionContainer rfc = m_requestFunctions.takeFirst(); - m_singleRequestCustomFunctionReply = rfc.second; - - int64_t result = rfc.first(); - - if (result == 0) - { -#ifdef REQUEST_HELPER_WITH_GUI - if (!m_quiet) + if (m_requestFunctions.isEmpty()) { - if (m_blockingCall) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), - tr("Request failed")); - } - else - { - connect(new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), - tr("Request failed")), &LtsWidgets::LtsMessageDialogNew::destroyed, - this, [this]() - { - failure(); - }); + if (!m_blockingCall) + emit signalSuccess(); + + done(); return; - } } + + const RequestFunctionContainer rfc = m_requestFunctions.takeFirst(); + m_singleRequestCustomFunctionReply = rfc.second; + + int64_t result = rfc.first(); + + if (result == 0) + { +#ifdef REQUEST_HELPER_WITH_GUI + if (!m_quiet) + { + if (m_blockingCall) + { + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Request failed")); + } + else + { + connect(new LtsWidgets::LtsMessageDialogNew(qobject_cast(parent()), tr("Request failed")), + &LtsWidgets::LtsMessageDialogNew::destroyed, this, [this]() { failure(); }); + + return; + } + } #endif - failure(); - } + failure(); + } } - -void RequestHelper::startSingleBackgroundRequest(const std::function &requestFunction, - const std::function &baseReplyHandler) +void RequestHelper::startSingleBackgroundRequest( + const std::function& requestFunction, + const std::function& baseReplyHandler) { - m_blockingCall = false; - startSingleRequest(requestFunction, baseReplyHandler); + m_blockingCall = false; + startSingleRequest(requestFunction, baseReplyHandler); } - void RequestHelper::startBackgroundRequests() { - m_blockingCall = false; - startRequests(); + m_blockingCall = false; + startRequests(); } - -void RequestHelper::setCustomWaitMessage(const QString &customWaitMessage) +void RequestHelper::setCustomWaitMessage(const QString& customWaitMessage) { - m_customWaitMessage = (customWaitMessage + QStringLiteral(" ...")); + m_customWaitMessage = (customWaitMessage + QStringLiteral(" ...")); } - bool RequestHelper::startRequests() { - if (m_requestFunctions.isEmpty()) - { + if (m_requestFunctions.isEmpty()) + { #ifdef LTS_DEBUG - qWarning("RequestHelper: started request helper without requests!"); + qWarning("RequestHelper: started request helper without requests!"); #endif - return true; - } + return true; + } - m_failed = false; + m_failed = false; #ifdef REQUEST_HELPER_WITH_GUI - if (!m_quiet) - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(m_customWaitMessage); - m_customWaitMessage.clear(); + if (!m_quiet) + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(m_customWaitMessage); + m_customWaitMessage.clear(); #endif - m_errorString.clear(); - m_repliedId = -1; + m_errorString.clear(); + m_repliedId = -1; - if (s_debug) - { - QTimer *t = new QTimer(this); - t->setInterval(2000); - connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); - connect(t, &QTimer::timeout, t, &QTimer::deleteLater); - t->start(); - } - else - { - slotNextRequest(); - - if (m_blockingCall) + if (s_debug) { - QEventLoop loop; - connect(this, &RequestHelper::signalQuitLoop, - &loop, &QEventLoop::quit, - Qt::QueuedConnection); - loop.exec(); + QTimer* t = new QTimer(this); + t->setInterval(2000); + connect(t, &QTimer::timeout, this, &RequestHelper::slotNextRequest, Qt::QueuedConnection); + connect(t, &QTimer::timeout, t, &QTimer::deleteLater); + t->start(); } - } + else + { + slotNextRequest(); + if (m_blockingCall) + { + QEventLoop loop; + connect(this, &RequestHelper::signalQuitLoop, &loop, &QEventLoop::quit, Qt::QueuedConnection); + loop.exec(); + } + } - return (!m_failed); + return (!m_failed); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h old mode 100755 new mode 100644 index 7352f9fc0..e1f85a771 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/LtsUtilsGuiDds/request_helper.h @@ -1,6 +1,5 @@ - #pragma once #ifdef REQUEST_HELPER_WITH_GUI @@ -12,112 +11,114 @@ #endif #include -#include - +#include #include -#include #include +#include #include - namespace LtsUtils { -template -dds::core::optional toOptional(T inVal) +template dds::core::optional toOptional(T inVal) { - return inVal != T() ? dds::core::optional(inVal) : dds::core::optional(); + return inVal != T() ? dds::core::optional(inVal) : dds::core::optional(); } -template -dds::core::optional optional() +template dds::core::optional optional() { - return dds::core::optional(); + return dds::core::optional(); } - -class LTSUTILSGUIDDS_INTERNAL_EXPORT RequestHelper : public QObject +class LTSUTILSGUIDDS_INTERNAL_EXPORT RequestHelper : public QObject { - Q_OBJECT + Q_OBJECT -public: - static bool s_debug; + public: + static bool s_debug; - explicit RequestHelper(QObject *parent = nullptr, bool quiet = false, - - const std::function &success = [](){}, - const std::function &failure = [](){}); - ~RequestHelper() = default; + explicit RequestHelper( + QObject* parent = nullptr, bool quiet = false, - bool quiet() const { return m_quiet; } - void setQuiet(bool quiet) { m_quiet = quiet; } - void addRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr); - bool startRequests(); + const std::function& success = []() {}, const std::function& failure = []() {}); + ~RequestHelper() = default; - - bool startSingleRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr - ); + bool quiet() const + { + return m_quiet; + } - - + void setQuiet(bool quiet) + { + m_quiet = quiet; + } - void startSingleBackgroundRequest(const std::function &requestFunction, - const std::function &baseReplyHandler = nullptr); - + void addRequest(const std::function& requestFunction, + const std::function& baseReplyHandler = nullptr); + bool startRequests(); - void startBackgroundRequests(); + bool + startSingleRequest(const std::function& requestFunction, + const std::function& baseReplyHandler = nullptr); - bool requestReply(const Core::FunctionReply &baseReply); - bool requestReply(const Core::FunctionReplyObject &replyObject); + void startSingleBackgroundRequest( + const std::function& requestFunction, + const std::function& baseReplyHandler = nullptr); - + void startBackgroundRequests(); - bool hasRequests() const { return !m_requestFunctions.isEmpty(); } + bool requestReply(const Core::FunctionReply& baseReply); + bool requestReply(const Core::FunctionReplyObject& replyObject); + bool hasRequests() const + { + return !m_requestFunctions.isEmpty(); + } - + int getRepliedId() const + { + return m_repliedId; + } - int getRepliedId() const { return m_repliedId; } + QString getErrorString() const + { + return m_errorString; + } - + void setCustomWaitMessage(const QString& customWaitMessage); - QString getErrorString() const { return m_errorString; } + bool failed() const + { + return m_failed; + } - + void failure(); - void setCustomWaitMessage(const QString &customWaitMessage); + private: + using RequestFunctionContainer = QPair, std::function>; - bool failed() const { return m_failed; } - void failure(); + QVector m_requestFunctions; + bool m_failed; + int m_repliedId; + std::function m_singleRequestCustomFunctionReply; + bool m_quiet; + bool m_blockingCall; + std::function m_successFn; + std::function m_failureFn; + QString m_errorString; + QString m_customWaitMessage; -private: - using RequestFunctionContainer = QPair, std::function>; + void done(); + bool _requestReply(const Core::FunctionReplyObject& fro, const Core::FunctionReply* baseReply); - QVector m_requestFunctions; - bool m_failed; - int m_repliedId; - std::function m_singleRequestCustomFunctionReply; - bool m_quiet; - bool m_blockingCall; - std::function m_successFn; - std::function m_failureFn; - QString m_errorString; - QString m_customWaitMessage; - - void done(); - bool _requestReply(const Core::FunctionReplyObject &fro, const Core::FunctionReply *baseReply); - -signals: - void signalNextRequest(); - void signalQuitLoop(); - void signalSuccess(); - void signalFailed(); - -private slots: - void slotNextRequest(); + signals: + void signalNextRequest(); + void signalQuitLoop(); + void signalSuccess(); + void signalFailed(); + private slots: + void slotNextRequest(); }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp old mode 100755 new mode 100644 index 99308ea52..1d5e184fe --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.cpp @@ -1,114 +1,100 @@ - #include "style_manager.h" #include #include - -#include #include - +#include namespace LtsUtils { struct StyleManagerHandler { - StyleManager styleManager; + StyleManager styleManager; }; Q_GLOBAL_STATIC(StyleManagerHandler, s_styleManagerHandler) - -StyleManager *StyleManager::getInstance() +StyleManager* StyleManager::getInstance() { - return &s_styleManagerHandler->styleManager; + return &s_styleManagerHandler->styleManager; } -bool StyleManager::loadStyle(const QString &stylePluginName, bool highDpi) +bool StyleManager::loadStyle(const QString& stylePluginName, bool highDpi) { - if (m_currentStylePluginLoader != nullptr) - { - + if (m_currentStylePluginLoader != nullptr) + { - QObject *pluginInstance = m_currentStylePluginLoader->instance(); - StylePlugin::Plugin *sp = qobject_cast(pluginInstance); + QObject* pluginInstance = m_currentStylePluginLoader->instance(); + StylePlugin::Plugin* sp = qobject_cast(pluginInstance); + + if (sp == nullptr) + { + qWarning() << "StyleManager::loadStyle: could not unload style plugin - wrong type (" + << pluginInstance->metaObject()->className() << ") - new style not loaded"; + return false; + } + + sp->unloadStyle(); + + m_currentStylePluginLoader = nullptr; + } + + LtsPluginManager::LtsPluginLoader* pluginLoader = LtsPluginManager::LtsPluginLoader::getInstance(); + + QPluginLoader* stylePluginLoader = nullptr; + int pluginsLoaded = 0; + + std::function loadPluginFn = + [&stylePluginLoader, &pluginsLoaded](const LtsPluginManager::PluginInstance& pi) { + stylePluginLoader = pi.pluginLoader; + pluginsLoaded++; + return true; + }; + + if (!pluginLoader->loadPlugins(LtsPluginManager::PluginType::STYLE, loadPluginFn, QStringList() << stylePluginName)) + { + qWarning() << "StyleManager::loadStyle: Error loading Style Plugin - using default Qt style"; + return false; + } + + if (pluginsLoaded == 0) + { + qWarning() << "StyleManager::loadStyle: Could not find Style Plugin" << stylePluginName + << "- using default Qt style"; + return false; + } + + if (pluginsLoaded > 1) + { + qWarning() << "StyleManager::loadStyle: Style Plugin" << stylePluginName + << " is ambiguous - using default Qt style"; + return false; + } + + if (stylePluginLoader == nullptr) + { + qWarning() << "StyleManager::loadStyle: No Style Plugin loader available - using default Qt style"; + return false; + } + + StylePlugin::Plugin* sp = qobject_cast(stylePluginLoader->instance()); if (sp == nullptr) { - qWarning() << "StyleManager::loadStyle: could not unload style plugin - wrong type (" - << pluginInstance->metaObject()->className() << ") - new style not loaded"; - return false; + qWarning() << "StyleManager::loadStyle: could not load style plugin - wrong type (" + << stylePluginLoader->instance()->metaObject()->className() << ") - new style not loaded"; + return false; } - sp->unloadStyle(); + sp->loadStyle(highDpi); - + m_currentStylePluginLoader = stylePluginLoader; + m_stylePluginName = stylePluginName; + emit signalStyleChanged(stylePluginName); - - - - - - - m_currentStylePluginLoader = nullptr; - } - - - - LtsPluginManager::LtsPluginLoader *pluginLoader = LtsPluginManager::LtsPluginLoader::getInstance(); - - QPluginLoader *stylePluginLoader = nullptr; - int pluginsLoaded = 0; - - std::function loadPluginFn = [&stylePluginLoader, &pluginsLoaded] - (const LtsPluginManager::PluginInstance &pi) - { - stylePluginLoader = pi.pluginLoader; - pluginsLoaded++; return true; - }; - - if (!pluginLoader->loadPlugins(LtsPluginManager::PluginType::STYLE, loadPluginFn, QStringList() << stylePluginName)) - { - qWarning() << "StyleManager::loadStyle: Error loading Style Plugin - using default Qt style"; - return false; - } - - if (pluginsLoaded == 0) - { - qWarning() << "StyleManager::loadStyle: Could not find Style Plugin" << stylePluginName << "- using default Qt style"; - return false; - } - - if (pluginsLoaded > 1) - { - qWarning() << "StyleManager::loadStyle: Style Plugin" << stylePluginName << " is ambiguous - using default Qt style"; - return false; - } - - if (stylePluginLoader == nullptr) - { - qWarning() << "StyleManager::loadStyle: No Style Plugin loader available - using default Qt style"; - return false; - } - - StylePlugin::Plugin *sp = qobject_cast(stylePluginLoader->instance()); - - if (sp == nullptr) - { - qWarning() << "StyleManager::loadStyle: could not load style plugin - wrong type (" - << stylePluginLoader->instance()->metaObject()->className() << ") - new style not loaded"; - return false; - } - - sp->loadStyle(highDpi); - - m_currentStylePluginLoader = stylePluginLoader; - m_stylePluginName = stylePluginName; - emit signalStyleChanged(stylePluginName); - - return true; } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h old mode 100755 new mode 100644 index c1cf3df57..c75342cb6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsGui/StyleManager/style_manager.h @@ -1,36 +1,38 @@ - #pragma once #include "ltsutilsguistylemanager_export.h" + #include - class QPluginLoader; - namespace LtsUtils { class LTSUTILSGUISTYLEMANAGER_EXPORT StyleManager : public QObject { - Q_OBJECT - using QObject::QObject; - ~StyleManager() = default; -public: - static StyleManager *getInstance(); + Q_OBJECT + using QObject::QObject; + ~StyleManager() = default; - bool loadStyle(const QString &stylePluginName, bool highDpi = false); - const QString ¤tStyleName() const { return m_stylePluginName; } + public: + static StyleManager* getInstance(); -private: - friend struct StyleManagerHandler; + bool loadStyle(const QString& stylePluginName, bool highDpi = false); - QPluginLoader *m_currentStylePluginLoader = nullptr; - QString m_stylePluginName; + const QString& currentStyleName() const + { + return m_stylePluginName; + } -signals: - void signalStyleChanged(const QString &stylePluginName); + private: + friend struct StyleManagerHandler; + QPluginLoader* m_currentStylePluginLoader = nullptr; + QString m_stylePluginName; + + signals: + void signalStyleChanged(const QString& stylePluginName); }; -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp old mode 100755 new mode 100644 index 00d9b576a..a0ca9f005 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -12,253 +13,236 @@ #include #include -#include - - namespace LtsUtils { -enum class SettingType -{ - String = 1, - StringList = 2, - Json = 3, - FunctionKeys = 4, - Boolean = 5, +enum class SettingType { + String = 1, + StringList = 2, + Json = 3, + FunctionKeys = 4, + Boolean = 5, }; QString typeToString(SettingType t) { - switch (t) - { - case SettingType::String: - return QStringLiteral("String"); - case SettingType::StringList: - return QStringLiteral("StringList"); - case SettingType::Json: - return QStringLiteral("Json"); - case SettingType::FunctionKeys: - return QStringLiteral("FunctionKeys"); - case SettingType::Boolean: - return QStringLiteral("Boolean"); - } - Q_ASSERT(false); - return QStringLiteral("Unknown SettingType (%1)").arg(int(t)); + switch (t) + { + case SettingType::String: + return QStringLiteral("String"); + case SettingType::StringList: + return QStringLiteral("StringList"); + case SettingType::Json: + return QStringLiteral("Json"); + case SettingType::FunctionKeys: + return QStringLiteral("FunctionKeys"); + case SettingType::Boolean: + return QStringLiteral("Boolean"); + } + Q_ASSERT(false); + return QStringLiteral("Unknown SettingType (%1)").arg(int(t)); } -SettingType stringToType(const QString &s) +SettingType stringToType(const QString& s) { - if (s == typeToString(SettingType::String)) + if (s == typeToString(SettingType::String)) + return SettingType::String; + if (s == typeToString(SettingType::StringList)) + return SettingType::StringList; + if (s == typeToString(SettingType::Json)) + return SettingType::Json; + if (s == typeToString(SettingType::FunctionKeys)) + return SettingType::FunctionKeys; + if (s == typeToString(SettingType::Boolean)) + return SettingType::Boolean; + Q_ASSERT(false); return SettingType::String; - if (s == typeToString(SettingType::StringList)) - return SettingType::StringList; - if (s == typeToString(SettingType::Json)) - return SettingType::Json; - if (s == typeToString(SettingType::FunctionKeys)) - return SettingType::FunctionKeys; - if (s == typeToString(SettingType::Boolean)) - return SettingType::Boolean; - Q_ASSERT(false); - return SettingType::String; } - -static QString craftKey(const QString &group, const QString &identifier) +static QString craftKey(const QString& group, const QString& identifier) { - return group + QLatin1Char('.') + identifier; + return group + QLatin1Char('.') + identifier; } +static OperatorSettings* s_operatorSettings = nullptr; - - -static OperatorSettings *s_operatorSettings = nullptr; static void cleanupOperatorSettings() { - delete s_operatorSettings; - s_operatorSettings = nullptr; + delete s_operatorSettings; + s_operatorSettings = nullptr; } -OperatorSettings *OperatorSettings::getInstance() +OperatorSettings* OperatorSettings::getInstance() { - if (!s_operatorSettings) - { - s_operatorSettings = new OperatorSettings; - qAddPostRoutine(&cleanupOperatorSettings); - } - return s_operatorSettings; + if (!s_operatorSettings) + { + s_operatorSettings = new OperatorSettings; + qAddPostRoutine(&cleanupOperatorSettings); + } + return s_operatorSettings; } +static ProjectSettings* s_projectSettings = nullptr; - - - -static ProjectSettings *s_projectSettings = nullptr; static void cleanupProjectSettings() { - delete s_projectSettings; - s_projectSettings = nullptr; + delete s_projectSettings; + s_projectSettings = nullptr; } -ProjectSettings *ProjectSettings::getInstance() +ProjectSettings* ProjectSettings::getInstance() { - if (!s_projectSettings) - { - s_projectSettings = new ProjectSettings; - qAddPostRoutine(&cleanupProjectSettings); - } - return s_projectSettings; -} - -bool ProjectSettings::initFromFile(const QString &filename) -{ - QFile f(filename); - if (!f.open(QIODevice::ReadOnly)) - return false; - - QJsonParseError jErr; - const QJsonObject settings = QJsonDocument::fromJson(f.readAll(), &jErr).object(); - if (jErr.error != QJsonParseError::NoError) - return false; - - const QJsonObject psObj = settings[QStringLiteral("ProjectSettings")].toObject(); - if (psObj.isEmpty()) - return false; - - QHash newData; - const QStringList &groupKeys(psObj.keys()); - for (const auto &gKey : groupKeys) - { - const QJsonObject objGroup(psObj[gKey].toObject()); - const QStringList &itemKeys(objGroup.keys()); - for (const auto &key : itemKeys) + if (!s_projectSettings) { - const QJsonObject obj(objGroup[key].toObject()); - const auto strType(obj[QStringLiteral("Type")].toString()); - const auto type = stringToType(strType); - const QJsonValue jVal(obj[QStringLiteral("Default")]); - QVariant val; - switch (type) - { - case SettingType::Json: - val = QJsonDocument(jVal.toObject()).toJson(); - break; - case SettingType::StringList: - { - const QJsonArray arr(jVal.toArray()); - QStringList sl; - sl.reserve(arr.size()); - for (const auto &ele : arr) - sl.push_back(ele.toString()); - val = sl; - break; - } - case SettingType::FunctionKeys: - val = jVal.toVariant(); - break; - case SettingType::String: - val = jVal.toString(); - break; - case SettingType::Boolean: - val = jVal.toBool(); - break; - } - newData[craftKey(gKey, key)] = val; + s_projectSettings = new ProjectSettings; + qAddPostRoutine(&cleanupProjectSettings); } - } - getInstance()->m_data = newData; - return true; + return s_projectSettings; } -bool ProjectSettings::isFunctionEnabled(const QString &group, const QString &function) +bool ProjectSettings::initFromFile(const QString& filename) { - const QStringList functionNames = getInstance()->value(QStringLiteral("Functionalities"), - QStringLiteral("IdentifierList")).toStringList(); + QFile f(filename); + if (!f.open(QIODevice::ReadOnly)) + return false; - return functionNames.contains(group + QLatin1Char(':') + function); + QJsonParseError jErr; + const QJsonObject settings = QJsonDocument::fromJson(f.readAll(), &jErr).object(); + if (jErr.error != QJsonParseError::NoError) + return false; + + const QJsonObject psObj = settings[QStringLiteral("ProjectSettings")].toObject(); + if (psObj.isEmpty()) + return false; + + QHash newData; + const QStringList& groupKeys(psObj.keys()); + for (const auto& gKey : groupKeys) + { + const QJsonObject objGroup(psObj[gKey].toObject()); + const QStringList& itemKeys(objGroup.keys()); + for (const auto& key : itemKeys) + { + const QJsonObject obj(objGroup[key].toObject()); + const auto strType(obj[QStringLiteral("Type")].toString()); + const auto type = stringToType(strType); + const QJsonValue jVal(obj[QStringLiteral("Default")]); + QVariant val; + switch (type) + { + case SettingType::Json: + val = QJsonDocument(jVal.toObject()).toJson(); + break; + case SettingType::StringList: { + const QJsonArray arr(jVal.toArray()); + QStringList sl; + sl.reserve(arr.size()); + for (const auto& ele : arr) + sl.push_back(ele.toString()); + val = sl; + break; + } + case SettingType::FunctionKeys: + val = jVal.toVariant(); + break; + case SettingType::String: + val = jVal.toString(); + break; + case SettingType::Boolean: + val = jVal.toBool(); + break; + } + newData[craftKey(gKey, key)] = val; + } + } + getInstance()->m_data = newData; + return true; } - - - -void Settings::init(const QByteArray &settings) +bool ProjectSettings::isFunctionEnabled(const QString& group, const QString& function) { - QByteArray uncompressed; - try - { - uncompressed = qUncompress(settings); - } - catch (...) - {} + const QStringList functionNames = + getInstance()->value(QStringLiteral("Functionalities"), QStringLiteral("IdentifierList")).toStringList(); - if (uncompressed.isEmpty()) - uncompressed = settings; - - QDataStream stream(uncompressed); - stream >> m_data; + return functionNames.contains(group + QLatin1Char(':') + function); } +void Settings::init(const QByteArray& settings) +{ + QByteArray uncompressed; + try + { + uncompressed = qUncompress(settings); + } + catch (...) + { + } + + if (uncompressed.isEmpty()) + uncompressed = settings; + + QDataStream stream(uncompressed); + stream >> m_data; +} QByteArray Settings::exportSettings() const { - if (m_data.isEmpty()) - return QByteArray(); + if (m_data.isEmpty()) + return QByteArray(); - QByteArray ba; - QDataStream stream(&ba, QIODevice::WriteOnly); - stream << m_data; - return qCompress(ba); + QByteArray ba; + QDataStream stream(&ba, QIODevice::WriteOnly); + stream << m_data; + return qCompress(ba); } - void Settings::clear() { - m_data.clear(); + m_data.clear(); } void Settings::dump() { - qWarning() << "Settings::m_data: keys=" << m_data.keys(); - QHashIterator it(m_data); - int i=0; - while (it.hasNext()) - { - it.next(); - qWarning() << i++ << ":" << " - key='" << it.key() << "' value -> '" << it.value() << "'"; - } - qWarning() << "Settings::m_data: ------------------"; + qWarning() << "Settings::m_data: keys=" << m_data.keys(); + QHashIterator it(m_data); + int i = 0; + while (it.hasNext()) + { + it.next(); + qWarning() << i++ << ":" + << " - key='" << it.key() << "' value -> '" << it.value() << "'"; + } + qWarning() << "Settings::m_data: ------------------"; } -void Settings::setValue(const QString &group, const QString &identifier, const QVariant &value) +void Settings::setValue(const QString& group, const QString& identifier, const QVariant& value) { - - m_data.insert(craftKey(group, identifier), value); - emit valueChanged(group, identifier, value); + + m_data.insert(craftKey(group, identifier), value); + emit valueChanged(group, identifier, value); } - -void Settings::removeValue(const QString &group, const QString &identifier) +void Settings::removeValue(const QString& group, const QString& identifier) { - if (m_data.remove(craftKey(group, identifier))) - emit valueRemoved(group, identifier); + if (m_data.remove(craftKey(group, identifier))) + emit valueRemoved(group, identifier); } - -QStringList Settings::identifiers(const QString &group) const +QStringList Settings::identifiers(const QString& group) const { - QStringList result; - for (auto it = m_data.begin(); it != m_data.end(); ++it) - { - const QStringList decrafted = QString(it.key()).split(QLatin1Char('.')); - if (decrafted.size() > 1 && QStringView(group).compare(decrafted.at(0)) == 0) - result.append(decrafted.at(0).mid(1)); - } - return result; + QStringList result; + for (auto it = m_data.begin(); it != m_data.end(); ++it) + { + const QStringList decrafted = QString(it.key()).split(QLatin1Char('.')); + if (decrafted.size() > 1 && QStringView(group).compare(decrafted.at(0)) == 0) + result.append(decrafted.at(0).mid(1)); + } + return result; } - -QVariant Settings::value(const QString &group, const QString &identifier, const QVariant &defaultValue) const +QVariant Settings::value(const QString& group, const QString& identifier, const QVariant& defaultValue) const { - return m_data.value(craftKey(group, identifier), defaultValue); + return m_data.value(craftKey(group, identifier), defaultValue); } -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h old mode 100755 new mode 100644 index 8ba86ac49..2169e9b68 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsUtils/LtsUtilsSettings/settings.h @@ -1,10 +1,11 @@ #pragma once +#include "ltsutilssettings_export.h" + +#include #include #include -#include -#include "ltsutilssettings_export.h" class QJsonObject; @@ -13,61 +14,51 @@ namespace LtsUtils class LTSUTILSSETTINGS_EXPORT Settings : public QObject { - Q_OBJECT + Q_OBJECT -public: - ~Settings() = default; + public: + ~Settings() = default; - + void setValue(const QString& group, const QString& identifier, const QVariant& value); - void setValue(const QString &group, const QString &identifier, const QVariant &value); + void removeValue(const QString& group, const QString& identifier); - + QVariant value(const QString& group, const QString& identifier, const QVariant& defaultValue = QVariant()) const; - void removeValue(const QString &group, const QString &identifier); + QStringList identifiers(const QString& group) const; - + void init(const QByteArray& settings); + QByteArray exportSettings() const; + void clear(); - QVariant value(const QString &group, const QString &identifier, const QVariant &defaultValue = QVariant()) const; + void dump(); - + protected: + Settings() = default; - QStringList identifiers(const QString &group) const; - - void init(const QByteArray &settings); - QByteArray exportSettings() const; - void clear(); - - void dump(); - -protected: - Settings() = default; - -signals: - void valueChanged(const QString &group, const QString &identifier, const QVariant &value); - void valueRemoved(const QString &group, const QString &identifier); - -protected: - QHash m_data; + signals: + void valueChanged(const QString& group, const QString& identifier, const QVariant& value); + void valueRemoved(const QString& group, const QString& identifier); + protected: + QHash m_data; }; class LTSUTILSSETTINGS_EXPORT OperatorSettings : public Settings { - Q_OBJECT -public: - static OperatorSettings *getInstance(); + Q_OBJECT + public: + static OperatorSettings* getInstance(); }; class LTSUTILSSETTINGS_EXPORT ProjectSettings : public Settings { - Q_OBJECT -public: - static ProjectSettings *getInstance(); + Q_OBJECT + public: + static ProjectSettings* getInstance(); - static bool initFromFile(const QString &filename); - static bool isFunctionEnabled(const QString &group, const QString &function); + static bool initFromFile(const QString& filename); + static bool isFunctionEnabled(const QString& group, const QString& function); }; - -} +} // namespace LtsUtils diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.cpp old mode 100755 new mode 100644 index b27b645f8..a043e71b5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.cpp @@ -1,150 +1,145 @@ - #include "LtsKeyPushButton.h" -#include "LtsVirtualKeyboard.h" -#include -#include -#include -#include +#include "LtsVirtualKeyboard.h" + +#include +#include +#include +#include namespace LtsVirtualKeyboard { -LtsKeyPushButton::LtsKeyPushButton(const QString ¬TranslatedText, const QString ¬TranslatedTextAlt, QWidget *parent) - : QToolButton(parent) - , m_parent(parent) - , m_notTranslatedText(notTranslatedText) - , m_notTranslatedTextAlt(notTranslatedTextAlt) - , m_altMode(false) - , m_capsMode(false) +LtsKeyPushButton::LtsKeyPushButton(const QString& notTranslatedText, const QString& notTranslatedTextAlt, + QWidget* parent) + : QToolButton(parent), m_parent(parent), m_notTranslatedText(notTranslatedText), + m_notTranslatedTextAlt(notTranslatedTextAlt), m_altMode(false), m_capsMode(false) { - setFocusPolicy(Qt::NoFocus); - setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); - - connect(this, &LtsKeyPushButton::pressedKey, this, &LtsKeyPushButton::getKeyPress); + setFocusPolicy(Qt::NoFocus); + setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); + + connect(this, &LtsKeyPushButton::pressedKey, this, &LtsKeyPushButton::getKeyPress); } void LtsKeyPushButton::getKeyPress() { - int keyCode = 0; - QKeyEvent *key = nullptr; - QString text = this->text(); - + int keyCode = 0; + QKeyEvent* key = nullptr; + QString text = this->text(); - if (!qobject_cast(m_parent)) - return; - LtsVirtualKeyboard *keyboard = qobject_cast(m_parent); + if (!qobject_cast(m_parent)) + return; + LtsVirtualKeyboard* keyboard = qobject_cast(m_parent); - - if (text == QStringLiteral("&&")) - text = QStringLiteral("&"); + if (text == QStringLiteral("&&")) + text = QStringLiteral("&"); - if (NO_SPECIAL_KEY(text) == false && (IS_BACK(text) == true || IS_TAB(text) == true || IS_RETURN(text) == true || IS_CTRL_LEFT(text) == true || - IS_ALT(text) == true || IS_CANC(text) == true || IS_CUT_LEFT(text) == true || IS_PASSWORD(text) || IS_PASTE(text) || IS_COPY(text))) - key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier, text); - else - { - keyCode = text.toUtf8()[0]; - if (m_capsMode == false) + if (NO_SPECIAL_KEY(text) == false && + (IS_BACK(text) == true || IS_TAB(text) == true || IS_RETURN(text) == true || IS_CTRL_LEFT(text) == true || + IS_ALT(text) == true || IS_CANC(text) == true || IS_CUT_LEFT(text) == true || IS_PASSWORD(text) || + IS_PASTE(text) || IS_COPY(text))) + key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier, text); + else { - text = text.toLower(); - key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier, text); + keyCode = text.toUtf8()[0]; + if (m_capsMode == false) + { + text = text.toLower(); + key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier, text); + } + else + key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::ShiftModifier, text); + } + keyboard->receiptChildKey(nullptr, key); + QCoreApplication::processEvents(); +} + +void LtsKeyPushButton::mousePressEvent(QMouseEvent*) +{ + if (!qobject_cast(m_parent)) + return; + QString text = this->text(); + QString defaultStyleButton = QStringLiteral(DEFAULT_STYLE_BUTTON); + QString changedColorButton = QStringLiteral(CHANGED_BACKGROUND_BUTTON); + + if (IS_CAPS(text) == true) + { + if (!styleSheet().contains(QStringLiteral(DEFAULT_BACKGROUND_BUTTON))) + changedColorButton = QStringLiteral(DEFAULT_BACKGROUND_BUTTON); + setStyleSheet(defaultStyleButton + changedColorButton); + repaint(); + QCoreApplication::processEvents(); + } + + else if (IS_FIN(text) == true) + setStyleSheet(defaultStyleButton + QStringLiteral(CHANGED_BACKGROUND_BUTTON)); + else + { + setStyleSheet(defaultStyleButton + changedColorButton); + repaint(); + QCoreApplication::processEvents(); + } + emit pressedKey(); + + m_oldYKey = 0; +} + +void LtsKeyPushButton::mouseReleaseEvent(QMouseEvent*) +{ + if (!qobject_cast(m_parent)) + return; + + LtsVirtualKeyboard* tmpKeyBoard = qobject_cast(m_parent); + + bool pressedEcho = IS_PASSWORD(text()) == true; + + if (IS_CAPS(text()) == false && pressedEcho == false) + setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); + else if (pressedEcho == true && tmpKeyBoard->isEnabledSwitchingEcho() == false) + setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); +} + +void LtsKeyPushButton::changeEvent(QEvent* event) +{ + if (event->type() == QEvent::LanguageChange) + { + setAltMode(m_altMode); } else - key = new QKeyEvent(QEvent::KeyPress, keyCode, Qt::ShiftModifier, text); - } - keyboard->receiptChildKey(nullptr, key); - QCoreApplication::processEvents(); -} - - -void LtsKeyPushButton::mousePressEvent(QMouseEvent *) -{ - if (!qobject_cast(m_parent)) - return; - QString text = this->text(); - QString defaultStyleButton = QStringLiteral(DEFAULT_STYLE_BUTTON); - QString changedColorButton = QStringLiteral(CHANGED_BACKGROUND_BUTTON); - - if (IS_CAPS(text) == true) - { - if (!styleSheet().contains(QStringLiteral(DEFAULT_BACKGROUND_BUTTON))) - changedColorButton = QStringLiteral(DEFAULT_BACKGROUND_BUTTON); - setStyleSheet(defaultStyleButton + changedColorButton); - repaint(); - QCoreApplication::processEvents(); - } - - - else if (IS_FIN(text) == true) - setStyleSheet(defaultStyleButton + QStringLiteral(CHANGED_BACKGROUND_BUTTON)); - else - { - setStyleSheet(defaultStyleButton + changedColorButton); - repaint(); - QCoreApplication::processEvents(); - } - emit pressedKey(); - - m_oldYKey = 0; -} - -void LtsKeyPushButton::mouseReleaseEvent(QMouseEvent * ) -{ - if (!qobject_cast(m_parent)) - return; - - LtsVirtualKeyboard *tmpKeyBoard = qobject_cast(m_parent); - - bool pressedEcho = IS_PASSWORD(text()) == true; - - if (IS_CAPS(text()) == false && pressedEcho == false) - setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); - else if (pressedEcho == true && tmpKeyBoard->isEnabledSwitchingEcho() == false) - setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON)); -} - -void LtsKeyPushButton::changeEvent(QEvent *event) -{ - if (event->type() == QEvent::LanguageChange) - { - setAltMode(m_altMode); - } - else - QToolButton::changeEvent(event); + QToolButton::changeEvent(event); } void LtsKeyPushButton::setAltMode(bool altmode) { - m_altMode = altmode; - if (m_altMode) - { - if (!IS_CANC(text()) && !IS_FIN(text()) && !IS_CAPS(text()) - && !IS_COPY(text()) && !IS_PASTE(text()) && !IS_CUT_LEFT(text()) ) - setText(m_notTranslatedTextAlt); - } - else - { - setText(m_notTranslatedText); - } - setObjectName(text()); + m_altMode = altmode; + if (m_altMode) + { + if (!IS_CANC(text()) && !IS_FIN(text()) && !IS_CAPS(text()) && !IS_COPY(text()) && !IS_PASTE(text()) && + !IS_CUT_LEFT(text())) + setText(m_notTranslatedTextAlt); + } + else + { + setText(m_notTranslatedText); + } + setObjectName(text()); - setCapsMode(m_capsMode); + setCapsMode(m_capsMode); } void LtsKeyPushButton::setCapsMode(bool caps) { - if (text().length() > 2 || IS_FIN(text())) - return; - if (m_notTranslatedText == QChar(223)) - return; - m_capsMode = caps; - if (m_capsMode) - { - setText(text().toUpper()); - } - else - setText(text().toLower()); + if (text().length() > 2 || IS_FIN(text())) + return; + if (m_notTranslatedText == QChar(223)) + return; + m_capsMode = caps; + if (m_capsMode) + { + setText(text().toUpper()); + } + else + setText(text().toLower()); } -} +} // namespace LtsVirtualKeyboard diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.h old mode 100755 new mode 100644 index abbbb83a2..bfa868393 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsKeyPushButton.h @@ -1,90 +1,82 @@ - #pragma once -#include -#include #include "ltsvirtualkeyboard_export.h" -#define DEFAULT_BACKGROUND_BUTTON "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #8C8F8C, stop: 1 #333831);" -#define CHANGED_BACKGROUND_BUTTON "background:lightgray;color:darkred;" - - - -#define DEFAULT_STYLE_BUTTON "color:white;border: 1px solid #000000;border-radius:6px;" - -#define STYLE_FOCUS_TEXT "border: 1px solid red" - - - +#include +#include +#define DEFAULT_BACKGROUND_BUTTON \ + "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #8C8F8C, stop: 1 #333831);" +#define CHANGED_BACKGROUND_BUTTON "background:lightgray;color:darkred;" +#define DEFAULT_STYLE_BUTTON "color:white;border: 1px solid #000000;border-radius:6px;" +#define STYLE_FOCUS_TEXT "border: 1px solid red" namespace LtsVirtualKeyboard { class LTSVIRTUALKEYBOARD_EXPORT LtsKeyPushButton : public QToolButton { - Q_OBJECT + Q_OBJECT +#define KEY_TAB LtsKeyPushButton::tr("TAB") +#define KEY_ALT LtsKeyPushButton::tr("!?#") +#define KEY_ALT2 LtsKeyPushButton::tr("Abc") +#define KEY_CAPS QStringLiteral("CAPS") +#define KEY_CTRL_LEFT LtsKeyPushButton::tr("CTRL") +#define KEY_CUT_LEFT LtsKeyPushButton::tr("cut") +#define KEY_COPY LtsKeyPushButton::tr("copy") +#define KEY_PASTE LtsKeyPushButton::tr("paste") +#define KEY_BACKSPACE LtsKeyPushButton::tr("<--") +#define KEY_HIDECHAR LtsKeyPushButton::tr("echo") +#define KEY_CANC QStringLiteral("->") +#define KEY_RETURN QStringLiteral("RETURN") +#define KEY_FIN QStringLiteral("Ok") +#define KEY_SHIFT QStringLiteral("SHIFT") +#define KEY_SPACE " " -#define KEY_TAB LtsKeyPushButton::tr("TAB") -#define KEY_ALT LtsKeyPushButton::tr("!?#") -#define KEY_ALT2 LtsKeyPushButton::tr("Abc") -#define KEY_CAPS QStringLiteral("CAPS") -#define KEY_CTRL_LEFT LtsKeyPushButton::tr("CTRL") -#define KEY_CUT_LEFT LtsKeyPushButton::tr("cut") -#define KEY_COPY LtsKeyPushButton::tr("copy") -#define KEY_PASTE LtsKeyPushButton::tr("paste") -#define KEY_BACKSPACE LtsKeyPushButton::tr("<--") -#define KEY_HIDECHAR LtsKeyPushButton::tr("echo") -#define KEY_CANC QStringLiteral("->") -#define KEY_RETURN QStringLiteral("RETURN") -#define KEY_FIN QStringLiteral("Ok") -#define KEY_SHIFT QStringLiteral("SHIFT") -#define KEY_SPACE " " +#define IS_KEY(keyTextPressed, keyValCompare) (keyTextPressed).contains((keyValCompare), Qt::CaseInsensitive) -#define IS_KEY(keyTextPressed, keyValCompare) (keyTextPressed).contains((keyValCompare), Qt::CaseInsensitive) +#define IS_TAB(text) IS_KEY(text, KEY_TAB) +#define IS_ALT(text) IS_KEY(text, KEY_ALT) +#define IS_ALT2(text) IS_KEY(text, KEY_ALT2) +#define IS_CAPS(text) IS_KEY(text, KEY_CAPS) +#define IS_CTRL_LEFT(text) IS_KEY(text, KEY_CTRL_LEFT) +#define IS_CUT_LEFT(text) IS_KEY(text, KEY_CUT_LEFT) +#define IS_BACK(text) IS_KEY(text, KEY_BACKSPACE) +#define IS_CANC(text) IS_KEY(text, KEY_CANC) +#define IS_RETURN(text) IS_KEY(text, KEY_RETURN) +#define IS_FIN(text) IS_KEY(text, KEY_FIN) +#define IS_SHIFT(text) IS_KEY(text, KEY_SHIFT) +#define IS_SPACE(text) IS_KEY(text, QStringLiteral(KEY_SPACE)) +#define IS_PASSWORD(text) IS_KEY(text, KEY_HIDECHAR) +#define IS_COPY(text) IS_KEY(text, KEY_COPY) +#define IS_PASTE(text) IS_KEY(text, KEY_PASTE) +#define NO_SPECIAL_KEY(text) ((text).length() == 1) -#define IS_TAB(text) IS_KEY(text, KEY_TAB) -#define IS_ALT(text) IS_KEY(text, KEY_ALT) -#define IS_ALT2(text) IS_KEY(text, KEY_ALT2) -#define IS_CAPS(text) IS_KEY(text, KEY_CAPS) -#define IS_CTRL_LEFT(text) IS_KEY(text, KEY_CTRL_LEFT) -#define IS_CUT_LEFT(text) IS_KEY(text, KEY_CUT_LEFT) -#define IS_BACK(text) IS_KEY(text, KEY_BACKSPACE) -#define IS_CANC(text) IS_KEY(text, KEY_CANC) -#define IS_RETURN(text) IS_KEY(text, KEY_RETURN) -#define IS_FIN(text) IS_KEY(text, KEY_FIN) -#define IS_SHIFT(text) IS_KEY(text, KEY_SHIFT) -#define IS_SPACE(text) IS_KEY(text, QStringLiteral(KEY_SPACE)) -#define IS_PASSWORD(text) IS_KEY(text, KEY_HIDECHAR) -#define IS_COPY(text) IS_KEY(text, KEY_COPY) -#define IS_PASTE(text) IS_KEY(text, KEY_PASTE) -#define NO_SPECIAL_KEY(text) ((text).length() == 1) + public: + LtsKeyPushButton(const QString& notTranslatedText, const QString& notTranslatedTextAlt, QWidget* parent = nullptr); + void setAltMode(bool altmode); + void setCapsMode(bool caps); -public: - LtsKeyPushButton(const QString ¬TranslatedText, const QString ¬TranslatedTextAlt, QWidget *parent = nullptr); - void setAltMode(bool altmode); - void setCapsMode(bool caps); + private slots: + void getKeyPress(); -private slots: - void getKeyPress(); + signals: + void pressedKey(); -signals: - void pressedKey(); + private: + QWidget* m_parent; + QString m_notTranslatedText; + QString m_notTranslatedTextAlt; + int m_oldYKey; + bool m_altMode; + bool m_capsMode; -private: - QWidget *m_parent; - QString m_notTranslatedText; - QString m_notTranslatedTextAlt; - int m_oldYKey; - bool m_altMode; - bool m_capsMode; - -protected: - void mousePressEvent(QMouseEvent *event); - void mouseReleaseEvent(QMouseEvent *event); - void changeEvent(QEvent *event); + protected: + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + void changeEvent(QEvent* event); }; -} +} // namespace LtsVirtualKeyboard diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.cpp old mode 100755 new mode 100644 index 83efc9476..b41910b94 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.cpp @@ -1,10 +1,8 @@ - #include "LtsVirtualKeyboard.h" #include - #include #include #include @@ -23,931 +21,871 @@ namespace LtsVirtualKeyboard { -static LtsVirtualKeyboard *s_ltsVirtualKeyboard = nullptr; +static LtsVirtualKeyboard* s_ltsVirtualKeyboard = nullptr; static bool lastState = false; -LtsVirtualKeyboard::LtsVirtualKeyboard(LtsSession::LtsSession *session, QWidget *activeForm, bool onlyNumericPad, QWidget *parent) - : QWidget(parent) - - , m_te(nullptr) - , m_le(nullptr) - , m_nextInput(nullptr) - , m_activeWindow(activeForm) - , m_echoMode(false) - , m_enablePasswordEcho(false) - , m_numericPad(onlyNumericPad) - , m_isAlt(false) - , m_isCap(false) - , m_enableEnter(true) - , m_ready(false) - , m_height(0) - , m_clipboard(QApplication::clipboard()) - , m_session(session) + +LtsVirtualKeyboard::LtsVirtualKeyboard(LtsSession::LtsSession* session, QWidget* activeForm, bool onlyNumericPad, + QWidget* parent) + : QWidget(parent) + + , + m_te(nullptr), m_le(nullptr), m_nextInput(nullptr), m_activeWindow(activeForm), m_echoMode(false), + m_enablePasswordEcho(false), m_numericPad(onlyNumericPad), m_isAlt(false), m_isCap(false), m_enableEnter(true), + m_ready(false), m_height(0), m_clipboard(QApplication::clipboard()), m_session(session) { - setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::Dialog); - setFocusPolicy(Qt::NoFocus); - - setWindowTitle(QString()); - connect(m_activeWindow, &QWidget::destroyed, - this, [this](QObject *obj) - { - if (static_cast(m_activeWindow) == obj) - m_activeWindow = nullptr; - }); + setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::Dialog); + setFocusPolicy(Qt::NoFocus); + + setWindowTitle(QString()); + connect(m_activeWindow, &QWidget::destroyed, this, [this](QObject* obj) { + if (static_cast(m_activeWindow) == obj) + m_activeWindow = nullptr; + }); } -LtsVirtualKeyboard::~LtsVirtualKeyboard() -{ -} +LtsVirtualKeyboard::~LtsVirtualKeyboard() {} -LtsVirtualKeyboard *LtsVirtualKeyboard::getInstance(LtsSession::LtsSession *session, QWidget *activeForm, bool onlyNumericPad, QWidget *parent) +LtsVirtualKeyboard* LtsVirtualKeyboard::getInstance(LtsSession::LtsSession* session, QWidget* activeForm, + bool onlyNumericPad, QWidget* parent) { - onlyNumericPad = false; + onlyNumericPad = false; - - - if (s_ltsVirtualKeyboard && onlyNumericPad == lastState ) - { - - if (activeForm) - s_ltsVirtualKeyboard->setActiveWindw(activeForm); - if (parent) - s_ltsVirtualKeyboard->setParent(parent); - s_ltsVirtualKeyboard->setSession(session); + if (s_ltsVirtualKeyboard && onlyNumericPad == lastState) + { + + if (activeForm) + s_ltsVirtualKeyboard->setActiveWindw(activeForm); + if (parent) + s_ltsVirtualKeyboard->setParent(parent); + s_ltsVirtualKeyboard->setSession(session); + + return s_ltsVirtualKeyboard; + } + cleanupLtsVirtualKeyboard(); + lastState = onlyNumericPad; + s_ltsVirtualKeyboard = new LtsVirtualKeyboard(session, activeForm, onlyNumericPad, parent); + s_ltsVirtualKeyboard->createKeyboard(); + qAddPostRoutine(&cleanupLtsVirtualKeyboard); return s_ltsVirtualKeyboard; - } - cleanupLtsVirtualKeyboard(); - lastState = onlyNumericPad; - s_ltsVirtualKeyboard = new LtsVirtualKeyboard(session, activeForm, onlyNumericPad, parent); - s_ltsVirtualKeyboard->createKeyboard(); - qAddPostRoutine(&cleanupLtsVirtualKeyboard); - - return s_ltsVirtualKeyboard; } void LtsVirtualKeyboard::cleanupLtsVirtualKeyboard() { - delete s_ltsVirtualKeyboard; - s_ltsVirtualKeyboard = nullptr; + delete s_ltsVirtualKeyboard; + s_ltsVirtualKeyboard = nullptr; } void LtsVirtualKeyboard::enableSwitchingEcho(bool status) { - m_enablePasswordEcho = status; + m_enablePasswordEcho = status; } bool LtsVirtualKeyboard::isEnabledSwitchingEcho() const { - return (m_enablePasswordEcho); + return (m_enablePasswordEcho); } -LtsKeyPushButton *LtsVirtualKeyboard::createNewKey(const QString &keyValue, const QString ¬TranslatedValue, const QString ¬TranslatedValueAlt) +LtsKeyPushButton* LtsVirtualKeyboard::createNewKey(const QString& keyValue, const QString& notTranslatedValue, + const QString& notTranslatedValueAlt) { - QString altText = notTranslatedValueAlt; - if (altText.isEmpty()) - altText = notTranslatedValue; - LtsKeyPushButton *tmp = new LtsKeyPushButton(notTranslatedValue, altText, this); - QString style = QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON); - QSize imageDim; - int width = 0, height = 0; + QString altText = notTranslatedValueAlt; + if (altText.isEmpty()) + altText = notTranslatedValue; + LtsKeyPushButton* tmp = new LtsKeyPushButton(notTranslatedValue, altText, this); + QString style = QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON); + QSize imageDim; + int width = 0, height = 0; - imageDim.setWidth(32); - imageDim.setHeight(32); + imageDim.setWidth(32); + imageDim.setHeight(32); - if (IS_PASSWORD(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setIcon(QPixmap(QStringLiteral(":/TastieraVirtuale/normalEcho"))); - } - else if (IS_PASTE(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setEnabled(false); - tmp->setIcon(QPixmap(QStringLiteral("icon:edit-paste.svg"))); - tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); - } - else if (IS_COPY(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setIcon(QPixmap(QStringLiteral("icon:edit-copy.svg"))); - tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); - } + if (IS_PASSWORD(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setIcon(QPixmap(QStringLiteral(":/TastieraVirtuale/normalEcho"))); + } + else if (IS_PASTE(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setEnabled(false); + tmp->setIcon(QPixmap(QStringLiteral("icon:edit-paste.svg"))); + tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); + } + else if (IS_COPY(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setIcon(QPixmap(QStringLiteral("icon:edit-copy.svg"))); + tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); + } - else if (IS_CUT_LEFT(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setIcon(QPixmap(QStringLiteral("icon:edit-cut.svg"))); - tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); - } + else if (IS_CUT_LEFT(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setIcon(QPixmap(QStringLiteral("icon:edit-cut.svg"))); + tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); + } - else if (IS_CAPS(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setIcon(QPixmap(QStringLiteral("icon:shift_capslook.svg"))); - tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); - } + else if (IS_CAPS(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setIcon(QPixmap(QStringLiteral("icon:shift_capslook.svg"))); + tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); + } - else if (IS_RETURN(keyValue) == true) - { - tmp->setIconSize(imageDim); - tmp->setIcon(QPixmap(QStringLiteral("icon:carriage_return.svg"))); - tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); - } + else if (IS_RETURN(keyValue) == true) + { + tmp->setIconSize(imageDim); + tmp->setIcon(QPixmap(QStringLiteral("icon:carriage_return.svg"))); + tmp->setToolButtonStyle(Qt::ToolButtonIconOnly); + } - tmp->setStyleSheet(style); + tmp->setStyleSheet(style); - - width = 54; - height = 40; + width = 54; + height = 40; #ifdef TABLET_MODE - width = width * 2.0; - height = height * 2.0; + width = width * 2.0; + height = height * 2.0; #endif - tmp->setMinimumSize(width, height); - tmp->setMaximumSize(width, height); + tmp->setMinimumSize(width, height); + tmp->setMaximumSize(width, height); - if (IS_SPACE(keyValue) == true) - { - tmp->setMinimumSize(width * 20, height); - tmp->setMaximumSize(width * 20, height); - } + if (IS_SPACE(keyValue) == true) + { + tmp->setMinimumSize(width * 20, height); + tmp->setMaximumSize(width * 20, height); + } - if (IS_FIN(keyValue) == true) - { - tmp->setStyleSheet(style + QStringLiteral(CHANGED_BACKGROUND_BUTTON)); - } - tmp->setText(keyValue); - tmp->setCapsMode(m_isCap); + if (IS_FIN(keyValue) == true) + { + tmp->setStyleSheet(style + QStringLiteral(CHANGED_BACKGROUND_BUTTON)); + } + tmp->setText(keyValue); + tmp->setCapsMode(m_isCap); + tmp->setObjectName(keyValue); - tmp->setObjectName(keyValue); - - return tmp; + return tmp; } -void LtsVirtualKeyboard::controlKeyEcho(QWidget *control) +void LtsVirtualKeyboard::controlKeyEcho(QWidget* control) { - Q_UNUSED(control); - QString textToSearch; - LtsKeyPushButton *echoControlKey; - QString tmpStyle; - QPushButton *pasteButton = findChild(KEY_PASTE); - QPushButton *cutButton = findChild(KEY_CUT_LEFT); - QPushButton *copyButton = findChild(KEY_COPY); + Q_UNUSED(control); + QString textToSearch; + LtsKeyPushButton* echoControlKey; + QString tmpStyle; + QPushButton* pasteButton = findChild(KEY_PASTE); + QPushButton* cutButton = findChild(KEY_CUT_LEFT); + QPushButton* copyButton = findChild(KEY_COPY); - textToSearch = KEY_HIDECHAR; + textToSearch = KEY_HIDECHAR; - if (pasteButton != nullptr && copyButton != nullptr) - { - cutButton->setEnabled(true); - copyButton->setEnabled(true); - if (m_clipboard->text().length() > 0) - pasteButton->setEnabled(true); - else - pasteButton->setEnabled(false); - } + if (pasteButton != nullptr && copyButton != nullptr) + { + cutButton->setEnabled(true); + copyButton->setEnabled(true); + if (m_clipboard->text().length() > 0) + pasteButton->setEnabled(true); + else + pasteButton->setEnabled(false); + } - echoControlKey = findChild(textToSearch); - if (echoControlKey != nullptr) - { - echoControlKey->setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON) + tmpStyle); - echoControlKey->setIcon(QPixmap(QStringLiteral(":/TastieraVirtuale/normalEcho"))); + echoControlKey = findChild(textToSearch); + if (echoControlKey != nullptr) + { + echoControlKey->setStyleSheet(QStringLiteral(DEFAULT_STYLE_BUTTON) + QStringLiteral(DEFAULT_BACKGROUND_BUTTON) + + tmpStyle); + echoControlKey->setIcon(QPixmap(QStringLiteral(":/TastieraVirtuale/normalEcho"))); - echoControlKey->repaint(); - QApplication::processEvents(); - } + echoControlKey->repaint(); + QApplication::processEvents(); + } } -void LtsVirtualKeyboard::setTextToCurrentWidget(const QString &text) +void LtsVirtualKeyboard::setTextToCurrentWidget(const QString& text) { + if (m_nextInput->inherits("QLineEdit")) + qobject_cast(m_nextInput)->setText(text); - if (m_nextInput->inherits("QLineEdit")) - qobject_cast(m_nextInput)->setText(text); + if (m_nextInput->inherits("QTextEdit")) + qobject_cast(m_nextInput)->setText(text); - if (m_nextInput->inherits("QTextEdit")) - qobject_cast(m_nextInput)->setText(text); + if (m_nextInput->inherits("QPlainTextEdit")) + qobject_cast(m_nextInput)->setPlainText(text); - if (m_nextInput->inherits("QPlainTextEdit")) - qobject_cast(m_nextInput)->setPlainText(text); + if (m_nextInput->inherits("QSpinBox")) + qobject_cast(m_nextInput)->setValue(text.toInt()); - if (m_nextInput->inherits("QSpinBox")) - qobject_cast(m_nextInput)->setValue(text.toInt()); - - if (m_nextInput->inherits("QDoubleSpinBox")) - qobject_cast(m_nextInput)->setValue(text.toDouble()); + if (m_nextInput->inherits("QDoubleSpinBox")) + qobject_cast(m_nextInput)->setValue(text.toDouble()); } QString LtsVirtualKeyboard::getTextFromCurrentWidget() { - if (qobject_cast(m_nextInput)) - return qobject_cast(m_nextInput)->text(); - - if (qobject_cast(m_nextInput)) - return qobject_cast(m_nextInput)->toPlainText(); - if (qobject_cast(m_nextInput)) - return qobject_cast(m_nextInput)->toPlainText(); - if (qobject_cast(m_nextInput)) - return QString::number(qobject_cast(m_nextInput)->value()); - if (qobject_cast(m_nextInput)) - return QString::number(qobject_cast(m_nextInput)->value()); - return QString(); + if (qobject_cast(m_nextInput)) + return qobject_cast(m_nextInput)->text(); + if (qobject_cast(m_nextInput)) + return qobject_cast(m_nextInput)->toPlainText(); + if (qobject_cast(m_nextInput)) + return qobject_cast(m_nextInput)->toPlainText(); + if (qobject_cast(m_nextInput)) + return QString::number(qobject_cast(m_nextInput)->value()); + if (qobject_cast(m_nextInput)) + return QString::number(qobject_cast(m_nextInput)->value()); + return QString(); } QString LtsVirtualKeyboard::getCurretText() const { - if (m_te->isVisible()) - return m_te->toPlainText(); - return m_le->text(); + if (m_te->isVisible()) + return m_te->toPlainText(); + return m_le->text(); } -void LtsVirtualKeyboard::setCurrentText(const QString &text) +void LtsVirtualKeyboard::setCurrentText(const QString& text) { - if(m_te->isVisible()) - m_te->setText(text); - else - m_le->setText(text); + if (m_te->isVisible()) + m_te->setText(text); + else + m_le->setText(text); } int LtsVirtualKeyboard::getCurrentTextCursorPosition() { - if(m_te->isVisible()) - return m_te->textCursor().position(); - return m_le->cursorPosition(); + if (m_te->isVisible()) + return m_te->textCursor().position(); + return m_le->cursorPosition(); } void LtsVirtualKeyboard::setCurrentTextCursorPosition(int cursor) { - if(m_te->isVisible()) - { - QTextCursor cur = m_te->textCursor(); - cur.setPosition(cursor); - m_te->setTextCursor(cur); - }else - { - m_le->setCursorPosition(cursor); - } - + if (m_te->isVisible()) + { + QTextCursor cur = m_te->textCursor(); + cur.setPosition(cursor); + m_te->setTextCursor(cur); + } + else + { + m_le->setCursorPosition(cursor); + } } bool LtsVirtualKeyboard::hasSelection() const { - if(m_te->isVisible()) - return m_te->textCursor().hasSelection(); - return m_le->hasSelectedText(); + if (m_te->isVisible()) + return m_te->textCursor().hasSelection(); + return m_le->hasSelectedText(); } QString LtsVirtualKeyboard::getSelectedText() const { - if (m_te->isVisible()) - return m_te->textCursor().selectedText(); - return m_le->selectedText(); + if (m_te->isVisible()) + return m_te->textCursor().selectedText(); + return m_le->selectedText(); } int LtsVirtualKeyboard::getSelectionStart() const { - if (m_te->isVisible()) - return m_te->textCursor().selectionStart(); - return m_le->selectionStart(); - + if (m_te->isVisible()) + return m_te->textCursor().selectionStart(); + return m_le->selectionStart(); } void LtsVirtualKeyboard::reinit() { - qDeleteAll(findChildren()); - m_te->deleteLater(); - m_le->deleteLater(); - delete layout(); - createKeyboard(); + qDeleteAll(findChildren()); + m_te->deleteLater(); + m_le->deleteLater(); + delete layout(); + createKeyboard(); } - -void LtsVirtualKeyboard::receiptChildKey(QWidget *focusThisControl, QKeyEvent *event, bool reset) +void LtsVirtualKeyboard::receiptChildKey(QWidget* focusThisControl, QKeyEvent* event, bool reset) { - if (!m_ready) - return; + if (!m_ready) + return; - if (reset == true) - { - m_nextInput = getNextTextbox(focusThisControl, true); - return; - } - if (m_nextInput == nullptr || !event) - { - return; - } - - - QString newKey = event->text(); - QString tmpReceiptString = getCurretText(); - int tmpPos = getCurrentTextCursorPosition(); - if (isNumericPad()) - newKey = newKey.trimmed(); - if (NO_SPECIAL_KEY(newKey) == false) - { - - if (IS_RETURN(newKey) == true) + if (reset == true) { - tmpReceiptString = tmpReceiptString.insert(tmpPos, QChar(13)); - - setTextToCurrentWidget(tmpReceiptString); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(tmpPos+1); + m_nextInput = getNextTextbox(focusThisControl, true); + return; } - else if (IS_FIN(newKey) == true) + if (m_nextInput == nullptr || !event) { - - hide(true); - - - if (!qobject_cast(m_nextInput) && !qobject_cast(m_nextInput)) - { - QKeyEvent event(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier); - QApplication::sendEvent(m_nextInput, &event); - } - m_nextInput->clearFocus(); - m_nextInput = nullptr; - - return; + return; } - - - - - - - - - - - - - - - else if (IS_BACK(newKey) == true) + + QString newKey = event->text(); + QString tmpReceiptString = getCurretText(); + int tmpPos = getCurrentTextCursorPosition(); + if (isNumericPad()) + newKey = newKey.trimmed(); + if (NO_SPECIAL_KEY(newKey) == false) { - if (!hasSelection()) - { - tmpReceiptString = tmpReceiptString.remove(tmpPos - 1, 1); - setTextToCurrentWidget(tmpReceiptString); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(tmpPos-1); - } - else - { - if (tmpPos - 1 >= 0) + + if (IS_RETURN(newKey) == true) { - int selectionStart = getSelectionStart(); - tmpReceiptString = tmpReceiptString.remove(selectionStart, getSelectedText().size()); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(selectionStart); - setTextToCurrentWidget(tmpReceiptString); - } - } - - } - else if (IS_CANC(newKey) == true) - { - tmpReceiptString = tmpReceiptString.remove(tmpPos, 1); - setTextToCurrentWidget(tmpReceiptString); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(tmpPos); - } - else if (IS_COPY(newKey) == true || IS_CUT_LEFT(newKey) == true) - { - LtsKeyPushButton *button = findChild(KEY_PASTE); - - if (button != nullptr) - { - if (hasSelection()) - { - m_clipboard->setText(getSelectedText()); - - if (IS_CUT_LEFT(newKey) == true) - { - int selectionStart =getSelectionStart(); - tmpReceiptString = tmpReceiptString.remove(selectionStart, getSelectedText().size()); - setCurrentText(tmpReceiptString); - - setCurrentTextCursorPosition(selectionStart); + tmpReceiptString = tmpReceiptString.insert(tmpPos, QChar(13)); setTextToCurrentWidget(tmpReceiptString); - } - button->setEnabled(true); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(tmpPos + 1); + } + else if (IS_FIN(newKey) == true) + { + + hide(true); + + if (!qobject_cast(m_nextInput) && !qobject_cast(m_nextInput)) + { + QKeyEvent event(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier); + QApplication::sendEvent(m_nextInput, &event); + } + m_nextInput->clearFocus(); + m_nextInput = nullptr; + + return; + } + + else if (IS_BACK(newKey) == true) + { + if (!hasSelection()) + { + tmpReceiptString = tmpReceiptString.remove(tmpPos - 1, 1); + setTextToCurrentWidget(tmpReceiptString); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(tmpPos - 1); + } + else + { + if (tmpPos - 1 >= 0) + { + int selectionStart = getSelectionStart(); + tmpReceiptString = tmpReceiptString.remove(selectionStart, getSelectedText().size()); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(selectionStart); + setTextToCurrentWidget(tmpReceiptString); + } + } + } + else if (IS_CANC(newKey) == true) + { + tmpReceiptString = tmpReceiptString.remove(tmpPos, 1); + setTextToCurrentWidget(tmpReceiptString); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(tmpPos); + } + else if (IS_COPY(newKey) == true || IS_CUT_LEFT(newKey) == true) + { + LtsKeyPushButton* button = findChild(KEY_PASTE); + + if (button != nullptr) + { + if (hasSelection()) + { + m_clipboard->setText(getSelectedText()); + + if (IS_CUT_LEFT(newKey) == true) + { + int selectionStart = getSelectionStart(); + tmpReceiptString = tmpReceiptString.remove(selectionStart, getSelectedText().size()); + setCurrentText(tmpReceiptString); + + setCurrentTextCursorPosition(selectionStart); + + setTextToCurrentWidget(tmpReceiptString); + } + button->setEnabled(true); + } + else + button->setEnabled(false); + } + } + else if (IS_PASTE(newKey) == true) + { + tmpReceiptString.insert(tmpPos, m_clipboard->text()); + setTextToCurrentWidget(tmpReceiptString); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(tmpPos + m_clipboard->text().length()); + } + else if (IS_ALT(newKey) == true || IS_ALT2(newKey) == true) + { + QList kList = findChildren(); + m_isAlt = !m_isAlt; + + auto i = kList.begin(); + + for (; i != kList.end(); ++i) + { + LtsKeyPushButton* tw = *i; + tw->setAltMode(m_isAlt); + } + } + else if (IS_CAPS(newKey) == true) + { + QList kList = findChildren(); + m_isCap = !m_isCap; + + auto i = kList.begin(); + + for (; i != kList.end(); ++i) + { + LtsKeyPushButton* tw = *i; + tw->setCapsMode(m_isCap); + } + } + } + else + { + if (getSelectedText().size()) + { + tmpPos = getSelectionStart(); + tmpReceiptString = tmpReceiptString.remove(tmpPos, getSelectedText().size()); + } + + tmpReceiptString = tmpReceiptString.insert(tmpPos, newKey); + setTextToCurrentWidget(tmpReceiptString); + setCurrentText(tmpReceiptString); + setCurrentTextCursorPosition(tmpPos + 1); + } +} + +void LtsVirtualKeyboard::switchKeyEchoMode(QWidget* control) +{ + setStatusEchoMode(!statusEchoMode()); + controlKeyEcho(control); +} + +QWidget* LtsVirtualKeyboard::getNextTextbox(QWidget* thisControl, bool reset) +{ + QWidget* tmpInputFound = nullptr; + m_echoMode = false; + if (m_activeWindow == nullptr) + { + m_nextInput = nullptr; + return (nullptr); + } + if (thisControl != nullptr) + { + if (m_activeWindow->findChild(thisControl->objectName()) == 0 && + m_activeWindow->findChild(thisControl->objectName()) == 0 && + m_activeWindow->findChild(thisControl->objectName()) == 0 && + m_activeWindow->findChild(thisControl->objectName()) == 0 && + m_activeWindow->findChild(thisControl->objectName()) == 0) + { + return (nullptr); } else - button->setEnabled(false); - } + { + return setCurrentTextStyle(thisControl); + } } - else if (IS_PASTE(newKey) == true) + if (m_nextInput == nullptr || reset == true) + m_nextInput = m_activeWindow->nextInFocusChain(); + else + m_nextInput = m_nextInput->nextInFocusChain(); + do { - tmpReceiptString.insert(tmpPos, m_clipboard->text()); - setTextToCurrentWidget(tmpReceiptString); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(tmpPos + m_clipboard->text().length()); - } - else if (IS_ALT(newKey) == true || IS_ALT2(newKey) == true) - { - QList kList = findChildren(); - m_isAlt = !m_isAlt; - - auto i = kList.begin(); - - for (; i != kList.end(); ++i) - { - LtsKeyPushButton *tw = *i; - tw->setAltMode(m_isAlt); - } - } - else if (IS_CAPS(newKey) == true) - { - QList kList = findChildren(); - m_isCap = !m_isCap; - - auto i = kList.begin(); - - for (; i != kList.end(); ++i) - { - LtsKeyPushButton *tw = *i; - tw->setCapsMode(m_isCap); - } - } - } - else - { - if (getSelectedText().size()) - { - tmpPos = getSelectionStart(); - tmpReceiptString = tmpReceiptString.remove(tmpPos, getSelectedText().size()); - } - - tmpReceiptString = tmpReceiptString.insert(tmpPos, newKey); - setTextToCurrentWidget(tmpReceiptString); - setCurrentText(tmpReceiptString); - setCurrentTextCursorPosition(tmpPos + 1); - } -} - - -void LtsVirtualKeyboard::switchKeyEchoMode(QWidget *control) -{ - setStatusEchoMode(!statusEchoMode()); - controlKeyEcho(control); -} - - -QWidget *LtsVirtualKeyboard::getNextTextbox(QWidget *thisControl, bool reset) -{ - QWidget *tmpInputFound = nullptr; - m_echoMode = false; - if (m_activeWindow == nullptr) - { - m_nextInput = nullptr; - return (nullptr); - } - if (thisControl != nullptr) - { - if (m_activeWindow->findChild(thisControl->objectName()) == 0 && - m_activeWindow->findChild(thisControl->objectName()) == 0 && - m_activeWindow->findChild(thisControl->objectName()) == 0 && - m_activeWindow->findChild(thisControl->objectName()) == 0 && - m_activeWindow->findChild(thisControl->objectName()) == 0) - { - return (nullptr); - } - else - { - return setCurrentTextStyle(thisControl); - } - } - if (m_nextInput == nullptr || reset == true) - m_nextInput = m_activeWindow->nextInFocusChain(); - else - m_nextInput = m_nextInput->nextInFocusChain(); - do - { - if (m_nextInput->inherits("QLineEdit") == true) - { - tmpInputFound = qobject_cast(m_nextInput); - return setCurrentTextStyle(tmpInputFound); - } - if (m_nextInput->inherits("QTextEdit") == true) - { - tmpInputFound = qobject_cast(m_nextInput); - return setCurrentTextStyle(tmpInputFound); - } - if (m_nextInput->inherits("QPlainTextEdit") == true) - { - tmpInputFound = qobject_cast(m_nextInput); - return setCurrentTextStyle(tmpInputFound); - } - if (m_nextInput->inherits("QSpinBox") == true) - { - tmpInputFound = qobject_cast(m_nextInput); - return setCurrentTextStyle(tmpInputFound); - } - if (m_nextInput->inherits("QDoubleSpinBox") == true) - { - tmpInputFound = qobject_cast(m_nextInput); - return setCurrentTextStyle(tmpInputFound); - } - m_nextInput = m_nextInput->nextInFocusChain(); - } - while (m_nextInput != nullptr); - return nullptr; -} - - -QWidget *LtsVirtualKeyboard::setCurrentTextStyle(QWidget *control) -{ - m_nextInput = control; - control->setStyleSheet(QStringLiteral(STYLE_FOCUS_TEXT)); - return (control); -} - -QWidget *LtsVirtualKeyboard::setDefaultTextStyle(QWidget *control) -{ - if (!m_nextInput) + if (m_nextInput->inherits("QLineEdit") == true) + { + tmpInputFound = qobject_cast(m_nextInput); + return setCurrentTextStyle(tmpInputFound); + } + if (m_nextInput->inherits("QTextEdit") == true) + { + tmpInputFound = qobject_cast(m_nextInput); + return setCurrentTextStyle(tmpInputFound); + } + if (m_nextInput->inherits("QPlainTextEdit") == true) + { + tmpInputFound = qobject_cast(m_nextInput); + return setCurrentTextStyle(tmpInputFound); + } + if (m_nextInput->inherits("QSpinBox") == true) + { + tmpInputFound = qobject_cast(m_nextInput); + return setCurrentTextStyle(tmpInputFound); + } + if (m_nextInput->inherits("QDoubleSpinBox") == true) + { + tmpInputFound = qobject_cast(m_nextInput); + return setCurrentTextStyle(tmpInputFound); + } + m_nextInput = m_nextInput->nextInFocusChain(); + } while (m_nextInput != nullptr); return nullptr; - QLineEdit le; - control->setStyleSheet(le.styleSheet()); - return (control); +} + +QWidget* LtsVirtualKeyboard::setCurrentTextStyle(QWidget* control) +{ + m_nextInput = control; + control->setStyleSheet(QStringLiteral(STYLE_FOCUS_TEXT)); + return (control); +} + +QWidget* LtsVirtualKeyboard::setDefaultTextStyle(QWidget* control) +{ + if (!m_nextInput) + return nullptr; + QLineEdit le; + control->setStyleSheet(le.styleSheet()); + return (control); } QSize LtsVirtualKeyboard::availableDesktopSize() const { #if QT_VERSION < QT_VERSION_CHECK(5, 12, 0) - return QApplication::desktop()->availableGeometry().size(); + return QApplication::desktop()->availableGeometry().size(); #else - const QWindow *win = window()->windowHandle(); - const QScreen *scr = (win && win->screen()) ? win->screen() : QGuiApplication::primaryScreen(); - return scr ? scr->availableSize() : QSize(1280, 1024); + const QWindow* win = window()->windowHandle(); + const QScreen* scr = (win && win->screen()) ? win->screen() : QGuiApplication::primaryScreen(); + return scr ? scr->availableSize() : QSize(1280, 1024); #endif } -void LtsVirtualKeyboard::init_keyboard(QWidget *focusThisControl) +void LtsVirtualKeyboard::init_keyboard(QWidget* focusThisControl) { - m_nextInput = focusThisControl; - checkInput(); - - receiptChildKey(focusThisControl, nullptr, true); + m_nextInput = focusThisControl; + checkInput(); + + receiptChildKey(focusThisControl, nullptr, true); } -void LtsVirtualKeyboard::show(QWidget *first, bool frameless) +void LtsVirtualKeyboard::show(QWidget* first, bool frameless) { - Q_UNUSED(frameless); - init_keyboard(first); + Q_UNUSED(frameless); + init_keyboard(first); - if (windowState() == Qt::WindowMinimized) - setWindowState(Qt::WindowNoState); - setStatusEchoMode(false); - setVisible(true); + if (windowState() == Qt::WindowMinimized) + setWindowState(Qt::WindowNoState); + setStatusEchoMode(false); + setVisible(true); - const auto availSize = availableDesktopSize(); - move((availSize.width() - width()) / 2, - (availSize.height() - height()) - 10); - QTimer::singleShot(300, this, [this]() { m_ready = true; }); + const auto availSize = availableDesktopSize(); + move((availSize.width() - width()) / 2, (availSize.height() - height()) - 10); + QTimer::singleShot(300, this, [this]() { m_ready = true; }); } - void LtsVirtualKeyboard::borderFrame(bool visible) { - if (visible == true) - setWindowFlags(Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::MSWindowsFixedSizeDialogHint); - else - setWindowFlags(Qt::Window | Qt::FramelessWindowHint); + if (visible == true) + setWindowFlags(Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::MSWindowsFixedSizeDialogHint); + else + setWindowFlags(Qt::Window | Qt::FramelessWindowHint); } void LtsVirtualKeyboard::checkInput() { - m_enableEnter = false; - m_echoMode = false; + m_enableEnter = false; + m_echoMode = false; - m_le->setVisible(true); - m_te->setVisible(false); - if (qobject_cast(m_nextInput)) - { - QLineEdit *le = qobject_cast(m_nextInput); - m_le->setEchoMode(le->echoMode()); - } - if (qobject_cast(m_nextInput) || qobject_cast(m_nextInput)) - { - m_le->setVisible(false); - m_te->setVisible(true); - m_enableEnter = true; - } + m_le->setVisible(true); + m_te->setVisible(false); + if (qobject_cast(m_nextInput)) + { + QLineEdit* le = qobject_cast(m_nextInput); + m_le->setEchoMode(le->echoMode()); + } + if (qobject_cast(m_nextInput) || qobject_cast(m_nextInput)) + { + m_le->setVisible(false); + m_te->setVisible(true); + m_enableEnter = true; + } - LtsKeyPushButton *crButton = findChild(KEY_RETURN); - if (crButton) - { - crButton->setEnabled(m_enableEnter); - } - - if (m_te->isVisible()) - setMaximumHeight(m_height+m_te->height()); - else - setMaximumHeight(m_height+m_le->height()); + LtsKeyPushButton* crButton = findChild(KEY_RETURN); + if (crButton) + { + crButton->setEnabled(m_enableEnter); + } + if (m_te->isVisible()) + setMaximumHeight(m_height + m_te->height()); + else + setMaximumHeight(m_height + m_le->height()); } bool LtsVirtualKeyboard::isNumericPad() const { - return (m_numericPad); + return (m_numericPad); } -void LtsVirtualKeyboard::focusThis(QWidget *control, bool numpad) +void LtsVirtualKeyboard::focusThis(QWidget* control, bool numpad) { - m_ready = false; - if (m_activeWindow != nullptr) - { - if (m_numericPad != numpad) + m_ready = false; + if (m_activeWindow != nullptr) { - m_numericPad = numpad; - reinit(); + if (m_numericPad != numpad) + { + m_numericPad = numpad; + reinit(); + } + + if (m_nextInput != nullptr) + m_nextInput = setDefaultTextStyle(m_nextInput); + init_keyboard(control); + controlKeyEcho(control); + + setCurrentText(getTextFromCurrentWidget()); + if (m_te->isVisible()) + m_te->moveCursor(QTextCursor::Start); + else + m_le->end(false); + if (m_nextInput) + setWindowTitle(m_nextInput->toolTip()); } - - if (m_nextInput != nullptr) - m_nextInput = setDefaultTextStyle(m_nextInput); - init_keyboard(control); - controlKeyEcho(control); - - setCurrentText(getTextFromCurrentWidget()); - if(m_te->isVisible()) - m_te->moveCursor(QTextCursor::Start); + QTimer::singleShot(300, this, [this]() { m_ready = true; }); + const auto availSize = availableDesktopSize(); + if (isNumericPad()) + move((availSize.width() - width()) / 2, (availSize.height() - height()) - 10); else - m_le->end(false); - if (m_nextInput) - setWindowTitle(m_nextInput->toolTip()); - } - QTimer::singleShot(300, this, [this]() { m_ready = true; }); - const auto availSize = availableDesktopSize(); - if (isNumericPad()) - move((availSize.width() - width()) / 2, - (availSize.height() - height()) - 10); - else - move(10, availSize.height() - height() - 10); + move(10, availSize.height() - height() - 10); } -void LtsVirtualKeyboard::closeEvent(QCloseEvent *event) +void LtsVirtualKeyboard::closeEvent(QCloseEvent* event) { - event->ignore(); + event->ignore(); } void LtsVirtualKeyboard::hide(bool changeColor) { - m_ready = false; - try - { - if (changeColor == true) + m_ready = false; + try + { + if (changeColor == true) + { + if (m_activeWindow != nullptr) + setDefaultTextStyle(m_nextInput); + } + if (!parent()) + setVisible(false); + } + catch (...) { - if (m_activeWindow != nullptr) - setDefaultTextStyle(m_nextInput); } - if (!parent()) - setVisible(false); - - } - catch (...) - { - } } - void LtsVirtualKeyboard::createKeyboard() { - LtsKeyPushButton *tmp = nullptr; - QVBoxLayout *tmpVLayout = new QVBoxLayout; - QHBoxLayout *tmpLayout = new QHBoxLayout; - QString tmpStyle; - QString backspace; - m_ready = false; - - m_te = new QTextEdit(this); - m_te->setMaximumHeight(210); - m_te->setMinimumHeight(210); + LtsKeyPushButton* tmp = nullptr; + QVBoxLayout* tmpVLayout = new QVBoxLayout; + QHBoxLayout* tmpLayout = new QHBoxLayout; + QString tmpStyle; + QString backspace; + m_ready = false; - m_te->setObjectName(QStringLiteral("internalLE")); - - tmpVLayout->addWidget(m_te); - - m_te->hide(); + m_te = new QTextEdit(this); + m_te->setMaximumHeight(210); + m_te->setMinimumHeight(210); - - m_le = new QLineEdit(this); - m_le->setObjectName(QStringLiteral("internalLE")); - - tmpVLayout->addWidget(m_le); + m_te->setObjectName(QStringLiteral("internalLE")); + tmpVLayout->addWidget(m_te); - if (isNumericPad() == true) - { - QGridLayout *gridLayout = new QGridLayout(this); - gridLayout->addLayout(tmpVLayout,0,0); - for (short i = 49; i <= 51; i++) - tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); - gridLayout->addLayout(tmpLayout, 3, 0); - tmpLayout = new QHBoxLayout(this); - for (short i = 52; i <= 54; i++) - tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); - gridLayout->addLayout(tmpLayout, 2, 0); - tmpLayout = new QHBoxLayout(this); - for (short i = 55; i <= 57; i++) - tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); - gridLayout->addLayout(tmpLayout, 1, 0); - tmpLayout = new QHBoxLayout(this); - tmp = createNewKey(QStringLiteral("0"), QStringLiteral("0"), QStringLiteral("0")); - tmp->setMinimumSize(tmp->minimumSize().width() * 2, tmp->minimumSize().height()); - tmpLayout->addWidget(tmp); - tmpLayout->addWidget(createNewKey(QStringLiteral("."), QStringLiteral(" . "), QStringLiteral(" . "))); - gridLayout->addLayout(tmpLayout, 4, 0); - tmpLayout = new QHBoxLayout(this); - tmpLayout->addWidget(createNewKey(QStringLiteral(","), QStringLiteral(" , "), QStringLiteral(" , "))); - backspace = QStringLiteral("BACKSPACE"); - tmpStyle = (KEY_BACKSPACE); + m_te->hide(); - tmp = createNewKey(tmpStyle, backspace); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); - tmpLayout->addWidget(tmp); + m_le = new QLineEdit(this); + m_le->setObjectName(QStringLiteral("internalLE")); - tmp = createNewKey(KEY_FIN,KEY_FIN); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); - tmpLayout->addWidget(tmp); - gridLayout->addLayout(tmpLayout, 5, 0); + tmpVLayout->addWidget(m_le); - - - setLayout(gridLayout); - setMaximumWidth(tmp->width()*3); - m_height= tmp->height()*5; - } - else - { - + if (isNumericPad() == true) + { + QGridLayout* gridLayout = new QGridLayout(this); + gridLayout->addLayout(tmpVLayout, 0, 0); + for (short i = 49; i <= 51; i++) + tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); + gridLayout->addLayout(tmpLayout, 3, 0); + tmpLayout = new QHBoxLayout(this); + for (short i = 52; i <= 54; i++) + tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); + gridLayout->addLayout(tmpLayout, 2, 0); + tmpLayout = new QHBoxLayout(this); + for (short i = 55; i <= 57; i++) + tmpLayout->addWidget(createNewKey(QChar(i), QString::number(i - 48), QString::number(i - 48))); + gridLayout->addLayout(tmpLayout, 1, 0); + tmpLayout = new QHBoxLayout(this); + tmp = createNewKey(QStringLiteral("0"), QStringLiteral("0"), QStringLiteral("0")); + tmp->setMinimumSize(tmp->minimumSize().width() * 2, tmp->minimumSize().height()); + tmpLayout->addWidget(tmp); + tmpLayout->addWidget(createNewKey(QStringLiteral("."), QStringLiteral(" . "), QStringLiteral(" . "))); + gridLayout->addLayout(tmpLayout, 4, 0); + tmpLayout = new QHBoxLayout(this); + tmpLayout->addWidget(createNewKey(QStringLiteral(","), QStringLiteral(" , "), QStringLiteral(" , "))); + backspace = QStringLiteral("BACKSPACE"); + tmpStyle = (KEY_BACKSPACE); - - tmpLayout->addWidget(createNewKey(QStringLiteral("^"), QStringLiteral("^"), QStringLiteral("^"))); - - tmpLayout->addWidget(createNewKey(QStringLiteral("1"), QStringLiteral("1"), QStringLiteral("!"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("2"), QStringLiteral("2"), QStringLiteral("\""))); - tmpLayout->addWidget(createNewKey(QStringLiteral("3"), QStringLiteral("3"), QChar(207))); - tmpLayout->addWidget(createNewKey(QStringLiteral("4"), QStringLiteral("4"), QStringLiteral("$"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("5"), QStringLiteral("5"), QStringLiteral("%"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("6"), QStringLiteral("6"), QStringLiteral("&&"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("7"), QStringLiteral("7"), QStringLiteral("/"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("8"), QStringLiteral("8"), QStringLiteral("("))); - tmpLayout->addWidget(createNewKey(QStringLiteral("9"), QStringLiteral("9"), QStringLiteral(")"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("0"), QStringLiteral("0"), QStringLiteral("="))); - tmpLayout->addWidget(createNewKey(QChar(223), QChar(223), QStringLiteral("?"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("`"), QChar(180), QStringLiteral("`"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("["), QStringLiteral("["), QStringLiteral("{"))); - backspace = QStringLiteral("<----"); - tmpStyle = KEY_BACKSPACE; - tmp = createNewKey(tmpStyle, backspace); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.2); - tmp->setMinimumWidth(tmp->maximumWidth() * 1.2); - tmpLayout->addWidget(tmp); - tmpLayout->insertStretch(-1, 1); - tmpVLayout->addLayout(tmpLayout); + tmp = createNewKey(tmpStyle, backspace); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); + tmpLayout->addWidget(tmp); + tmp = createNewKey(KEY_FIN, KEY_FIN); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); + tmpLayout->addWidget(tmp); + gridLayout->addLayout(tmpLayout, 5, 0); - - tmpLayout = new QHBoxLayout(); + setLayout(gridLayout); + setMaximumWidth(tmp->width() * 3); + m_height = tmp->height() * 5; + } + else + { - QVBoxLayout *layoutReturn = new QVBoxLayout(); - tmp = createNewKey(KEY_ALT, KEY_ALT, KEY_ALT2); - tmp->setMaximumWidth(tmp->maximumWidth()); - tmp->setMinimumWidth(tmp->minimumWidth()); - tmpLayout->addWidget(tmp); + tmpLayout->addWidget(createNewKey(QStringLiteral("^"), QStringLiteral("^"), QStringLiteral("^"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("Q"), QStringLiteral("Q"), QStringLiteral("@"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("W"), QStringLiteral("W"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("E"), QStringLiteral("E"), QChar(8364))); - tmpLayout->addWidget(createNewKey(QStringLiteral("R"), QStringLiteral("R"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("T"), QStringLiteral("T"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("Z"), QStringLiteral("Z"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("U"), QStringLiteral("U"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("I"), QStringLiteral("I"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("O"), QStringLiteral("O"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("P"), QStringLiteral("P"))); - tmpLayout->addWidget(createNewKey(QChar(220), QChar(220))); - tmpLayout->addWidget(createNewKey(QStringLiteral("+"), QStringLiteral("+"), QStringLiteral("*"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("]"), QStringLiteral("]"), QStringLiteral("}"))); - tmpStyle = KEY_CANC; - tmp = createNewKey(tmpStyle, QStringLiteral("->")); - tmp->setMaximumWidth(tmp->maximumWidth()); - tmp->setMinimumWidth(tmp->minimumWidth()); - tmpLayout->addWidget(tmp); - tmpLayout->insertStretch(-1, 1); - - + tmpLayout->addWidget(createNewKey(QStringLiteral("1"), QStringLiteral("1"), QStringLiteral("!"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("2"), QStringLiteral("2"), QStringLiteral("\""))); + tmpLayout->addWidget(createNewKey(QStringLiteral("3"), QStringLiteral("3"), QChar(207))); + tmpLayout->addWidget(createNewKey(QStringLiteral("4"), QStringLiteral("4"), QStringLiteral("$"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("5"), QStringLiteral("5"), QStringLiteral("%"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("6"), QStringLiteral("6"), QStringLiteral("&&"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("7"), QStringLiteral("7"), QStringLiteral("/"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("8"), QStringLiteral("8"), QStringLiteral("("))); + tmpLayout->addWidget(createNewKey(QStringLiteral("9"), QStringLiteral("9"), QStringLiteral(")"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("0"), QStringLiteral("0"), QStringLiteral("="))); + tmpLayout->addWidget(createNewKey(QChar(223), QChar(223), QStringLiteral("?"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("`"), QChar(180), QStringLiteral("`"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("["), QStringLiteral("["), QStringLiteral("{"))); + backspace = QStringLiteral("<----"); + tmpStyle = KEY_BACKSPACE; + tmp = createNewKey(tmpStyle, backspace); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.2); + tmp->setMinimumWidth(tmp->maximumWidth() * 1.2); + tmpLayout->addWidget(tmp); + tmpLayout->insertStretch(-1, 1); + tmpVLayout->addLayout(tmpLayout); + tmpLayout = new QHBoxLayout(); - layoutReturn->addLayout(tmpLayout, 1); + QVBoxLayout* layoutReturn = new QVBoxLayout(); + tmp = createNewKey(KEY_ALT, KEY_ALT, KEY_ALT2); + tmp->setMaximumWidth(tmp->maximumWidth()); + tmp->setMinimumWidth(tmp->minimumWidth()); + tmpLayout->addWidget(tmp); - - tmpLayout = new QHBoxLayout(); - tmp = createNewKey(KEY_CAPS, KEY_CAPS); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.5 + 5); - tmpLayout->addWidget(tmp); - tmpLayout->addWidget(createNewKey(QStringLiteral("A"), QStringLiteral("A"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("S"), QStringLiteral("S"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("D"), QStringLiteral("D"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("F"), QStringLiteral("F"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("G"), QStringLiteral("G"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("H"), QStringLiteral("H"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("J"), QStringLiteral("J"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("K"), QStringLiteral("K"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("L"), QStringLiteral("L"))); - tmpLayout->addWidget(createNewKey(QChar(214), QChar(214))); - tmpLayout->addWidget(createNewKey(QChar(196), QChar(196))); - tmpLayout->addWidget(createNewKey(QStringLiteral("'"), QStringLiteral("'"), QStringLiteral("#"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("|"), QStringLiteral("|"), QStringLiteral("\\"))); - tmpLayout->insertStretch(-1, 1); + tmpLayout->addWidget(createNewKey(QStringLiteral("Q"), QStringLiteral("Q"), QStringLiteral("@"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("W"), QStringLiteral("W"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("E"), QStringLiteral("E"), QChar(8364))); + tmpLayout->addWidget(createNewKey(QStringLiteral("R"), QStringLiteral("R"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("T"), QStringLiteral("T"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("Z"), QStringLiteral("Z"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("U"), QStringLiteral("U"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("I"), QStringLiteral("I"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("O"), QStringLiteral("O"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("P"), QStringLiteral("P"))); + tmpLayout->addWidget(createNewKey(QChar(220), QChar(220))); + tmpLayout->addWidget(createNewKey(QStringLiteral("+"), QStringLiteral("+"), QStringLiteral("*"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("]"), QStringLiteral("]"), QStringLiteral("}"))); + tmpStyle = KEY_CANC; + tmp = createNewKey(tmpStyle, QStringLiteral("->")); + tmp->setMaximumWidth(tmp->maximumWidth()); + tmp->setMinimumWidth(tmp->minimumWidth()); + tmpLayout->addWidget(tmp); + tmpLayout->insertStretch(-1, 1); - layoutReturn->setSpacing(5); - layoutReturn->addLayout(tmpLayout, 1); - - tmpLayout = new QHBoxLayout(); - tmpLayout->addLayout(layoutReturn, 1); - + layoutReturn->addLayout(tmpLayout, 1); - tmp = createNewKey(KEY_RETURN, QStringLiteral("RETURN")); - tmp->setEnabled(m_enableEnter); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.4); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.4); - tmp->setMinimumHeight(tmp->minimumHeight() * 1.4); - - tmpLayout->addWidget(tmp, 2); + tmpLayout = new QHBoxLayout(); + tmp = createNewKey(KEY_CAPS, KEY_CAPS); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.5 + 5); + tmpLayout->addWidget(tmp); + tmpLayout->addWidget(createNewKey(QStringLiteral("A"), QStringLiteral("A"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("S"), QStringLiteral("S"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("D"), QStringLiteral("D"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("F"), QStringLiteral("F"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("G"), QStringLiteral("G"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("H"), QStringLiteral("H"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("J"), QStringLiteral("J"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("K"), QStringLiteral("K"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("L"), QStringLiteral("L"))); + tmpLayout->addWidget(createNewKey(QChar(214), QChar(214))); + tmpLayout->addWidget(createNewKey(QChar(196), QChar(196))); + tmpLayout->addWidget(createNewKey(QStringLiteral("'"), QStringLiteral("'"), QStringLiteral("#"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("|"), QStringLiteral("|"), QStringLiteral("\\"))); + tmpLayout->insertStretch(-1, 1); - - tmpVLayout->addLayout(tmpLayout); + layoutReturn->setSpacing(5); + layoutReturn->addLayout(tmpLayout, 1); + tmpLayout = new QHBoxLayout(); + tmpLayout->addLayout(layoutReturn, 1); - - tmpLayout = new QHBoxLayout(); - tmp = createNewKey(KEY_CUT_LEFT, KEY_CUT_LEFT); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.2); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.2); - tmpLayout->addWidget(tmp); - tmpLayout->addWidget(createNewKey(QStringLiteral("<"), QStringLiteral("<"), QStringLiteral(">"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("Y"), QStringLiteral("Y"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("X"), QStringLiteral("X"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("C"), QStringLiteral("C"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("V"), QStringLiteral("V"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("B"), QStringLiteral("B"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("N"), QStringLiteral("N"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("M"), QStringLiteral("M"))); - tmpLayout->addWidget(createNewKey(QStringLiteral(","), QStringLiteral(","), QStringLiteral(";"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("."), QStringLiteral("."), QStringLiteral(":"))); - tmpLayout->addWidget(createNewKey(QStringLiteral("-"), QStringLiteral("-"), QStringLiteral("_"))); - tmpLayout->insertStretch(-1, 1); + tmp = createNewKey(KEY_RETURN, QStringLiteral("RETURN")); + tmp->setEnabled(m_enableEnter); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.4); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.4); + tmp->setMinimumHeight(tmp->minimumHeight() * 1.4); - - tmpVLayout->addLayout(tmpLayout); - tmpLayout = new QHBoxLayout(); + tmpLayout->addWidget(tmp, 2); - tmp = createNewKey(KEY_COPY, KEY_COPY); - tmp->setMaximumWidth(tmp->maximumWidth()); - tmp->setMinimumWidth(tmp->maximumWidth()); - tmpLayout->addWidget(tmp); + tmpVLayout->addLayout(tmpLayout); - tmp = createNewKey(KEY_PASTE, KEY_PASTE); - tmp->setMaximumWidth(tmp->maximumWidth()); - tmp->setMinimumWidth(tmp->maximumWidth()); - tmpLayout->addWidget(tmp); + tmpLayout = new QHBoxLayout(); + tmp = createNewKey(KEY_CUT_LEFT, KEY_CUT_LEFT); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.2); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.2); + tmpLayout->addWidget(tmp); + tmpLayout->addWidget(createNewKey(QStringLiteral("<"), QStringLiteral("<"), QStringLiteral(">"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("Y"), QStringLiteral("Y"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("X"), QStringLiteral("X"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("C"), QStringLiteral("C"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("V"), QStringLiteral("V"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("B"), QStringLiteral("B"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("N"), QStringLiteral("N"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("M"), QStringLiteral("M"))); + tmpLayout->addWidget(createNewKey(QStringLiteral(","), QStringLiteral(","), QStringLiteral(";"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("."), QStringLiteral("."), QStringLiteral(":"))); + tmpLayout->addWidget(createNewKey(QStringLiteral("-"), QStringLiteral("-"), QStringLiteral("_"))); + tmpLayout->insertStretch(-1, 1); - QWidget *empty = new QWidget(this); - empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - tmpLayout->addWidget(empty); + tmpVLayout->addLayout(tmpLayout); + tmpLayout = new QHBoxLayout(); - tmp = createNewKey(QStringLiteral(KEY_SPACE), QStringLiteral(" ")); - tmp->setMinimumWidth(300); - tmp->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - tmpLayout->addWidget(tmp, 3); + tmp = createNewKey(KEY_COPY, KEY_COPY); + tmp->setMaximumWidth(tmp->maximumWidth()); + tmp->setMinimumWidth(tmp->maximumWidth()); + tmpLayout->addWidget(tmp); - empty = new QWidget(this); - empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); - tmpLayout->addWidget(empty); + tmp = createNewKey(KEY_PASTE, KEY_PASTE); + tmp->setMaximumWidth(tmp->maximumWidth()); + tmp->setMinimumWidth(tmp->maximumWidth()); + tmpLayout->addWidget(tmp); - tmp = createNewKey(KEY_FIN, KEY_FIN); - tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); - tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); - tmpLayout->addWidget(tmp); + QWidget* empty = new QWidget(this); + empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + tmpLayout->addWidget(empty); - tmpVLayout->addLayout(tmpLayout); - setLayout(tmpVLayout); + tmp = createNewKey(QStringLiteral(KEY_SPACE), QStringLiteral(" ")); + tmp->setMinimumWidth(300); + tmp->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + tmpLayout->addWidget(tmp, 3); + + empty = new QWidget(this); + empty->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + tmpLayout->addWidget(empty); + + tmp = createNewKey(KEY_FIN, KEY_FIN); + tmp->setMaximumWidth(tmp->maximumWidth() * 1.5); + tmp->setMinimumWidth(tmp->minimumWidth() * 1.5); + tmpLayout->addWidget(tmp); + + tmpVLayout->addLayout(tmpLayout); + setLayout(tmpVLayout); + + m_height = tmp->height() * 5 + 10; + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + } - m_height = tmp->height()*5+10; setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - } - - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); } -} +} // namespace LtsVirtualKeyboard diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.h old mode 100755 new mode 100644 index 4f4dccae3..4b6a49924 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsVirtualKeyboard/LtsVirtualKeyboard.h @@ -1,12 +1,11 @@ - #pragma once -#include - #include "LtsKeyPushButton.h" #include "ltsvirtualkeyboard_export.h" + #include +#include class QClipboard; class QLabel; @@ -17,82 +16,96 @@ class QTextEdit; namespace LtsVirtualKeyboard { -class LTSVIRTUALKEYBOARD_EXPORT LtsVirtualKeyboard : public QWidget +class LTSVIRTUALKEYBOARD_EXPORT LtsVirtualKeyboard : public QWidget { - Q_OBJECT + Q_OBJECT + private: + LtsVirtualKeyboard(LtsSession::LtsSession* session, QWidget* activeForm = nullptr, bool onlyNumericPad = false, + QWidget* parent = nullptr); + ~LtsVirtualKeyboard(); -private: - LtsVirtualKeyboard(LtsSession::LtsSession *session, QWidget *activeForm = nullptr, bool onlyNumericPad = false, QWidget *parent = nullptr); - ~LtsVirtualKeyboard(); + public: + static LtsVirtualKeyboard* getInstance(LtsSession::LtsSession* session, QWidget* activeForm = nullptr, + bool onlyNumericPad = false, QWidget* parent = nullptr); + static void cleanupLtsVirtualKeyboard(); -public: - static LtsVirtualKeyboard *getInstance(LtsSession::LtsSession *session, QWidget *activeForm = nullptr, bool onlyNumericPad = false, QWidget *parent = nullptr); - static void cleanupLtsVirtualKeyboard(); + void createKeyboard(); - void createKeyboard(); - bool statusEchoMode() const { return (m_echoMode); } - void setStatusEchoMode(bool echo) { m_echoMode = echo; } - void receiptChildKey(QWidget *focusThisControl = nullptr, QKeyEvent *event = nullptr, bool reset = false); - void switchKeyEchoMode(QWidget *control); - void enableSwitchingEcho(bool status); - bool isEnabledSwitchingEcho() const; - void borderFrame(bool visible = true); - void checkInput(); - QWidget *setDefaultTextStyle(QWidget *control); - bool isNumericPad() const; - QLabel *zoomedWidget(); - void setActiveWindw(QWidget *widget) { m_activeWindow = widget; } - void setSession(LtsSession::LtsSession *session) { m_session= session; } + bool statusEchoMode() const + { + return (m_echoMode); + } + void setStatusEchoMode(bool echo) + { + m_echoMode = echo; + } - + void receiptChildKey(QWidget* focusThisControl = nullptr, QKeyEvent* event = nullptr, bool reset = false); + void switchKeyEchoMode(QWidget* control); + void enableSwitchingEcho(bool status); + bool isEnabledSwitchingEcho() const; + void borderFrame(bool visible = true); + void checkInput(); + QWidget* setDefaultTextStyle(QWidget* control); + bool isNumericPad() const; + QLabel* zoomedWidget(); + void setActiveWindw(QWidget* widget) + { + m_activeWindow = widget; + } -public slots: - void show(QWidget *first = nullptr, bool frameless = false); - void hide(bool changeColor); - void focusThis(QWidget *control, bool numpad = false); + void setSession(LtsSession::LtsSession* session) + { + m_session = session; + } -protected: - void closeEvent(QCloseEvent *event) override; + public slots: + void show(QWidget* first = nullptr, bool frameless = false); + void hide(bool changeColor); + void focusThis(QWidget* control, bool numpad = false); -private: - QSize availableDesktopSize() const; - void init_keyboard(QWidget *focusThisControl); - QWidget *setCurrentTextStyle(QWidget *control); - LtsKeyPushButton *createNewKey(const QString &keyValue, const QString ¬TranslatedValue, const QString ¬TranslatedValueAlt = QString()); - QWidget *getNextTextbox(QWidget *thisControl = nullptr, bool reset = false); - void controlKeyEcho(QWidget *control); - void setTextToCurrentWidget(const QString &text); - QString getTextFromCurrentWidget(); - QString getCurretText()const; - void setCurrentText(const QString &text); - int getCurrentTextCursorPosition(); - void setCurrentTextCursorPosition(int cursor); - bool hasSelection() const; - QString getSelectedText() const; - int getSelectionStart() const; - void reinit(); -private: + protected: + void closeEvent(QCloseEvent* event) override; - QTextEdit *m_te; - QLineEdit *m_le; + private: + QSize availableDesktopSize() const; + void init_keyboard(QWidget* focusThisControl); + QWidget* setCurrentTextStyle(QWidget* control); + LtsKeyPushButton* createNewKey(const QString& keyValue, const QString& notTranslatedValue, + const QString& notTranslatedValueAlt = QString()); + QWidget* getNextTextbox(QWidget* thisControl = nullptr, bool reset = false); + void controlKeyEcho(QWidget* control); + void setTextToCurrentWidget(const QString& text); + QString getTextFromCurrentWidget(); + QString getCurretText() const; + void setCurrentText(const QString& text); + int getCurrentTextCursorPosition(); + void setCurrentTextCursorPosition(int cursor); + bool hasSelection() const; + QString getSelectedText() const; + int getSelectionStart() const; + void reinit(); - QWidget *m_nextInput; - QWidget *m_activeWindow; - bool m_echoMode; - bool m_enablePasswordEcho; - bool m_numericPad; - bool m_isAlt; - bool m_isCap; - bool m_enableEnter; - bool m_ready; + private: + QTextEdit* m_te; + QLineEdit* m_le; - int m_height; - QClipboard *m_clipboard; - LtsSession::LtsSession *m_session; + QWidget* m_nextInput; + QWidget* m_activeWindow; + bool m_echoMode; + bool m_enablePasswordEcho; + bool m_numericPad; + bool m_isAlt; + bool m_isCap; + bool m_enableEnter; + bool m_ready; + int m_height; + QClipboard* m_clipboard; + LtsSession::LtsSession* m_session; }; -} +} // namespace LtsVirtualKeyboard diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp old mode 100755 new mode 100644 index cb6d93881..174041202 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.cpp @@ -9,30 +9,26 @@ namespace LtsWebSocket { - - - -InvalidMessage::InvalidMessage(ReplyHandler *client, const QString &uuid, const QString &errorText) - : AbstractClientMessage(client, QString(), 1, uuid) - , m_errorText(errorText) -{} +InvalidMessage::InvalidMessage(ReplyHandler* client, const QString& uuid, const QString& errorText) + : AbstractClientMessage(client, QString(), 1, uuid), m_errorText(errorText) +{ +} void InvalidMessage::process() { - ErrorMessage::ErrorData errorData; + ErrorMessage::ErrorData errorData; - errorData.errorClass = 1; - errorData.errorMessage = m_errorText; - errorData.uuid = m_uuid; + errorData.errorClass = 1; + errorData.errorMessage = m_errorText; + errorData.uuid = m_uuid; - m_client->addReply(new ErrorMessage(errorData)); + m_client->addReply(new ErrorMessage(errorData)); } bool InvalidMessage::hasValidData() const { - - return true; + + return true; } - -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h old mode 100755 new mode 100644 index 65d4c4b96..9f4371f0f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message.h @@ -5,66 +5,50 @@ #include "ltswebsocketcommon_export.h" #include "reply_message.h" -#include #include +#include namespace LtsWebSocket { - - class LTSWEBSOCKETCOMMON_EXPORT AbstractClientMessage { -public: - AbstractClientMessage(ReplyHandler *client, const QString &type, const int typeId, const QString &uuid, const QJsonValue &data = QJsonValue()) - : m_type(type) - , m_typeId(typeId) - , m_uuid(uuid) - , m_data(data) - , m_client(client) - {} + public: + AbstractClientMessage(ReplyHandler* client, const QString& type, const int typeId, const QString& uuid, + const QJsonValue& data = QJsonValue()) + : m_type(type), m_typeId(typeId), m_uuid(uuid), m_data(data), m_client(client) + { + } - virtual ~AbstractClientMessage() = default; - - - - virtual void process() = 0; - - - - virtual bool hasValidData() const = 0; - - - - void reply(ReplyMessage *reply) - { - m_client->addReply(reply); - } - -protected: - const QString m_type; - const int m_typeId; - const QString m_uuid; - const QJsonValue m_data; - ReplyHandler *m_client; - -}; + virtual ~AbstractClientMessage() = default; + virtual void process() = 0; + virtual bool hasValidData() const = 0; + void reply(ReplyMessage* reply) + { + m_client->addReply(reply); + } + protected: + const QString m_type; + const int m_typeId; + const QString m_uuid; + const QJsonValue m_data; + ReplyHandler* m_client; +}; class LTSWEBSOCKETCOMMON_EXPORT InvalidMessage final : public AbstractClientMessage { -public: - explicit InvalidMessage(ReplyHandler *client, const QString &uuid, const QString &errorText); + public: + explicit InvalidMessage(ReplyHandler* client, const QString& uuid, const QString& errorText); - void process() override; - bool hasValidData() const override; + void process() override; + bool hasValidData() const override; -private: - QString m_errorText; + private: + QString m_errorText; +}; -}; - -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp old mode 100755 new mode 100644 index 26a9c20cf..949a92596 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/client_message_factory.cpp @@ -1,6 +1,5 @@ - #include "client_message_factory.h" #include "client_connection.h" @@ -11,59 +10,54 @@ namespace LtsWebSocket { - -QJsonParseError AbstractClientMessageFactory::parseMessage(const QString &message) +QJsonParseError AbstractClientMessageFactory::parseMessage(const QString& message) { - QJsonParseError error; - QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error); + QJsonParseError error; + QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8(), &error); + + if (error.error != QJsonParseError::NoError) + return error; + + QJsonObject obj = doc.object(); + + m_data = obj.value(JsonKeys::DATA()); + m_type = obj.value(JsonKeys::TYPE()).toString(); + m_typeId = obj.value(JsonKeys::TYPEID()).toInt(); + m_uuid = obj.value(JsonKeys::UUID_()).toString(); - if (error.error != QJsonParseError::NoError) return error; - - QJsonObject obj = doc.object(); - - m_data = obj.value(JsonKeys::DATA()); - m_type = obj.value(JsonKeys::TYPE()).toString(); - m_typeId = obj.value(JsonKeys::TYPEID()).toInt(); - m_uuid = obj.value(JsonKeys::UUID_()).toString(); - - return error; } -AbstractClientMessage *AbstractClientMessageFactory::checkAttributes(ReplyHandler *client, - const QString &message) const +AbstractClientMessage* AbstractClientMessageFactory::checkAttributes(ReplyHandler* client, const QString& message) const { - if (!m_uuid.isEmpty() && !m_type.isEmpty()) - return nullptr; - if (m_uuid.isEmpty()) - { - WARNING_LOG(m_logger) << "Got message without uuid: " << message << "'"; - return new LtsWebSocket::InvalidMessage(client, QString(), QStringLiteral("Got message without uuid")); - } - WARNING_LOG(m_logger) << "Got message no type: " << message << "'"; - return new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Message has no type")); + if (!m_uuid.isEmpty() && !m_type.isEmpty()) + return nullptr; + if (m_uuid.isEmpty()) + { + WARNING_LOG(m_logger) << "Got message without uuid: " << message << "'"; + return new LtsWebSocket::InvalidMessage(client, QString(), QStringLiteral("Got message without uuid")); + } + WARNING_LOG(m_logger) << "Got message no type: " << message << "'"; + return new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Message has no type")); } -AbstractClientMessage *AbstractClientMessageFactory::checkResult(ReplyHandler *client, - const QString &message, - AbstractClientMessage *result) const +AbstractClientMessage* AbstractClientMessageFactory::checkResult(ReplyHandler* client, const QString& message, + AbstractClientMessage* result) const { - if (result == nullptr) - { - WARNING_LOG(m_logger) << "Could not parse message: " << message; - result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Invalid type")); - } + if (result == nullptr) + { + WARNING_LOG(m_logger) << "Could not parse message: " << message; + result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Invalid type")); + } - if (!result->hasValidData()) - { - WARNING_LOG(m_logger) << "Resulting JSon message has invalid data... " << message; - delete result; - result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Has invalid data part")); - } + if (!result->hasValidData()) + { + WARNING_LOG(m_logger) << "Resulting JSon message has invalid data... " << message; + delete result; + result = new LtsWebSocket::InvalidMessage(client, m_uuid, QStringLiteral("Has invalid data part")); + } - return result; + return result; } - - -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h old mode 100755 new mode 100644 index e3d241f6a..f51198864 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/connection_handler.h @@ -1,64 +1,50 @@ #pragma once -#include - -#include -#include -#include - #include "logger.h" +#include +#include +#include +#include + namespace LtsWebSocket { class MessageHandler; class ClientConnection; class ReplyMessage; - - -class ConnectionHandler - : public QObject +class ConnectionHandler : public QObject { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit ConnectionHandler(QObject* parent = nullptr); + ~ConnectionHandler(); - explicit ConnectionHandler(QObject *parent = nullptr); - ~ConnectionHandler(); + bool init(const QString& serviceName, unsigned short port); - + void sendToAllClients(ReplyMessage* message); - bool init(const QString &serviceName, unsigned short port); + unsigned short webSocketPort() + { + return m_server->serverPort(); + } - + signals: - void sendToAllClients(ReplyMessage *message); + void newTextMessageFromClient(ClientConnection* client, const QString& message); - + void clientDisconnected(ClientConnection* client); - unsigned short webSocketPort() { return m_server->serverPort(); } + void clientConnected(ClientConnection* client); -signals: - + private slots: + void onServerError(QWebSocketProtocol::CloseCode closeCode); + void onNewConnection(); - void newTextMessageFromClient(ClientConnection *client, const QString &message); - - - - void clientDisconnected(ClientConnection *client); - - - - void clientConnected(ClientConnection *client); - -private slots: - void onServerError(QWebSocketProtocol::CloseCode closeCode); - void onNewConnection(); - -private: - NGL::INGLLogger &m_logger; - QWebSocketServer *m_server; - QSet m_connections; + private: + NGL::INGLLogger& m_logger; + QWebSocketServer* m_server; + QSet m_connections; }; -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h old mode 100755 new mode 100644 index 489171ce9..9d682e9b7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/data_manager_base_dl.h @@ -1,47 +1,40 @@ #pragma once -#include -#include - #include "reply_message.h" +#include +#include + namespace LtsWebSocket { - -template -class DataManagerBaseDl +template class DataManagerBaseDl { -protected: - - - explicit DataManagerBaseDl(const std::shared_ptr &dbInterface, NGL::INGLLogger &logger) - : m_logger(logger) - , m_dbInterface(dbInterface) - {} - - - - template - ReplyMessage *toBaseDataMessageFromDb(const QString &uuid) const - { - QVector dataVec; - - if (!m_dbInterface->select(dataVec)) + protected: + explicit DataManagerBaseDl(const std::shared_ptr& dbInterface, NGL::INGLLogger& logger) + : m_logger(logger), m_dbInterface(dbInterface) { - const QString errorMessage = QStringLiteral("Error reading data from database!"); - ERROR_LOG(m_logger) << errorMessage; - ErrorMessage::ErrorData errData; - errData.errorMessage = errorMessage; - errData.uuid = uuid; - return new ErrorMessage(errData); } - return new MessageType (m_dbInterface->template toJson(dataVec), uuid); - } + template ReplyMessage* toBaseDataMessageFromDb(const QString& uuid) const + { + QVector dataVec; -protected: - std::shared_ptr m_dbInterface; -}; -} + if (!m_dbInterface->select(dataVec)) + { + const QString errorMessage = QStringLiteral("Error reading data from database!"); + ERROR_LOG(m_logger) << errorMessage; + ErrorMessage::ErrorData errData; + errData.errorMessage = errorMessage; + errData.uuid = uuid; + return new ErrorMessage(errData); + } + + return new MessageType(m_dbInterface->template toJson(dataVec), uuid); + } + + protected: + std::shared_ptr m_dbInterface; +}; +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h old mode 100755 new mode 100644 index b5c69c09c..2aa992813 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/json_keys.h @@ -7,20 +7,42 @@ namespace LtsWebSocket { - namespace JsonKeys { - - inline QString DATA() { return QStringLiteral("data"); } - inline QString UUID_() { return QStringLiteral("uuid"); } - inline QString TYPE() { return QStringLiteral("type"); } - inline QString TYPEID() { return QStringLiteral("typeId"); } - - inline QString ERROR_() { return QStringLiteral("error"); } +inline QString DATA() +{ + return QStringLiteral("data"); +} - - inline QString ERROR_MESSAGE() { return QStringLiteral("errorMessage"); } - inline QString ERROR_CLASS() { return QStringLiteral("errorClass"); } -} -} +inline QString UUID_() +{ + return QStringLiteral("uuid"); +} + +inline QString TYPE() +{ + return QStringLiteral("type"); +} + +inline QString TYPEID() +{ + return QStringLiteral("typeId"); +} + +inline QString ERROR_() +{ + return QStringLiteral("error"); +} + +inline QString ERROR_MESSAGE() +{ + return QStringLiteral("errorMessage"); +} + +inline QString ERROR_CLASS() +{ + return QStringLiteral("errorClass"); +} +} // namespace JsonKeys +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp old mode 100755 new mode 100644 index 61d789a23..a90b01bbf --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.cpp @@ -1,6 +1,5 @@ - #include "logger.h" #include @@ -8,25 +7,24 @@ namespace LtsWebSocket { -LOGGER_T getLogger(const char *name) +LOGGER_T getLogger(const char* name) { - static const char ns[] = "Lts.WebSocket."; - std::string loggerName; - const size_t len = strlen(name); - loggerName.reserve(sizeof(ns) + len); - loggerName.append(ns, sizeof(ns) - 1); - loggerName.append(name, len); + static const char ns[] = "Lts.WebSocket."; + 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(); - } + try + { + return NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger(loggerName); + } + catch (const std::exception& ex) + { + fprintf(stderr, "Error retrieving logger: %s", ex.what()); + abort(); + } } -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h old mode 100755 new mode 100644 index 64879c47e..11afe3543 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/logger.h @@ -1,18 +1,19 @@ - #pragma once #include "ltswebsocketcommon_export.h" + #include namespace LtsWebSocket { -typedef NGL::INGLLogger &LOGGER_T; +typedef NGL::INGLLogger& LOGGER_T; -LTSWEBSOCKETCOMMON_EXPORT LOGGER_T getLogger(const char *name); -inline LOGGER_T getLogger(const QString &loggerName) +LTSWEBSOCKETCOMMON_EXPORT LOGGER_T getLogger(const char* name); + +inline LOGGER_T getLogger(const QString& loggerName) { - return getLogger(loggerName.toUtf8().constData()); + return getLogger(loggerName.toUtf8().constData()); } -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp old mode 100755 new mode 100644 index 86eaec1c7..0dd076149 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.cpp @@ -2,199 +2,191 @@ #include "lts_web_socket_client.h" +#include "client_connection.h" + #include #include #include -#include "client_connection.h" - namespace LtsWebSocket { class WebSocketHelper : public QObject { - Q_OBJECT -public: - WebSocketHelper(AbstractClientMessageFactory *messageFactory, - LtsWebSocketClient *webSocketClient, - NGL::INGLLogger &logger); - ~WebSocketHelper(); + Q_OBJECT + public: + WebSocketHelper(AbstractClientMessageFactory* messageFactory, LtsWebSocketClient* webSocketClient, + NGL::INGLLogger& logger); + ~WebSocketHelper(); -public Q_SLOTS: - void doOpen(const QString &hostname, const unsigned short port); - void doClose(); - void doSendTextMessage(const QString &msg); - void onConnected(); - void onDisconnected(); - void onError(QAbstractSocket::SocketError error); - void parseMessage(const QString &message); -Q_SIGNALS: - void messageParsed(AbstractClientMessage *clientMessage); - void connected(); - void disconnected(); - void dataReceived(); - void error(QAbstractSocket::SocketError); -private: - AbstractClientMessageFactory *m_messageFactory; - LtsWebSocketClient *m_webSocketClient; - QWebSocket *m_socket; + public Q_SLOTS: + void doOpen(const QString& hostname, const unsigned short port); + void doClose(); + void doSendTextMessage(const QString& msg); + void onConnected(); + void onDisconnected(); + void onError(QAbstractSocket::SocketError error); + void parseMessage(const QString& message); + Q_SIGNALS: + void messageParsed(AbstractClientMessage* clientMessage); + void connected(); + void disconnected(); + void dataReceived(); + void error(QAbstractSocket::SocketError); + + private: + AbstractClientMessageFactory* m_messageFactory; + LtsWebSocketClient* m_webSocketClient; + QWebSocket* m_socket; }; -WebSocketHelper::WebSocketHelper(AbstractClientMessageFactory *messageFactory, - LtsWebSocketClient *webSocketClient, - NGL::INGLLogger &logger) - : QObject() - , m_messageFactory(messageFactory) - , m_webSocketClient(webSocketClient) - , m_socket(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)) - , m_logger(logger) +WebSocketHelper::WebSocketHelper(AbstractClientMessageFactory* messageFactory, LtsWebSocketClient* webSocketClient, + NGL::INGLLogger& logger) + : QObject(), m_messageFactory(messageFactory), m_webSocketClient(webSocketClient), + m_socket(new QWebSocket(QString(), QWebSocketProtocol::VersionLatest, this)), m_logger(logger) { - connect(m_socket, &QWebSocket::textMessageReceived, this, &WebSocketHelper::parseMessage); - connect(m_socket, &QWebSocket::textFrameReceived, this, &WebSocketHelper::dataReceived); - connect(m_socket, &QWebSocket::connected, this, &WebSocketHelper::onConnected); - connect(m_socket, &QWebSocket::disconnected, this, &WebSocketHelper::onDisconnected); - connect(m_socket, QOverload::of(&QWebSocket::error), this, &WebSocketHelper::error); + connect(m_socket, &QWebSocket::textMessageReceived, this, &WebSocketHelper::parseMessage); + connect(m_socket, &QWebSocket::textFrameReceived, this, &WebSocketHelper::dataReceived); + connect(m_socket, &QWebSocket::connected, this, &WebSocketHelper::onConnected); + connect(m_socket, &QWebSocket::disconnected, this, &WebSocketHelper::onDisconnected); + connect(m_socket, QOverload::of(&QWebSocket::error), this, &WebSocketHelper::error); } WebSocketHelper::~WebSocketHelper() { - m_socket->close(); - delete m_socket; + m_socket->close(); + delete m_socket; } -void WebSocketHelper::doOpen(const QString &hostname, const unsigned short port) +void WebSocketHelper::doOpen(const QString& hostname, const unsigned short port) { - const QUrl url(QStringLiteral("ws://%1:%2/").arg(hostname).arg(port)); + const QUrl url(QStringLiteral("ws://%1:%2/").arg(hostname).arg(port)); - if (m_socket->state() == QAbstractSocket::SocketState::ConnectedState) - { - if (m_socket->requestUrl() != url) - doClose(); - else + if (m_socket->state() == QAbstractSocket::SocketState::ConnectedState) { - INFO_LOG(m_logger) << "Web socket to url: " << url.toDisplayString() << " is already open."; - return; + if (m_socket->requestUrl() != url) + doClose(); + else + { + INFO_LOG(m_logger) << "Web socket to url: " << url.toDisplayString() << " is already open."; + return; + } } - } - INFO_LOG(m_logger) << "Opening web socket to url: " << url.toDisplayString(); - m_socket->open(url); + INFO_LOG(m_logger) << "Opening web socket to url: " << url.toDisplayString(); + m_socket->open(url); } void WebSocketHelper::doClose() { - INFO_LOG(m_logger) << "Closing web socket to url:" << m_socket->requestUrl().toDisplayString(); - m_socket->close(); + INFO_LOG(m_logger) << "Closing web socket to url:" << m_socket->requestUrl().toDisplayString(); + m_socket->close(); } -void WebSocketHelper::doSendTextMessage(const QString &msg) +void WebSocketHelper::doSendTextMessage(const QString& msg) { - if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) - { - ERROR_LOG(m_logger) << "Message could not be send, socket is not connected."; - return; - } - DEBUG_LOG(m_logger) << "Sending message: " << msg; - m_socket->sendTextMessage(msg); + if (!m_socket || m_socket->state() != QAbstractSocket::ConnectedState) + { + ERROR_LOG(m_logger) << "Message could not be send, socket is not connected."; + return; + } + DEBUG_LOG(m_logger) << "Sending message: " << msg; + m_socket->sendTextMessage(msg); } void WebSocketHelper::onConnected() { - INFO_LOG(m_logger) << "Connected to server url: " << m_socket->requestUrl().toDisplayString() - << " using local port: " << m_socket->localPort(); - emit connected(); + INFO_LOG(m_logger) << "Connected to server url: " << m_socket->requestUrl().toDisplayString() + << " using local port: " << m_socket->localPort(); + emit connected(); } void WebSocketHelper::onDisconnected() { - INFO_LOG(m_logger) << "Disconnected from server url: " << m_socket->requestUrl().toDisplayString(); - emit disconnected(); + INFO_LOG(m_logger) << "Disconnected from server url: " << m_socket->requestUrl().toDisplayString(); + emit disconnected(); } void WebSocketHelper::onError(QAbstractSocket::SocketError error) { - ERROR_LOG(m_logger) << "Error occured: " << error << " closing socket."; - m_socket->close(); + ERROR_LOG(m_logger) << "Error occured: " << error << " closing socket."; + m_socket->close(); } -void WebSocketHelper::parseMessage(const QString &message) +void WebSocketHelper::parseMessage(const QString& message) { - const QString pingMsg(QStringLiteral("ping")); - if (message.startsWith(pingMsg)) - { - doSendTextMessage(PongMessage(message.mid(pingMsg.size())).toJsonString()); - return; - } + const QString pingMsg(QStringLiteral("ping")); + if (message.startsWith(pingMsg)) + { + doSendTextMessage(PongMessage(message.mid(pingMsg.size())).toJsonString()); + return; + } - AbstractClientMessage *clientMessage = nullptr; - auto result = m_messageFactory->parseMessage(message); - if (QJsonParseError::NoError == result.error) - clientMessage = m_messageFactory->createMessage(m_webSocketClient, message); - else - { - WARNING_LOG(m_logger) << "Could not parse incoming message: '" << message - << "', error: " << result.errorString(); - clientMessage = new InvalidMessage(m_webSocketClient, QString(), - QStringLiteral("Got message which is not JSON conform (%1)").arg(result.errorString())); - } - if (clientMessage) - emit messageParsed(clientMessage); + AbstractClientMessage* clientMessage = nullptr; + auto result = m_messageFactory->parseMessage(message); + if (QJsonParseError::NoError == result.error) + clientMessage = m_messageFactory->createMessage(m_webSocketClient, message); + else + { + WARNING_LOG(m_logger) << "Could not parse incoming message: '" << message + << "', error: " << result.errorString(); + clientMessage = + new InvalidMessage(m_webSocketClient, QString(), + QStringLiteral("Got message which is not JSON conform (%1)").arg(result.errorString())); + } + if (clientMessage) + emit messageParsed(clientMessage); } - - - -LtsWebSocketClient::LtsWebSocketClient(AbstractClientMessageFactory *messageFactory, QObject *parent) - : QObject(parent) - , m_messageFactory(messageFactory) - , m_webSocketHelperThread(new QThread(this)) +LtsWebSocketClient::LtsWebSocketClient(AbstractClientMessageFactory* messageFactory, QObject* parent) + : QObject(parent), m_messageFactory(messageFactory), m_webSocketHelperThread(new QThread(this)) { - m_webSocketHelper = new WebSocketHelper(m_messageFactory, this, m_logger); - m_webSocketHelper->moveToThread(m_webSocketHelperThread); - m_webSocketHelperThread->start(); + m_webSocketHelper = new WebSocketHelper(m_messageFactory, this, m_logger); + m_webSocketHelper->moveToThread(m_webSocketHelperThread); + m_webSocketHelperThread->start(); - connect(m_webSocketHelper, &WebSocketHelper::connected, this, &LtsWebSocketClient::connected); - connect(m_webSocketHelper, &WebSocketHelper::disconnected, this, &LtsWebSocketClient::disconnected); - connect(m_webSocketHelper, &WebSocketHelper::dataReceived, this, &LtsWebSocketClient::dataReceived); - connect(m_webSocketHelper, &WebSocketHelper::messageParsed, this, &LtsWebSocketClient::onNewClientMessage); + connect(m_webSocketHelper, &WebSocketHelper::connected, this, &LtsWebSocketClient::connected); + connect(m_webSocketHelper, &WebSocketHelper::disconnected, this, &LtsWebSocketClient::disconnected); + connect(m_webSocketHelper, &WebSocketHelper::dataReceived, this, &LtsWebSocketClient::dataReceived); + connect(m_webSocketHelper, &WebSocketHelper::messageParsed, this, &LtsWebSocketClient::onNewClientMessage); - connect(this, &LtsWebSocketClient::onOpen, m_webSocketHelper, &WebSocketHelper::doOpen); - connect(this, &LtsWebSocketClient::onClose, m_webSocketHelper, &WebSocketHelper::doClose); - connect(this, &LtsWebSocketClient::onSendTextMessage, m_webSocketHelper, &WebSocketHelper::doSendTextMessage); + connect(this, &LtsWebSocketClient::onOpen, m_webSocketHelper, &WebSocketHelper::doOpen); + connect(this, &LtsWebSocketClient::onClose, m_webSocketHelper, &WebSocketHelper::doClose); + connect(this, &LtsWebSocketClient::onSendTextMessage, m_webSocketHelper, &WebSocketHelper::doSendTextMessage); } LtsWebSocketClient::~LtsWebSocketClient() { - m_webSocketHelper->disconnect(this); - m_webSocketHelperThread->quit(); - m_webSocketHelperThread->wait(); - delete m_webSocketHelper; + m_webSocketHelper->disconnect(this); + m_webSocketHelperThread->quit(); + m_webSocketHelperThread->wait(); + delete m_webSocketHelper; } -void LtsWebSocketClient::open(const QString &hostname, const unsigned short port) +void LtsWebSocketClient::open(const QString& hostname, const unsigned short port) { - emit onOpen(hostname, port); + emit onOpen(hostname, port); } void LtsWebSocketClient::close() { - emit onClose(); + emit onClose(); } -void LtsWebSocketClient::addReply(ReplyMessage *message) +void LtsWebSocketClient::addReply(ReplyMessage* message) { - const QString msg(message->toJsonString()); - emit onSendTextMessage(msg); - delete message; + const QString msg(message->toJsonString()); + emit onSendTextMessage(msg); + delete message; } -void LtsWebSocketClient::onNewClientMessage(AbstractClientMessage *clientMessage) +void LtsWebSocketClient::onNewClientMessage(AbstractClientMessage* clientMessage) { - if (!clientMessage) - return; - clientMessage->process(); - delete clientMessage; + if (!clientMessage) + return; + clientMessage->process(); + delete clientMessage; } -} +} // namespace LtsWebSocket #include "lts_web_socket_client.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h old mode 100755 new mode 100644 index 00fa9e8a1..5597ce95b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_client.h @@ -2,65 +2,51 @@ #pragma once -#include -#include - -#include "ltswebsocketclient_export.h" #include "client_message_factory.h" #include "logger.h" +#include "ltswebsocketclient_export.h" +#include +#include class QThread; + namespace LtsWebSocket { class WebSocketHelper; - - -class LTSWEBSOCKETCLIENT_EXPORT LtsWebSocketClient - : public QObject - , public ReplyHandler +class LTSWEBSOCKETCLIENT_EXPORT LtsWebSocketClient : public QObject, public ReplyHandler { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit LtsWebSocketClient(AbstractClientMessageFactory* messageFactory, QObject* parent = nullptr); + ~LtsWebSocketClient(); - explicit LtsWebSocketClient(AbstractClientMessageFactory *messageFactory, QObject *parent = nullptr); - ~LtsWebSocketClient(); + void open(const QString& hostname, const unsigned short port); - + void close(); - void open(const QString &hostname, const unsigned short port); + void addReply(ReplyMessage* message) override; - + signals: + void connected(); + void disconnected(); + void dataReceived(); - void close(); + private slots: - + void onNewClientMessage(AbstractClientMessage* clientMessage); - void addReply(ReplyMessage *message) override; + signals: + void onOpen(const QString& hostname, const unsigned short port); + void onClose(); + void onSendTextMessage(const QString& msg); -signals: - void connected(); - void disconnected(); - void dataReceived(); + private: + NGL::INGLLogger& m_logger; + AbstractClientMessageFactory* m_messageFactory; -private slots: - - - void onNewClientMessage(AbstractClientMessage *clientMessage); - -signals: - void onOpen(const QString &hostname, const unsigned short port); - void onClose(); - void onSendTextMessage(const QString &msg); - -private: - -NGL::INGLLogger &m_logger; - AbstractClientMessageFactory *m_messageFactory; - - QThread *m_webSocketHelperThread; - WebSocketHelper *m_webSocketHelper; + QThread* m_webSocketHelperThread; + WebSocketHelper* m_webSocketHelper; }; -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp old mode 100755 new mode 100644 index 9d3351f00..c72492b80 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.cpp @@ -2,117 +2,120 @@ #include "lts_web_socket_server.h" -#include "connection_handler.h" #include "client_connection.h" +#include "connection_handler.h" + #include namespace LtsWebSocket { -LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory *messageFactory, QObject *parent) - : QObject(parent) - , m_queueTimer(new QTimer(this)) - , m_messageFactory(messageFactory) - , m_connectionHandler(nullptr) +LtsWebSocketServer::LtsWebSocketServer(AbstractClientMessageFactory* messageFactory, QObject* parent) + : QObject(parent), m_queueTimer(new QTimer(this)), m_messageFactory(messageFactory), m_connectionHandler(nullptr) { - connect(m_queueTimer, &QTimer::timeout, - this, &LtsWebSocketServer::onQueueTimerTimeout); + connect(m_queueTimer, &QTimer::timeout, this, &LtsWebSocketServer::onQueueTimerTimeout); - m_queueTimer->setSingleShot(true); + m_queueTimer->setSingleShot(true); } LtsWebSocketServer::~LtsWebSocketServer() = default; -bool LtsWebSocketServer::init(const QString &serviceName, const unsigned short port) +bool LtsWebSocketServer::init(const QString& serviceName, const unsigned short port) { - m_connectionHandler.reset(new ConnectionHandler(this)); + m_connectionHandler.reset(new ConnectionHandler(this)); - if (!m_connectionHandler->init(serviceName, port)) - { - ERROR_LOG(m_logger) << "Could not init m_connectionHandler with servicename: " << serviceName << ((port == 0) ? QStringLiteral(" random port") : QStringLiteral(" port: ") + QString::number(port)); - m_connectionHandler.reset(); - return false; - } + if (!m_connectionHandler->init(serviceName, port)) + { + ERROR_LOG(m_logger) << "Could not init m_connectionHandler with servicename: " << serviceName + << ((port == 0) ? QStringLiteral(" random port") + : QStringLiteral(" port: ") + QString::number(port)); + m_connectionHandler.reset(); + return false; + } - connect(m_connectionHandler.get(), &ConnectionHandler::newTextMessageFromClient, this, &LtsWebSocketServer::onNewTextMessage); - connect(m_connectionHandler.get(), &ConnectionHandler::clientDisconnected, this, &LtsWebSocketServer::clientDisconnected); - connect(m_connectionHandler.get(), &ConnectionHandler::clientConnected, this, &LtsWebSocketServer::clientConnected); + connect(m_connectionHandler.get(), &ConnectionHandler::newTextMessageFromClient, this, + &LtsWebSocketServer::onNewTextMessage); + connect(m_connectionHandler.get(), &ConnectionHandler::clientDisconnected, this, + &LtsWebSocketServer::clientDisconnected); + connect(m_connectionHandler.get(), &ConnectionHandler::clientConnected, this, &LtsWebSocketServer::clientConnected); - m_queueTimer->start(m_messageDelay); + m_queueTimer->start(m_messageDelay); - return true; + return true; } -bool LtsWebSocketServer::init(const QString &serviceName, const QPair &portRange) +bool LtsWebSocketServer::init(const QString& serviceName, const QPair& portRange) { - if (portRange.first < 1025 || portRange.first > portRange.second) + if (portRange.first < 1025 || portRange.first > portRange.second) + return init(serviceName); + + for (quint16 currentPort = portRange.first; currentPort <= portRange.second; ++currentPort) + { + if (init(serviceName, currentPort)) + return true; + } + return init(serviceName); - - for (quint16 currentPort = portRange.first; currentPort <= portRange.second; ++ currentPort) - { - if (init(serviceName, currentPort)) - return true; - } - - return init(serviceName); } -void LtsWebSocketServer::sendToAllClients(ReplyMessage *message) +void LtsWebSocketServer::sendToAllClients(ReplyMessage* message) { - DEBUG_LOG(m_logger) << "Sending message to all clients: " << message->toJsonString(); - m_connectionHandler->sendToAllClients(message); + DEBUG_LOG(m_logger) << "Sending message to all clients: " << message->toJsonString(); + m_connectionHandler->sendToAllClients(message); } unsigned short LtsWebSocketServer::webSocketPort() const { - return m_connectionHandler->webSocketPort(); + return m_connectionHandler->webSocketPort(); } void LtsWebSocketServer::setMessageDelay(qint32 delay) { - m_messageDelay = delay; + m_messageDelay = delay; } -void LtsWebSocketServer::onNewTextMessage(ReplyHandler *client, const QString &message) +void LtsWebSocketServer::onNewTextMessage(ReplyHandler* client, const QString& message) { - const QString pingMsg(QStringLiteral("ping")); - if (message.startsWith(pingMsg)) - { - client->addReply(new PongMessage(message.mid(pingMsg.size()))); - return; - } - DEBUG_LOG(m_logger) << "Got new message: " << message; + const QString pingMsg(QStringLiteral("ping")); + if (message.startsWith(pingMsg)) + { + client->addReply(new PongMessage(message.mid(pingMsg.size()))); + return; + } + DEBUG_LOG(m_logger) << "Got new message: " << message; - m_messageQueue.append({client, message}); + m_messageQueue.append({client, message}); - if (!m_queueTimer->isActive()) - m_queueTimer->start(m_messageDelay); + if (!m_queueTimer->isActive()) + m_queueTimer->start(m_messageDelay); } void LtsWebSocketServer::onQueueTimerTimeout() { - if (m_messageQueue.isEmpty()) - return; + if (m_messageQueue.isEmpty()) + return; - MessageCredentials credentials = m_messageQueue.takeFirst(); - AbstractClientMessage *clientMessage = nullptr; - auto result = m_messageFactory->parseMessage(credentials.message); + MessageCredentials credentials = m_messageQueue.takeFirst(); + AbstractClientMessage* clientMessage = nullptr; + auto result = m_messageFactory->parseMessage(credentials.message); - if (QJsonParseError::NoError == result.error) - clientMessage = m_messageFactory->createMessage(credentials.client, credentials.message); - else - { - WARNING_LOG(m_logger) << "Could not parse incoming message: '" << credentials.message << "', error: " << result.errorString(); + if (QJsonParseError::NoError == result.error) + clientMessage = m_messageFactory->createMessage(credentials.client, credentials.message); + else + { + WARNING_LOG(m_logger) << "Could not parse incoming message: '" << credentials.message + << "', error: " << result.errorString(); - clientMessage = new InvalidMessage(credentials.client, QString(), QStringLiteral("Got message which is not JSON conform")); - } + clientMessage = + new InvalidMessage(credentials.client, QString(), QStringLiteral("Got message which is not JSON conform")); + } - if (clientMessage) - clientMessage->process(); + if (clientMessage) + clientMessage->process(); - delete clientMessage; + delete clientMessage; - m_queueTimer->start(m_messageDelay); + m_queueTimer->start(m_messageDelay); } -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h old mode 100755 new mode 100644 index ce944cfd4..cda8f2e88 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/lts_web_socket_server.h @@ -1,15 +1,14 @@ #pragma once -#include - -#include - -#include "ltswebsocketserver_export.h" #include "client_message_factory.h" #include "logger.h" -#include +#include "ltswebsocketserver_export.h" + +#include #include +#include +#include class QTimer; @@ -18,72 +17,48 @@ namespace LtsWebSocket class ConnectionHandler; class ClientConnection; - - -class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer - : public QObject +class LTSWEBSOCKETSERVER_EXPORT LtsWebSocketServer : public QObject { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit LtsWebSocketServer(AbstractClientMessageFactory* messageFactory, QObject* parent = nullptr); + virtual ~LtsWebSocketServer(); - explicit LtsWebSocketServer(AbstractClientMessageFactory *messageFactory, QObject *parent = nullptr); - virtual ~LtsWebSocketServer(); + bool init(const QString& serviceName, const unsigned short port = 0); - + bool init(const QString& serviceName, const QPair& portRange); - bool init(const QString &serviceName, const unsigned short port = 0); + void sendToAllClients(ReplyMessage* message); - + unsigned short webSocketPort() const; - bool init(const QString &serviceName, const QPair &portRange); + void setMessageDelay(qint32 delay); + signals: - + void clientDisconnected(ClientConnection* client); - void sendToAllClients(ReplyMessage *message); + void clientConnected(ClientConnection* client); - + private slots: - unsigned short webSocketPort() const; + void onNewTextMessage(ReplyHandler* client, const QString& message); - + void onQueueTimerTimeout(); - void setMessageDelay(qint32 delay); -signals: - + private: + struct MessageCredentials + { + ReplyHandler* client{nullptr}; + QString message; - void clientDisconnected(ClientConnection *client); + MessageCredentials(ReplyHandler* client, const QString& message) : client(client), message(message) {} + }; - - - void clientConnected(ClientConnection *client); - -private slots: - - - void onNewTextMessage(ReplyHandler *client, const QString &message); - - - - void onQueueTimerTimeout(); - -private: - struct MessageCredentials - { - ReplyHandler *client {nullptr}; - QString message; - - MessageCredentials(ReplyHandler *client, const QString &message) - : client(client) - , message(message) - {} - }; - - QQueue m_messageQueue; - QTimer *m_queueTimer { nullptr }; - AbstractClientMessageFactory *m_messageFactory { nullptr }; - std::unique_ptr m_connectionHandler; - qint32 m_messageDelay { 0 }; - LOGGER_T m_logger; + QQueue m_messageQueue; + QTimer* m_queueTimer{nullptr}; + AbstractClientMessageFactory* m_messageFactory{nullptr}; + std::unique_ptr m_connectionHandler; + qint32 m_messageDelay{0}; + LOGGER_T m_logger; }; -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h old mode 100755 new mode 100644 index 5c0931cae..67aa3bf06 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/message_transmitter.h @@ -1,17 +1,12 @@ - namespace LtsWebSocketServer { class ReplyMessage; - - class MessageHandler { -public: - - - virtual void addMessage(ReplyMessage *message) = 0; + public: + virtual void addMessage(ReplyMessage* message) = 0; }; -} +} // namespace LtsWebSocketServer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp old mode 100755 new mode 100644 index 842e9134c..57908fc9a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.cpp @@ -1,6 +1,5 @@ - #include "reply_message.h" #include "json_keys.h" @@ -10,32 +9,26 @@ namespace LtsWebSocket { - QString ReplyMessage::toJsonString() const { - return QString::fromUtf8(QJsonDocument(m_jsonRepresentation).toJson(QJsonDocument::Compact)); + return QString::fromUtf8(QJsonDocument(m_jsonRepresentation).toJson(QJsonDocument::Compact)); } -ReplyMessage::ReplyMessage(const QString &type, const int typeId, const QString &uuid) +ReplyMessage::ReplyMessage(const QString& type, const int typeId, const QString& uuid) { - m_jsonRepresentation.insert(JsonKeys::TYPE(), type); - m_jsonRepresentation.insert(JsonKeys::TYPEID(), typeId); + m_jsonRepresentation.insert(JsonKeys::TYPE(), type); + m_jsonRepresentation.insert(JsonKeys::TYPEID(), typeId); - if (!uuid.isEmpty()) - m_jsonRepresentation.insert(JsonKeys::UUID_(), uuid); + if (!uuid.isEmpty()) + m_jsonRepresentation.insert(JsonKeys::UUID_(), uuid); } - - -ErrorMessage::ErrorMessage(const ErrorMessage::ErrorData &data) - : ReplyMessage(JsonKeys::ERROR_(), -1, QUuid::createUuid().toString()) +ErrorMessage::ErrorMessage(const ErrorMessage::ErrorData& data) + : ReplyMessage(JsonKeys::ERROR_(), -1, QUuid::createUuid().toString()) { - m_jsonRepresentation.insert(JsonKeys::DATA(), - QJsonObject({{JsonKeys::UUID_(), data.uuid}, - {JsonKeys::ERROR_CLASS(), data.errorClass}, - {JsonKeys::ERROR_MESSAGE(), data.errorMessage} - })); + m_jsonRepresentation.insert(JsonKeys::DATA(), QJsonObject({{JsonKeys::UUID_(), data.uuid}, + {JsonKeys::ERROR_CLASS(), data.errorClass}, + {JsonKeys::ERROR_MESSAGE(), data.errorMessage}})); } - -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h old mode 100755 new mode 100644 index 8cff9c00c..6b6f4354a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWebSocket/reply_message.h @@ -4,67 +4,52 @@ #include "ltswebsocketcommon_export.h" -#include #include #include +#include namespace LtsWebSocket { - - class LTSWEBSOCKETCOMMON_EXPORT ReplyMessage { -public: - + public: + virtual ~ReplyMessage() = default; - virtual ~ReplyMessage() = default; + virtual QString toJsonString() const; - - - virtual QString toJsonString() const; - - QJsonObject json() const { return m_jsonRepresentation; } - -protected: - ReplyMessage() = default; - ReplyMessage(const QString &type, const int typeId, const QString &uuid); - -protected: - QJsonObject m_jsonRepresentation; -}; + QJsonObject json() const + { + return m_jsonRepresentation; + } + protected: + ReplyMessage() = default; + ReplyMessage(const QString& type, const int typeId, const QString& uuid); + protected: + QJsonObject m_jsonRepresentation; +}; class LTSWEBSOCKETCOMMON_EXPORT ReplyHandler { -public: - virtual ~ReplyHandler() = default; - + public: + virtual ~ReplyHandler() = default; - virtual void addReply(ReplyMessage *message) = 0; -}; + virtual void addReply(ReplyMessage* message) = 0; +}; - - - - -class LTSWEBSOCKETCOMMON_EXPORT ErrorMessage final - : public ReplyMessage +class LTSWEBSOCKETCOMMON_EXPORT ErrorMessage final : public ReplyMessage { -public: - + public: + struct ErrorData + { + int errorClass = 0; + QString uuid; + QString errorMessage; + }; - struct ErrorData - { - int errorClass = 0; - QString uuid; - QString errorMessage; - }; + explicit ErrorMessage(const ErrorData& data); +}; - - - explicit ErrorMessage(const ErrorData &data); -}; - -} +} // namespace LtsWebSocket diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp old mode 100755 new mode 100644 index 5773b96ff..73d8de27e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.cpp @@ -1,131 +1,122 @@ - #include "lts_image_cropper.h" + +#include #include #include -#include namespace LtsWidgets { -LtsImageCropper::LtsImageCropper(QWidget *parent, const QSize &size, const QPixmap &pixmap) - : QGraphicsView(parent) - , m_scene(new QGraphicsScene(this)) - , m_maxScale(2.0f) - , m_multiplier(1.0f) +LtsImageCropper::LtsImageCropper(QWidget* parent, const QSize& size, const QPixmap& pixmap) + : QGraphicsView(parent), m_scene(new QGraphicsScene(this)), m_maxScale(2.0f), m_multiplier(1.0f) { - if(!size.isNull()) - setFixedSize(size); + if (!size.isNull()) + setFixedSize(size); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setFrameStyle(QFrame::NoFrame); - setDragMode(QGraphicsView::ScrollHandDrag); - setTransformationAnchor(QGraphicsView::AnchorViewCenter); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setFrameStyle(QFrame::NoFrame); + setDragMode(QGraphicsView::ScrollHandDrag); + setTransformationAnchor(QGraphicsView::AnchorViewCenter); - m_scene->setBackgroundBrush(Qt::Dense6Pattern); - setScene(m_scene); + m_scene->setBackgroundBrush(Qt::Dense6Pattern); + setScene(m_scene); - setPixmap(pixmap); + setPixmap(pixmap); } LtsImageCropper::~LtsImageCropper() { - delete m_pixmapItem; + delete m_pixmapItem; } -void LtsImageCropper::setPixmap(const QPixmap &pixmap) +void LtsImageCropper::setPixmap(const QPixmap& pixmap) { - if(pixmap.isNull()) - return; + if (pixmap.isNull()) + return; - delete m_pixmapItem; + delete m_pixmapItem; - m_pixmapItem = new QGraphicsPixmapItem(pixmap); - m_scene->addItem(m_pixmapItem); + m_pixmapItem = new QGraphicsPixmapItem(pixmap); + m_scene->addItem(m_pixmapItem); - setTransform(QTransform()); - m_currentZoom = 1.0; + setTransform(QTransform()); + m_currentZoom = 1.0; - - double sx = static_cast(size().height()) / pixmap.height(); - double sy = static_cast(size().width()) / pixmap.width(); - if(sx > 1 ) - scale(sx,sx); - if(sy > 1) - scale(sy,sy); + double sx = static_cast(size().height()) / pixmap.height(); + double sy = static_cast(size().width()) / pixmap.width(); + if (sx > 1) + scale(sx, sx); + if (sy > 1) + scale(sy, sy); - - double ratioWidth = 1.0 * size().width() / pixmap.width(); - double ratioHeight = 1.0 * size().height() / pixmap.height(); - m_minScale = qMax(ratioHeight,ratioWidth); + double ratioWidth = 1.0 * size().width() / pixmap.width(); + double ratioHeight = 1.0 * size().height() / pixmap.height(); + m_minScale = qMax(ratioHeight, ratioWidth); - calculateScaleStep(); + calculateScaleStep(); - - m_scene->setSceneRect(pixmap.rect()); - centerOn(m_scene->sceneRect().center()); + m_scene->setSceneRect(pixmap.rect()); + centerOn(m_scene->sceneRect().center()); } -void LtsImageCropper::setImage(const QImage &image) +void LtsImageCropper::setImage(const QImage& image) { - setPixmap(QPixmap::fromImage(image)); + setPixmap(QPixmap::fromImage(image)); } void LtsImageCropper::setMultiplier(double multiplier) { - m_multiplier = multiplier; - calculateScaleStep(); + m_multiplier = multiplier; + calculateScaleStep(); } void LtsImageCropper::calculateScaleStep() { - m_stepScale = (m_maxScale - m_minScale) / 100.0; + m_stepScale = (m_maxScale - m_minScale) / 100.0; } QImage LtsImageCropper::image() { - return grab().toImage(); + return grab().toImage(); } -void LtsImageCropper::wheelEvent(QWheelEvent *event) +void LtsImageCropper::wheelEvent(QWheelEvent* event) { - if(!m_pixmapItem) - return; + if (!m_pixmapItem) + return; - auto value = event->pixelDelta(); - if(value.isNull()) - value = event->angleDelta() / 15.0; + auto value = event->pixelDelta(); + if (value.isNull()) + value = event->angleDelta() / 15.0; - - double scrollZoom = m_stepScale * value.y() * m_multiplier / 8.0; + double scrollZoom = m_stepScale * value.y() * m_multiplier / 8.0; - m_currentZoom += scrollZoom; + m_currentZoom += scrollZoom; - if(m_currentZoom > m_maxScale) - m_currentZoom = m_maxScale; - else if (m_currentZoom < m_minScale) - m_currentZoom = m_minScale; + if (m_currentZoom > m_maxScale) + m_currentZoom = m_maxScale; + else if (m_currentZoom < m_minScale) + m_currentZoom = m_minScale; - - setTransform(QTransform(m_currentZoom, transform().m12(), transform().m13(), - transform().m21(), m_currentZoom, transform().m23(), - transform().m31(), transform().m32(), 1)); + setTransform(QTransform(m_currentZoom, transform().m12(), transform().m13(), transform().m21(), m_currentZoom, + transform().m23(), transform().m31(), transform().m32(), 1)); } -void LtsImageCropper::mousePressEvent(QMouseEvent *event) +void LtsImageCropper::mousePressEvent(QMouseEvent* event) { - QApplication::setOverrideCursor(Qt::DragMoveCursor); - update(); - QGraphicsView::mousePressEvent(event); + QApplication::setOverrideCursor(Qt::DragMoveCursor); + update(); + QGraphicsView::mousePressEvent(event); } -void LtsImageCropper::mouseReleaseEvent(QMouseEvent *event) +void LtsImageCropper::mouseReleaseEvent(QMouseEvent* event) { - QApplication::restoreOverrideCursor(); - update(); - QGraphicsView::mouseReleaseEvent(event); + QApplication::restoreOverrideCursor(); + update(); + QGraphicsView::mouseReleaseEvent(event); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h old mode 100755 new mode 100644 index 30b365843..490b68181 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/LtsImageCropper/lts_image_cropper.h @@ -1,81 +1,71 @@ - #pragma once -#include - #include "ltswidgets_export.h" + #include +#include namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsImageCropper : public QGraphicsView { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) - Q_PROPERTY(double multiplier READ multiplier WRITE setMultiplier) - Q_PROPERTY(double maxZoom READ maxZoom WRITE setMaxZoom) + Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) + Q_PROPERTY(double multiplier READ multiplier WRITE setMultiplier) + Q_PROPERTY(double maxZoom READ maxZoom WRITE setMaxZoom) -public: - + public: + LtsImageCropper(QWidget* parent = nullptr, const QSize& size = {}, const QPixmap& pixmap = {}); + ~LtsImageCropper(); - LtsImageCropper(QWidget *parent = nullptr, const QSize &size = {} , const QPixmap &pixmap = {}); - ~LtsImageCropper(); + void setPixmap(const QPixmap& pixmap); - + void setImage(const QImage& image); - void setPixmap(const QPixmap &pixmap); + void setMultiplier(double multiplier); - + void setMaxZoom(double maxZoom) + { + m_maxScale = maxZoom; + } - void setImage(const QImage &image); + QPixmap pixmap() + { + return grab(); + } - + QImage image(); - void setMultiplier(double multiplier); + double multiplier() const + { + return m_multiplier; + } - + double maxZoom() const + { + return m_maxScale; + } - void setMaxZoom(double maxZoom) { m_maxScale = maxZoom; } + private: + QGraphicsScene* m_scene = nullptr; + QGraphicsPixmapItem* m_pixmapItem = nullptr; - + double m_currentZoom; + double m_minScale; + double m_maxScale; + double m_stepScale; + double m_multiplier; - QPixmap pixmap() { return grab(); } - - - - QImage image(); - - - - double multiplier() const { return m_multiplier; } - - - - double maxZoom() const { return m_maxScale; } - -private: - QGraphicsScene *m_scene = nullptr; - QGraphicsPixmapItem *m_pixmapItem = nullptr; - - double m_currentZoom; - double m_minScale; - double m_maxScale; - double m_stepScale; - double m_multiplier; - - void calculateScaleStep(); - -protected: - void wheelEvent(QWheelEvent *event) override; - void mousePressEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; + void calculateScaleStep(); + protected: + void wheelEvent(QWheelEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h old mode 100755 new mode 100644 index 86510be1c..ea80bb90c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_sequence_widget.h @@ -1,90 +1,59 @@ #ifndef LTS_ABSTRACT_SEQUENCE_WIDGET_H #define LTS_ABSTRACT_SEQUENCE_WIDGET_H - - - #pragma once -#include - +#include "ltswidgets_export.h" #include #include -#include "ltswidgets_export.h" +#include class QToolButton; + namespace LtsWidgets { - class LTSWIDGETS_EXPORT LtsAbstractSequenceWidget : public QGroupBox { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit LtsAbstractSequenceWidget(QWidget* parent = nullptr, const bool& readOnly = false); + ~LtsAbstractSequenceWidget(); - explicit LtsAbstractSequenceWidget(QWidget *parent = nullptr, const bool &readOnly = false); + virtual void addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible = true); - ~LtsAbstractSequenceWidget(); + virtual void getValue(QWidget* contentType, const QString& findObjectName) const; - + virtual void setMemberCount(int count); - virtual void addWidget(QWidget* widget, bool isReadOnly, bool isButtonVisible = true); - + virtual uint32_t getMemberCount() const; - virtual void getValue(QWidget *contentType, - const QString &findObjectName) const; + virtual int getMemberlistSize(); - + protected: + virtual QToolButton* pbAddMember() const; - virtual void setMemberCount(int count); + virtual QString getObjectName(int index) const; - + virtual void setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, + bool isButtonVisible = true) = 0; - virtual uint32_t getMemberCount() const; + signals: - + void addMember(); - virtual int getMemberlistSize(); + private slots: + virtual void addMemberWidget(QWidget* member, bool isReadOnly, bool isButtonVisible = true); -protected: - - - - virtual QToolButton *pbAddMember() const; - - - - - virtual QString getObjectName(int index) const; - - - - virtual void setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible = true) = 0; - -signals: - - - void addMember(); - -private slots: - - - virtual void addMemberWidget(QWidget *member, bool isReadOnly, bool isButtonVisible = true); - - - - virtual void deleteMemberWidget(QObject *member); - -private: - bool m_readOnly; - QToolButton *m_pbAddMember = nullptr; - QList m_memberList; - + virtual void deleteMemberWidget(QObject* member); + private: + bool m_readOnly; + QToolButton* m_pbAddMember = nullptr; + QList m_memberList; }; -} +} // namespace LtsWidgets -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h old mode 100755 new mode 100644 index dd0366de3..d10dfc7cd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_abstract_table_model.h @@ -1,286 +1,264 @@ - #pragma once #include "lts_base.h" #include - -#include #include - -#include +#include #include - +#include namespace LtsWidgets { -template -class LtsAbstractTableModel : public QAbstractTableModel +template class LtsAbstractTableModel : public QAbstractTableModel { -public: - LtsAbstractTableModel(const QVector &header, QObject *parent) - : QAbstractTableModel(parent) - , m_vecColumns(header) - {} - - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override - { - if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section>= 0 && section < m_vecColumns.size()) - return m_vecColumns[section]; - - return QAbstractTableModel::headerData(section, orientation, role); - } - - bool isEmpty(const QModelIndex &parent = QModelIndex()) - { - return parent.isValid() ? true : m_vecData.isEmpty(); - } - - int rowCount(const QModelIndex &parent = QModelIndex()) const override - { - return parent.isValid() ? 0 : m_vecData.size(); - } - - int columnCount(const QModelIndex &parent = QModelIndex()) const override - { - return parent.isValid() ? 0 : m_vecColumns.size(); - } - - void clear() - { - beginResetModel(); - m_vecData.clear(); - endResetModel(); - } - - bool indexIsValid(const QModelIndex &idx) const - { - if (!idx.isValid()) - return false; - if (idx.row() < 0 || idx.row() >= m_vecData.size()) - return false; - return true; - } - - virtual bool removeRow(int row) - { - return removeRows(row, 1); - } - - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override - { - if (parent.isValid()) - return false; - - if (row < 0 || row >= m_vecData.size()) - return false; - - int range = std::min(row + count, m_vecData.size()); - - beginRemoveRows(QModelIndex(), row, range - 1); - m_vecData.erase(m_vecData.begin() + row, m_vecData.begin() + range); - endRemoveRows(); - - return true; - } - - virtual bool insertRow(const T &item) - { - if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) - return false; - beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); - m_vecData.append(item); - endInsertRows(); - return true; - } - - template - void insertRows(const CONT &items) - { - if (items.isEmpty()) - return; - const int cntBefore = m_vecData.size(); - for (const auto &item : items) - { - if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) - continue; - m_vecData += item; - } - const int cntAfter = m_vecData.size(); - if (cntBefore == cntAfter) - return; - beginInsertRows(QModelIndex(), cntBefore, cntAfter - 1); - endInsertRows(); - } - - void setData(const QVector &vecData) - { - clear(); - insertRows(vecData); - } - - - - void update() - { - if (!m_vecData.isEmpty()) - emit dataChanged(index(0, 0), index(m_vecData.size() - 1, columnCount() - 1)); - } - - T getRowData(int row) const - { - if (row < 0 || row >= m_vecData.size()) - return T(); - return m_vecData.at(row); - } - - bool setRowData(int row, const T &data) - { - if (row < 0 || row >= m_vecData.size()) - return false; - - m_vecData[row] = data; - emit dataChanged(index(row, 0), index(row, columnCount() - 1)); - return true; - } - - QModelIndex findIndexForId(int id, int column = 0) const - { - const int row = findRowForId(id); - if (row < 0) - return QModelIndex(); - return index(row, column); - } - - int getId(const QModelIndex &mi) const - { - if (!indexIsValid(mi)) - return -1; - return getIdInternal(m_vecData.at(mi.row())); - } - -protected: - template - class HasId - { - template - static std::true_type testSignature(const int &(CLS::*)() const); - template - static std::true_type testSignature(int (CLS::*)() const); - - template - static decltype(testSignature(&CLS::id)) test(std::nullptr_t); - - template - static std::false_type test(...); - public: - using type = decltype(test(nullptr)); - static const bool value = type::value; - }; - - - template ::value, int>::type = 0> - int getIdInternal(const F &data) const - { - return data.id(); - } - - - virtual int getId(const T &data) const - { - Q_ASSERT(false); - Q_UNUSED(data); - return -1; - } - - template < typename F = T, typename std::enable_if < !HasId::value, int>::type = 0> - int getIdInternal(const F &data) const - { - return getId(data); - } - - template - class HasIsDeleted - { - template - static std::true_type testSignature(const bool &(CLS::*)() const); - template - static std::true_type testSignature(bool (CLS::*)() const); - - template - static decltype(testSignature(&CLS::isDeleted)) test(std::nullptr_t); - - template - static std::false_type test(...); - - public: - using type = decltype(test(nullptr)); - static const bool value = type::value; - }; - - template ::value, int>::type = 0> - bool isDeletedInternal(const F &data) const - { - return data.isDeleted(); - } - - virtual int isDeleted(const T &data) const - { - Q_UNUSED(data); - return false; - } - template < typename F = T, typename std::enable_if < !HasIsDeleted::value, int>::type = 0> - bool isDeletedInternal(const F &data) const - { - return isDeleted(data); - } - - - virtual bool isFiltered(const T &data, DataModification modType) const - { - Q_UNUSED(data); - Q_UNUSED(modType); - return false; - } - - - virtual bool onDataChanged(const T &data, DataModification modType) - { - if (isFiltered(data, modType)) - return false; - - const int id = getIdInternal(data); - const int row = findRowForId(id); - - - if (modType == DataModification::eRemoved || isDeletedInternal(data)) + LtsAbstractTableModel(const QVector& header, QObject* parent) + : QAbstractTableModel(parent), m_vecColumns(header) { - if (row >= 0) - return removeRow(row); - return false; } - if (modType == DataModification::eAdded && row < 0) - return insertRow(data); - - return setRowData(row, data); - } - - int findRowForId(int id) const - { - for (int i = 0; i < m_vecData.size(); ++i) + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override { - if (getIdInternal(m_vecData.at(i)) == id) - return i; - } - return -1; - } + if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section >= 0 && section < m_vecColumns.size()) + return m_vecColumns[section]; - QVector m_vecData; - QVector m_vecColumns; + return QAbstractTableModel::headerData(section, orientation, role); + } + + bool isEmpty(const QModelIndex& parent = QModelIndex()) + { + return parent.isValid() ? true : m_vecData.isEmpty(); + } + + int rowCount(const QModelIndex& parent = QModelIndex()) const override + { + return parent.isValid() ? 0 : m_vecData.size(); + } + + int columnCount(const QModelIndex& parent = QModelIndex()) const override + { + return parent.isValid() ? 0 : m_vecColumns.size(); + } + + void clear() + { + beginResetModel(); + m_vecData.clear(); + endResetModel(); + } + + bool indexIsValid(const QModelIndex& idx) const + { + if (!idx.isValid()) + return false; + if (idx.row() < 0 || idx.row() >= m_vecData.size()) + return false; + return true; + } + + virtual bool removeRow(int row) + { + return removeRows(row, 1); + } + + bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override + { + if (parent.isValid()) + return false; + + if (row < 0 || row >= m_vecData.size()) + return false; + + int range = std::min(row + count, m_vecData.size()); + + beginRemoveRows(QModelIndex(), row, range - 1); + m_vecData.erase(m_vecData.begin() + row, m_vecData.begin() + range); + endRemoveRows(); + + return true; + } + + virtual bool insertRow(const T& item) + { + if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) + return false; + beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); + m_vecData.append(item); + endInsertRows(); + return true; + } + + template void insertRows(const CONT& items) + { + if (items.isEmpty()) + return; + const int cntBefore = m_vecData.size(); + for (const auto& item : items) + { + if (isFiltered(item, DataModification::eAdded) || isDeletedInternal(item)) + continue; + m_vecData += item; + } + const int cntAfter = m_vecData.size(); + if (cntBefore == cntAfter) + return; + beginInsertRows(QModelIndex(), cntBefore, cntAfter - 1); + endInsertRows(); + } + + void setData(const QVector& vecData) + { + clear(); + insertRows(vecData); + } + + void update() + { + if (!m_vecData.isEmpty()) + emit dataChanged(index(0, 0), index(m_vecData.size() - 1, columnCount() - 1)); + } + + T getRowData(int row) const + { + if (row < 0 || row >= m_vecData.size()) + return T(); + return m_vecData.at(row); + } + + bool setRowData(int row, const T& data) + { + if (row < 0 || row >= m_vecData.size()) + return false; + + m_vecData[row] = data; + emit dataChanged(index(row, 0), index(row, columnCount() - 1)); + return true; + } + + QModelIndex findIndexForId(int id, int column = 0) const + { + const int row = findRowForId(id); + if (row < 0) + return QModelIndex(); + return index(row, column); + } + + int getId(const QModelIndex& mi) const + { + if (!indexIsValid(mi)) + return -1; + return getIdInternal(m_vecData.at(mi.row())); + } + + protected: + template class HasId + { + template static std::true_type testSignature(const int& (CLS::*)() const); + template static std::true_type testSignature(int (CLS::*)() const); + + template static decltype(testSignature(&CLS::id)) test(std::nullptr_t); + + template static std::false_type test(...); + + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; + }; + + template ::value, int>::type = 0> + int getIdInternal(const F& data) const + { + return data.id(); + } + + virtual int getId(const T& data) const + { + Q_ASSERT(false); + Q_UNUSED(data); + return -1; + } + + template ::value, int>::type = 0> + int getIdInternal(const F& data) const + { + return getId(data); + } + + template class HasIsDeleted + { + template static std::true_type testSignature(const bool& (CLS::*)() const); + template static std::true_type testSignature(bool (CLS::*)() const); + + template static decltype(testSignature(&CLS::isDeleted)) test(std::nullptr_t); + + template static std::false_type test(...); + + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; + }; + + template ::value, int>::type = 0> + bool isDeletedInternal(const F& data) const + { + return data.isDeleted(); + } + + virtual int isDeleted(const T& data) const + { + Q_UNUSED(data); + return false; + } + + template ::value, int>::type = 0> + bool isDeletedInternal(const F& data) const + { + return isDeleted(data); + } + + virtual bool isFiltered(const T& data, DataModification modType) const + { + Q_UNUSED(data); + Q_UNUSED(modType); + return false; + } + + virtual bool onDataChanged(const T& data, DataModification modType) + { + if (isFiltered(data, modType)) + return false; + + const int id = getIdInternal(data); + const int row = findRowForId(id); + + if (modType == DataModification::eRemoved || isDeletedInternal(data)) + { + if (row >= 0) + return removeRow(row); + return false; + } + + if (modType == DataModification::eAdded && row < 0) + return insertRow(data); + + return setRowData(row, data); + } + + int findRowForId(int id) const + { + for (int i = 0; i < m_vecData.size(); ++i) + { + if (getIdInternal(m_vecData.at(i)) == id) + return i; + } + return -1; + } + + QVector m_vecData; + QVector m_vecColumns; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp old mode 100755 new mode 100644 index 1ca5aaab1..dc627a2ed --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.cpp @@ -1,247 +1,233 @@ - #include "lts_angle_edit.h" -#include + #include "ui_lts_angle_edit.h" #include - +#include namespace LtsWidgets { -inline constexpr double pi() { return M_PI; } -inline constexpr double deg2rad() { return pi() / 180.; } -inline constexpr double rad2deg() { return 1. / deg2rad(); } +inline constexpr double pi() +{ + return M_PI; +} + +inline constexpr double deg2rad() +{ + return pi() / 180.; +} + +inline constexpr double rad2deg() +{ + return 1. / deg2rad(); +} constexpr int maxAngleDeg = 360; constexpr int maxAngleMil = 6400; -constexpr std::tuple c_limDeg (0, maxAngleDeg,0, 10); -constexpr std::tuple c_limMil(0, maxAngleMil,0, 50); -constexpr std::tuple c_limRad(-99999, 99999, 3, 1); +constexpr std::tuple c_limDeg(0, maxAngleDeg, 0, 10); +constexpr std::tuple c_limMil(0, maxAngleMil, 0, 50); +constexpr std::tuple c_limRad(-99999, 99999, 3, 1); -inline constexpr double mil2Deg(const double &mil) +inline constexpr double mil2Deg(const double& mil) { - return maxAngleDeg * mil / maxAngleMil; -} -inline constexpr double deg2Mil(const double &angleDeg) -{ - return maxAngleMil * angleDeg / maxAngleDeg; -} -inline constexpr double deg2Rad(const double &angleDeg) -{ - return angleDeg * deg2rad(); -} -inline constexpr double rad2Degree(const double &angleRad) -{ - return angleRad * 180/pi(); -} -inline constexpr double mil2Rad(const double &mil) -{ - return deg2Rad(mil2Deg(mil)); -} -inline constexpr double rad2Mil(const double &angleRad) -{ - return deg2Mil(rad2Degree(angleRad)); + return maxAngleDeg * mil / maxAngleMil; } - - -LtsAngleEdit::LtsAngleEdit(QWidget *parent) : - QWidget(parent), - m_ui(new Ui_LtsAngleEdit) +inline constexpr double deg2Mil(const double& angleDeg) { - m_ui->setupUi(this); + return maxAngleMil * angleDeg / maxAngleDeg; +} +inline constexpr double deg2Rad(const double& angleDeg) +{ + return angleDeg * deg2rad(); +} + +inline constexpr double rad2Degree(const double& angleRad) +{ + return angleRad * 180 / pi(); +} + +inline constexpr double mil2Rad(const double& mil) +{ + return deg2Rad(mil2Deg(mil)); +} + +inline constexpr double rad2Mil(const double& angleRad) +{ + return deg2Mil(rad2Degree(angleRad)); +} + +LtsAngleEdit::LtsAngleEdit(QWidget* parent) : QWidget(parent), m_ui(new Ui_LtsAngleEdit) +{ + m_ui->setupUi(this); } LtsAngleEdit::~LtsAngleEdit() { - delete m_ui; + delete m_ui; } - - void LtsAngleEdit::initAngleEditWidget(const unsigned int sboxCount) { - - m_dboxLimitMap.insert(AngleUnitType::Deg, c_limDeg); - m_dboxLimitMap.insert(AngleUnitType::Mil, c_limMil); - m_dboxLimitMap.insert(AngleUnitType::Rad, c_limRad); - m_hiddenUnits.clear(); - m_hiddenUnits.insert((int)AngleUnitType::Rad); - - for(unsigned int i=0; i spinbox = QSharedPointer(new QDoubleSpinBox(this) ); - spinbox->setValue(0); - spinbox->setAlignment(Qt::AlignRight); - spinbox->setMinimumWidth(91); - - spinbox.data()->setObjectName(spinBoxName+QString::number(m_sBoxMap.count())); - m_ui->hLayoutSpinbox->addWidget(spinbox.data(), 0); - m_sBoxMap.insert(m_sBoxMap.count(), spinbox); - } - m_ui->hLayoutSpinbox->setContentsMargins(1,1,1,1); + m_dboxLimitMap.insert(AngleUnitType::Deg, c_limDeg); + m_dboxLimitMap.insert(AngleUnitType::Mil, c_limMil); + m_dboxLimitMap.insert(AngleUnitType::Rad, c_limRad); + m_hiddenUnits.clear(); + m_hiddenUnits.insert((int)AngleUnitType::Rad); + for (unsigned int i = 0; i < sboxCount; ++i) + { + QSharedPointer spinbox = QSharedPointer(new QDoubleSpinBox(this)); + spinbox->setValue(0); + spinbox->setAlignment(Qt::AlignRight); + spinbox->setMinimumWidth(91); - - connect(m_ui->cBoxAngleUnit, qOverload(&QComboBox::currentIndexChanged), - this, &LtsAngleEdit::onCBoxAngleUnitChanged); + spinbox.data()->setObjectName(spinBoxName + QString::number(m_sBoxMap.count())); + m_ui->hLayoutSpinbox->addWidget(spinbox.data(), 0); + m_sBoxMap.insert(m_sBoxMap.count(), spinbox); + } + m_ui->hLayoutSpinbox->setContentsMargins(1, 1, 1, 1); - setCboxUnit(); - + connect(m_ui->cBoxAngleUnit, qOverload(&QComboBox::currentIndexChanged), this, + &LtsAngleEdit::onCBoxAngleUnitChanged); + + setCboxUnit(); } - - void LtsAngleEdit::setValue(const double value, unsigned int dboxIndex) { - if ((int)dboxIndex > m_sBoxMap.count()) - return; - auto spinbox = m_sBoxMap.value(dboxIndex); - spinbox->setValue(value); + if ((int)dboxIndex > m_sBoxMap.count()) + return; + auto spinbox = m_sBoxMap.value(dboxIndex); + spinbox->setValue(value); } - - void LtsAngleEdit::setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex) { - setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit),dboxIndex); + setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit), dboxIndex); } -void LtsAngleEdit::hideUnits(const QVector &list) +void LtsAngleEdit::hideUnits(const QVector& list) { - for(auto u : list) - m_hiddenUnits.insert((int)u); - setCboxUnit(); + for (auto u : list) + m_hiddenUnits.insert((int)u); + setCboxUnit(); } -void LtsAngleEdit::showUnits(const QVector &list) +void LtsAngleEdit::showUnits(const QVector& list) { - for (const auto &u : list) - m_hiddenUnits.remove((int)u); - setCboxUnit(); + for (const auto& u : list) + m_hiddenUnits.remove((int)u); + setCboxUnit(); } - - void LtsAngleEdit::setCboxUnit() { - m_ui->cBoxAngleUnit->clear(); - const std::vector allUnits = {AngleUnitType::Deg, AngleUnitType::Mil, AngleUnitType::Rad}; - for(const auto &u : allUnits) - { - if (m_hiddenUnits.contains((int)u)) - continue; - m_ui->cBoxAngleUnit->insertItem(static_cast(u), toString(u),static_cast(u)); - } + m_ui->cBoxAngleUnit->clear(); + const std::vector allUnits = {AngleUnitType::Deg, AngleUnitType::Mil, AngleUnitType::Rad}; + for (const auto& u : allUnits) + { + if (m_hiddenUnits.contains((int)u)) + continue; + m_ui->cBoxAngleUnit->insertItem(static_cast(u), toString(u), static_cast(u)); + } - setAngleUnit(AngleUnitType::Deg); + setAngleUnit(AngleUnitType::Deg); } - - void LtsAngleEdit::setValue(const double value, AngleUnitType valueUnit) { - - setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit),0); + + setValue(getAngleConverted(value, getAngleCurrentUnit(), valueUnit), 0); } - - -void LtsAngleEdit::setAngleUnit(const AngleUnitType &type) +void LtsAngleEdit::setAngleUnit(const AngleUnitType& type) { - m_ui->cBoxAngleUnit->setCurrentIndex(static_cast(type)); + m_ui->cBoxAngleUnit->setCurrentIndex(static_cast(type)); } - - LtsAngleEdit::AngleUnitType LtsAngleEdit::getAngleCurrentUnit() const { - return static_cast(m_ui->cBoxAngleUnit->currentIndex()); + return static_cast(m_ui->cBoxAngleUnit->currentIndex()); } - - double LtsAngleEdit::getAngle(unsigned int sboxIndex) const { - if ((int)sboxIndex > m_sBoxMap.count()) - return 0; - auto spinbox = m_sBoxMap.value(sboxIndex); - return spinbox->value(); + if ((int)sboxIndex > m_sBoxMap.count()) + return 0; + auto spinbox = m_sBoxMap.value(sboxIndex); + return spinbox->value(); } - - QString LtsAngleEdit::toString(LtsAngleEdit::AngleUnitType t) { - switch(t) - { - case AngleUnitType::Deg: - return tr("Degree"); - case AngleUnitType::Mil: - return tr("Mil"); - case AngleUnitType::Rad: - return tr("Radian"); - default: + switch (t) + { + case AngleUnitType::Deg: + return tr("Degree"); + case AngleUnitType::Mil: + return tr("Mil"); + case AngleUnitType::Rad: + return tr("Radian"); + default: + return tr(""); + } return tr(""); - } - return tr(""); } void LtsAngleEdit::onCBoxAngleUnitChanged() { - AngleUnitType newUnit = static_cast(m_ui->cBoxAngleUnit->currentData().toInt()); - for(auto dbox : std::as_const(m_sBoxMap)) - { - const double value = getAngleConverted(dbox->value(), newUnit, m_currAngleUnit); - auto mapVal = m_dboxLimitMap.value(newUnit); - dbox->setMinimum(std::get(mapVal)); - dbox->setMaximum(std::get(mapVal)); - dbox->setDecimals(std::get(mapVal)); - dbox->setSingleStep(std::get(mapVal)); - dbox->setValue(value); - } - m_currAngleUnit = newUnit; + AngleUnitType newUnit = static_cast(m_ui->cBoxAngleUnit->currentData().toInt()); + for (auto dbox : std::as_const(m_sBoxMap)) + { + const double value = getAngleConverted(dbox->value(), newUnit, m_currAngleUnit); + auto mapVal = m_dboxLimitMap.value(newUnit); + dbox->setMinimum(std::get(mapVal)); + dbox->setMaximum(std::get(mapVal)); + dbox->setDecimals(std::get(mapVal)); + dbox->setSingleStep(std::get(mapVal)); + dbox->setValue(value); + } + m_currAngleUnit = newUnit; } - - -double LtsAngleEdit::getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, LtsAngleEdit::AngleUnitType oldAngleUnit) +double LtsAngleEdit::getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, + LtsAngleEdit::AngleUnitType oldAngleUnit) { - double convertedAngle = angle; - if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Mil ) - convertedAngle = deg2Mil(angle); - else if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Rad ) - convertedAngle = deg2Rad(angle); - else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Deg ) - convertedAngle = mil2Deg(angle); - else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Rad ) - convertedAngle = mil2Rad(angle); - else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Deg ) - convertedAngle = rad2Degree(angle); - else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Mil ) - convertedAngle = rad2Mil(angle); + double convertedAngle = angle; + if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Mil) + convertedAngle = deg2Mil(angle); + else if (oldAngleUnit == AngleUnitType::Deg && newAngleUnit == AngleUnitType::Rad) + convertedAngle = deg2Rad(angle); + else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Deg) + convertedAngle = mil2Deg(angle); + else if (oldAngleUnit == AngleUnitType::Mil && newAngleUnit == AngleUnitType::Rad) + convertedAngle = mil2Rad(angle); + else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Deg) + convertedAngle = rad2Degree(angle); + else if (oldAngleUnit == AngleUnitType::Rad && newAngleUnit == AngleUnitType::Mil) + convertedAngle = rad2Mil(angle); - return convertedAngle; + return convertedAngle; } void LtsAngleEdit::setEnable(int sbIndex, bool enabled) { - if ((int)sbIndex > m_sBoxMap.count()) - return; - m_sBoxMap.value(sbIndex)->setEnabled(enabled); + if ((int)sbIndex > m_sBoxMap.count()) + return; + m_sBoxMap.value(sbIndex)->setEnabled(enabled); } void LtsAngleEdit::showSpinbox(int sbIndex, bool visible) { - if ((int)sbIndex > m_sBoxMap.count()) - return; - m_sBoxMap.value(sbIndex)->setVisible(visible); -} - + if ((int)sbIndex > m_sBoxMap.count()) + return; + m_sBoxMap.value(sbIndex)->setVisible(visible); } +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h old mode 100755 new mode 100644 index ce11ea890..af7b045e1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_angle_edit.h @@ -1,72 +1,61 @@ - #pragma once -#include - -#include -#include -#include #include "ltswidgets_export.h" +#include +#include +#include +#include class Ui_LtsAngleEdit; + namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsAngleEdit : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit LtsAngleEdit(QWidget *parent = nullptr); - ~LtsAngleEdit(); + public: + explicit LtsAngleEdit(QWidget* parent = nullptr); + ~LtsAngleEdit(); - enum class AngleUnitType : unsigned int - { - Deg = 0, - Mil = 1, - Rad = 2 - }; - Q_ENUM(AngleUnitType) + enum class AngleUnitType : unsigned int { Deg = 0, Mil = 1, Rad = 2 }; + Q_ENUM(AngleUnitType) - enum LimTuple : int - { - AngleMin, - AngleMax, - DecimalPlace, - SingleStep - }; + enum LimTuple : int { AngleMin, AngleMax, DecimalPlace, SingleStep }; - const QString spinBoxName = QStringLiteral("sboxAngleValue"); - QString toString(AngleUnitType t); - void setAngleUnit(const AngleUnitType &type); - void setValue(const double value, unsigned int dboxIndex=0); - void setValue(const double value, AngleUnitType valueUnit); - void setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex); + const QString spinBoxName = QStringLiteral("sboxAngleValue"); + QString toString(AngleUnitType t); + void setAngleUnit(const AngleUnitType& type); + void setValue(const double value, unsigned int dboxIndex = 0); + void setValue(const double value, AngleUnitType valueUnit); + void setValue(const double value, AngleUnitType valueUnit, unsigned int dboxIndex); - void hideUnits(const QVector &list); - void showUnits(const QVector &list); - LtsAngleEdit::AngleUnitType getAngleCurrentUnit() const; - void initAngleEditWidget(const unsigned int sboxCount); - double getAngle(unsigned int sboxIndex = 0) const; - double getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, LtsAngleEdit::AngleUnitType oldAngleUnit); + void hideUnits(const QVector& list); + void showUnits(const QVector& list); + LtsAngleEdit::AngleUnitType getAngleCurrentUnit() const; + void initAngleEditWidget(const unsigned int sboxCount); + double getAngle(unsigned int sboxIndex = 0) const; + double getAngleConverted(const double angle, LtsAngleEdit::AngleUnitType newAngleUnit, + LtsAngleEdit::AngleUnitType oldAngleUnit); - void setEnable(int sbIndex, bool enabled); - void showSpinbox(int sbIndex, bool visible); + void setEnable(int sbIndex, bool enabled); + void showSpinbox(int sbIndex, bool visible); -protected: - void setCboxUnit(); + protected: + void setCboxUnit(); -private Q_SLOTS: - void onCBoxAngleUnitChanged(); -private: - Ui_LtsAngleEdit *m_ui; - QMap> m_sBoxMap; - QMap> m_dboxLimitMap; - AngleUnitType m_currAngleUnit; - QSet m_hiddenUnits; + private Q_SLOTS: + void onCBoxAngleUnitChanged(); + + private: + Ui_LtsAngleEdit* m_ui; + QMap> m_sBoxMap; + QMap> m_dboxLimitMap; + AngleUnitType m_currAngleUnit; + QSet m_hiddenUnits; }; -} - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h old mode 100755 new mode 100644 index 98011be57..779de9ccd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_background_widget.h @@ -1,13 +1,10 @@ - #pragma once -#include - #include "ltswidgets_export.h" #include - +#include class QPixmap; class QEvent; @@ -15,38 +12,34 @@ class QEvent; namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsBackgroundWidget : public QDialog { - Q_OBJECT + Q_OBJECT -public: - explicit LtsBackgroundWidget(QWidget *parent = nullptr); + public: + explicit LtsBackgroundWidget(QWidget* parent = nullptr); -protected: - void paintEvent(QPaintEvent *e) override; - void closeEvent(QCloseEvent *e) override; - void resizeEvent(QResizeEvent *e) override; - bool event(QEvent *e) override; + protected: + void paintEvent(QPaintEvent* e) override; + void closeEvent(QCloseEvent* e) override; + void resizeEvent(QResizeEvent* e) override; + bool event(QEvent* e) override; -private: - void setBackground(); - void setUltraWide(bool set = true); + private: + void setBackground(); + void setUltraWide(bool set = true); -signals: - + signals: - void signalOperatorAction(); + void signalOperatorAction(); -public slots: - + public slots: - void showFullScreen(); -private: - QPixmap m_pixmap; - bool m_isUltraWide; + void showFullScreen(); + private: + QPixmap m_pixmap; + bool m_isUltraWide; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h old mode 100755 new mode 100644 index 7929997cd..140215709 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base.h @@ -1,270 +1,228 @@ - #pragma once #include "ltswidgets_export.h" #include - -#include -#include +#include #include #include #include -#include - +#include #include - namespace LtsWidgets { class LtsDialog; inline QString readableDuration(qint64 msecs, bool foldDays = true) { - if (msecs == 0) - return QObject::tr("---"); + if (msecs == 0) + return QObject::tr("---"); - - if (msecs % 1000 != 0 && msecs < 1000 * 60) - return QObject::tr("%1 seconds").arg(QLocale().toString(msecs / 1000.0, 'f', 3)); + if (msecs % 1000 != 0 && msecs < 1000 * 60) + return QObject::tr("%1 seconds").arg(QLocale().toString(msecs / 1000.0, 'f', 3)); - qint64 secs = msecs / 1000; - qint64 mins = secs / 60; - qint64 hours = mins / 60; - qint64 days = hours / 24; + qint64 secs = msecs / 1000; + qint64 mins = secs / 60; + qint64 hours = mins / 60; + qint64 days = hours / 24; - if (foldDays) - days = 0; - else - hours = hours % 24; + if (foldDays) + days = 0; + else + hours = hours % 24; - mins = mins % 60; - secs = secs % 60; + mins = mins % 60; + secs = secs % 60; - - if (!secs && !mins && !hours) - return QObject::tr("%n day(s)", "", days); - if (!secs && !mins && !days) - return QObject::tr("%n hour(s)", "", hours); - if (!secs && !hours && !days) - return QObject::tr("%n minute(s)", "", mins); - if (!mins && !hours && !days) - return QObject::tr("%n second(s)", "", secs); + if (!secs && !mins && !hours) + return QObject::tr("%n day(s)", "", days); + if (!secs && !mins && !days) + return QObject::tr("%n hour(s)", "", hours); + if (!secs && !hours && !days) + return QObject::tr("%n minute(s)", "", mins); + if (!mins && !hours && !days) + return QObject::tr("%n second(s)", "", secs); - QString strSecs = QObject::tr("%1s").arg(secs, 2, 10, QLatin1Char('0')); - QString strMins = QObject::tr("%1m").arg(mins, 2, 10, QLatin1Char('0')); - QString strHours = QObject::tr("%1h").arg(hours, 2, 10, QLatin1Char('0')); - QString strDays = QObject::tr("%1d").arg(days); + QString strSecs = QObject::tr("%1s").arg(secs, 2, 10, QLatin1Char('0')); + QString strMins = QObject::tr("%1m").arg(mins, 2, 10, QLatin1Char('0')); + QString strHours = QObject::tr("%1h").arg(hours, 2, 10, QLatin1Char('0')); + QString strDays = QObject::tr("%1d").arg(days); - QString retVal; - if (days) - retVal += strDays + QLatin1Char(' '); - if (days || hours) - retVal.append(strHours); - if (mins || hours || days) - retVal.append(strMins); - if (secs) - retVal.append(strSecs); + QString retVal; + if (days) + retVal += strDays + QLatin1Char(' '); + if (days || hours) + retVal.append(strHours); + if (mins || hours || days) + retVal.append(strMins); + if (secs) + retVal.append(strSecs); - return retVal; + return retVal; } -inline void addTouchScroll(QWidget *widget) +inline void addTouchScroll(QWidget* widget) { - if (!widget) - return; - widget->setAttribute(Qt::WA_AcceptTouchEvents); + if (!widget) + return; + widget->setAttribute(Qt::WA_AcceptTouchEvents); - { - QScrollArea *sca = qobject_cast(widget); - if (sca) { - QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); - return; + QScrollArea* sca = qobject_cast(widget); + if (sca) + { + QScroller::grabGesture(sca->viewport(), QScroller::LeftMouseButtonGesture); + return; + } } - } - { - QAbstractItemView *aiv = qobject_cast(widget); - if (aiv) { - QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); - aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); - aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); - return; + QAbstractItemView* aiv = qobject_cast(widget); + if (aiv) + { + QScroller::grabGesture(aiv->viewport(), QScroller::LeftMouseButtonGesture); + aiv->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); + aiv->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + return; + } } - } } -enum class ButtonSize -{ - eDefault = 40, - - - - - +enum class ButtonSize { + eDefault = 40, }; +enum class ButtonStyle { eAll = 1, eTextOnly, eIconOnly, eTextNextToIcon }; -enum class ButtonStyle -{ - eAll = 1, - eTextOnly, - eIconOnly, - eTextNextToIcon +enum class LayoutArea { + eUnknown, + eInfoTab, + eDialogTab, + eSpecialTab, + eMainTab, }; -enum class LayoutArea -{ - eUnknown, - eInfoTab, - eDialogTab, - eSpecialTab, - eMainTab, +enum class ExercisePart { + ePlanning, + eExecution, + eAfterAction, + eSpecial, }; -enum class ExercisePart -{ - ePlanning, - eExecution, - eAfterAction, - eSpecial, -}; - - namespace ExerciseState { - enum State - { - - eUnknown = 0, - eCreated = 1 << 0, - eStarted = 1 << 1, - ePaused = 1 << 2, - eStopped = 1 << 4, +enum State { + + eUnknown = 0, + eCreated = 1 << 0, + eStarted = 1 << 1, + ePaused = 1 << 2, + eStopped = 1 << 4, eTerminated = 1 << 5, eAll = eCreated | eStarted | ePaused | eStopped | eTerminated - }; +}; - Q_DECLARE_OPERATORS_FOR_FLAGS(QFlags) -} +Q_DECLARE_OPERATORS_FOR_FLAGS(QFlags) +} // namespace ExerciseState -typedef ExerciseState::State ExcState; -typedef QFlags ExerciseStates; +typedef ExerciseState::State ExcState; +typedef QFlags ExerciseStates; -enum class CreateInstantType -{ - DontCreateInstant, - CreateInstantAndAddAction, - CreateInstantAndDiscardAction, +enum class CreateInstantType { + DontCreateInstant, + CreateInstantAndAddAction, + CreateInstantAndDiscardAction, }; struct PluginData { - - using createWidgetFuncPtr = std::function; - using directFuncPtr = std::function; - createWidgetFuncPtr createWidgetFunc = nullptr; - directFuncPtr directFunc = nullptr; - QStringList iconPaths; - QIcon menuIcon; - QString tooltip; - qulonglong dropHandlerKey = 0; - QString menuText; - QString menuGroup; - LtsUtils::LtsTranslatableIdentifier translatableMenuGroup; - QString identifier; - bool closable = true; - LayoutArea layoutArea = LayoutArea::eDialogTab; - int operatorRight = 0; - CreateInstantType createInstant = CreateInstantType::DontCreateInstant; - bool visibleInMenu = true; - ExercisePart exercisePart = ExercisePart::eSpecial; - ExerciseStates exerciseStates = ExerciseState::eAll; + using createWidgetFuncPtr = std::function; + using directFuncPtr = std::function; - PluginData() = default; - PluginData(const QString &_menuGroup, - const QString &_menuText, - const QString &_identifier, - const createWidgetFuncPtr &_cwfp, - int _operatorRight, - ExercisePart _exercisePart = ExercisePart::eSpecial, - ExerciseStates _exerciseStates = ExerciseState::eAll) - : PluginData(_menuGroup, _menuText, _identifier, QIcon(), _cwfp, _operatorRight, _exercisePart, _exerciseStates) - {} + createWidgetFuncPtr createWidgetFunc = nullptr; + directFuncPtr directFunc = nullptr; + QStringList iconPaths; + QIcon menuIcon; + QString tooltip; + qulonglong dropHandlerKey = 0; + QString menuText; + QString menuGroup; + LtsUtils::LtsTranslatableIdentifier translatableMenuGroup; + QString identifier; + bool closable = true; + LayoutArea layoutArea = LayoutArea::eDialogTab; + int operatorRight = 0; + CreateInstantType createInstant = CreateInstantType::DontCreateInstant; + bool visibleInMenu = true; + ExercisePart exercisePart = ExercisePart::eSpecial; + ExerciseStates exerciseStates = ExerciseState::eAll; - PluginData(const QString &_menuGroup, - const QString &_menuText, - const QString &_identifier, - const QIcon &_icon, - const createWidgetFuncPtr &_cwfp, - int _operatorRight, - ExercisePart _exercisePart = ExercisePart::eSpecial, - ExerciseStates _exerciseStates = ExerciseState::eAll) - : createWidgetFunc(_cwfp) - , menuIcon(_icon) - , menuText(_menuText) - , menuGroup(_menuGroup) - , identifier(_identifier) - , operatorRight(_operatorRight) - , exercisePart(_exercisePart) - , exerciseStates(_exerciseStates) - { - } + PluginData() = default; - static PluginData createGroup(const QString &menuGroup, - const QString &menuText, - const QString &identifier, - int operatorRight) - { - return PluginData(menuGroup, menuText, identifier, nullptr, operatorRight, ExercisePart::eSpecial); - } - bool isValid() const { return createWidgetFunc != nullptr; } + PluginData(const QString& _menuGroup, const QString& _menuText, const QString& _identifier, + const createWidgetFuncPtr& _cwfp, int _operatorRight, + ExercisePart _exercisePart = ExercisePart::eSpecial, + ExerciseStates _exerciseStates = ExerciseState::eAll) + : PluginData(_menuGroup, _menuText, _identifier, QIcon(), _cwfp, _operatorRight, _exercisePart, _exerciseStates) + { + } + + PluginData(const QString& _menuGroup, const QString& _menuText, const QString& _identifier, const QIcon& _icon, + const createWidgetFuncPtr& _cwfp, int _operatorRight, + ExercisePart _exercisePart = ExercisePart::eSpecial, + ExerciseStates _exerciseStates = ExerciseState::eAll) + : createWidgetFunc(_cwfp), menuIcon(_icon), menuText(_menuText), menuGroup(_menuGroup), identifier(_identifier), + operatorRight(_operatorRight), exercisePart(_exercisePart), exerciseStates(_exerciseStates) + { + } + + static PluginData createGroup(const QString& menuGroup, const QString& menuText, const QString& identifier, + int operatorRight) + { + return PluginData(menuGroup, menuText, identifier, nullptr, operatorRight, ExercisePart::eSpecial); + } + + bool isValid() const + { + return createWidgetFunc != nullptr; + } }; - - class LTSWIDGETS_EXPORT Designer { - Q_GADGET -public: - enum ButtonSize - { - eDefault = static_cast(LtsWidgets::ButtonSize::eDefault), + Q_GADGET + public: + enum ButtonSize { + eDefault = static_cast(LtsWidgets::ButtonSize::eDefault), + }; + Q_ENUM(ButtonSize) + enum ButtonStyle { + eAll = static_cast(LtsWidgets::ButtonStyle::eAll), + eTextOnly = static_cast(LtsWidgets::ButtonStyle::eTextOnly), + eIconOnly = static_cast(LtsWidgets::ButtonStyle::eIconOnly), + eTextNextToIcon = static_cast(LtsWidgets::ButtonStyle::eTextNextToIcon) + }; + Q_ENUM(ButtonStyle) - - - - }; - Q_ENUM(ButtonSize) - enum ButtonStyle - { - eAll = static_cast(LtsWidgets::ButtonStyle::eAll), - eTextOnly = static_cast(LtsWidgets::ButtonStyle::eTextOnly), - eIconOnly = static_cast(LtsWidgets::ButtonStyle::eIconOnly), - eTextNextToIcon = static_cast(LtsWidgets::ButtonStyle::eTextNextToIcon) - }; - Q_ENUM(ButtonStyle) - enum LayoutArea - { - eUnknownArea = static_cast(LtsWidgets::LayoutArea::eUnknown), - eInfoTab = static_cast(LtsWidgets::LayoutArea::eInfoTab), - eDialogTab = static_cast(LtsWidgets::LayoutArea::eDialogTab), - eSpecialTab = static_cast(LtsWidgets::LayoutArea::eSpecialTab), - eMainTab = static_cast(LtsWidgets::LayoutArea::eMainTab) - }; - Q_ENUM(LayoutArea) + enum LayoutArea { + eUnknownArea = static_cast(LtsWidgets::LayoutArea::eUnknown), + eInfoTab = static_cast(LtsWidgets::LayoutArea::eInfoTab), + eDialogTab = static_cast(LtsWidgets::LayoutArea::eDialogTab), + eSpecialTab = static_cast(LtsWidgets::LayoutArea::eSpecialTab), + eMainTab = static_cast(LtsWidgets::LayoutArea::eMainTab) + }; + Q_ENUM(LayoutArea) }; -} +} // namespace LtsWidgets Q_DECLARE_METATYPE(LtsWidgets::Designer::ButtonSize) Q_DECLARE_METATYPE(LtsWidgets::Designer::ButtonStyle) Q_DECLARE_METATYPE(LtsWidgets::Designer::LayoutArea) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h old mode 100755 new mode 100644 index 60e09c779..8b0fe05c3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_base_layout_widget.h @@ -1,19 +1,16 @@ - #pragma once -#include - #include "lts_base.h" -#include "ltswidgets_export.h" #include "lts_notification_box.h" +#include "ltswidgets_export.h" #include "qevent.h" -#include #include +#include #include #include - +#include class QButtonGroup; class QPropertyAnimation; @@ -31,7 +28,10 @@ namespace IDL enum class PartitionType; } -namespace LtsUtils { class Promise; } +namespace LtsUtils +{ +class Promise; +} namespace LtsWidgets { @@ -43,305 +43,253 @@ class LtsToolBox; struct ExerciseData { - QString exName; - QString exDescription; - int phId = -1; - QString phName; - QString phDescription; - QString exStateString; - ExcState exState = ExerciseState::eUnknown; - QColor exStateCol; - QString partitionType; + QString exName; + QString exDescription; + int phId = -1; + QString phName; + QString phDescription; + QString exStateString; + ExcState exState = ExerciseState::eUnknown; + QColor exStateCol; + QString partitionType; - bool operator==(const ExerciseData &o) const - { - return exName == o.exName && - exDescription == o.exDescription && - phId == o.phId && - phName == o.phName && - phDescription == o.phDescription && - exStateString == o.exStateString && - exState == o.exState && - exStateCol == o.exStateCol && - partitionType == o.partitionType; - } - bool operator!=(const ExerciseData &o) const - { - return !operator ==(o); - } + bool operator==(const ExerciseData& o) const + { + return exName == o.exName && exDescription == o.exDescription && phId == o.phId && phName == o.phName && + phDescription == o.phDescription && exStateString == o.exStateString && exState == o.exState && + exStateCol == o.exStateCol && partitionType == o.partitionType; + } + bool operator!=(const ExerciseData& o) const + { + return !operator==(o); + } }; - - - class LTSWIDGETS_EXPORT LtsBaseLayoutWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - - explicit LtsBaseLayoutWidget(QWidget *parent = nullptr, bool splitMenu = true); - ~LtsBaseLayoutWidget(); - - - - void hideVisibleLayouts(); - - - - void resetLayoutVisibility(); - - - - void setMenuVisible(bool visible); - - - - bool isMenuVisible() const; - - bool isTopBarVisible() const; - void setTopBarVisible(bool visible); - - - - bool isMenuCollapsed() const; - - - - void collapseMenu(bool collapse = true); - - - - void setSessionInfo(const int domainId, const IDL::PartitionType &partitionType, const int partitionId, const QString &workspaceId); - - - - LtsDragIcon *addMenuAction(const PluginData &plData, bool isFirstRun = false); - - - - bool removeMenuAction(const PluginData &plData); - - - - bool removeMenuAction(LtsDragIcon *icon); - - bool removeMenuAction(const QString &byIdentifier); - - - - void clearMenuActions(); - - void setAppName(const QString &appName); - bool isDialogFocused(const LtsDialog *dialog) const; - - - - void setCustomText(const QString &text); - const QString customText() const; - - - - LtsTabWidget *getTabFromLayoutArea(LayoutArea area) const; - - - - LtsDialog *getWidget(const QString &menuGroup, const QString &identifier, LayoutArea area = LayoutArea::eUnknown); - - - - QWidget *getMenu() const; - - - - LtsToolBarArea *getToolbar() const; - - - - void setOperatorName(const QString &operatorName, bool showTerminalButton); - - - - void setProfilePicture(const QPixmap &profilePicture); - - - - void setExerciseData(const ExerciseData &data); - - - - void initilizationFinished(); - - - - void addNotification(QToolButton *noti); - - - - bool isWidgetsHidden() const; - - bool notificationExists(const QString &identifier) const; - const QMap &mapButtons() const { return m_mapButtons; } - void setToolBarActions(const QStringList &actions); - QStringList toolBarActions() const; - void setFunctionKeys(const QMap &actions); - QMap functionKeys() const; - void setWorkspaceId(const QString &workspaceId) { m_workspaceId = workspaceId; } - - - - void showMessage(const QString &title, const QString &text, LtsNotificationBox::MessageType type = LtsNotificationBox::MessageType::Info, const std::function &clickedLinkCallback = nullptr, bool closeOnLinkClicked = true, const QString &identifier = {}); - bool messageIdentifierExists(const QString &identifier) const; - - void executeAction(const QString &actionIdentifier); - bool isSecondaryWidget() const { return m_isSecondaryWidget; } - void setSecondaryWidget() { m_isSecondaryWidget = true; } - - - - void removeQueuedMessage(const QString &messageIdentifier); - - -public slots: - bool slotClose(); - void slotLogout(); - - void slotScreenCountChanged(int count); - - - - void onMenuEntryClicked(); - - void onHideAnimated(); - void onReShowAnimated(); - - - - bool addWidget(LtsWidgets::LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true); - - - - bool addOrReplaceWidget(LtsDialog *dialog, const QString &menuGroup, const QString &identifier, LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true ); - - bool focusTab(const QString &menuGroup, const QString &identifier, LtsWidgets::LayoutArea area); - - - - void executeCreateInstantFunctions(const LtsWidgets::PluginData &plData); - - void setExerciseTime(qint64 mSecsSinceEpoch); - bool haveUnsavedChanges(); - - - - - - bool notifyUnsavedChanges(); - - - - void setIrreplaceableOnce() { m_irreplaceableOnce = true; } - bool irreplaceableReset() { bool r = m_irreplaceableOnce; m_irreplaceableOnce = false; return r; } - bool isIrreplaceable() const { return m_irreplaceableOnce; } - - - - void showWidgets(); - - - - void hideWidgets(); - - -private slots: - - - void slotOperatorMenuClicked(); - - void setCurrentTime(); - - -signals: - - - - - void signalClose(); - void signalLogout(); - void signalShowOperatorSettings(); - void signalRetranslateActions(); - void signalSwap(); - void signalStapleTopicLockHandler(LtsWidgets::LtsDialog *widget); - void signalSuccessfullyPlaced(); - - - - void signalNotifyUnsavedChanges(bool &reject); - -protected: - - - void closeEvent(QCloseEvent *event) override; - - void showEvent(QShowEvent *event) override; - void changeEvent(QEvent *e) override; - - -private: - void addDebugMenu(); - void retranslate(); - void addTouchScroll(QWidget *widget); - LtsDragIcon *createButton(const PluginData &plData); - int getIndexOfTab(LtsTabWidget *tab); - LtsToolBox *getToolBox(const ExercisePart &exercisePart) const; - QPushButton *getExercisePartButton(const ExercisePart &exercisePart) const; - void checkExercisePartButtonVisibility(); - void checkMenuGroup(const QString &menuGroup, const ExercisePart &exercisePart); - bool isDialogFocused(const LtsDialog *dialog, const LayoutArea &layoutArea) const; - bool isDialogFocused(const LtsDialog *dialog, const LtsTabWidget *tab) const; - void applyExerciseStateRestricition(); - void executePluginData(const PluginData &plData); - void showNextQueuedMessage(); - - - struct Message - { public: - QString title; - QString text; - LtsNotificationBox::MessageType type; - std::function clickedLinkCallback; - bool closeOnLinkClicked; - QString identifier; - }; + explicit LtsBaseLayoutWidget(QWidget* parent = nullptr, bool splitMenu = true); + ~LtsBaseLayoutWidget(); - ExerciseData m_exerciseData; - QMap m_mapButtons; - QList m_mainSplitterSizes; - QList m_menuSplitterSizes; - bool m_isHidden; - QPropertyAnimation *m_currentAnimation{nullptr}; - Ui::LtsBaseLayoutWidget *m_ui{nullptr}; - IDL::PartitionType m_partitionType; - int m_domainId; - int m_partitionId; - QString m_operatorName; - bool m_firstShow; - bool m_showTerminalButton; - qint64 m_exerciseTime; - QTimer *m_setCurrentTimeTimer{nullptr}; - bool m_irreplaceableOnce; - QButtonGroup *m_bg{nullptr}; - QString m_workspaceId; - int m_screenCount; - bool m_menuCollapsed; - QMap, bool> m_oldLayoutVisibilityStates; - LtsNotificationBox *m_notiBox{nullptr}; - QStringList m_notFoundYet; - bool m_isSecondaryWidget { false }; - QVector m_currentMessage; - QVector m_messageQueue; + void hideVisibleLayouts(); + + void resetLayoutVisibility(); + + void setMenuVisible(bool visible); + + bool isMenuVisible() const; + + bool isTopBarVisible() const; + void setTopBarVisible(bool visible); + + bool isMenuCollapsed() const; + + void collapseMenu(bool collapse = true); + + void setSessionInfo(const int domainId, const IDL::PartitionType& partitionType, const int partitionId, + const QString& workspaceId); + + LtsDragIcon* addMenuAction(const PluginData& plData, bool isFirstRun = false); + + bool removeMenuAction(const PluginData& plData); + + bool removeMenuAction(LtsDragIcon* icon); + + bool removeMenuAction(const QString& byIdentifier); + + void clearMenuActions(); + + void setAppName(const QString& appName); + bool isDialogFocused(const LtsDialog* dialog) const; + + void setCustomText(const QString& text); + const QString customText() const; + + LtsTabWidget* getTabFromLayoutArea(LayoutArea area) const; + + LtsDialog* getWidget(const QString& menuGroup, const QString& identifier, LayoutArea area = LayoutArea::eUnknown); + + QWidget* getMenu() const; + + LtsToolBarArea* getToolbar() const; + + void setOperatorName(const QString& operatorName, bool showTerminalButton); + + void setProfilePicture(const QPixmap& profilePicture); + + void setExerciseData(const ExerciseData& data); + + void initilizationFinished(); + + void addNotification(QToolButton* noti); + + bool isWidgetsHidden() const; + + bool notificationExists(const QString& identifier) const; + + const QMap& mapButtons() const + { + return m_mapButtons; + } + + void setToolBarActions(const QStringList& actions); + QStringList toolBarActions() const; + void setFunctionKeys(const QMap& actions); + QMap functionKeys() const; + + void setWorkspaceId(const QString& workspaceId) + { + m_workspaceId = workspaceId; + } + + void showMessage(const QString& title, const QString& text, + LtsNotificationBox::MessageType type = LtsNotificationBox::MessageType::Info, + const std::function& clickedLinkCallback = nullptr, + bool closeOnLinkClicked = true, const QString& identifier = {}); + bool messageIdentifierExists(const QString& identifier) const; + + void executeAction(const QString& actionIdentifier); + + bool isSecondaryWidget() const + { + return m_isSecondaryWidget; + } + + void setSecondaryWidget() + { + m_isSecondaryWidget = true; + } + + void removeQueuedMessage(const QString& messageIdentifier); + + public slots: + bool slotClose(); + void slotLogout(); + + void slotScreenCountChanged(int count); + + void onMenuEntryClicked(); + + void onHideAnimated(); + void onReShowAnimated(); + + bool addWidget(LtsWidgets::LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + LtsWidgets::LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, + bool focusNewTab = true); + + bool addOrReplaceWidget(LtsDialog* dialog, const QString& menuGroup, const QString& identifier, + LayoutArea area = LayoutArea::eUnknown, bool setClosable = true, bool focusNewTab = true); + + bool focusTab(const QString& menuGroup, const QString& identifier, LtsWidgets::LayoutArea area); + + void executeCreateInstantFunctions(const LtsWidgets::PluginData& plData); + + void setExerciseTime(qint64 mSecsSinceEpoch); + bool haveUnsavedChanges(); + + bool notifyUnsavedChanges(); + + void setIrreplaceableOnce() + { + m_irreplaceableOnce = true; + } + + bool irreplaceableReset() + { + bool r = m_irreplaceableOnce; + m_irreplaceableOnce = false; + return r; + } + + bool isIrreplaceable() const + { + return m_irreplaceableOnce; + } + + void showWidgets(); + + void hideWidgets(); + + private slots: + + void slotOperatorMenuClicked(); + + void setCurrentTime(); + + signals: + + void signalClose(); + void signalLogout(); + void signalShowOperatorSettings(); + void signalRetranslateActions(); + void signalSwap(); + void signalStapleTopicLockHandler(LtsWidgets::LtsDialog* widget); + void signalSuccessfullyPlaced(); + + void signalNotifyUnsavedChanges(bool& reject); + + protected: + void closeEvent(QCloseEvent* event) override; + + void showEvent(QShowEvent* event) override; + void changeEvent(QEvent* e) override; + + private: + void addDebugMenu(); + void retranslate(); + void addTouchScroll(QWidget* widget); + LtsDragIcon* createButton(const PluginData& plData); + int getIndexOfTab(LtsTabWidget* tab); + LtsToolBox* getToolBox(const ExercisePart& exercisePart) const; + QPushButton* getExercisePartButton(const ExercisePart& exercisePart) const; + void checkExercisePartButtonVisibility(); + void checkMenuGroup(const QString& menuGroup, const ExercisePart& exercisePart); + bool isDialogFocused(const LtsDialog* dialog, const LayoutArea& layoutArea) const; + bool isDialogFocused(const LtsDialog* dialog, const LtsTabWidget* tab) const; + void applyExerciseStateRestricition(); + void executePluginData(const PluginData& plData); + void showNextQueuedMessage(); + + struct Message + { + public: + QString title; + QString text; + LtsNotificationBox::MessageType type; + std::function clickedLinkCallback; + bool closeOnLinkClicked; + QString identifier; + }; + + ExerciseData m_exerciseData; + QMap m_mapButtons; + QList m_mainSplitterSizes; + QList m_menuSplitterSizes; + bool m_isHidden; + QPropertyAnimation* m_currentAnimation{nullptr}; + Ui::LtsBaseLayoutWidget* m_ui{nullptr}; + IDL::PartitionType m_partitionType; + int m_domainId; + int m_partitionId; + QString m_operatorName; + bool m_firstShow; + bool m_showTerminalButton; + qint64 m_exerciseTime; + QTimer* m_setCurrentTimeTimer{nullptr}; + bool m_irreplaceableOnce; + QButtonGroup* m_bg{nullptr}; + QString m_workspaceId; + int m_screenCount; + bool m_menuCollapsed; + QMap, bool> m_oldLayoutVisibilityStates; + LtsNotificationBox* m_notiBox{nullptr}; + QStringList m_notFoundYet; + bool m_isSecondaryWidget{false}; + QVector m_currentMessage; + QVector m_messageQueue; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp old mode 100755 new mode 100644 index be35119b8..151ec05c1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.cpp @@ -1,6 +1,5 @@ - #include "lts_bitfield_widget.h" #include @@ -8,122 +7,119 @@ namespace LtsWidgets { -LtsBitfieldWidget::LtsBitfieldWidget(QWidget *parent, quint8 value) - : QWidget(parent) - , m_value(value) +LtsBitfieldWidget::LtsBitfieldWidget(QWidget* parent, quint8 value) : QWidget(parent), m_value(value) { - setObjectName(QString::fromUtf8("LtsBitfieldWidget")); + setObjectName(QString::fromUtf8("LtsBitfieldWidget")); } -void LtsBitfieldWidget::paintEvent(QPaintEvent *pe) +void LtsBitfieldWidget::paintEvent(QPaintEvent* pe) { - QWidget::paintEvent(pe); + QWidget::paintEvent(pe); - QPainter painter; - painter.begin(this); - painter.setPen(Qt::SolidLine); - - if (m_hasCaption) - { - QFont font = painter.font(); - font.setPointSizeF( (height()/2.0 > width()/8.0) ? width()/8.0 : height()/2.0 ); - painter.setFont(font); - } - - for (int i = 0; i < 8; ++i) - { - QRectF bitGraphic; - - bitGraphic.setLeft(width() / 8.0 * i); - bitGraphic.setWidth((width() / 8.0) - 1); - bitGraphic.setHeight(height() - 1); - - bool bitVal = (m_value & (1 << (7 - i))) > 0; - - painter.fillRect(bitGraphic, QBrush(bitVal ? m_onColor : m_offColor, Qt::SolidPattern)); + QPainter painter; + painter.begin(this); + painter.setPen(Qt::SolidLine); if (m_hasCaption) { - painter.setPen(bitVal ? m_offColor : m_onColor); - painter.drawText(bitGraphic, Qt::AlignCenter, bitVal ? QStringLiteral("1") : QStringLiteral("0")); + QFont font = painter.font(); + font.setPointSizeF((height() / 2.0 > width() / 8.0) ? width() / 8.0 : height() / 2.0); + painter.setFont(font); } - painter.setPen(Qt::gray); - painter.drawRect(bitGraphic); - } + for (int i = 0; i < 8; ++i) + { + QRectF bitGraphic; - painter.end(); + bitGraphic.setLeft(width() / 8.0 * i); + bitGraphic.setWidth((width() / 8.0) - 1); + bitGraphic.setHeight(height() - 1); + + bool bitVal = (m_value & (1 << (7 - i))) > 0; + + painter.fillRect(bitGraphic, QBrush(bitVal ? m_onColor : m_offColor, Qt::SolidPattern)); + + if (m_hasCaption) + { + painter.setPen(bitVal ? m_offColor : m_onColor); + painter.drawText(bitGraphic, Qt::AlignCenter, bitVal ? QStringLiteral("1") : QStringLiteral("0")); + } + + painter.setPen(Qt::gray); + painter.drawRect(bitGraphic); + } + + painter.end(); } void LtsBitfieldWidget::setHasCaption(bool hasCaption) { - if (m_hasCaption == hasCaption) - return; + if (m_hasCaption == hasCaption) + return; - m_hasCaption = hasCaption; - repaint(); + m_hasCaption = hasCaption; + repaint(); - emit hasCaptionChanged(hasCaption); + emit hasCaptionChanged(hasCaption); } -void LtsBitfieldWidget::setOnColor(const QColor &onColor) +void LtsBitfieldWidget::setOnColor(const QColor& onColor) { - if (m_onColor == onColor) - return; + if (m_onColor == onColor) + return; - m_onColor = onColor; - repaint(); + m_onColor = onColor; + repaint(); } -void LtsBitfieldWidget::setOffColor(const QColor &offColor) +void LtsBitfieldWidget::setOffColor(const QColor& offColor) { - if (m_offColor == offColor) - return; + if (m_offColor == offColor) + return; - m_offColor = offColor; - repaint(); + m_offColor = offColor; + repaint(); } -void LtsBitfieldWidget::mousePressEvent(QMouseEvent *event) +void LtsBitfieldWidget::mousePressEvent(QMouseEvent* event) { - if (!m_isEditable) - { - QWidget::mousePressEvent(event); - return; - } - - for (int i = 0; i < 8; ++i) - { - if (event->pos().x() > width()/8 * i && - event->pos().x() < width()/8 * (i + 1)) + if (!m_isEditable) { - m_value ^= (1 << (7 - i)); - emit valueChanged(m_value); - break; + QWidget::mousePressEvent(event); + return; } - } - repaint(); + + for (int i = 0; i < 8; ++i) + { + if (event->pos().x() > width() / 8 * i && event->pos().x() < width() / 8 * (i + 1)) + { + m_value ^= (1 << (7 - i)); + emit valueChanged(m_value); + break; + } + } + repaint(); } void LtsBitfieldWidget::setEditable(bool editable) { - if (m_isEditable == editable) - return; + if (m_isEditable == editable) + return; - m_isEditable = editable; + m_isEditable = editable; - emit isEditableChanged(m_isEditable); + emit isEditableChanged(m_isEditable); } void LtsBitfieldWidget::setValue(quint8 value) { - if (m_value == value) - return; + if (m_value == value) + return; - m_value = value; - repaint(); + m_value = value; + repaint(); - emit valueChanged(m_value); + emit valueChanged(m_value); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h old mode 100755 new mode 100644 index 21eac20cf..6225cfb87 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_bitfield_widget.h @@ -1,96 +1,84 @@ - #pragma once -#include - -#include -#include - #include "ltswidgets_export.h" +#include +#include +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsBitfieldWidget : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(quint8 value READ value WRITE setValue NOTIFY valueChanged) - Q_PROPERTY(bool isEditable READ isEditable WRITE setEditable NOTIFY isEditableChanged) - Q_PROPERTY(bool hasCaption READ hasCaption WRITE setHasCaption NOTIFY hasCaptionChanged) - Q_PROPERTY(QColor onColor READ onColor WRITE setOnColor) - Q_PROPERTY(QColor offColor READ offColor WRITE setOffColor) + Q_PROPERTY(quint8 value READ value WRITE setValue NOTIFY valueChanged) + Q_PROPERTY(bool isEditable READ isEditable WRITE setEditable NOTIFY isEditableChanged) + Q_PROPERTY(bool hasCaption READ hasCaption WRITE setHasCaption NOTIFY hasCaptionChanged) + Q_PROPERTY(QColor onColor READ onColor WRITE setOnColor) + Q_PROPERTY(QColor offColor READ offColor WRITE setOffColor) -public: - explicit LtsBitfieldWidget(QWidget *parent = nullptr, quint8 value = 0); + public: + explicit LtsBitfieldWidget(QWidget* parent = nullptr, quint8 value = 0); -signals: - void valueChanged(quint8 newValue); - void isEditableChanged(bool option); - void hasCaptionChanged(bool option); + signals: + void valueChanged(quint8 newValue); + void isEditableChanged(bool option); + void hasCaptionChanged(bool option); -public slots: - + public slots: - void setValue(quint8 value); + void setValue(quint8 value); - + void setEditable(bool editable); - void setEditable(bool editable); + void setHasCaption(bool hasCaption); - + void setOnColor(const QColor& onColor); - void setHasCaption(bool hasCaption); + void setOffColor(const QColor& offColor); - + public: + quint8 value() const + { + return m_value; + } - void setOnColor(const QColor &onColor); + bool isEditable() const + { + return m_isEditable; + } - + bool hasCaption() const + { + return m_hasCaption; + } - void setOffColor(const QColor &offColor); + QColor onColor() const + { + return m_onColor; + } + QColor offColor() const + { + return m_offColor; + } -public: - + private: + void mousePressEvent(QMouseEvent* event) override; - quint8 value() const { return m_value; } + void paintEvent(QPaintEvent* pe) override; - + private: + quint8 m_value = 0; - bool isEditable() const { return m_isEditable; } + bool m_isEditable = true; + bool m_hasCaption = true; - - - bool hasCaption() const { return m_hasCaption; } - - - - QColor onColor() const {return m_onColor;} - - - - QColor offColor() const {return m_offColor;} - -private: - - - void mousePressEvent(QMouseEvent *event) override; - - - - void paintEvent(QPaintEvent *pe) override; - -private: - quint8 m_value = 0; - - bool m_isEditable = true; - bool m_hasCaption = true; - - QColor m_onColor = Qt::black; - QColor m_offColor = Qt::white; + QColor m_onColor = Qt::black; + QColor m_offColor = Qt::white; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h old mode 100755 new mode 100644 index 93d22ecf4..badd4c081 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_checkable_table_model.h @@ -1,131 +1,129 @@ - #pragma once #include "lts_abstract_table_model.h" - namespace LtsWidgets { -template -class LtsCheckableTableModel : public LtsAbstractTableModel +template class LtsCheckableTableModel : public LtsAbstractTableModel { -public: - LtsCheckableTableModel(const QVector &header, int checkableColumn, QObject *parent) - : LtsAbstractTableModel(header, parent) - , m_checkableColumn(checkableColumn) - { - } - - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override - { - if (role == Qt::CheckStateRole && index.column() == m_checkableColumn && LtsAbstractTableModel::indexIsValid(index)) - return LtsAbstractTableModel::m_vecData.at(index.row()).first ? Qt::Checked : Qt::Unchecked; - return QVariant(); - } - - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override - { - if (role == Qt::CheckStateRole) + public: + LtsCheckableTableModel(const QVector& header, int checkableColumn, QObject* parent) + : LtsAbstractTableModel(header, parent), m_checkableColumn(checkableColumn) { - switchCheckbox(index); - return true; - } - return QAbstractItemModel::setData(index, value, role); - } - - Qt::ItemFlags flags(const QModelIndex &index) const override - { - Qt::ItemFlags flags(LtsWidgets::LtsAbstractTableModel::flags(index) & ~Qt::ItemIsSelectable); - if (index.column() == m_checkableColumn) - return flags.setFlag(Qt::ItemIsUserCheckable); - - return flags; - } - - QVector getCheckedIds() const - { - QVector ids; - - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) - { - const T &entry = LtsAbstractTableModel::m_vecData.at(row); - if (entry.first) - ids << entry.second.id(); } - return ids; - } - - QVector getUncheckedIds() const - { - QVector ids; - - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { - const T &entry = LtsAbstractTableModel::m_vecData.at(row); - if (!entry.first) - ids << entry.second.id(); + if (role == Qt::CheckStateRole && index.column() == m_checkableColumn && + LtsAbstractTableModel::indexIsValid(index)) + return LtsAbstractTableModel::m_vecData.at(index.row()).first ? Qt::Checked : Qt::Unchecked; + return QVariant(); } - return ids; - } - - bool setChecked(const QVector &vecCheckedIds) - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override { - T &entry = LtsAbstractTableModel::m_vecData[row]; - bool bContains = vecCheckedIds.contains(entry.second.id()); - if (entry.first != bContains) - { - entry.first = bContains; - const QModelIndex idx(LtsAbstractTableModel::index(row, m_checkableColumn, QModelIndex())); - emit LtsAbstractTableModel::dataChanged(idx, idx, {Qt::CheckStateRole}); - } + if (role == Qt::CheckStateRole) + { + switchCheckbox(index); + return true; + } + return QAbstractItemModel::setData(index, value, role); } - return true; - } - bool isFiltered(const T &data, DataModification modType) const override - { - Q_UNUSED(data); - Q_UNUSED(modType); - return false; - } - -public slots: - void switchCheckbox(const QModelIndex &index) - { - auto entry = LtsAbstractTableModel::getRowData(index.row()); - entry.first = !entry.first; - LtsAbstractTableModel::setRowData(index.row(), entry); - } - - void selectAll() - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + Qt::ItemFlags flags(const QModelIndex& index) const override { - T entry = LtsAbstractTableModel::m_vecData.at(row); - entry.first = true; - LtsAbstractTableModel::setRowData(row, entry); - } - } + Qt::ItemFlags flags(LtsWidgets::LtsAbstractTableModel::flags(index) & ~Qt::ItemIsSelectable); + if (index.column() == m_checkableColumn) + return flags.setFlag(Qt::ItemIsUserCheckable); - void unselectAll() - { - for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + return flags; + } + + QVector getCheckedIds() const { - T entry = LtsAbstractTableModel::m_vecData.at(row); - entry.first = false; - LtsAbstractTableModel::setRowData(row, entry); + QVector ids; + + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + const T& entry = LtsAbstractTableModel::m_vecData.at(row); + if (entry.first) + ids << entry.second.id(); + } + + return ids; } - } -private: - int m_checkableColumn; + QVector getUncheckedIds() const + { + QVector ids; + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + const T& entry = LtsAbstractTableModel::m_vecData.at(row); + if (!entry.first) + ids << entry.second.id(); + } + + return ids; + } + + bool setChecked(const QVector& vecCheckedIds) + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + T& entry = LtsAbstractTableModel::m_vecData[row]; + bool bContains = vecCheckedIds.contains(entry.second.id()); + if (entry.first != bContains) + { + entry.first = bContains; + const QModelIndex idx(LtsAbstractTableModel::index(row, m_checkableColumn, QModelIndex())); + emit LtsAbstractTableModel::dataChanged(idx, idx, {Qt::CheckStateRole}); + } + } + + return true; + } + + bool isFiltered(const T& data, DataModification modType) const override + { + Q_UNUSED(data); + Q_UNUSED(modType); + return false; + } + + public slots: + + void switchCheckbox(const QModelIndex& index) + { + auto entry = LtsAbstractTableModel::getRowData(index.row()); + entry.first = !entry.first; + LtsAbstractTableModel::setRowData(index.row(), entry); + } + + void selectAll() + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + T entry = LtsAbstractTableModel::m_vecData.at(row); + entry.first = true; + LtsAbstractTableModel::setRowData(row, entry); + } + } + + void unselectAll() + { + for (int row = 0; row < LtsAbstractTableModel::rowCount(); ++row) + { + T entry = LtsAbstractTableModel::m_vecData.at(row); + entry.first = false; + LtsAbstractTableModel::setRowData(row, entry); + } + } + + private: + int m_checkableColumn; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp old mode 100755 new mode 100644 index 2a9efa15b..bc994c005 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_column_filter_proxy_model.cpp @@ -1,156 +1,150 @@ - #include "lts_column_filter_proxy_model.h" #include - #include - namespace LtsWidgets { -LtsColumnFilterProxyModel::LtsColumnFilterProxyModel(QObject *parent) - : QSortFilterProxyModel(parent) +LtsColumnFilterProxyModel::LtsColumnFilterProxyModel(QObject* parent) : QSortFilterProxyModel(parent) { - setSortCaseSensitivity(Qt::CaseInsensitive); + setSortCaseSensitivity(Qt::CaseInsensitive); } -bool LtsColumnFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const +bool LtsColumnFilterProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { - return LtsUtils::lessThan(sourceModel()->data(left), sourceModel()->data(right)); + return LtsUtils::lessThan(sourceModel()->data(left), sourceModel()->data(right)); } -void LtsColumnFilterProxyModel::onSetColumnStringFilter(const QString &newFilterString, int column) +void LtsColumnFilterProxyModel::onSetColumnStringFilter(const QString& newFilterString, int column) { - setColumnStringFilter(newFilterString, column); + setColumnStringFilter(newFilterString, column); } -void LtsColumnFilterProxyModel::onSetColumnDataFilter(const QVariant &newFilterData, int column) +void LtsColumnFilterProxyModel::onSetColumnDataFilter(const QVariant& newFilterData, int column) { - setColumnDataFilter(newFilterData, column); + setColumnDataFilter(newFilterData, column); } -void LtsColumnFilterProxyModel::setColumnStringFilter(const QString &newFilterString, int column) +void LtsColumnFilterProxyModel::setColumnStringFilter(const QString& newFilterString, int column) { - if (column < 0) - return; - auto it = m_columnStringFilters.find(column); - if (newFilterString.isEmpty()) - { - if (it == m_columnStringFilters.end()) - return; - m_columnStringFilters.erase(it); - } - else - { - auto rx = QRegularExpression(newFilterString, - QRegularExpression::CaseInsensitiveOption); - if (it == m_columnStringFilters.end()) + if (column < 0) + return; + auto it = m_columnStringFilters.find(column); + if (newFilterString.isEmpty()) { - m_columnStringFilters.insert(column, rx); + if (it == m_columnStringFilters.end()) + return; + m_columnStringFilters.erase(it); } else { - if (rx == it.value()) - return; - it.value() = rx; + auto rx = QRegularExpression(newFilterString, QRegularExpression::CaseInsensitiveOption); + if (it == m_columnStringFilters.end()) + { + m_columnStringFilters.insert(column, rx); + } + else + { + if (rx == it.value()) + return; + it.value() = rx; + } } - } - invalidateFilter(); + invalidateFilter(); } -void LtsColumnFilterProxyModel::setColumnDataFilter(const QVariant &newFilterData, int column) +void LtsColumnFilterProxyModel::setColumnDataFilter(const QVariant& newFilterData, int column) { - if (column < 0) - return; - auto it = m_columnDataFilters.find(column); - if (newFilterData.isNull()) - { - if (it == m_columnDataFilters.end()) - return; - m_columnDataFilters.erase(it); - } - else - { - if (it == m_columnDataFilters.end()) + if (column < 0) + return; + auto it = m_columnDataFilters.find(column); + if (newFilterData.isNull()) { - m_columnDataFilters[column] = newFilterData; + if (it == m_columnDataFilters.end()) + return; + m_columnDataFilters.erase(it); } else { - if (newFilterData == it.value()) - return; - it.value() = newFilterData; + if (it == m_columnDataFilters.end()) + { + m_columnDataFilters[column] = newFilterData; + } + else + { + if (newFilterData == it.value()) + return; + it.value() = newFilterData; + } } - } - invalidateFilter(); + invalidateFilter(); } - -bool LtsColumnFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool LtsColumnFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - - const auto sm = sourceModel(); - bool bRet = true; - for (auto it = m_columnDataFilters.begin(); bRet && it != m_columnDataFilters.end(); ++it) - { - const QModelIndex idx = sm->index(source_row, it.key(), source_parent); - const QVariant _data = sm->data(idx, LtsWidgets::LtsColumnFilterProxyModel::ComboboxFilterRole).toString(); - bRet = _data == it.value(); - if (!bRet) - break; - } - for (auto it = m_columnStringFilters.begin(); bRet && it != m_columnStringFilters.end(); ++it) - { - const QRegularExpression &rx = it.value(); - if (!rx.isValid()) - continue; - const QModelIndex idx = sm->index(source_row, it.key(), source_parent); - const QString _data = sm->data(idx, Qt::DisplayRole).toString(); - bRet = _data.contains(rx); - if (!bRet) - break; - } + const auto sm = sourceModel(); + bool bRet = true; + for (auto it = m_columnDataFilters.begin(); bRet && it != m_columnDataFilters.end(); ++it) + { + const QModelIndex idx = sm->index(source_row, it.key(), source_parent); + const QVariant _data = sm->data(idx, LtsWidgets::LtsColumnFilterProxyModel::ComboboxFilterRole).toString(); + bRet = _data == it.value(); + if (!bRet) + break; + } + + for (auto it = m_columnStringFilters.begin(); bRet && it != m_columnStringFilters.end(); ++it) + { + const QRegularExpression& rx = it.value(); + if (!rx.isValid()) + continue; + const QModelIndex idx = sm->index(source_row, it.key(), source_parent); + const QString _data = sm->data(idx, Qt::DisplayRole).toString(); + bRet = _data.contains(rx); + if (!bRet) + break; + } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) - if (!bRet && m_bRecursiveFiltering) - { - const QModelIndex idx = sm->index(source_row, 0, source_parent); - if (checkIfOneChildIsVisible(idx)) - return true; - } + if (!bRet && m_bRecursiveFiltering) + { + const QModelIndex idx = sm->index(source_row, 0, source_parent); + if (checkIfOneChildIsVisible(idx)) + return true; + } #endif - return bRet; + return bRet; } #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) void LtsColumnFilterProxyModel::setRecursiveFilteringEnabled(bool recursive) { - if (m_bRecursiveFiltering == recursive) - return; - m_bRecursiveFiltering = recursive; - invalidateFilter(); + if (m_bRecursiveFiltering == recursive) + return; + m_bRecursiveFiltering = recursive; + invalidateFilter(); } bool LtsColumnFilterProxyModel::recursiveFilteringEnabled() const { - return m_bRecursiveFiltering; + return m_bRecursiveFiltering; } -bool LtsColumnFilterProxyModel::checkIfOneChildIsVisible(const QModelIndex &parent) const +bool LtsColumnFilterProxyModel::checkIfOneChildIsVisible(const QModelIndex& parent) const { - const auto sm = sourceModel(); - const int childCount = sm->rowCount(parent); - for (int i = 0; i < childCount; ++i) - { - if (filterAcceptsRow(i, parent)) - return true; - } - return false; + const auto sm = sourceModel(); + const int childCount = sm->rowCount(parent); + for (int i = 0; i < childCount; ++i) + { + if (filterAcceptsRow(i, parent)) + return true; + } + return false; } #endif -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h old mode 100755 new mode 100644 index 4a9468e61..db7873c14 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit.h @@ -1,23 +1,19 @@ - #pragma once -#include - - #include "ltswidgets_export.h" #include "qcheckbox.h" #include "qpushbutton.h" +#include #include #include - namespace Ui { -class LtsDateTimeEditLe; -class LtsDateTimeEdit; -} +class LtsDateTimeEditLe; +class LtsDateTimeEdit; +} // namespace Ui class QLineEdit; class QShortcut; @@ -26,189 +22,228 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable) - Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool checkable READ isCheckable WRITE setCheckable) + Q_PROPERTY(bool checked READ isChecked WRITE setChecked NOTIFY toggled) -public: - - using CurrentTimeCallback = std::function; + public: + using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool checkable = false); - ~LtsDateTimeEdit(); + explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool checkable = false); + ~LtsDateTimeEdit(); - bool setupUiTouch(); + bool setupUiTouch(); + qint64 msecsSinceEpoch() const; + bool isEmpty() const; + bool isValidDate() const; - qint64 msecsSinceEpoch() const; - bool isEmpty() const; - bool isValidDate() const; + void setAutoForward(const bool af) + { + m_autoForward = af; + } - void setAutoForward(const bool af) { m_autoForward = af; } - bool getAutoForward() const { return m_autoForward; } + bool getAutoForward() const + { + return m_autoForward; + } - void setEditTimezone(const bool edit); - bool getEditTimezone() const { return m_editTimezone; } + void setEditTimezone(const bool edit); - void setWithButtons(const bool buttons); - bool getWithButtons() const { return m_withButtons; } + bool getEditTimezone() const + { + return m_editTimezone; + } - void setWithSlider(const bool slider); - bool getWithSlider() const { return m_withSlider; } + void setWithButtons(const bool buttons); - void setReadOnly(const bool readOnly); - bool isReadOnly() const { return m_readOnly; } + bool getWithButtons() const + { + return m_withButtons; + } - void setCheckable(bool checkable); - bool isCheckable() const { return m_checkable; } - void setChecked(bool bChecked); - bool isChecked() const; + void setWithSlider(const bool slider); - void setWithNowButton(bool nowButton); - bool withNowButton() const { return m_withNowButton; } + bool getWithSlider() const + { + return m_withSlider; + } - - void setMinimumTimeMSec(qint64 msec); - qint64 minimumTimeMSec() const { return m_minTimeMSec; } + void setReadOnly(const bool readOnly); - - void setMaximumTimeMSec(qint64 msec); - qint64 maximumTimeMSec() const { return m_maxTimeMSec; } + bool isReadOnly() const + { + return m_readOnly; + } - void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } + void setCheckable(bool checkable); - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); + bool isCheckable() const + { + return m_checkable; + } - bool setTimezone(char tz); - char getTimezone() const; - qint64 getTimezoneAsSecs() const; + void setChecked(bool bChecked); + bool isChecked() const; - void setSubWidgetsProperties(const QString &name, const QVariant &value); + void setWithNowButton(bool nowButton); -Q_SIGNALS: - void dateTimeChanged(); - void toggled(bool on); + bool withNowButton() const + { + return m_withNowButton; + } -public Q_SLOTS: - bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); - void clear(); + void setMinimumTimeMSec(qint64 msec); -private: - void clearTimezone(); + qint64 minimumTimeMSec() const + { + return m_minTimeMSec; + } - void setMinMaxMonth(int minMonth, int maxMonth); + void setMaximumTimeMSec(qint64 msec); - bool setMonth(int month); - int getMonth() const; + qint64 maximumTimeMSec() const + { + return m_maxTimeMSec; + } - bool setDay(int day); - int getDay() const; + void setMinMaxTimeMSec(qint64 min, qint64 max) + { + setMinimumTimeMSec(min); + setMaximumTimeMSec(max); + } - bool setHHMMSS(int hour, int minute, int second); - int getHour() const; - int getMinute() const; - int getSecond() const; + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); - bool setYear(int year); - int getYear() const; + bool setTimezone(char tz); + char getTimezone() const; + qint64 getTimezoneAsSecs() const; - bool isEmptyDay() const; - bool isEmptyHHMMSS() const; - bool isEmptyTimezone() const; - bool isEmptyMonth() const; - bool isEmptyYear() const; + void setSubWidgetsProperties(const QString& name, const QVariant& value); - bool hasFocus() const; + Q_SIGNALS: + void dateTimeChanged(); + void toggled(bool on); - bool isDataAcceptable(); + public Q_SLOTS: + bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); + void clear(); - void showInvalidData(bool setFocus); + private: + void clearTimezone(); - bool isLineEditDataAcceptable(QLineEdit *le) const; + void setMinMaxMonth(int minMonth, int maxMonth); - bool isDayAcceptable() const; - bool isHHMMSSAcceptable() const; - bool isMonthAcceptable() const; - bool isYearAcceptable() const; - bool isTzAcceptable() const; + bool setMonth(int month); + int getMonth() const; - QCheckBox* checkBox() const; - QPushButton* pbNow() const; + bool setDay(int day); + int getDay() const; -private Q_SLOTS: - void setFixedDateTime(); - void setOffsetDateTime(); + bool setHHMMSS(int hour, int minute, int second); + int getHour() const; + int getMinute() const; + int getSecond() const; - void setSliderValue(int val); - void valueDayChanged(const QString &str); - void fixupHHMMSS(); - void valueMonthChanged(const QString &str); - void valueMonthChanged2(const QString &str); - void valueTimezoneChangedStr(const QString &str); - void valueTimezoneChangedInt(int newTimezone); - void valueYearChanged(const QString &str); + bool setYear(int year); + int getYear() const; - void onBackHourClicked(); - void onBackMinuteClicked(); - void onBackSecondClicked(); - void onForwardSecondClicked(); - void onForwardMinuteClicked(); - void onForwardHourClicked(); + bool isEmptyDay() const; + bool isEmptyHHMMSS() const; + bool isEmptyTimezone() const; + bool isEmptyMonth() const; + bool isEmptyYear() const; - void onCheckBoxChanged(); - void disableControls(); - void enableControls(); - void enaDisaControls(bool bEnable); + bool hasFocus() const; - void onFocusOutHHMMSS(); - void onFocusOutTZ(); - void onFocusOutDay(); - void onFocusOutMonth(); - void onFocusOutYear(); + bool isDataAcceptable(); - void onFocusOutBackspace(); - void onFocusOut(); + void showInvalidData(bool setFocus); - void onHmsWheelEvent(bool bForward, int cursorPos); - void onDayWheelEvent(bool bForward, int cursorPos); - void onMonthWheelEvent(bool bForward, int cursorPos); - void onYearWheelEvent(bool bForward, int cursorPos); + bool isLineEditDataAcceptable(QLineEdit* le) const; -private: - Ui::LtsDateTimeEditLe *m_uiLe{nullptr}; - Ui::LtsDateTimeEdit *m_uiTouch{nullptr}; - QShortcut *m_scFixed = nullptr; - QShortcut *m_scOffset = nullptr; + bool isDayAcceptable() const; + bool isHHMMSSAcceptable() const; + bool isMonthAcceptable() const; + bool isYearAcceptable() const; + bool isTzAcceptable() const; - CurrentTimeCallback m_getCurrentTimeCallback = nullptr; + QCheckBox* checkBox() const; + QPushButton* pbNow() const; - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; + private Q_SLOTS: + void setFixedDateTime(); + void setOffsetDateTime(); - qint64 m_curTimeMSec = -1; + void setSliderValue(int val); + void valueDayChanged(const QString& str); + void fixupHHMMSS(); + void valueMonthChanged(const QString& str); + void valueMonthChanged2(const QString& str); + void valueTimezoneChangedStr(const QString& str); + void valueTimezoneChangedInt(int newTimezone); + void valueYearChanged(const QString& str); - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_checkable = false; - bool m_withNowButton = false; + void onBackHourClicked(); + void onBackMinuteClicked(); + void onBackSecondClicked(); + void onForwardSecondClicked(); + void onForwardMinuteClicked(); + void onForwardHourClicked(); - int m_minMonth{0}; - int m_maxMonth{0}; + void onCheckBoxChanged(); + void disableControls(); + void enableControls(); + void enaDisaControls(bool bEnable); + void onFocusOutHHMMSS(); + void onFocusOutTZ(); + void onFocusOutDay(); + void onFocusOutMonth(); + void onFocusOutYear(); - bool m_backspacePressed = false; - bool m_recursionAvoid = false; - bool m_dateIsAcceptable = false; + void onFocusOutBackspace(); + void onFocusOut(); + + void onHmsWheelEvent(bool bForward, int cursorPos); + void onDayWheelEvent(bool bForward, int cursorPos); + void onMonthWheelEvent(bool bForward, int cursorPos); + void onYearWheelEvent(bool bForward, int cursorPos); + + private: + Ui::LtsDateTimeEditLe* m_uiLe{nullptr}; + Ui::LtsDateTimeEdit* m_uiTouch{nullptr}; + QShortcut* m_scFixed = nullptr; + QShortcut* m_scOffset = nullptr; + + CurrentTimeCallback m_getCurrentTimeCallback = nullptr; + + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; + + qint64 m_curTimeMSec = -1; + + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_checkable = false; + bool m_withNowButton = false; + + int m_minMonth{0}; + int m_maxMonth{0}; + + bool m_backspacePressed = false; + bool m_recursionAvoid = false; + bool m_dateIsAcceptable = false; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h old mode 100755 new mode 100644 index 405f97495..0532ac4e3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_p.h @@ -1,44 +1,46 @@ #pragma once -#include - #include +#include namespace LtsWidgets { class LineEdit : public QLineEdit { - Q_OBJECT -public: - using QLineEdit::QLineEdit; + Q_OBJECT + public: + using QLineEdit::QLineEdit; - void clear(); - bool isEmpty() const; -protected: - void contextMenuEvent(QContextMenuEvent *e) override; - void focusOutEvent(QFocusEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; -Q_SIGNALS: - void focusOutBackspace(); - void focusOut(); + void clear(); + bool isEmpty() const; + + protected: + void contextMenuEvent(QContextMenuEvent* e) override; + void focusOutEvent(QFocusEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; + Q_SIGNALS: + void focusOutBackspace(); + void focusOut(); }; class DigitsLineEdit final : public LineEdit { - Q_OBJECT -public: - DigitsLineEdit(QWidget *parent = nullptr); + Q_OBJECT + public: + DigitsLineEdit(QWidget* parent = nullptr); - void setExactNumDigits(int num); - void setCursorPosition(int curPos); - void setValue(int val); - int getValue() const; -Q_SIGNALS: - void wheelEventReceived(bool bForward, int cursorPos); -protected: - void wheelEvent(QWheelEvent *event) override; - void keyPressEvent(QKeyEvent *event) override; -private: - int m_exactNumDigits = -1; + void setExactNumDigits(int num); + void setCursorPosition(int curPos); + void setValue(int val); + int getValue() const; + Q_SIGNALS: + void wheelEventReceived(bool bForward, int cursorPos); + + protected: + void wheelEvent(QWheelEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; + + private: + int m_exactNumDigits = -1; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h old mode 100755 new mode 100644 index 0ef46aabc..e2304254f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_rc.h @@ -1,21 +1,17 @@ - #pragma once -#include - - #include "ltswidgets_export.h" +#include #include #include - namespace Ui { -class LtsDateTimeEditLe; -class LtsDateTimeEdit; -} +class LtsDateTimeEditLe; +class LtsDateTimeEdit; +} // namespace Ui class QLineEdit; class QShortcut; @@ -24,184 +20,223 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) -public: - - using CurrentTimeCallback = std::function; + public: + using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool withCheckBox = false); - ~LtsDateTimeEdit(); + explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool withCheckBox = false); + ~LtsDateTimeEdit(); - bool setupUiTouch(); + bool setupUiTouch(); + qint64 msecsSinceEpoch() const; + bool isEmpty() const; + bool isValidDate() const; - qint64 msecsSinceEpoch() const; - bool isEmpty() const; - bool isValidDate() const; + void setAutoForward(const bool af) + { + m_autoForward = af; + } - void setAutoForward(const bool af) { m_autoForward = af; } - bool getAutoForward() const { return m_autoForward; } + bool getAutoForward() const + { + return m_autoForward; + } - void setEditTimezone(const bool edit); - bool getEditTimezone() const { return m_editTimezone; } + void setEditTimezone(const bool edit); - void setWithButtons(const bool buttons); - bool getWithButtons() const { return m_withButtons; } + bool getEditTimezone() const + { + return m_editTimezone; + } - void setWithSlider(const bool slider); - bool getWithSlider() const { return m_withSlider; } + void setWithButtons(const bool buttons); - void setReadOnly(const bool readOnly); - bool isReadOnly() const { return m_readOnly; } + bool getWithButtons() const + { + return m_withButtons; + } - void setWithCheckBox(bool checkBoxEnabled); - bool withCheckBox() const { return m_withCheckBox; } - void setCheckBoxChecked(bool bChecked); - bool isCheckBoxChecked() const; + void setWithSlider(const bool slider); - void setWithNowButton(bool nowButton); - bool withNowButton() const { return m_withNowButton; } + bool getWithSlider() const + { + return m_withSlider; + } - - void setMinimumTimeMSec(qint64 msec); - qint64 minimumTimeMSec() const { return m_minTimeMSec; } + void setReadOnly(const bool readOnly); - - void setMaximumTimeMSec(qint64 msec); - qint64 maximumTimeMSec() const { return m_maxTimeMSec; } + bool isReadOnly() const + { + return m_readOnly; + } - void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } + void setWithCheckBox(bool checkBoxEnabled); - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); + bool withCheckBox() const + { + return m_withCheckBox; + } - bool setTimezone(char tz); - char getTimezone() const; - qint64 getTimezoneAsSecs() const; + void setCheckBoxChecked(bool bChecked); + bool isCheckBoxChecked() const; - void setSubWidgetsProperties(const QString &name, const QVariant &value); + void setWithNowButton(bool nowButton); -Q_SIGNALS: - void dateTimeChanged(); + bool withNowButton() const + { + return m_withNowButton; + } -public Q_SLOTS: - bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); - void clear(); + void setMinimumTimeMSec(qint64 msec); -private: - void clearTimezone(); + qint64 minimumTimeMSec() const + { + return m_minTimeMSec; + } - void setMinMaxMonth(int minMonth, int maxMonth); + void setMaximumTimeMSec(qint64 msec); - bool setMonth(int month); - int getMonth() const; + qint64 maximumTimeMSec() const + { + return m_maxTimeMSec; + } - bool setDay(int day); - int getDay() const; + void setMinMaxTimeMSec(qint64 min, qint64 max) + { + setMinimumTimeMSec(min); + setMaximumTimeMSec(max); + } - bool setHHMMSS(int hour, int minute, int second); - int getHour() const; - int getMinute() const; - int getSecond() const; + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); - bool setYear(int year); - int getYear() const; + bool setTimezone(char tz); + char getTimezone() const; + qint64 getTimezoneAsSecs() const; - bool isEmptyDay() const; - bool isEmptyHHMMSS() const; - bool isEmptyTimezone() const; - bool isEmptyMonth() const; - bool isEmptyYear() const; + void setSubWidgetsProperties(const QString& name, const QVariant& value); - bool hasFocus() const; + Q_SIGNALS: + void dateTimeChanged(); - bool isDataAcceptable(); + public Q_SLOTS: + bool setMsecsSinceEpoch(qint64 msec, bool setToNearestPossible = true); + void clear(); - void showInvalidData(bool setFocus); + private: + void clearTimezone(); - bool isLineEditDataAcceptable(QLineEdit *le) const; + void setMinMaxMonth(int minMonth, int maxMonth); - bool isDayAcceptable() const; - bool isHHMMSSAcceptable() const; - bool isMonthAcceptable() const; - bool isYearAcceptable() const; - bool isTzAcceptable() const; + bool setMonth(int month); + int getMonth() const; -private Q_SLOTS: - void setFixedDateTime(); - void setOffsetDateTime(); + bool setDay(int day); + int getDay() const; - void setSliderValue(int val); - void valueDayChanged(const QString &str); - void fixupHHMMSS(); - void valueMonthChanged(const QString &str); - void valueMonthChanged2(const QString &str); - void valueTimezoneChangedStr(const QString &str); - void valueTimezoneChangedInt(int newTimezone); - void valueYearChanged(const QString &str); + bool setHHMMSS(int hour, int minute, int second); + int getHour() const; + int getMinute() const; + int getSecond() const; - void onBackHourClicked(); - void onBackMinuteClicked(); - void onBackSecondClicked(); - void onForwardSecondClicked(); - void onForwardMinuteClicked(); - void onForwardHourClicked(); + bool setYear(int year); + int getYear() const; - void onCheckBoxChanged(); - void disableControls(); - void enableControls(); - void enaDisaControls(bool bEnable); + bool isEmptyDay() const; + bool isEmptyHHMMSS() const; + bool isEmptyTimezone() const; + bool isEmptyMonth() const; + bool isEmptyYear() const; - void onFocusOutHHMMSS(); - void onFocusOutTZ(); - void onFocusOutDay(); - void onFocusOutMonth(); - void onFocusOutYear(); + bool hasFocus() const; - void onFocusOutBackspace(); - void onFocusOut(); + bool isDataAcceptable(); - void onHmsWheelEvent(bool bForward, int cursorPos); - void onDayWheelEvent(bool bForward, int cursorPos); - void onMonthWheelEvent(bool bForward, int cursorPos); - void onYearWheelEvent(bool bForward, int cursorPos); + void showInvalidData(bool setFocus); -private: - Ui::LtsDateTimeEditLe *m_uiLe{nullptr}; - Ui::LtsDateTimeEdit *m_uiTouch{nullptr}; - QShortcut *m_scFixed = nullptr; - QShortcut *m_scOffset = nullptr; + bool isLineEditDataAcceptable(QLineEdit* le) const; - CurrentTimeCallback m_getCurrentTimeCallback = nullptr; + bool isDayAcceptable() const; + bool isHHMMSSAcceptable() const; + bool isMonthAcceptable() const; + bool isYearAcceptable() const; + bool isTzAcceptable() const; - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; + private Q_SLOTS: + void setFixedDateTime(); + void setOffsetDateTime(); - qint64 m_curTimeMSec = -1; + void setSliderValue(int val); + void valueDayChanged(const QString& str); + void fixupHHMMSS(); + void valueMonthChanged(const QString& str); + void valueMonthChanged2(const QString& str); + void valueTimezoneChangedStr(const QString& str); + void valueTimezoneChangedInt(int newTimezone); + void valueYearChanged(const QString& str); - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_withCheckBox = false; - bool m_withNowButton = false; + void onBackHourClicked(); + void onBackMinuteClicked(); + void onBackSecondClicked(); + void onForwardSecondClicked(); + void onForwardMinuteClicked(); + void onForwardHourClicked(); - int m_minMonth{0}; - int m_maxMonth{0}; + void onCheckBoxChanged(); + void disableControls(); + void enableControls(); + void enaDisaControls(bool bEnable); + void onFocusOutHHMMSS(); + void onFocusOutTZ(); + void onFocusOutDay(); + void onFocusOutMonth(); + void onFocusOutYear(); - bool m_backspacePressed = false; - bool m_recursionAvoid = false; - bool m_dateIsAcceptable = false; + void onFocusOutBackspace(); + void onFocusOut(); + + void onHmsWheelEvent(bool bForward, int cursorPos); + void onDayWheelEvent(bool bForward, int cursorPos); + void onMonthWheelEvent(bool bForward, int cursorPos); + void onYearWheelEvent(bool bForward, int cursorPos); + + private: + Ui::LtsDateTimeEditLe* m_uiLe{nullptr}; + Ui::LtsDateTimeEdit* m_uiTouch{nullptr}; + QShortcut* m_scFixed = nullptr; + QShortcut* m_scOffset = nullptr; + + CurrentTimeCallback m_getCurrentTimeCallback = nullptr; + + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; + + qint64 m_curTimeMSec = -1; + + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_withCheckBox = false; + bool m_withNowButton = false; + + int m_minMonth{0}; + int m_maxMonth{0}; + + bool m_backspacePressed = false; + bool m_recursionAvoid = false; + bool m_dateIsAcceptable = false; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp old mode 100755 new mode 100644 index 0f143f714..a0898de6d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.cpp @@ -1,389 +1,364 @@ - #include "lts_date_time_edit_touch.h" + #include "ui_lts_date_time_edit_touch.h" -#include #include #include #include +#include namespace LtsWidgets { -LtsDateTimeEdit::LtsDateTimeEdit(QWidget *parent, bool withNowButton, bool withCheckBox) - : QWidget(parent) - , m_withCheckBox(withCheckBox) - , m_withNowButton(withNowButton) - , m_tzOffset(0) - , m_minMonth(1) - , m_maxMonth(12) - , m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, SLOT(onSetFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(onSetOffsetDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)) - , m_getCurrentTimeCallback(nullptr) - , m_ui(new Ui::LtsDateTimeEdit) +LtsDateTimeEdit::LtsDateTimeEdit(QWidget* parent, bool withNowButton, bool withCheckBox) + : QWidget(parent), m_withCheckBox(withCheckBox), m_withNowButton(withNowButton), m_tzOffset(0), m_minMonth(1), + m_maxMonth(12), m_scFixed(new QShortcut(QKeySequence(Qt::ShiftModifier + Qt::Key_F2), this, + SLOT(onSetFixedDateTime()), nullptr, Qt::WidgetWithChildrenShortcut)), + m_scOffset(new QShortcut(QKeySequence(Qt::Key_F2), this, SLOT(onSetOffsetDateTime()), nullptr, + Qt::WidgetWithChildrenShortcut)), + m_getCurrentTimeCallback(nullptr), m_ui(new Ui::LtsDateTimeEdit) { - m_ui->setupUi(this); - setFocusPolicy(Qt::StrongFocus); + m_ui->setupUi(this); + setFocusPolicy(Qt::StrongFocus); + for (int i = 65; i < 91; i++) + { + if (QChar(i).toUpper() == QChar::fromLatin1('I')) + continue; + m_ui->cbxTimeZone->addItem(QChar(i), QChar(i)); + } - for (int i = 65; i < 91; i++ ) - { - if (QChar(i).toUpper() == QChar::fromLatin1('I')) - continue; - m_ui->cbxTimeZone->addItem(QChar(i), QChar(i)); + connect(m_ui->pbNow, &QPushButton::clicked, this, &LtsDateTimeEdit::onSetOffsetDateTime); + connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spDay, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spHour, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spMinutes, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spSeconds, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->spYear, &QSpinBox::editingFinished, this, &LtsDateTimeEdit::onDateTimeChanged); - } + connect(m_ui->checkBox, &QCheckBox::toggled, this, &LtsDateTimeEdit::onCheckBoxChanged); + connect(m_ui->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::onTimeZoneChanged); - connect(m_ui->pbNow, &QPushButton::clicked, - this, &LtsDateTimeEdit::onSetOffsetDateTime); - connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spDay, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spHour, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spMinutes, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spSeconds, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::onDateTimeChanged); - connect(m_ui->spYear, &QSpinBox::editingFinished, - this, &LtsDateTimeEdit::onDateTimeChanged); + connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), this, + &LtsDateTimeEdit::onMonthChanged); - connect(m_ui->checkBox, &QCheckBox::toggled, - this, &LtsDateTimeEdit::onCheckBoxChanged); - connect(m_ui->cbxTimeZone, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::onTimeZoneChanged); + m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); - connect(m_ui->cbxMonth, static_cast(&QComboBox::currentIndexChanged), - this, &LtsDateTimeEdit::onMonthChanged); + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findText(QString(QLatin1Char(DTG::timezone())))); + onTimeZoneChanged(); + setMinMaxMonth(1, 12); - m_tzOffset = DTG::timezone2Secs(QLatin1Char(DTG::timezone()).toLatin1()); + int offset = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) + .toLongLong() / + 1000; + m_ui->pbNow->setToolTip(tr("Set to current time plus %n second(s) offset", "", offset)); - - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findText(QString(QLatin1Char(DTG::timezone())))); - onTimeZoneChanged(); - setMinMaxMonth(1,12); + updateDateTimeType(); - - int offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong()/1000; - m_ui->pbNow->setToolTip(tr("Set to current time plus %n second(s) offset", "", offset)); - - updateDateTimeType(); - - m_ui->checkBox->setVisible(m_withCheckBox); - m_ui->pbNow->setVisible(m_withNowButton); + m_ui->checkBox->setVisible(m_withCheckBox); + m_ui->pbNow->setVisible(m_withNowButton); } LtsDateTimeEdit::~LtsDateTimeEdit() { - delete m_ui; + delete m_ui; } void LtsDateTimeEdit::updateDateTimeType() { - switch (DTG::dateTimeType()) - { - case DTG::DateTimeType::DTG: - break; - case DTG::DateTimeType::DDMMYYYY_HHMMSS_Z: - break; - case DTG::DateTimeType::DDMMYYYY_Z_HHMMSS: - break; - default: - break; - } + switch (DTG::dateTimeType()) + { + case DTG::DateTimeType::DTG: + break; + case DTG::DateTimeType::DDMMYYYY_HHMMSS_Z: + break; + case DTG::DateTimeType::DDMMYYYY_Z_HHMMSS: + break; + default: + break; + } } bool LtsDateTimeEdit::setTimezone(char tz) { - QChar tzLocal = QChar(QLatin1Char(tz)).toUpper(); - if (tzLocal.toLatin1() == 'J') - tzLocal = QLatin1Char('Z'); - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tzLocal)); - int offset = DTG::timezone2Secs(tzLocal.toLatin1()); - if (offset != m_tzOffset) - { - const auto ms = msecsSinceEpoch(); - m_tzOffset = offset; - setMsecsSinceEpoch(ms+m_tzOffset); - } - return true; + QChar tzLocal = QChar(QLatin1Char(tz)).toUpper(); + if (tzLocal.toLatin1() == 'J') + tzLocal = QLatin1Char('Z'); + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tzLocal)); + int offset = DTG::timezone2Secs(tzLocal.toLatin1()); + if (offset != m_tzOffset) + { + const auto ms = msecsSinceEpoch(); + m_tzOffset = offset; + setMsecsSinceEpoch(ms + m_tzOffset); + } + return true; } char LtsDateTimeEdit::getTimezone() const { - QChar tz = m_ui->cbxTimeZone->currentText().at(0).toUpper(); + QChar tz = m_ui->cbxTimeZone->currentText().at(0).toUpper(); + if (tz.toLatin1() == 'J') + tz = QLatin1Char('Z'); - if (tz.toLatin1() == 'J') - tz = QLatin1Char('Z'); - - if (tz.isNull()) - return DTG::timezone(); - return tz.toLatin1(); + if (tz.isNull()) + return DTG::timezone(); + return tz.toLatin1(); } - -void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth ) +void LtsDateTimeEdit::setMinMaxMonth(int minMonth, int maxMonth) { - if (m_minMonth != minMonth) - m_minMonth = minMonth; - if (m_maxMonth != maxMonth) - m_maxMonth = maxMonth; + if (m_minMonth != minMonth) + m_minMonth = minMonth; + if (m_maxMonth != maxMonth) + m_maxMonth = maxMonth; - int currentMonth = m_ui->cbxMonth->currentData().toInt(); - m_ui->cbxMonth->blockSignals(true); - m_ui->cbxMonth->clear(); - for (int i =1; i<= 12 ; i++) - { - if (i < m_minMonth) - continue; - if (i > m_maxMonth) - break; - QDate date(1777,i,1); - m_ui->cbxMonth->addItem(date.toString(QStringLiteral("MMM")),i); - - } - m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(currentMonth)); - m_ui->cbxMonth->blockSignals(false); + int currentMonth = m_ui->cbxMonth->currentData().toInt(); + m_ui->cbxMonth->blockSignals(true); + m_ui->cbxMonth->clear(); + for (int i = 1; i <= 12; i++) + { + if (i < m_minMonth) + continue; + if (i > m_maxMonth) + break; + QDate date(1777, i, 1); + m_ui->cbxMonth->addItem(date.toString(QStringLiteral("MMM")), i); + } + m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(currentMonth)); + m_ui->cbxMonth->blockSignals(false); } - -void LtsDateTimeEdit::setDateTime(const QDateTime &datetime) +void LtsDateTimeEdit::setDateTime(const QDateTime& datetime) { - if (!datetime.isValid() && m_withCheckBox) - { - m_ui->checkBox->setChecked(false); - return; - } + if (!datetime.isValid() && m_withCheckBox) + { + m_ui->checkBox->setChecked(false); + return; + } - QDateTime dt = datetime.toUTC().addSecs(m_tzOffset); - dt.setOffsetFromUtc(m_tzOffset); + QDateTime dt = datetime.toUTC().addSecs(m_tzOffset); + dt.setOffsetFromUtc(m_tzOffset); - - QDateTime oldDateTime = dateTime(); - if (dt == oldDateTime) - return; + QDateTime oldDateTime = dateTime(); + if (dt == oldDateTime) + return; - blockSignals(true); + blockSignals(true); - m_ui->spDay->setValue(dt.date().day()); - m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(dt.date().month())); - - - - - m_ui->spYear->setValue(dt.date().year()-2000); + m_ui->spDay->setValue(dt.date().day()); + m_ui->cbxMonth->setCurrentIndex(m_ui->cbxMonth->findData(dt.date().month())); - m_ui->spHour->setValue(dt.time().hour()); - m_ui->spMinutes->setValue(dt.time().minute()); - m_ui->spSeconds->setValue(dt.time().second()); + m_ui->spYear->setValue(dt.date().year() - 2000); - blockSignals(false); + m_ui->spHour->setValue(dt.time().hour()); + m_ui->spMinutes->setValue(dt.time().minute()); + m_ui->spSeconds->setValue(dt.time().second()); - const QDateTime dtNew = dateTime(); - if (dtNew != oldDateTime) - emit dateTimeChanged(); + blockSignals(false); + + const QDateTime dtNew = dateTime(); + if (dtNew != oldDateTime) + emit dateTimeChanged(); } - void LtsDateTimeEdit::onDateTimeChanged() { - emit dateTimeChanged(); + emit dateTimeChanged(); - QDateTime dateTime; - dateTime = dateTime.addYears(m_ui->spYear->value()); - dateTime = dateTime.addMonths(m_ui->cbxMonth->currentData().toInt()); - dateTime = dateTime.addDays(m_ui->spDay->value()); - dateTime = dateTime.addSecs(m_ui->spHour->value()*60*60 + m_ui->spMinutes->value()*60 + m_ui->spSeconds->value()); - if (dateTime.isValid()) - { - m_dateTime = dateTime; - - } + QDateTime dateTime; + dateTime = dateTime.addYears(m_ui->spYear->value()); + dateTime = dateTime.addMonths(m_ui->cbxMonth->currentData().toInt()); + dateTime = dateTime.addDays(m_ui->spDay->value()); + dateTime = + dateTime.addSecs(m_ui->spHour->value() * 60 * 60 + m_ui->spMinutes->value() * 60 + m_ui->spSeconds->value()); + if (dateTime.isValid()) + { + m_dateTime = dateTime; + } } void LtsDateTimeEdit::onTimeZoneChanged() { - if (m_ui->cbxMonth->currentText().isEmpty()) - { - return; - } - QChar tz = m_ui->cbxTimeZone->currentText().at(0); - if (tz.isLower()) - tz = tz.toUpper(); - if (tz.toLatin1() == 'J') - tz = QLatin1Char('Z'); - m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tz)); - int offset = DTG::timezone2Secs(tz.toLatin1()); - if (offset != m_tzOffset) - { - const auto ms = msecsSinceEpoch(); - m_tzOffset = offset; - setMsecsSinceEpoch(ms+m_tzOffset); - } + if (m_ui->cbxMonth->currentText().isEmpty()) + { + return; + } + QChar tz = m_ui->cbxTimeZone->currentText().at(0); + if (tz.isLower()) + tz = tz.toUpper(); + if (tz.toLatin1() == 'J') + tz = QLatin1Char('Z'); + m_ui->cbxTimeZone->setCurrentIndex(m_ui->cbxTimeZone->findData(tz)); + int offset = DTG::timezone2Secs(tz.toLatin1()); + if (offset != m_tzOffset) + { + const auto ms = msecsSinceEpoch(); + m_tzOffset = offset; + setMsecsSinceEpoch(ms + m_tzOffset); + } } void LtsDateTimeEdit::onMonthChanged(int month) { - - Q_UNUSED(month); + + Q_UNUSED(month); } void LtsDateTimeEdit::setWithCheckBox(bool checkBoxEnabled) { - if (m_withCheckBox == checkBoxEnabled) - return; + if (m_withCheckBox == checkBoxEnabled) + return; - m_withCheckBox = checkBoxEnabled; - m_ui->checkBox->setVisible(m_withCheckBox); - if (!m_withCheckBox) - m_ui->checkBox->setChecked(true); - emit withCheckBoxChanged(m_withCheckBox); + m_withCheckBox = checkBoxEnabled; + m_ui->checkBox->setVisible(m_withCheckBox); + if (!m_withCheckBox) + m_ui->checkBox->setChecked(true); + emit withCheckBoxChanged(m_withCheckBox); } bool LtsDateTimeEdit::isCheckBoxChecked() const { - return m_ui->checkBox->isChecked(); + return m_ui->checkBox->isChecked(); } void LtsDateTimeEdit::setWithNowButton(bool nowButton) { - if (m_withNowButton == nowButton) - return; + if (m_withNowButton == nowButton) + return; - m_withNowButton = nowButton; - m_ui->pbNow->setVisible(m_withNowButton); - emit withNowButtonChanged(m_withNowButton); + m_withNowButton = nowButton; + m_ui->pbNow->setVisible(m_withNowButton); + emit withNowButtonChanged(m_withNowButton); } void LtsDateTimeEdit::onCheckBoxChanged(bool checked) { - m_ui->spDay->setEnabled(checked); - m_ui->spHour->setEnabled(checked); - m_ui->spMinutes->setEnabled(checked); - m_ui->spSeconds->setEnabled(checked); - m_ui->spYear->setEnabled(checked); - m_ui->cbxMonth->setEnabled(checked); - m_ui->cbxTimeZone->setEnabled(checked); - m_ui->pbNow->setEnabled(checked); - emit dateTimeChanged(); + m_ui->spDay->setEnabled(checked); + m_ui->spHour->setEnabled(checked); + m_ui->spMinutes->setEnabled(checked); + m_ui->spSeconds->setEnabled(checked); + m_ui->spYear->setEnabled(checked); + m_ui->cbxMonth->setEnabled(checked); + m_ui->cbxTimeZone->setEnabled(checked); + m_ui->pbNow->setEnabled(checked); + emit dateTimeChanged(); } void LtsDateTimeEdit::setMsecsSinceEpoch(qint64 mSecsSinceEpoch) { - if (mSecsSinceEpoch == 0 && m_withCheckBox) - { - m_ui->checkBox->setChecked(false); - return; - } - m_ui->checkBox->setChecked(true); - setDateTime(QDateTime::fromMSecsSinceEpoch(mSecsSinceEpoch).toUTC()); + if (mSecsSinceEpoch == 0 && m_withCheckBox) + { + m_ui->checkBox->setChecked(false); + return; + } + m_ui->checkBox->setChecked(true); + setDateTime(QDateTime::fromMSecsSinceEpoch(mSecsSinceEpoch).toUTC()); } qint64 LtsDateTimeEdit::msecsSinceEpoch() const { - const QDateTime dt(dateTime()); - if (dt.isNull()) - return 0; - return dt.toMSecsSinceEpoch(); + const QDateTime dt(dateTime()); + if (dt.isNull()) + return 0; + return dt.toMSecsSinceEpoch(); } void LtsDateTimeEdit::clear() { - m_ui->spDay->clear(); - m_ui->spHour->clear(); - m_ui->spMinutes->clear(); - m_ui->spSeconds->clear(); - m_ui->spYear->clear(); - emit dateTimeChanged(); + m_ui->spDay->clear(); + m_ui->spHour->clear(); + m_ui->spMinutes->clear(); + m_ui->spSeconds->clear(); + m_ui->spYear->clear(); + emit dateTimeChanged(); } void LtsDateTimeEdit::setCheckBoxChecked(bool bChecked) { - m_ui->checkBox->setChecked(bChecked); + m_ui->checkBox->setChecked(bChecked); } QDateTime LtsDateTimeEdit::dateTime() const { - if (!m_ui->checkBox->isChecked()) - return QDateTime(); + if (!m_ui->checkBox->isChecked()) + return QDateTime(); - QDateTime final; - int year = 0; - if (m_ui->spYear->value() < 1000) - { - year=m_ui->spYear->value()+2000; - } - else - { - year=m_ui->spYear->value(); - } - QDate date(year,m_ui->cbxMonth->currentData().toInt(), m_ui->spDay->value()); - final.setDate(date); - final = final.addSecs(m_ui->spHour->value()*60*60 + m_ui->spMinutes->value()*60 + m_ui->spSeconds->value()); + QDateTime final; + int year = 0; + if (m_ui->spYear->value() < 1000) + { + year = m_ui->spYear->value() + 2000; + } + else + { + year = m_ui->spYear->value(); + } + QDate date(year, m_ui->cbxMonth->currentData().toInt(), m_ui->spDay->value()); + final.setDate(date); + final = final.addSecs(m_ui->spHour->value() * 60 * 60 + m_ui->spMinutes->value() * 60 + m_ui->spSeconds->value()); - if (!final.isValid()) - return QDateTime(); + if (!final.isValid()) + return QDateTime(); - - return QDateTime(final.date(), final.time(), Qt::OffsetFromUTC, m_tzOffset).toUTC(); + return QDateTime(final.date(), final.time(), Qt::OffsetFromUTC, m_tzOffset).toUTC(); } void LtsDateTimeEdit::setMaximumTimeMSec(qint64 msec) { - const auto maximumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); - m_ui->spYear->setMaximum(maximumDate.year()-2000); - - - - + const auto maximumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); + m_ui->spYear->setMaximum(maximumDate.year() - 2000); } qint64 LtsDateTimeEdit::minimumTimeMSec() const { - QDate date; - date.setDate(m_ui->spYear->minimum(), m_maxMonth, m_ui->spMinutes->minimum() ); - return QDateTime(date).toMSecsSinceEpoch(); + QDate date; + date.setDate(m_ui->spYear->minimum(), m_maxMonth, m_ui->spMinutes->minimum()); + return QDateTime(date).toMSecsSinceEpoch(); } void LtsDateTimeEdit::setMinimumTimeMSec(qint64 msec) { - const auto minimumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); - - m_ui->spYear->setMinimum(minimumDate.year()-2000); - + const auto minimumDate(QDateTime::fromMSecsSinceEpoch(msec).date()); + + m_ui->spYear->setMinimum(minimumDate.year() - 2000); } -void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb) +void LtsDateTimeEdit::setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb) { - m_getCurrentTimeCallback = cb; + m_getCurrentTimeCallback = cb; } void LtsDateTimeEdit::onSetFixedDateTime() { - setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0).toLongLong()); + setMsecsSinceEpoch(LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("FixedTime"), 0) + .toLongLong()); } void LtsDateTimeEdit::onSetOffsetDateTime() { - if (!m_getCurrentTimeCallback) - return; - qint64 offset = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0).toLongLong(); - - setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); -} + if (!m_getCurrentTimeCallback) + return; + qint64 offset = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("Offset"), 0) + .toLongLong(); + setMsecsSinceEpoch((m_getCurrentTimeCallback() / 1000) * 1000 + offset); +} void LtsDateTimeEdit::setSubWidgetsProperties(QString name, QVariant value) { - m_ui->spDay->setProperty(name.toStdString().c_str(), value); - m_ui->spHour->setProperty(name.toStdString().c_str(), value); - m_ui->spMinutes->setProperty(name.toStdString().c_str(), value); - m_ui->spSeconds->setProperty(name.toStdString().c_str(), value); - m_ui->spYear->setProperty(name.toStdString().c_str(), value); - + m_ui->spDay->setProperty(name.toStdString().c_str(), value); + m_ui->spHour->setProperty(name.toStdString().c_str(), value); + m_ui->spMinutes->setProperty(name.toStdString().c_str(), value); + m_ui->spSeconds->setProperty(name.toStdString().c_str(), value); + m_ui->spYear->setProperty(name.toStdString().c_str(), value); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h old mode 100755 new mode 100644 index 611d23159..f38dad7e6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_date_time_edit_touch.h @@ -1,12 +1,10 @@ - #pragma once -#include - #include "ltswidgets_export.h" #include +#include #include #include @@ -23,119 +21,170 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsDateTimeEdit : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) - Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) - Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) - Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) - Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) - Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) - Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) + Q_PROPERTY(bool autoForward READ getAutoForward WRITE setAutoForward) + Q_PROPERTY(bool editTimezone READ getEditTimezone WRITE setEditTimezone) + Q_PROPERTY(bool withButtons READ getWithButtons WRITE setWithButtons) + Q_PROPERTY(bool withSlider READ getWithSlider WRITE setWithSlider) + Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly) + Q_PROPERTY(bool withNowButton READ withNowButton WRITE setWithNowButton) + Q_PROPERTY(bool withCheckBox READ withCheckBox WRITE setWithCheckBox) -public: - using CurrentTimeCallback = std::function; - explicit LtsDateTimeEdit(QWidget *parent = nullptr, bool withNowButton = true, bool withCheckBox = false); - ~LtsDateTimeEdit(); + public: + using CurrentTimeCallback = std::function; + explicit LtsDateTimeEdit(QWidget* parent = nullptr, bool withNowButton = true, bool withCheckBox = false); + ~LtsDateTimeEdit(); - qint64 msecsSinceEpoch() const; - bool isEmpty() const { return msecsSinceEpoch() == 0; } + qint64 msecsSinceEpoch() const; - void setAutoForward(const bool af) { m_autoForward = af; } - bool getAutoForward() const { return m_autoForward; } + bool isEmpty() const + { + return msecsSinceEpoch() == 0; + } - void setEditTimezone(const bool edit) { m_editTimezone = edit; } - bool getEditTimezone() const { return m_editTimezone; } + void setAutoForward(const bool af) + { + m_autoForward = af; + } - void setWithButtons(const bool buttons) { m_withButtons = buttons; } - bool getWithButtons() const { return m_withButtons; } + bool getAutoForward() const + { + return m_autoForward; + } - void setWithSlider(const bool slider) { m_withSlider = slider; } - bool getWithSlider() const { return m_withSlider; } + void setEditTimezone(const bool edit) + { + m_editTimezone = edit; + } - void setReadOnly(const bool readOnly) { m_readOnly = readOnly; } - bool isReadOnly() const { return m_readOnly; } + bool getEditTimezone() const + { + return m_editTimezone; + } - bool withCheckBox() const { return m_withCheckBox; } - void setCheckBoxChecked(bool bChecked); - bool isCheckBoxChecked() const; + void setWithButtons(const bool buttons) + { + m_withButtons = buttons; + } - bool withNowButton() const { return m_withNowButton; } - void setDateTime(const QDateTime &datetime); + bool getWithButtons() const + { + return m_withButtons; + } - - void setMinimumTimeMSec(qint64 msec); - qint64 minimumTimeMSec() const; + void setWithSlider(const bool slider) + { + m_withSlider = slider; + } - - void setMaximumTimeMSec(qint64 msec); - qint64 maximumTimeMSec() const { return m_maxTimeMSec; }; + bool getWithSlider() const + { + return m_withSlider; + } - void setMinMaxTimeMSec(qint64 min, qint64 max) { setMinimumTimeMSec(min); setMaximumTimeMSec(max); } + void setReadOnly(const bool readOnly) + { + m_readOnly = readOnly; + } - void setRetrieveCurrentTimeCallback(const CurrentTimeCallback &cb); - void updateDateTimeType(); + bool isReadOnly() const + { + return m_readOnly; + } - bool setTimezone(char tz); - char getTimezone() const; + bool withCheckBox() const + { + return m_withCheckBox; + } + void setCheckBoxChecked(bool bChecked); + bool isCheckBoxChecked() const; - void setSubWidgetsProperties(QString name, QVariant value); + bool withNowButton() const + { + return m_withNowButton; + } - bool isValidDate() const - { - - return m_dateTime.isValid(); - } + void setDateTime(const QDateTime& datetime); -private: - QDateTime dateTime() const; - void setMinMaxMonth(int minMonth, int maxMonth); + void setMinimumTimeMSec(qint64 msec); + qint64 minimumTimeMSec() const; -public slots: - void setWithCheckBox(bool checkBoxEnabled); - void setWithNowButton(bool nowButton); - void setMsecsSinceEpoch(qint64 mSecsSinceEpoch); - void clear(); + void setMaximumTimeMSec(qint64 msec); - void onSetFixedDateTime(); - void onSetOffsetDateTime(); + qint64 maximumTimeMSec() const + { + return m_maxTimeMSec; + }; -public slots: - void onDateTimeChanged(); + void setMinMaxTimeMSec(qint64 min, qint64 max) + { + setMinimumTimeMSec(min); + setMaximumTimeMSec(max); + } -signals: - void dateTimeChanged(); - void withCheckBoxChanged(bool checkBoxEnabled); - void withNowButtonChanged(bool nowButton); + void setRetrieveCurrentTimeCallback(const CurrentTimeCallback& cb); + void updateDateTimeType(); -private slots: - void onCheckBoxChanged(bool checked); - void onTimeZoneChanged(); - void onMonthChanged(int month); + bool setTimezone(char tz); + char getTimezone() const; -private: + void setSubWidgetsProperties(QString name, QVariant value); - qint64 m_minTimeMSec = 0; - qint64 m_maxTimeMSec = 0; - qint64 m_curTimeMSec = -1; + bool isValidDate() const + { - bool m_editTimezone = true; - bool m_autoForward = true; - bool m_withButtons = false; - bool m_withSlider = false; - bool m_readOnly = false; - bool m_withCheckBox = false; - bool m_withNowButton = false; + return m_dateTime.isValid(); + } - int m_tzOffset; - int m_minMonth; - int m_maxMonth; - QShortcut *m_scFixed; - QShortcut *m_scOffset; - QDateTime m_dateTime; - CurrentTimeCallback m_getCurrentTimeCallback; - Ui::LtsDateTimeEdit *m_ui; + private: + QDateTime dateTime() const; + void setMinMaxMonth(int minMonth, int maxMonth); + + public slots: + void setWithCheckBox(bool checkBoxEnabled); + void setWithNowButton(bool nowButton); + void setMsecsSinceEpoch(qint64 mSecsSinceEpoch); + void clear(); + + void onSetFixedDateTime(); + void onSetOffsetDateTime(); + + public slots: + void onDateTimeChanged(); + + signals: + void dateTimeChanged(); + void withCheckBoxChanged(bool checkBoxEnabled); + void withNowButtonChanged(bool nowButton); + + private slots: + void onCheckBoxChanged(bool checked); + void onTimeZoneChanged(); + void onMonthChanged(int month); + + private: + qint64 m_minTimeMSec = 0; + qint64 m_maxTimeMSec = 0; + qint64 m_curTimeMSec = -1; + + bool m_editTimezone = true; + bool m_autoForward = true; + bool m_withButtons = false; + bool m_withSlider = false; + bool m_readOnly = false; + bool m_withCheckBox = false; + bool m_withNowButton = false; + + int m_tzOffset; + int m_minMonth; + int m_maxMonth; + QShortcut* m_scFixed; + QShortcut* m_scOffset; + QDateTime m_dateTime; + CurrentTimeCallback m_getCurrentTimeCallback; + Ui::LtsDateTimeEdit* m_ui; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp old mode 100755 new mode 100644 index 1bd215710..894ce5bd6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.cpp @@ -1,217 +1,199 @@ - #include "lts_dialog_button_box.h" -#include "ui_lts_dialog_button_box.h" #include "lts_message_dialog.h" +#include "ui_lts_dialog_button_box.h" + #include #include namespace LtsWidgets { -LtsDialogButtonBox::LtsDialogButtonBox(QWidget *parent) - : QWidget(parent) - , m_isTablet(LtsSessionData::LtsSessionData::getInstance()->isTablet()) - , m_ui(new Ui::LtsDialogButtonBox) +LtsDialogButtonBox::LtsDialogButtonBox(QWidget* parent) + : QWidget(parent), m_isTablet(LtsSessionData::LtsSessionData::getInstance()->isTablet()), + m_ui(new Ui::LtsDialogButtonBox) { - m_ui->setupUi(this); - _setVisibilityForAll(false); + m_ui->setupUi(this); + _setVisibilityForAll(false); - - QMenu *libraryMenu = new QMenu(m_ui->pbLibrary); - libraryMenu->addAction(QIcon(QLatin1String(":/style/library_load.svg")), - tr("Load"), this, &LtsDialogButtonBox::signalLibraryLoadClicked); - libraryMenu->addAction(QIcon(QLatin1String(":/style/library_save.svg")), - tr("Save"), this, &LtsDialogButtonBox::signalLibrarySaveClicked); - m_ui->pbLibrary->setMenu(libraryMenu); + QMenu* libraryMenu = new QMenu(m_ui->pbLibrary); + libraryMenu->addAction(QIcon(QLatin1String(":/style/library_load.svg")), tr("Load"), this, + &LtsDialogButtonBox::signalLibraryLoadClicked); + libraryMenu->addAction(QIcon(QLatin1String(":/style/library_save.svg")), tr("Save"), this, + &LtsDialogButtonBox::signalLibrarySaveClicked); + m_ui->pbLibrary->setMenu(libraryMenu); - - m_ui->pbOk->setVisible(true); - m_ui->pbClose->setVisible(true); - + m_ui->pbOk->setVisible(true); + m_ui->pbClose->setVisible(true); } - LtsDialogButtonBox::~LtsDialogButtonBox() { - delete m_ui; + delete m_ui; } - void LtsDialogButtonBox::_setVisibilityForAll(bool visible) { - const auto buttons = findChildren(); - for (QPushButton *button : buttons) - button->setVisible(visible); + const auto buttons = findChildren(); + for (QPushButton* button : buttons) + button->setVisible(visible); } - -void LtsDialogButtonBox::setText(DialogButton button, const QString &text) +void LtsDialogButtonBox::setText(DialogButton button, const QString& text) { - - QPushButton *btn = getButton(button); + QPushButton* btn = getButton(button); - if (btn) - btn->setText(text); + if (btn) + btn->setText(text); } - -void LtsDialogButtonBox::setToolTip(DialogButton button, const QString &text) +void LtsDialogButtonBox::setToolTip(DialogButton button, const QString& text) { - QPushButton *btn = getButton(button); + QPushButton* btn = getButton(button); - if (btn) - btn->setToolTip(text); + if (btn) + btn->setToolTip(text); } - -void LtsDialogButtonBox::setIcon(DialogButton button, const QIcon &icon) +void LtsDialogButtonBox::setIcon(DialogButton button, const QIcon& icon) { - QPushButton *btn = getButton(button); + QPushButton* btn = getButton(button); - if (btn) - btn->setIcon(icon); + if (btn) + btn->setIcon(icon); } - -void LtsDialogButtonBox::setMenu(DialogButton button, QMenu *menu) +void LtsDialogButtonBox::setMenu(DialogButton button, QMenu* menu) { - QPushButton *btn = getButton(button); + QPushButton* btn = getButton(button); - if (btn) - btn->setMenu(menu); + if (btn) + btn->setMenu(menu); } - -QPushButton *LtsDialogButtonBox::getButton(DialogButton button) const +QPushButton* LtsDialogButtonBox::getButton(DialogButton button) const { - switch (button) - { - case DialogButton::ReadOnly: - return m_ui->pbReadOnly; - case DialogButton::Ok: - return m_ui->pbOk; - case DialogButton::Apply: - return m_ui->pbApply; - case DialogButton::Close: - return m_ui->pbClose; - case DialogButton::Yes: - return m_ui->pbYes; - case DialogButton::No: - return m_ui->pbNo; - case DialogButton::Remove: - return m_ui->pbRemove; - case DialogButton::Hide: - return m_ui->pbHide; - case DialogButton::Add: - return m_ui->pbAdd; - case DialogButton::Help: - return m_ui->pbHelp; - case DialogButton::Edit: - return m_ui->pbEdit; - case DialogButton::Save: - return m_ui->pbSave; - case DialogButton::Load: - return m_ui->pbLoad; - case DialogButton::Show: - return m_ui->pbShow; - case DialogButton::Import: - return m_ui->pbImport; - case DialogButton::Export: - return m_ui->pbExport; - case DialogButton::Library: - return m_ui->pbLibrary; - case DialogButton::CenterMap: - return m_ui->pbCenterMap; - case DialogButton::ZoomMapTo: - return m_ui->pbZoomMapTo; - case DialogButton::Print: - return m_ui->pbPrint; + switch (button) + { + case DialogButton::ReadOnly: + return m_ui->pbReadOnly; + case DialogButton::Ok: + return m_ui->pbOk; + case DialogButton::Apply: + return m_ui->pbApply; + case DialogButton::Close: + return m_ui->pbClose; + case DialogButton::Yes: + return m_ui->pbYes; + case DialogButton::No: + return m_ui->pbNo; + case DialogButton::Remove: + return m_ui->pbRemove; + case DialogButton::Hide: + return m_ui->pbHide; + case DialogButton::Add: + return m_ui->pbAdd; + case DialogButton::Help: + return m_ui->pbHelp; + case DialogButton::Edit: + return m_ui->pbEdit; + case DialogButton::Save: + return m_ui->pbSave; + case DialogButton::Load: + return m_ui->pbLoad; + case DialogButton::Show: + return m_ui->pbShow; + case DialogButton::Import: + return m_ui->pbImport; + case DialogButton::Export: + return m_ui->pbExport; + case DialogButton::Library: + return m_ui->pbLibrary; + case DialogButton::CenterMap: + return m_ui->pbCenterMap; + case DialogButton::ZoomMapTo: + return m_ui->pbZoomMapTo; + case DialogButton::Print: + return m_ui->pbPrint; #ifdef LTS_DEBUG - case DialogButton::_debug_: - return m_ui->_pbChanges; + case DialogButton::_debug_: + return m_ui->_pbChanges; #endif - } - Q_ASSERT(false); - return nullptr; + } + Q_ASSERT(false); + return nullptr; } - void LtsDialogButtonBox::slotRemoveClicked() { - if (LtsMessageDialog::showMessage(this, - tr("Are you sure you want to delete the selected entry(ies)?"), - tr("Remove selected entry(ies)"), - Behaviour::Modal, - Button::Yes | Button::No) - == Button::Yes) - emit signalRemoveClicked(); + if (LtsMessageDialog::showMessage(this, tr("Are you sure you want to delete the selected entry(ies)?"), + tr("Remove selected entry(ies)"), Behaviour::Modal, + Button::Yes | Button::No) == Button::Yes) + emit signalRemoveClicked(); } - -void LtsDialogButtonBox::setButtonsVisible(QPushButton *pb) +void LtsDialogButtonBox::setButtonsVisible(QPushButton* pb) { - if (!pb || (pb == m_ui->pbPrint && m_isTablet)) - return; - m_ui->line->setVisible(true); - pb->setVisible(true); + if (!pb || (pb == m_ui->pbPrint && m_isTablet)) + return; + m_ui->line->setVisible(true); + pb->setVisible(true); } - void LtsDialogButtonBox::setButtonVisible(DialogButton button, bool visible) { - QPushButton *pb = getButton(button); - if (!pb) - return; - if (m_isTablet && pb == m_ui->pbPrint) - { - pb->setVisible(false); - return; - } - pb->setVisible(visible); + QPushButton* pb = getButton(button); + if (!pb) + return; + if (m_isTablet && pb == m_ui->pbPrint) + { + pb->setVisible(false); + return; + } + pb->setVisible(visible); } - bool LtsDialogButtonBox::isButtonVisible(DialogButton button) const { - const QPushButton *pb = getButton(button); - return (pb ? pb->isVisible() : false); + const QPushButton* pb = getButton(button); + return (pb ? pb->isVisible() : false); } - void LtsDialogButtonBox::setButtonEnabled(DialogButton button, bool enabled) { - QPushButton *pb = getButton(button); + QPushButton* pb = getButton(button); - switch (button) - { - case DialogButton::Close: - case DialogButton::Ok: - case DialogButton::Apply: - - - { + switch (button) + { + case DialogButton::Close: + case DialogButton::Ok: + case DialogButton::Apply: + + { #ifdef LTS_DEBUG - LtsMessageDialog::showMessage(this, QStringLiteral("Hier stimmt etwas nicht. Bitte MIKE bescheid geben WAS geklickt oder gemacht wurde als dieser Dialog auftauchte, damit ich es fixen kann. Danke."), QStringLiteral(">>> STOP <<<")); + LtsMessageDialog::showMessage( + this, + QStringLiteral("Hier stimmt etwas nicht. Bitte MIKE bescheid geben WAS geklickt oder gemacht wurde als " + "dieser Dialog auftauchte, damit ich es fixen kann. Danke."), + QStringLiteral(">>> STOP <<<")); #endif - break; - } + break; + } - default: - break; - } + default: + break; + } - if (pb) - pb->setEnabled(enabled); + if (pb) + pb->setEnabled(enabled); } - bool LtsDialogButtonBox::isButtonEnabled(DialogButton button) const { - auto *that = const_cast(this); - const QPushButton *pb = that->getButton(button); - return (pb ? pb->isEnabled() : false); + auto* that = const_cast(this); + const QPushButton* pb = that->getButton(button); + return (pb ? pb->isEnabled() : false); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h old mode 100755 new mode 100644 index fc24e2c0b..8c5f61d97 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_button_box.h @@ -1,14 +1,12 @@ - #pragma once -#include - -#include "ltswidgets_export.h" #include "lts_message_dialog.h" +#include "ltswidgets_export.h" -#include +#include #include +#include namespace Ui { @@ -17,181 +15,159 @@ class LtsDialogButtonBox; namespace LtsWidgets { -enum class DialogButton -{ - - ReadOnly, - Ok, - Apply, - Close, - Yes, - No, +enum class DialogButton { - - Remove, - Hide, - Add, - Help, - Edit, - Save, - Load, - Show, - Import, - Export, - CenterMap, - ZoomMapTo, - Library, - Print, + ReadOnly, + Ok, + Apply, + Close, + Yes, + No, + + Remove, + Hide, + Add, + Help, + Edit, + Save, + Load, + Show, + Import, + Export, + CenterMap, + ZoomMapTo, + Library, + Print, #ifdef LTS_DEBUG - _debug_, + _debug_, #endif }; - - - - - - class LTSWIDGETS_EXPORT LtsDialogButtonBox : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit LtsDialogButtonBox(QWidget *parent); - ~LtsDialogButtonBox(); + public: + explicit LtsDialogButtonBox(QWidget* parent); + ~LtsDialogButtonBox(); - - - template - void connectButton(DialogButton button, const typename QtPrivate::FunctionPointer::Object *receiver, - Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) - { - + template + void connectButton(DialogButton button, const typename QtPrivate::FunctionPointer::Object* receiver, + Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) { - switch (button) - { + + { + switch (button) + { #ifdef LTS_DEBUG - case DialogButton::_debug_: + case DialogButton::_debug_: #endif - case DialogButton::Close: - case DialogButton::Ok: - case DialogButton::ReadOnly: - case DialogButton::Apply: - case DialogButton::Help: - { - LtsMessageDialog::showMessage(this, - QStringLiteral("Bitte den fuer das Plugin verantwortlichen kontaktieren:
" - "m_buttonBox nicht mit Ok, Apply, Help, _debug_ oder Close verbinden
" - "Note: Bitte nur m_buttonBox verwenden, keine LtsDialogButtonBox selber erstellen" - "Ok & Apply werden automatisch zur virtual Methode 'apply()' im LtsDialog weitergeleitet.
" - "Close schließt einfach den Dialog - im Destruktor oder in 'aboutToClose()' ist der 'Close Code' gut aufgehoben.
" - "
" - "FIXEN !!!!!"), - QStringLiteral("--- STOP --- !!! FIXEN !!! ---")); - break; - } + case DialogButton::Close: + case DialogButton::Ok: + case DialogButton::ReadOnly: + case DialogButton::Apply: + case DialogButton::Help: { + LtsMessageDialog::showMessage( + this, + QStringLiteral( + "Bitte den fuer das Plugin verantwortlichen kontaktieren:
" + "m_buttonBox nicht mit Ok, Apply, Help, _debug_ oder Close verbinden
" + "Note: Bitte nur m_buttonBox verwenden, keine LtsDialogButtonBox selber erstellen" + "Ok & Apply werden automatisch zur virtual Methode 'apply()' im LtsDialog " + "weitergeleitet.
" + "Close schließt einfach den Dialog - im Destruktor oder in 'aboutToClose()' ist der 'Close " + "Code' gut aufgehoben.
" + "
" + "FIXEN !!!!!"), + QStringLiteral("--- STOP --- !!! FIXEN !!! ---")); + break; + } - default: - break; - } + default: + break; + } + } + + QPushButton* theSender = getButton(button); + + if (!theSender) + return; + + switch (button) + { + case DialogButton::Remove: { + connect(this, &LtsDialogButtonBox::signalRemoveClicked, receiver, slot, type); + connect(theSender, &QPushButton::clicked, this, &LtsDialogButtonBox::slotRemoveClicked); + + break; + } + case DialogButton::Export: + case DialogButton::Import: { + if (m_isTablet) + { + theSender->setVisible(false); + return; + } + Q_FALLTHROUGH(); + } + default: + connect(theSender, &QPushButton::clicked, receiver, slot, type); + break; + } + + setButtonsVisible(theSender); } - - QPushButton *theSender = getButton(button); - - if (!theSender) - return; - - - switch (button) + template + bool connectLibraryButton(const typename QtPrivate::FunctionPointer::Object* receiver, Func1 slotLoad, + Func2 slotSave, Qt::ConnectionType type = Qt::AutoConnection) { - case DialogButton::Remove: - { - connect(this, &LtsDialogButtonBox::signalRemoveClicked, receiver, slot, type); - connect(theSender, &QPushButton::clicked, this, &LtsDialogButtonBox::slotRemoveClicked); - - break; - } - case DialogButton::Export: - case DialogButton::Import: - { - if (m_isTablet) - { - theSender->setVisible(false); - return; - } - Q_FALLTHROUGH(); - } - default: - connect(theSender, &QPushButton::clicked, receiver, slot, type); - break; + QPushButton* theSender = getButton(DialogButton::Library); + if (!theSender) + return false; + if (m_isTablet) + { + theSender->setVisible(false); + return true; + } + setButtonsVisible(theSender); + type = static_cast(type | Qt::UniqueConnection); + return (connect(this, &LtsDialogButtonBox::signalLibraryLoadClicked, receiver, slotLoad, type) && + connect(this, &LtsDialogButtonBox::signalLibrarySaveClicked, receiver, slotSave, type)); } - setButtonsVisible(theSender); - } - template - bool connectLibraryButton(const typename QtPrivate::FunctionPointer::Object *receiver, - Func1 slotLoad, - Func2 slotSave, - Qt::ConnectionType type = Qt::AutoConnection) - { - QPushButton *theSender = getButton(DialogButton::Library); - if (!theSender) - return false; - if (m_isTablet) - { - theSender->setVisible(false); - return true; - } - setButtonsVisible(theSender); - type = static_cast(type | Qt::UniqueConnection); - return (connect(this, &LtsDialogButtonBox::signalLibraryLoadClicked, receiver, slotLoad, type) && - connect(this, &LtsDialogButtonBox::signalLibrarySaveClicked, receiver, slotSave, type)); - } + void setText(DialogButton button, const QString& text); - + void setToolTip(DialogButton button, const QString& text); + void setIcon(DialogButton button, const QIcon& icon); + void setMenu(DialogButton button, QMenu* menu); - void setText(DialogButton button, const QString &text); + void setButtonEnabled(DialogButton button, bool enabled = true); + bool isButtonEnabled(DialogButton button) const; - void setToolTip(DialogButton button, const QString &text); - void setIcon(DialogButton button, const QIcon &icon); - void setMenu(DialogButton button, QMenu *menu); + void setButtonVisible(DialogButton button, bool visible = true); + bool isButtonVisible(DialogButton button) const; - + QPushButton* getButton(DialogButton button) const; - void setButtonEnabled(DialogButton button, bool enabled = true); - bool isButtonEnabled(DialogButton button) const; + void _setVisibilityForAll(bool visible); - void setButtonVisible(DialogButton button, bool visible = true); - bool isButtonVisible(DialogButton button) const; + signals: + void signalRemoveClicked(); + void signalHelpClicked(); + void signalLibraryLoadClicked(); + void signalLibrarySaveClicked(); - + private slots: + void slotRemoveClicked(); - QPushButton *getButton(DialogButton button) const; + private: + const bool m_isTablet; - + void setButtonsVisible(QPushButton* pb); - void _setVisibilityForAll(bool visible); - -signals: - void signalRemoveClicked(); - void signalHelpClicked(); - void signalLibraryLoadClicked(); - void signalLibrarySaveClicked(); - -private slots: - void slotRemoveClicked(); - -private: - const bool m_isTablet; - - - - void setButtonsVisible(QPushButton *pb); - - Ui::LtsDialogButtonBox *m_ui; + Ui::LtsDialogButtonBox* m_ui; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp old mode 100755 new mode 100644 index c9c6820eb..0323c9838 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.cpp @@ -1,172 +1,153 @@ - #include "lts_dialog_helper.h" + #include "lts_dialog.h" #include "ui_lts_dialog_helper.h" +#include #include #include -#include - namespace LtsWidgets { class LDHScrollBar : public QScrollBar { - Q_OBJECT -public: - using QScrollBar::QScrollBar; + Q_OBJECT + public: + using QScrollBar::QScrollBar; - void showEvent(QShowEvent *e) override - { - QScrollBar::showEvent(e); - emit scrollbarVisiblityChanged(true); - } - void hideEvent(QHideEvent *e) override - { - QScrollBar::hideEvent(e); - emit scrollbarVisiblityChanged(false); - } -Q_SIGNALS: - void scrollbarVisiblityChanged(bool visible); + void showEvent(QShowEvent* e) override + { + QScrollBar::showEvent(e); + emit scrollbarVisiblityChanged(true); + } + + void hideEvent(QHideEvent* e) override + { + QScrollBar::hideEvent(e); + emit scrollbarVisiblityChanged(false); + } + + Q_SIGNALS: + void scrollbarVisiblityChanged(bool visible); }; - -LtsDialogHelper::LtsDialogHelper(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::LtsDialogHelper()) - , m_dialog(nullptr) +LtsDialogHelper::LtsDialogHelper(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsDialogHelper()), m_dialog(nullptr) { - m_ui->setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); - auto hScroll = new LDHScrollBar(this); - auto vScroll = new LDHScrollBar(this); - m_ui->scrollArea->setHorizontalScrollBar(hScroll); - m_ui->scrollArea->setVerticalScrollBar(vScroll); - connect(hScroll, &LDHScrollBar::scrollbarVisiblityChanged, - this, &LtsDialogHelper::onHScrollBarVisibilityChanged); - connect(vScroll, &LDHScrollBar::scrollbarVisiblityChanged, - this, &LtsDialogHelper::onVScrollBarVisibilityChanged); + m_ui->setupUi(this); + setAttribute(Qt::WA_DeleteOnClose); + auto hScroll = new LDHScrollBar(this); + auto vScroll = new LDHScrollBar(this); + m_ui->scrollArea->setHorizontalScrollBar(hScroll); + m_ui->scrollArea->setVerticalScrollBar(vScroll); + connect(hScroll, &LDHScrollBar::scrollbarVisiblityChanged, this, &LtsDialogHelper::onHScrollBarVisibilityChanged); + connect(vScroll, &LDHScrollBar::scrollbarVisiblityChanged, this, &LtsDialogHelper::onVScrollBarVisibilityChanged); #ifdef TABLET_MODE - QList scrollWidgets = findChildren(); + QList scrollWidgets = findChildren(); - for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) - { - QWidget *widget = *i; + for (auto i = scrollWidgets.begin(); i != scrollWidgets.end(); ++i) + { + QWidget* widget = *i; - QVariant isConst = widget->property("const"); - if (isConst.isValid() && isConst.toBool()) - continue; + QVariant isConst = widget->property("const"); + if (isConst.isValid() && isConst.toBool()) + continue; - LtsWidgets::addTouchScroll(widget); - } + LtsWidgets::addTouchScroll(widget); + } #endif m_ui->buttonBox->setMinimumHeight(m_ui->buttonBox->sizeHint().height()); } - LtsDialogHelper::~LtsDialogHelper() { - m_ui->scrollArea->horizontalScrollBar()->disconnect(this); - m_ui->scrollArea->verticalScrollBar()->disconnect(this); - delete m_ui; + m_ui->scrollArea->horizontalScrollBar()->disconnect(this); + m_ui->scrollArea->verticalScrollBar()->disconnect(this); + delete m_ui; } - -LtsDialogButtonBox *LtsDialogHelper::getButtonBox() +LtsDialogButtonBox* LtsDialogHelper::getButtonBox() { - return m_ui->buttonBox; + return m_ui->buttonBox; } - -void LtsDialogHelper::setDialog(LtsDialog *dialog) +void LtsDialogHelper::setDialog(LtsDialog* dialog) { - if (m_dialog != nullptr) - return; + if (m_dialog != nullptr) + return; - m_dialog = dialog; - m_dialog->setContentsMargins(QMargins()); - if (m_dialog->layout()) - m_dialog->layout()->setContentsMargins(QMargins()); - m_ui->scrollArea->setWidget(m_dialog); + m_dialog = dialog; + m_dialog->setContentsMargins(QMargins()); + if (m_dialog->layout()) + m_dialog->layout()->setContentsMargins(QMargins()); + m_ui->scrollArea->setWidget(m_dialog); - - { - connect(dialog, &LtsDialog::destroyed, this, [this]() { - m_dialog = nullptr; - deleteLater(); - }); - } - - - + connect(dialog, &LtsDialog::destroyed, this, [this]() { + m_dialog = nullptr; + deleteLater(); + }); + } } -LtsDialog *LtsDialogHelper::getDialog() +LtsDialog* LtsDialogHelper::getDialog() { - return m_dialog; + return m_dialog; } void LtsDialogHelper::retranslate() { - if (m_dialog == nullptr) - return; + if (m_dialog == nullptr) + return; - m_dialog->setContentsMargins(QMargins()); - if (m_dialog->layout()) - m_dialog->layout()->setContentsMargins(QMargins()); + m_dialog->setContentsMargins(QMargins()); + if (m_dialog->layout()) + m_dialog->layout()->setContentsMargins(QMargins()); - bool oldChangesFlag = m_dialog->m_changesMade; + bool oldChangesFlag = m_dialog->m_changesMade; - + m_dialog->retranslate(); - m_dialog->retranslate(); - - if (oldChangesFlag) - m_dialog->slotChangesMade(); - else - m_dialog->resetChanges(); + if (oldChangesFlag) + m_dialog->slotChangesMade(); + else + m_dialog->resetChanges(); } - -void LtsDialogHelper::resizeEvent(QResizeEvent *e) +void LtsDialogHelper::resizeEvent(QResizeEvent* e) { - emit signalSizeChanged(e->size()); + emit signalSizeChanged(e->size()); } - -void LtsDialogHelper::changeEvent(QEvent *e) +void LtsDialogHelper::changeEvent(QEvent* e) { - QWidget::changeEvent(e); - if (e->type() == QEvent::LanguageChange) - retranslate(); + QWidget::changeEvent(e); + if (e->type() == QEvent::LanguageChange) + retranslate(); } - void LtsDialogHelper::onHScrollBarVisibilityChanged(bool visible) { - if (m_dialog == nullptr || !m_dialog->layout()) - return; + if (m_dialog == nullptr || !m_dialog->layout()) + return; - QMargins m = m_dialog->layout()->contentsMargins(); - m.setBottom(visible ? -1 : 0); - m_dialog->layout()->setContentsMargins(m); + QMargins m = m_dialog->layout()->contentsMargins(); + m.setBottom(visible ? -1 : 0); + m_dialog->layout()->setContentsMargins(m); } - void LtsDialogHelper::onVScrollBarVisibilityChanged(bool visible) { - if (m_dialog == nullptr || !m_dialog->layout()) - return; + if (m_dialog == nullptr || !m_dialog->layout()) + return; - QMargins m = m_dialog->layout()->contentsMargins(); - m.setRight(visible ? -1 : 0); - m_dialog->layout()->setContentsMargins(m); + QMargins m = m_dialog->layout()->contentsMargins(); + m.setRight(visible ? -1 : 0); + m_dialog->layout()->setContentsMargins(m); } -} +} // namespace LtsWidgets #include "lts_dialog_helper.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h old mode 100755 new mode 100644 index 314403187..2981e5dab --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_dialog_helper.h @@ -1,52 +1,50 @@ - #pragma once #include - -#include #include - +#include namespace Ui { class LtsDialogHelper; } - namespace LtsWidgets { class LtsDialogButtonBox; class LtsDialog; - - class LtsDialogHelper : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit LtsDialogHelper(QWidget *parent = nullptr); - ~LtsDialogHelper(); + public: + explicit LtsDialogHelper(QWidget* parent = nullptr); + ~LtsDialogHelper(); - LtsDialogButtonBox *getButtonBox(); - void setDialog(LtsDialog *dialog); - LtsDialog *getDialog(); - bool compare(const LtsDialog *dialog) const { return (dialog == m_dialog); } - void retranslate(); + LtsDialogButtonBox* getButtonBox(); + void setDialog(LtsDialog* dialog); + LtsDialog* getDialog(); -signals: - void signalSizeChanged(const QSize &size); + bool compare(const LtsDialog* dialog) const + { + return (dialog == m_dialog); + } -private: - void resizeEvent(QResizeEvent *e) override; - void changeEvent(QEvent *e) override; - void onHScrollBarVisibilityChanged(bool visible); - void onVScrollBarVisibilityChanged(bool visible); + void retranslate(); - Ui::LtsDialogHelper *m_ui; - LtsDialog *m_dialog; + signals: + void signalSizeChanged(const QSize& size); + private: + void resizeEvent(QResizeEvent* e) override; + void changeEvent(QEvent* e) override; + void onHScrollBarVisibilityChanged(bool visible); + void onVScrollBarVisibilityChanged(bool visible); + + Ui::LtsDialogHelper* m_ui; + LtsDialog* m_dialog; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h old mode 100755 new mode 100644 index 84289ae8f..dbaf598d0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drag_icon.h @@ -1,247 +1,231 @@  - #pragma once -#include - #include "lts_base.h" #include "lts_drop_handler.h" #include "ltswidgets_export.h" -#include #include +#include +#include #include - class QButtonGroup; class QHBoxLayout; class QLabel; class QMenu; -namespace LtsWidgets { +namespace LtsWidgets +{ class LtsToolButton; - - class LTSWIDGETS_EXPORT LtsDragIcon : public QWidget { -public: - Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QString context READ context WRITE setContext) - Q_PROPERTY(QString identifier READ identifier WRITE setIdentifier) - Q_PROPERTY(QIcon icon READ icon WRITE setIcon) - Q_PROPERTY(LtsWidgets::Designer::ButtonSize eButtonSize READ iconSizeDesigner WRITE setIconSizeDesigner) - Q_PROPERTY(bool eForceFixedSize READ isForceFixedSize WRITE setForceFixedSize) - Q_PROPERTY(bool isCheckable READ isCheckable WRITE setCheckable) - Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) - Q_PROPERTY(bool showDragIcon READ showDragIcon WRITE setShowDragIcon) - Q_PROPERTY(bool isDraggable READ isDraggable WRITE setDraggable) + public: + Q_OBJECT + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QString context READ context WRITE setContext) + Q_PROPERTY(QString identifier READ identifier WRITE setIdentifier) + Q_PROPERTY(QIcon icon READ icon WRITE setIcon) + Q_PROPERTY(LtsWidgets::Designer::ButtonSize eButtonSize READ iconSizeDesigner WRITE setIconSizeDesigner) + Q_PROPERTY(bool eForceFixedSize READ isForceFixedSize WRITE setForceFixedSize) + Q_PROPERTY(bool isCheckable READ isCheckable WRITE setCheckable) + Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) + Q_PROPERTY(bool showDragIcon READ showDragIcon WRITE setShowDragIcon) + Q_PROPERTY(bool isDraggable READ isDraggable WRITE setDraggable) + Q_PROPERTY(LtsWidgets::Designer::ButtonStyle eStyle READ buttonStyleDesigner WRITE setButtonStyleDesigner) - - Q_PROPERTY(LtsWidgets::Designer::ButtonStyle eStyle READ buttonStyleDesigner WRITE setButtonStyleDesigner) + void setButtonStyleDesigner(Designer::ButtonStyle t) + { + setButtonStyle(static_cast(t)); + } + Designer::ButtonStyle buttonStyleDesigner() const + { + return static_cast(buttonStyle()); + } - + void setIconSizeDesigner(Designer::ButtonSize t) + { + setIconSize(static_cast(t)); + } - void setButtonStyleDesigner(Designer::ButtonStyle t) { setButtonStyle(static_cast(t)); } + Designer::ButtonSize iconSizeDesigner() const + { + return static_cast(iconSize()); + } - + public: + explicit LtsDragIcon(QWidget* parent); - Designer::ButtonStyle buttonStyleDesigner() const { return static_cast(buttonStyle()); } + virtual ~LtsDragIcon() = default; - + void setMenu(QMenu* menu); - void setIconSizeDesigner(Designer::ButtonSize t) { setIconSize(static_cast(t)); } + QMenu* menu() const; - + void setText(const QString& text); - Designer::ButtonSize iconSizeDesigner() const { return static_cast(iconSize()); } + QString text() const + { + return m_text; + } -public: - + void setContext(const QString& context); - explicit LtsDragIcon(QWidget *parent); + QString context() const + { + return m_context; + } - virtual ~LtsDragIcon() = default; + void setCheckable(bool checkable); - + bool isCheckable(); - void setMenu(QMenu *menu); + void setDraggable(bool draggable); - + bool isDraggable() const + { + return m_isDraggable; + } - QMenu* menu() const; + void setChecked(bool checked); - + bool isChecked() const; - void setText(const QString &text); + void setShowDragIcon(bool showDragIcon) + { + m_showDragIcon = showDragIcon; + } - + bool showDragIcon() const + { + return m_showDragIcon; + } - QString text() const { return m_text; } + void setSameWidgetDrop(bool drop); - + bool sameWidgetDrop() const; - void setContext(const QString &context); + void setButtonStyle(ButtonStyle style); - + ButtonStyle buttonStyle() const + { + return m_style; + } - QString context() const { return m_context; } + void setIconSize(ButtonSize buttonSize); - + ButtonSize iconSize() const + { + return m_buttonSize; + } - void setCheckable(bool checkable); + void setButtonVisible(bool visible); - + bool buttonVisible() const; - bool isCheckable(); + void setIcon(const QIcon& icon); + QIcon icon() const + { + return m_icon; + } - + void setForceFixedSize(bool force); - void setDraggable(bool draggable); + bool isForceFixedSize() const + { + return m_forceFixedSize; + } - + void setAction(QAction* action); - bool isDraggable() const { return m_isDraggable; } + void addToButtonGroup(QButtonGroup* btnGrp, int btnGrpId); - + void setDropHandlerKey(qulonglong key) + { + m_dropHandlerKey = key; + } - void setChecked(bool checked); + void addMimeData(const QString& mimeType, const QByteArray& data); + bool removeMimeData(const QString& mimeType); + void removeAllMimeData(); - + void setAcceptDrops(bool on); - bool isChecked() const; + qulonglong dropHandlerKey() const + { + return m_dropHandlerKey; + } - + void setIdentifier(const QString& id) + { + m_identifier = id; + } - void setShowDragIcon(bool showDragIcon) { m_showDragIcon = showDragIcon; } - bool showDragIcon() const { return m_showDragIcon; } + QString identifier() const + { + return m_identifier; + } - + void setModification(const QString& id) + { + m_modification = id; + setIcon(m_icon); + } - void setSameWidgetDrop(bool drop); + QString modification() const + { + return m_modification; + } - + void removeModification() + { + m_modification = QString(); + setIcon(m_icon); + } - bool sameWidgetDrop() const; + signals: - + void clicked(); - void setButtonStyle(ButtonStyle style); + void toggled(bool); + void newDropEvent(QDropEvent* e); + void dropSuc(); - + void enabledChanged(bool); - ButtonStyle buttonStyle() const { return m_style; } + protected: + void dragEnterEvent(QDragEnterEvent* e) override; + void dropEvent(QDropEvent* e) override; + void initButton(); - + private: + void setStyleToButton(); + QIcon modifyIcon(const QIcon& icon); + void generateToolTip(); - void setIconSize(ButtonSize buttonSize); - - - - ButtonSize iconSize() const { return m_buttonSize; } - - - - void setButtonVisible(bool visible); - - - - bool buttonVisible() const; - - - - void setIcon(const QIcon &icon); - - - - QIcon icon() const { return m_icon; } - - - - void setForceFixedSize(bool force); - - - - bool isForceFixedSize() const { return m_forceFixedSize; } - - - - void setAction(QAction *action); - - - - void addToButtonGroup(QButtonGroup *btnGrp, int btnGrpId); - - - - void setDropHandlerKey(qulonglong key) { m_dropHandlerKey = key; } - - - - void addMimeData(const QString &mimeType, const QByteArray &data); - bool removeMimeData(const QString &mimeType); - void removeAllMimeData(); - - - - void setAcceptDrops(bool on); - - qulonglong dropHandlerKey() const { return m_dropHandlerKey; } - - - void setIdentifier(const QString &id) { m_identifier = id; } - QString identifier() const { return m_identifier; } - - void setModification(const QString &id) { m_modification = id; setIcon(m_icon); } - QString modification() const { return m_modification; } - void removeModification() { m_modification = QString(); setIcon(m_icon);} - -signals: - - - void clicked(); - - - - void toggled(bool); - void newDropEvent(QDropEvent *e); - void dropSuc(); - - void enabledChanged(bool); - -protected: - void dragEnterEvent(QDragEnterEvent *e) override; - void dropEvent(QDropEvent *e) override; - void initButton(); - -private: - void setStyleToButton(); - QIcon modifyIcon(const QIcon &icon); - void generateToolTip(); - -protected slots: - void changeEvent(QEvent *event) override; - -private: - QHBoxLayout *m_lay; - LtsToolButton *m_toolButton; - QIcon m_icon; - QLabel *m_dragLabel; - QString m_text; - QString m_identifier; - QString m_modification; - ButtonStyle m_style; - bool m_forceFixedSize; - bool m_isDraggable; - qulonglong m_dropHandlerKey; - ButtonSize m_buttonSize; - bool m_showDragIcon; - QString m_context; + protected slots: + void changeEvent(QEvent* event) override; + + private: + QHBoxLayout* m_lay; + LtsToolButton* m_toolButton; + QIcon m_icon; + QLabel* m_dragLabel; + QString m_text; + QString m_identifier; + QString m_modification; + ButtonStyle m_style; + bool m_forceFixedSize; + bool m_isDraggable; + qulonglong m_dropHandlerKey; + ButtonSize m_buttonSize; + bool m_showDragIcon; + QString m_context; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h old mode 100755 new mode 100644 index e1df572b2..5da8c6c29 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_drop_handler.h @@ -1,31 +1,22 @@ - #pragma once - class QMimeData; - namespace LtsWidgets { - - class LtsDropHandler - { - public: +class LtsDropHandler +{ + public: + LtsDropHandler() = default; + virtual ~LtsDropHandler() = default; - LtsDropHandler() = default; - virtual ~LtsDropHandler() = default; + LtsDropHandler(const LtsDropHandler&) = delete; + LtsDropHandler& operator=(const LtsDropHandler&) = delete; - LtsDropHandler( const LtsDropHandler & ) = delete; - LtsDropHandler & operator = ( const LtsDropHandler & ) = delete; + virtual void doDrop(int x, int y, const QMimeData* mimeData) const = 0; +}; - - - virtual void doDrop( int x, int y, const QMimeData * mimeData ) const = 0; - - }; - - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp old mode 100755 new mode 100644 index 738d94886..513cf6a1d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.cpp @@ -1,60 +1,55 @@ - #include "lts_elided_label.h" #include #include - namespace LtsWidgets { void LtsElidedLabel::setElideMode(Qt::TextElideMode elideMode) { - m_elideMode = elideMode; - m_cachedText.clear(); - update(); + m_elideMode = elideMode; + m_cachedText.clear(); + update(); } -void LtsElidedLabel::resizeEvent(QResizeEvent *e) +void LtsElidedLabel::resizeEvent(QResizeEvent* e) { - QLabel::resizeEvent(e); - m_cachedText.clear(); + QLabel::resizeEvent(e); + m_cachedText.clear(); } -void LtsElidedLabel::paintEvent(QPaintEvent *e) +void LtsElidedLabel::paintEvent(QPaintEvent* e) { - if (m_elideMode == Qt::ElideNone) - return QLabel::paintEvent(e); + if (m_elideMode == Qt::ElideNone) + return QLabel::paintEvent(e); - updateCachedTexts(); - QLabel::setText(m_cachedElidedText); - QLabel::paintEvent(e); - QLabel::setText(m_cachedText); + updateCachedTexts(); + QLabel::setText(m_cachedElidedText); + QLabel::paintEvent(e); + QLabel::setText(m_cachedText); } void LtsElidedLabel::updateCachedTexts() { - - const auto txt = text(); - if (m_cachedText == txt) - return; - m_cachedText = txt; - const QFontMetrics fm(fontMetrics()); - m_cachedElidedText = fm.elidedText(text(), - m_elideMode, - width(), - Qt::TextShowMnemonic); - if (!m_cachedText.isEmpty()) - { - const QString showFirstCharacter = m_cachedText.at(0) + QStringLiteral("..."); + + const auto txt = text(); + if (m_cachedText == txt) + return; + m_cachedText = txt; + const QFontMetrics fm(fontMetrics()); + m_cachedElidedText = fm.elidedText(text(), m_elideMode, width(), Qt::TextShowMnemonic); + if (!m_cachedText.isEmpty()) + { + const QString showFirstCharacter = m_cachedText.at(0) + QStringLiteral("..."); #if QT_VERSION < QT_VERSION_CHECK(5, 11, 0) - const int width = fm.width(showFirstCharacter); + const int width = fm.width(showFirstCharacter); #else - const int width = fm.horizontalAdvance(showFirstCharacter); + const int width = fm.horizontalAdvance(showFirstCharacter); #endif - setMinimumWidth(width + 1); - } + setMinimumWidth(width + 1); + } } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h old mode 100755 new mode 100644 index 7623f9010..59d7955f7 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_elided_label.h @@ -1,37 +1,40 @@ - #pragma once -#include +#include "ltswidgets_export.h" #include -#include "ltswidgets_export.h" +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsElidedLabel : public QLabel { - Q_OBJECT -public: - Q_PROPERTY(Qt::TextElideMode ElideMode READ elideMode WRITE setElideMode) + Q_OBJECT + public: + Q_PROPERTY(Qt::TextElideMode ElideMode READ elideMode WRITE setElideMode) - using QLabel::QLabel; + using QLabel::QLabel; - void setElideMode(Qt::TextElideMode elideMode); - Qt::TextElideMode elideMode() const { return m_elideMode; } + void setElideMode(Qt::TextElideMode elideMode); -protected: - void paintEvent(QPaintEvent *e) override; - void resizeEvent(QResizeEvent *e) override; + Qt::TextElideMode elideMode() const + { + return m_elideMode; + } -private: - void updateCachedTexts(); + protected: + void paintEvent(QPaintEvent* e) override; + void resizeEvent(QResizeEvent* e) override; -private: - Qt::TextElideMode m_elideMode = Qt::ElideRight; - QString m_cachedElidedText; - QString m_cachedText; + private: + void updateCachedTexts(); + + private: + Qt::TextElideMode m_elideMode = Qt::ElideRight; + QString m_cachedElidedText; + QString m_cachedText; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp old mode 100755 new mode 100644 index 9f5372bb0..bee3b1e21 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.cpp @@ -1,58 +1,55 @@ - #include "lts_events.h" namespace LtsWidgets { QEvent::Type LtsLinkEvent::eventTypeId() { - static QEvent::Type sLinkEventId = QEvent::None; - if (sLinkEventId == QEvent::None) - sLinkEventId = static_cast(QEvent::registerEventType()); - return sLinkEventId; + static QEvent::Type sLinkEventId = QEvent::None; + if (sLinkEventId == QEvent::None) + sLinkEventId = static_cast(QEvent::registerEventType()); + return sLinkEventId; } QEvent::Type SaveImageEvent::saveImageEventId() { - static QEvent::Type sSaveImageEventId = QEvent::None; - if (sSaveImageEventId == QEvent::None) - sSaveImageEventId = static_cast(QEvent::registerEventType()); - return sSaveImageEventId; + static QEvent::Type sSaveImageEventId = QEvent::None; + if (sSaveImageEventId == QEvent::None) + sSaveImageEventId = static_cast(QEvent::registerEventType()); + return sSaveImageEventId; } QEvent::Type SetMarkerEvent::setMarkerEventId() { - static QEvent::Type sSetMarkerEventId = QEvent::None; - if (sSetMarkerEventId == QEvent::None) - sSetMarkerEventId = static_cast(QEvent::registerEventType()); - return sSetMarkerEventId; + static QEvent::Type sSetMarkerEventId = QEvent::None; + if (sSetMarkerEventId == QEvent::None) + sSetMarkerEventId = static_cast(QEvent::registerEventType()); + return sSetMarkerEventId; } QEvent::Type AddMarkerEvent::addMarkerEventId() { - static QEvent::Type sAddMarkerEventId = QEvent::None; - if (sAddMarkerEventId == QEvent::None) - sAddMarkerEventId = static_cast(QEvent::registerEventType()); - return sAddMarkerEventId; + static QEvent::Type sAddMarkerEventId = QEvent::None; + if (sAddMarkerEventId == QEvent::None) + sAddMarkerEventId = static_cast(QEvent::registerEventType()); + return sAddMarkerEventId; } QEvent::Type AddSnapshotEvent::addSnapshotEventId() { - static QEvent::Type eventId = QEvent::None; - if (eventId == QEvent::None) - eventId = static_cast(QEvent::registerEventType()); - return eventId; + static QEvent::Type eventId = QEvent::None; + if (eventId == QEvent::None) + eventId = static_cast(QEvent::registerEventType()); + return eventId; } QEvent::Type SaveSnapshotEvent::saveSnapshotEventId() { - static QEvent::Type eventId = QEvent::None; - if (eventId == QEvent::None) - eventId = static_cast(QEvent::registerEventType()); - return eventId; + static QEvent::Type eventId = QEvent::None; + if (eventId == QEvent::None) + eventId = static_cast(QEvent::registerEventType()); + return eventId; } - - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h old mode 100755 new mode 100644 index 9f759a990..aa993907a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_events.h @@ -1,95 +1,121 @@ - #pragma once #include "ltswidgets_export.h" -#include #include +#include #include #include -#include #include - +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsLinkEvent : public QEvent { -public: - explicit LtsLinkEvent(QUrl url, QWidget *sourceBaseLayoutWidget) - : QEvent(eventTypeId()) - , m_url(std::move(url)) - , m_sourceBaseLayoutWidget(sourceBaseLayoutWidget) - {} + public: + explicit LtsLinkEvent(QUrl url, QWidget* sourceBaseLayoutWidget) + : QEvent(eventTypeId()), m_url(std::move(url)), m_sourceBaseLayoutWidget(sourceBaseLayoutWidget) + { + } - static QEvent::Type eventTypeId(); - QWidget *sourceBaseLayoutWidget() const { return m_sourceBaseLayoutWidget.data(); } - QUrl url() const { return m_url; } -private: - QUrl m_url; - QPointer m_sourceBaseLayoutWidget; + static QEvent::Type eventTypeId(); + + QWidget* sourceBaseLayoutWidget() const + { + return m_sourceBaseLayoutWidget.data(); + } + + QUrl url() const + { + return m_url; + } + + private: + QUrl m_url; + QPointer m_sourceBaseLayoutWidget; }; class LTSWIDGETS_EXPORT SaveImageEvent : public QEvent { -public: - SaveImageEvent(QWidget *w, QPixmap &&pm) - : QEvent(saveImageEventId()), m_widget(w), m_pix(std::move(pm)) - {} + public: + SaveImageEvent(QWidget* w, QPixmap&& pm) : QEvent(saveImageEventId()), m_widget(w), m_pix(std::move(pm)) {} - const QPixmap &pixmap() const { return m_pix; } - QWidget *widget() const { return m_widget.data(); } - static QEvent::Type saveImageEventId(); -private: - QPointer m_widget; - QPixmap m_pix; + const QPixmap& pixmap() const + { + return m_pix; + } + + QWidget* widget() const + { + return m_widget.data(); + } + + static QEvent::Type saveImageEventId(); + + private: + QPointer m_widget; + QPixmap m_pix; }; class LTSWIDGETS_EXPORT AddMarkerEvent : public QEvent { -public: - AddMarkerEvent() - : QEvent(addMarkerEventId()) - {} - static QEvent::Type addMarkerEventId(); + public: + AddMarkerEvent() : QEvent(addMarkerEventId()) {} + + static QEvent::Type addMarkerEventId(); }; class LTSWIDGETS_EXPORT SetMarkerEvent : public QEvent { -public: - SetMarkerEvent(const QString &description) - : QEvent(setMarkerEventId()), m_description(description) - {} - const QString &getDescription() const { return m_description; } - void setDescription(const QString &description) { m_description = description; } - static QEvent::Type setMarkerEventId(); -private: - QString m_description; + public: + SetMarkerEvent(const QString& description) : QEvent(setMarkerEventId()), m_description(description) {} + + const QString& getDescription() const + { + return m_description; + } + + void setDescription(const QString& description) + { + m_description = description; + } + + static QEvent::Type setMarkerEventId(); + + private: + QString m_description; }; class LTSWIDGETS_EXPORT AddSnapshotEvent : public QEvent { -public: - AddSnapshotEvent() - : QEvent(addSnapshotEventId()) - {} - static QEvent::Type addSnapshotEventId(); + public: + AddSnapshotEvent() : QEvent(addSnapshotEventId()) {} + + static QEvent::Type addSnapshotEventId(); }; class LTSWIDGETS_EXPORT SaveSnapshotEvent : public QEvent { -public: - SaveSnapshotEvent(const QString &description) - : QEvent(saveSnapshotEventId()), m_description(description) - {} - const QString &getDescription() const { return m_description; } - void setDescription(const QString &description) { m_description = description; } - static QEvent::Type saveSnapshotEventId(); -private: - QString m_description; + public: + SaveSnapshotEvent(const QString& description) : QEvent(saveSnapshotEventId()), m_description(description) {} + + const QString& getDescription() const + { + return m_description; + } + + void setDescription(const QString& description) + { + m_description = description; + } + + static QEvent::Type saveSnapshotEventId(); + + private: + QString m_description; }; - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h old mode 100755 new mode 100644 index a1ef0b7f5..79a420eef --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_frameless_dialog.h @@ -1,47 +1,37 @@ - #pragma once -#include - -#include - #include "lts_base.h" #include "ltswidgets_export.h" +#include +#include namespace LtsWidgets { - -enum class Behaviour -{ - Popup = 0, - Modal, +enum class Behaviour { + Popup = 0, + Modal, }; - - - -class LTSWIDGETS_EXPORT LtsFramelessDialog : public QDialog +class LTSWIDGETS_EXPORT LtsFramelessDialog : public QDialog { - Q_OBJECT + Q_OBJECT -public: - + public: + explicit LtsFramelessDialog(QWidget* parent = nullptr, const Behaviour& behaviour = Behaviour::Popup); + virtual ~LtsFramelessDialog(); - explicit LtsFramelessDialog(QWidget *parent = nullptr, const Behaviour &behaviour = Behaviour::Popup); - virtual ~LtsFramelessDialog(); + public Q_SLOTS: + void onUpdateGeometry(); -public Q_SLOTS: - void onUpdateGeometry(); -private: - QRect screenRectFromPoint(const QPoint &pos) const; - void addTouchScroll(QWidget *widget); - -protected: - void showEvent(QShowEvent *event) override; + private: + QRect screenRectFromPoint(const QPoint& pos) const; + void addTouchScroll(QWidget* widget); + protected: + void showEvent(QShowEvent* event) override; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp old mode 100755 new mode 100644 index b64f6b50e..f8f4685a8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.cpp @@ -1,225 +1,195 @@ #include "lts_global_wait_dialog.h" -#include "lts_progress_dialog_helper.h" -#include "lts_overlay_loading.h" + #include "lts_dialog.h" #include "lts_frameless_dialog.h" +#include "lts_overlay_loading.h" +#include "lts_progress_dialog_helper.h" #include #include - #ifdef Q_OS_UNIX -#include -#include -#include +#include +#include +#include #endif - namespace LtsWidgets { LtsGlobalWaitDialog::~LtsGlobalWaitDialog() { - delete m_progressDialog; + delete m_progressDialog; } - LtsGlobalWaitDialog::LtsGlobalWaitDialog() - : m_waitingCount(0) - , m_visible(true) - , m_progressDialog(new LtsProgressDialogHelper(nullptr)) - , m_hideTimer(new QTimer(this)) + : m_waitingCount(0), m_visible(true), m_progressDialog(new LtsProgressDialogHelper(nullptr)), + m_hideTimer(new QTimer(this)) { - m_hideTimer->setSingleShot(true); - m_hideTimer->setInterval(500); - connect(m_hideTimer, &QTimer::timeout, - this, &LtsGlobalWaitDialog::hideIt); + m_hideTimer->setSingleShot(true); + m_hideTimer->setInterval(500); + connect(m_hideTimer, &QTimer::timeout, this, &LtsGlobalWaitDialog::hideIt); } - void LtsGlobalWaitDialog::unarm() { - m_armed = false; - hideIt(); -} - - -void LtsGlobalWaitDialog::rearm() -{ - m_armed = true; - setVisible(true); -} - - -void LtsGlobalWaitDialog::setVisible(bool visible) -{ - if (m_waitingCount > 0 && visible) - showIt(); - - if (m_waitingCount < 1 && !visible) + m_armed = false; hideIt(); } +void LtsGlobalWaitDialog::rearm() +{ + m_armed = true; + setVisible(true); +} + +void LtsGlobalWaitDialog::setVisible(bool visible) +{ + if (m_waitingCount > 0 && visible) + showIt(); + + if (m_waitingCount < 1 && !visible) + hideIt(); +} void LtsGlobalWaitDialog::showIt() { - if (m_progressDialog->isShown()) - return; + if (m_progressDialog->isShown()) + return; - m_hideTimer->stop(); - if (m_armed) - { - m_progressDialog->slotShowWaitForReplyWindow(); - } + m_hideTimer->stop(); + if (m_armed) + { + m_progressDialog->slotShowWaitForReplyWindow(); + } } - void LtsGlobalWaitDialog::hideIt() { - if (!m_progressDialog->isShown()) - return; + if (!m_progressDialog->isShown()) + return; - m_hideTimer->stop(); - m_progressDialog->slotStopWaitForReplyWindow(); + m_hideTimer->stop(); + m_progressDialog->slotStopWaitForReplyWindow(); } - void bt() { #ifdef Q_OS_UNIX - void *callstack[128]; - const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); - int nFrames = backtrace(callstack, nMaxFrames); - char **symbols = backtrace_symbols(callstack, nFrames); + void* callstack[128]; + const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); + int nFrames = backtrace(callstack, nMaxFrames); + char** symbols = backtrace_symbols(callstack, nFrames); - for (int i = 1; i < nFrames; i++) - { - QString address(QStringLiteral("0x%1").arg(QString::number(*(quintptr *)callstack[i], 16))); - QString function; - int offset = -1; - - Dl_info info; - if (dladdr(callstack[i], &info) && info.dli_sname) + for (int i = 1; i < nFrames; i++) { - char *demangled = nullptr; - int status = -1; - if (info.dli_sname[0] == '_') - demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status); + QString address(QStringLiteral("0x%1").arg(QString::number(*(quintptr*)callstack[i], 16))); + QString function; + int offset = -1; - function = QString::fromUtf8(status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname); - offset = (char *)callstack[i] - (char *)info.dli_saddr; + Dl_info info; + if (dladdr(callstack[i], &info) && info.dli_sname) + { + char* demangled = nullptr; + int status = -1; + if (info.dli_sname[0] == '_') + demangled = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status); - free(demangled); - } - else - { - function = QString::fromUtf8(symbols[i]); + function = QString::fromUtf8(status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname); + offset = (char*)callstack[i] - (char*)info.dli_saddr; + + free(demangled); + } + else + { + function = QString::fromUtf8(symbols[i]); + } } - - } - - free(symbols); - - + free(symbols); #endif } - -void LtsGlobalWaitDialog::wait(QWidget *parent, const QString &customText) +void LtsGlobalWaitDialog::wait(QWidget* parent, const QString& customText) { - m_progressDialog->setParentWidget(parent); - if (m_waitingCount < 1 && m_visible) - showIt(); + m_progressDialog->setParentWidget(parent); + if (m_waitingCount < 1 && m_visible) + showIt(); - setCustomText(customText); + setCustomText(customText); - m_waitingCount++; - - - - + m_waitingCount++; } - -void LtsGlobalWaitDialog::setCustomText(const QString &customText) +void LtsGlobalWaitDialog::setCustomText(const QString& customText) { - m_progressDialog->setCustomText(customText); + m_progressDialog->setCustomText(customText); } - void LtsGlobalWaitDialog::done() { - if (m_waitingCount == 0) - { - - m_hideTimer->start(); - return; - } + if (m_waitingCount == 0) + { - Q_ASSERT(m_waitingCount > 0); + m_hideTimer->start(); + return; + } - m_waitingCount--; - + Q_ASSERT(m_waitingCount > 0); - if (m_waitingCount == 0) - m_hideTimer->start(); + m_waitingCount--; + + if (m_waitingCount == 0) + m_hideTimer->start(); } -static LtsGlobalWaitDialog *s_gwdInstance = nullptr; +static LtsGlobalWaitDialog* s_gwdInstance = nullptr; + void LtsGlobalWaitDialog::cleanupGwdInstance() { - delete s_gwdInstance; - s_gwdInstance = nullptr; + delete s_gwdInstance; + s_gwdInstance = nullptr; } -LtsGlobalWaitDialog *LtsGlobalWaitDialog::getInstance() +LtsGlobalWaitDialog* LtsGlobalWaitDialog::getInstance() { - if (!s_gwdInstance) - { - s_gwdInstance = new LtsGlobalWaitDialog; - qAddPostRoutine(&LtsGlobalWaitDialog::cleanupGwdInstance); - } - return s_gwdInstance; + if (!s_gwdInstance) + { + s_gwdInstance = new LtsGlobalWaitDialog; + qAddPostRoutine(&LtsGlobalWaitDialog::cleanupGwdInstance); + } + return s_gwdInstance; } -} +} // namespace LtsWidgets - - -Waiter::Waiter(const QString &customText) +Waiter::Waiter(const QString& customText) { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(nullptr, customText); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->wait(nullptr, customText); } - -Waiter::Waiter(LtsWidgets::LtsDialog *parent, const QString &customText) - : m_parent(parent) +Waiter::Waiter(LtsWidgets::LtsDialog* parent, const QString& customText) : m_parent(parent) { - m_oldClosableState = m_parent->isClosable(); - m_parent->setClosable(false); - m_parent->setCurrentlyBlocking(true); - auto *wait = new LtsWidgets::LtsOverlayLoading; - wait->setText(customText.isEmpty() ? QObject::tr("Waiting for server reply...") : customText); - m_parent->setOverlay(wait); - m_loadingOverlay = wait; + m_oldClosableState = m_parent->isClosable(); + m_parent->setClosable(false); + m_parent->setCurrentlyBlocking(true); + auto* wait = new LtsWidgets::LtsOverlayLoading; + wait->setText(customText.isEmpty() ? QObject::tr("Waiting for server reply...") : customText); + m_parent->setOverlay(wait); + m_loadingOverlay = wait; } - Waiter::~Waiter() { - if (m_loadingOverlay == nullptr) - { - LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); - return; - } + if (m_loadingOverlay == nullptr) + { + LtsWidgets::LtsGlobalWaitDialog::getInstance()->done(); + return; + } - m_parent->setClosable(m_oldClosableState); - m_parent->setCurrentlyBlocking(false); - m_loadingOverlay->deleteLater(); + m_parent->setClosable(m_oldClosableState); + m_parent->setCurrentlyBlocking(false); + m_loadingOverlay->deleteLater(); } - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h old mode 100755 new mode 100644 index 2a3232d5f..94ad28fde --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_global_wait_dialog.h @@ -1,69 +1,67 @@ - #pragma once #include "ltswidgets_export.h" #include - class QTimer; class QWidget; - namespace LtsWidgets { class LtsDialog; class LtsOverlayLoading; class LtsProgressDialogHelper; - class LTSWIDGETS_EXPORT LtsGlobalWaitDialog : public QObject { - Q_OBJECT + Q_OBJECT -public: - static LtsGlobalWaitDialog* getInstance(); - void wait(QWidget *parent, const QString &customText = QString()); - void wait(const QString &customText = QString()) { wait(nullptr, customText); } - void done(); - void setVisible(bool visible = true); - void setCustomText(const QString &customText = QString()); - void unarm(); - void rearm(); + public: + static LtsGlobalWaitDialog* getInstance(); + void wait(QWidget* parent, const QString& customText = QString()); -private: - friend struct LtsGlobalWaitDialogHandler; + void wait(const QString& customText = QString()) + { + wait(nullptr, customText); + } - LtsGlobalWaitDialog(); - ~LtsGlobalWaitDialog(); - static void cleanupGwdInstance(); + void done(); + void setVisible(bool visible = true); + void setCustomText(const QString& customText = QString()); + void unarm(); + void rearm(); - void showIt(); - void hideIt(); + private: + friend struct LtsGlobalWaitDialogHandler; - int m_waitingCount; - bool m_visible; - bool m_armed { true }; - LtsProgressDialogHelper *m_progressDialog; - QTimer *m_hideTimer; + LtsGlobalWaitDialog(); + ~LtsGlobalWaitDialog(); + static void cleanupGwdInstance(); + + void showIt(); + void hideIt(); + + int m_waitingCount; + bool m_visible; + bool m_armed{true}; + LtsProgressDialogHelper* m_progressDialog; + QTimer* m_hideTimer; }; -} - - - +} // namespace LtsWidgets class LTSWIDGETS_EXPORT Waiter { -public: - explicit Waiter(const QString &customText = {}); - explicit Waiter(LtsWidgets::LtsDialog *parent, const QString &customText = {}); - ~Waiter(); + public: + explicit Waiter(const QString& customText = {}); + explicit Waiter(LtsWidgets::LtsDialog* parent, const QString& customText = {}); + ~Waiter(); -private: - LtsWidgets::LtsOverlayLoading *m_loadingOverlay { nullptr }; - LtsWidgets::LtsDialog *m_parent { nullptr }; - bool m_oldClosableState { false }; + private: + LtsWidgets::LtsOverlayLoading* m_loadingOverlay{nullptr}; + LtsWidgets::LtsDialog* m_parent{nullptr}; + bool m_oldClosableState{false}; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h old mode 100755 new mode 100644 index 99995c6f5..adc09caa9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_grid_layout.h @@ -1,62 +1,48 @@ - #pragma once -#include -#include -#include - -#include "ltswidgets_export.h" #include "lts_base.h" +#include "ltswidgets_export.h" + +#include +#include +#include class QWidget; namespace LtsWidgets { - class LTSWIDGETS_EXPORT LtsGridLayout : public QGridLayout { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget* parent = nullptr, int maxColumn = 1); - explicit LtsGridLayout(LtsWidgets::ButtonSize buttonSize, QWidget *parent = nullptr, int maxColumn = 1); + void add_widget(QWidget* widget); - + void setAutoSize(bool enable); - void add_widget(QWidget *widget); + void setMaxColumn(int max); - + private: + void addWidgetInternal(QWidget* widget); - void setAutoSize(bool enable); - - - - void setMaxColumn(int max); - - -private: - void addWidgetInternal(QWidget *widget); - -public Q_SLOTS: - void onParentResize(QResizeEvent *e); - - -private Q_SLOTS: - void onWidgetDestroyed(); -private: - - LtsWidgets::ButtonSize m_buttonSize; - int m_defaultMaxColumn; - int m_maxColumn; - int m_colSize; - QVector m_widgetList; - QRect m_oldGeo; - QSize m_oldSize; - bool m_autoSize; + public Q_SLOTS: + void onParentResize(QResizeEvent* e); + private Q_SLOTS: + void onWidgetDestroyed(); + private: + LtsWidgets::ButtonSize m_buttonSize; + int m_defaultMaxColumn; + int m_maxColumn; + int m_colSize; + QVector m_widgetList; + QRect m_oldGeo; + QSize m_oldSize; + bool m_autoSize; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h old mode 100755 new mode 100644 index 8c0d1ddf7..27c3c2b07 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_height_plot_widget.h @@ -1,70 +1,55 @@ - #pragma once -#include - -#include -#include -#include -#include - #include "ltswidgets_export.h" +#include +#include +#include +#include +#include + class LTSWIDGETS_EXPORT LtsHeightPlotWidget final : public QWidget { - Q_OBJECT -public: - explicit LtsHeightPlotWidget(QWidget *parent = nullptr); - virtual ~LtsHeightPlotWidget(); + Q_OBJECT + public: + explicit LtsHeightPlotWidget(QWidget* parent = nullptr); + virtual ~LtsHeightPlotWidget(); - void clearView(); + void clearView(); - + void setData(const QVector>& data); - void setData(const QVector > &data); - + void setMarks(const QVector& data); - void setMarks(const QVector &data); + void setBackgroundBrush(const QBrush& brush); - + void setTextFont(const QFont& f); - void setBackgroundBrush(const QBrush &brush); - + void setAxisPen(const QPen& pen); - void setTextFont(const QFont &f); - + void setPositionPen(const QPen& pen); - void setAxisPen(const QPen &pen); - + void setViewLinePen(const QPen& pen); - void setPositionPen(const QPen &pen); - + void setContourBrush(const QBrush& brush); - void setViewLinePen(const QPen &pen); - + void setMarkerPen(const QPen& pen); - void setContourBrush(const QBrush &brush); - + Q_SIGNALS: - void setMarkerPen(const QPen &pen); + void mousePositionChanged(const QPointF& curPoint, double curHeight, double mouseHeight); -Q_SIGNALS: - + void startLineOfSight(const QPointF& startPoint); - void mousePositionChanged(const QPointF &curPoint, double curHeight, double mouseHeight); - + void stopLineOfSight(); - void startLineOfSight(const QPointF &startPoint); - + protected: + void resizeEvent(QResizeEvent* e) override; + void paintEvent(QPaintEvent* e) override; + void mouseMoveEvent(QMouseEvent* e) override; + void mouseReleaseEvent(QMouseEvent* e) override; - void stopLineOfSight(); -protected: - void resizeEvent(QResizeEvent *e) override; - void paintEvent(QPaintEvent *e) override; - void mouseMoveEvent(QMouseEvent *e) override; - void mouseReleaseEvent(QMouseEvent *e) override; - - class Private; - Private *const d; + class Private; + Private* const d; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp old mode 100755 new mode 100644 index b74298644..f5e3385d9 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.cpp @@ -1,28 +1,27 @@ - #include "lts_info_dialog.h" + #include "ui_lts_info_dialog.h" -#include -#include #include - +#include +#include #ifndef LTS_VERSION_MAJOR - #define LTS_VERSION_MAJOR "undefined" +#define LTS_VERSION_MAJOR "undefined" #endif #ifndef LTS_VERSION_MINOR - #define LTS_VERSION_MINOR "undefined" +#define LTS_VERSION_MINOR "undefined" #endif #ifndef LTS_VERSION_PATCH - #define LTS_VERSION_PATCH "undefined" +#define LTS_VERSION_PATCH "undefined" #endif #ifndef LTS_VERSION_DATE - #define LTS_VERSION_DATE "undefined" +#define LTS_VERSION_DATE "undefined" #endif #ifndef JENKINS_BUILD_NUMBER - #define JENKINS_BUILD_NUMBER "unknown" +#define JENKINS_BUILD_NUMBER "unknown" #endif static const char ver_major[] = LTS_VERSION_MAJOR; static const char ver_minor[] = LTS_VERSION_MINOR; @@ -33,49 +32,43 @@ static const char ver_jenkins[] = JENKINS_BUILD_NUMBER; namespace LtsWidgets { -LtsInfoDialog::LtsInfoDialog(QWidget *parent) - : LtsFramelessDialog(parent) - , m_ui(new Ui::LtsInfoDialog) +LtsInfoDialog::LtsInfoDialog(QWidget* parent) : LtsFramelessDialog(parent), m_ui(new Ui::LtsInfoDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - QFont f = font(); - f.setBold(true); - m_ui->lblVersion->setFont(f); - m_ui->lblDate->setFont(f); + QFont f = font(); + f.setBold(true); + m_ui->lblVersion->setFont(f); + m_ui->lblDate->setFont(f); - const 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)); - m_ui->lblVersion->setText(versionString); - m_ui->lblDate->setText(QString::fromLatin1(ver_date)); + const 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)); + m_ui->lblVersion->setText(versionString); + m_ui->lblDate->setText(QString::fromLatin1(ver_date)); - - QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); - if (!QFile(projectLogoFilename).exists()) - projectLogoFilename = QStringLiteral(":/project/logo.png"); + QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); + if (!QFile(projectLogoFilename).exists()) + projectLogoFilename = QStringLiteral(":/project/logo.png"); - QPixmap pixmap(projectLogoFilename); + QPixmap pixmap(projectLogoFilename); - if (pixmap.isNull()) - { - qWarning() << "LtsInfoDialog: project logo missing or is not an valid image " << projectLogoFilename; - } - else - { - int max = m_ui->lblProjectLogo->maximumHeight(); - pixmap = pixmap.scaled(999, max * 0.85f, Qt::KeepAspectRatio, Qt::SmoothTransformation); - m_ui->lblProjectLogo->setPixmap(pixmap); - } - connect(m_ui->pbClose, &QPushButton::clicked, this, &LtsInfoDialog::close); + if (pixmap.isNull()) + { + qWarning() << "LtsInfoDialog: project logo missing or is not an valid image " << projectLogoFilename; + } + else + { + int max = m_ui->lblProjectLogo->maximumHeight(); + pixmap = pixmap.scaled(999, max * 0.85f, Qt::KeepAspectRatio, Qt::SmoothTransformation); + m_ui->lblProjectLogo->setPixmap(pixmap); + } + connect(m_ui->pbClose, &QPushButton::clicked, this, &LtsInfoDialog::close); } - LtsInfoDialog::~LtsInfoDialog() { - delete m_ui; + delete m_ui; } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h old mode 100755 new mode 100644 index be790fb05..e8830b6f1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_info_dialog.h @@ -1,12 +1,10 @@ - #pragma once -#include - #include "lts_frameless_dialog.h" #include "ltswidgets_export.h" +#include namespace Ui { @@ -17,13 +15,13 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsInfoDialog : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - explicit LtsInfoDialog(QWidget *parent = nullptr); - ~LtsInfoDialog(); + public: + explicit LtsInfoDialog(QWidget* parent = nullptr); + ~LtsInfoDialog(); -private: - Ui::LtsInfoDialog *m_ui; + private: + Ui::LtsInfoDialog* m_ui; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp old mode 100755 new mode 100644 index 8915e52a4..22ca53fbb --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.cpp @@ -1,148 +1,137 @@ - #include "lts_led_widget.h" + #include #include #include + namespace LtsWidgets { -void LtsLedWidget::resizeEvent(QResizeEvent *event) +void LtsLedWidget::resizeEvent(QResizeEvent* event) { - switch (m_aspectHint) { - case AspectHint::NoHint: - { - + switch (m_aspectHint) + { + case AspectHint::NoHint: { - - - - QWidget::resizeEvent(event); - break; - } - case AspectHint::HeightIsWidth: - setMinimumHeight(event->size().width()); - setMaximumHeight(event->size().width()); - setMinimumWidth(0); - setMaximumWidth(65000); - break; - case AspectHint::WidthIsHeight: - setMinimumHeight(0); - setMaximumHeight(65000); - setMinimumWidth(event->size().height()); - setMaximumWidth(event->size().height()); - break; - } + QWidget::resizeEvent(event); + break; + } + case AspectHint::HeightIsWidth: + setMinimumHeight(event->size().width()); + setMaximumHeight(event->size().width()); + setMinimumWidth(0); + setMaximumWidth(65000); + break; + case AspectHint::WidthIsHeight: + setMinimumHeight(0); + setMaximumHeight(65000); + setMinimumWidth(event->size().height()); + setMaximumWidth(event->size().height()); + break; + } } +static constexpr double GRADIENT_KEY_LOWER = 0.3; +static constexpr double GRADIENT_KEY_UPPER = 0.9; +static constexpr int GRADIENT_VALUE_LOWER = 125; +static constexpr int GRADIENT_VALUE_UPPER = 165; +static constexpr double GRADIENT_CENTER_OFFSET = 5.0; +static constexpr double GRADIENT_FOCALPOINT_OFFSET = 2.7; +static constexpr double PERCENTAGE_OF_BORDER = 0.1; +static constexpr int DARK_FACTOR = 200; - -static constexpr double GRADIENT_KEY_LOWER = 0.3; -static constexpr double GRADIENT_KEY_UPPER = 0.9; -static constexpr int GRADIENT_VALUE_LOWER = 125; -static constexpr int GRADIENT_VALUE_UPPER = 165; -static constexpr double GRADIENT_CENTER_OFFSET = 5.0; -static constexpr double GRADIENT_FOCALPOINT_OFFSET = 2.7; -static constexpr double PERCENTAGE_OF_BORDER = 0.1; -static constexpr int DARK_FACTOR = 200; - -LtsLedWidget::LtsLedWidget(QWidget *parent, const QColor &oncolor, const QColor &offcolor, bool useGradient, int animtime) - : QWidget(parent) - , m_status(true) - , m_oncolor(oncolor) - , m_offcolor(offcolor) - , m_currentcolor(oncolor) - , m_gradient(useGradient) - , m_animTime(animtime) +LtsLedWidget::LtsLedWidget(QWidget* parent, const QColor& oncolor, const QColor& offcolor, bool useGradient, + int animtime) + : QWidget(parent), m_status(true), m_oncolor(oncolor), m_offcolor(offcolor), m_currentcolor(oncolor), + m_gradient(useGradient), m_animTime(animtime) { - setObjectName(QString::fromUtf8("LtsLedWidget")); + setObjectName(QString::fromUtf8("LtsLedWidget")); } -void LtsLedWidget::paintEvent(QPaintEvent *pe) +void LtsLedWidget::paintEvent(QPaintEvent* pe) { - Q_UNUSED(pe); - QPainter p; - p.begin(this); - p.setOpacity(QWidget::isEnabled() ? 1.00 : 0.5); + Q_UNUSED(pe); + QPainter p; + p.begin(this); + p.setOpacity(QWidget::isEnabled() ? 1.00 : 0.5); - int minSize = height() > width() ? width() : height(); - if (m_gradient) - { - QRadialGradient grad(QPointF(width(), height()) / GRADIENT_CENTER_OFFSET, - minSize, - QPointF(width(), height()) / GRADIENT_FOCALPOINT_OFFSET); - grad.setColorAt(GRADIENT_KEY_LOWER, m_currentcolor.lighter(GRADIENT_VALUE_LOWER)); - grad.setColorAt(GRADIENT_KEY_UPPER, m_currentcolor.darker(GRADIENT_VALUE_UPPER)); - p.setBrush(grad); - } - else - p.setBrush(QBrush(m_currentcolor, Qt::SolidPattern)); + int minSize = height() > width() ? width() : height(); + if (m_gradient) + { + QRadialGradient grad(QPointF(width(), height()) / GRADIENT_CENTER_OFFSET, minSize, + QPointF(width(), height()) / GRADIENT_FOCALPOINT_OFFSET); + grad.setColorAt(GRADIENT_KEY_LOWER, m_currentcolor.lighter(GRADIENT_VALUE_LOWER)); + grad.setColorAt(GRADIENT_KEY_UPPER, m_currentcolor.darker(GRADIENT_VALUE_UPPER)); + p.setBrush(grad); + } + else + p.setBrush(QBrush(m_currentcolor, Qt::SolidPattern)); - p.setRenderHint(QPainter::Antialiasing); - p.setPen(QPen(Qt::black, PERCENTAGE_OF_BORDER * minSize, Qt::SolidLine, Qt::SquareCap)); - p.drawEllipse(QPointF(width(), height()) / 2.0, - width() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER)), - height() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER))); - p.end(); + p.setRenderHint(QPainter::Antialiasing); + p.setPen(QPen(Qt::black, PERCENTAGE_OF_BORDER * minSize, Qt::SolidLine, Qt::SquareCap)); + p.drawEllipse(QPointF(width(), height()) / 2.0, width() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER)), + height() / (2.0 * (1.00 + PERCENTAGE_OF_BORDER))); + p.end(); } void LtsLedWidget::animate() { - QPropertyAnimation *anim = new QPropertyAnimation(this, "currentcolor"); - anim->setDuration(m_animTime); - anim->setEasingCurve(QEasingCurve::OutBack); - anim->setStartValue(m_currentcolor); - anim->setEndValue(m_status ? m_oncolor : m_offcolor == Qt::black ? m_oncolor.darker(DARK_FACTOR) : m_offcolor); - anim->start(QPropertyAnimation::DeleteWhenStopped); + QPropertyAnimation* anim = new QPropertyAnimation(this, "currentcolor"); + anim->setDuration(m_animTime); + anim->setEasingCurve(QEasingCurve::OutBack); + anim->setStartValue(m_currentcolor); + anim->setEndValue(m_status ? m_oncolor : m_offcolor == Qt::black ? m_oncolor.darker(DARK_FACTOR) : m_offcolor); + anim->start(QPropertyAnimation::DeleteWhenStopped); } void LtsLedWidget::setStatus(bool status) { - if (m_status == status) - return; - m_status = status; - animate(); + if (m_status == status) + return; + m_status = status; + animate(); } void LtsLedWidget::setUseGradient(bool useGradient) { - if (m_gradient == useGradient) - return; - m_gradient = useGradient; - repaint(); + if (m_gradient == useGradient) + return; + m_gradient = useGradient; + repaint(); } -void LtsLedWidget::setColor(const QColor &oncolor, const QColor &offcolor) +void LtsLedWidget::setColor(const QColor& oncolor, const QColor& offcolor) { - setOnColor(oncolor); - setOffColor(offcolor); + setOnColor(oncolor); + setOffColor(offcolor); } -void LtsLedWidget::setOnColor(const QColor &oncolor) +void LtsLedWidget::setOnColor(const QColor& oncolor) { - if (m_oncolor == oncolor) - return; - m_oncolor = oncolor; - if (m_status) - animate(); + if (m_oncolor == oncolor) + return; + m_oncolor = oncolor; + if (m_status) + animate(); } -void LtsLedWidget::setOffColor(const QColor &offcolor) +void LtsLedWidget::setOffColor(const QColor& offcolor) { - if (m_offcolor == offcolor) - return; - m_offcolor = offcolor; - if (!m_status) - animate(); + if (m_offcolor == offcolor) + return; + m_offcolor = offcolor; + if (!m_status) + animate(); } -void LtsLedWidget::setCurrentColor(const QColor ¤tcolor) +void LtsLedWidget::setCurrentColor(const QColor& currentcolor) { - if (m_currentcolor == currentcolor) - return; - m_currentcolor = currentcolor; - repaint(); + if (m_currentcolor == currentcolor) + return; + m_currentcolor = currentcolor; + repaint(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h old mode 100755 new mode 100644 index e1723488f..d4cdac569 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_led_widget.h @@ -1,118 +1,107 @@ #pragma once -#include - -#include #include "ltswidgets_export.h" +#include +#include + namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsLedWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - enum class AspectHint - { - WidthIsHeight, - NoHint, - HeightIsWidth - }; - Q_ENUM(AspectHint) + public: + enum class AspectHint { WidthIsHeight, NoHint, HeightIsWidth }; + Q_ENUM(AspectHint) - Q_PROPERTY(QColor oncolor READ onColor WRITE setOnColor) - Q_PROPERTY(QColor offcolor READ offColor WRITE setOffColor) - Q_PROPERTY(bool status READ status WRITE setStatus) - Q_PROPERTY(bool usesGradient READ usesGradient WRITE setUseGradient) - Q_PROPERTY(int animTime READ animTime WRITE setAnimTime) - Q_PROPERTY(AspectHint aspectHint READ aspectHint WRITE setAspectHint) - Q_PROPERTY(QColor currentcolor READ currentColor WRITE setCurrentColor DESIGNABLE false) + Q_PROPERTY(QColor oncolor READ onColor WRITE setOnColor) + Q_PROPERTY(QColor offcolor READ offColor WRITE setOffColor) + Q_PROPERTY(bool status READ status WRITE setStatus) + Q_PROPERTY(bool usesGradient READ usesGradient WRITE setUseGradient) + Q_PROPERTY(int animTime READ animTime WRITE setAnimTime) + Q_PROPERTY(AspectHint aspectHint READ aspectHint WRITE setAspectHint) + Q_PROPERTY(QColor currentcolor READ currentColor WRITE setCurrentColor DESIGNABLE false) - + explicit LtsLedWidget(QWidget* parent = nullptr, const QColor& oncolor = Qt::red, + const QColor& offcolor = Qt::black, bool useGradient = true, int animtime = 0); - explicit LtsLedWidget(QWidget *parent = nullptr, const QColor &oncolor = Qt::red, const QColor &offcolor = Qt::black, bool useGradient = true, int animtime = 0); + void paintEvent(QPaintEvent* pe); - void paintEvent(QPaintEvent *pe); + void setAnimTime(int time) + { + m_animTime = time; + } - + int animTime() const + { + return m_animTime; + } - void setAnimTime(int time) { m_animTime = time; } + bool status() const + { + return m_status; + } - + void setUseGradient(bool useGradient); - int animTime() const { return m_animTime; } + bool usesGradient() const + { + return m_gradient; + } - + void setOnColor(const QColor& oncolor); - bool status() const { return m_status; } + QColor onColor() const + { + return m_oncolor; + } - + void setOffColor(const QColor& offcolor); - void setUseGradient(bool useGradient); + QColor offColor() const + { + return m_offcolor; + } - + void setColor(const QColor& oncolor, const QColor& offcolor = Qt::black); - bool usesGradient() const { return m_gradient; } + QColor currentColor() const + { + return m_currentcolor; + } - + void resizeEvent(QResizeEvent* event); - void setOnColor(const QColor &oncolor); + AspectHint aspectHint() const + { + return m_aspectHint; + } - + public slots: - QColor onColor() const { return m_oncolor; } + void setStatus(bool status); - + void setAspectHint(AspectHint aspectHint) + { + m_aspectHint = aspectHint; + } - void setOffColor(const QColor &offcolor); + private: + void setCurrentColor(const QColor& currentcolor); - + void animate(); - QColor offColor() const { return m_offcolor; } + bool m_status; + QColor m_oncolor; + QColor m_offcolor; + QColor m_currentcolor; - - - void setColor(const QColor &oncolor, const QColor &offcolor = Qt::black); - - - - QColor currentColor() const { return m_currentcolor; } - - void resizeEvent(QResizeEvent *event); - - AspectHint aspectHint() const { return m_aspectHint; } - -public slots: - - - void setStatus(bool status); - - void setAspectHint(AspectHint aspectHint) - { - m_aspectHint = aspectHint; - } - -private: - - - void setCurrentColor(const QColor ¤tcolor); - - - - void animate(); - - bool m_status; - QColor m_oncolor; - QColor m_offcolor; - QColor m_currentcolor; - - bool m_gradient; - int m_animTime; - AspectHint m_aspectHint = AspectHint::NoHint; + bool m_gradient; + int m_animTime; + AspectHint m_aspectHint = AspectHint::NoHint; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h old mode 100755 new mode 100644 index 9de10b3c2..027b17268 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog.h @@ -1,87 +1,69 @@ #pragma once -#include "ltswidgets_export.h" #include "lts_frameless_dialog.h" +#include "ltswidgets_export.h" +#include #include #include -#include - class QWidget; class QHBoxLayout; - namespace LtsWidgets { +enum class Button { + UNKNOWN = 0, + Ok = 1, + Yes = 2, + No = 4, + Cancel = 8, - -enum class Button -{ - UNKNOWN = 0, - Ok = 1, - Yes = 2, - No = 4, - Cancel = 8, - - Apply = 16, - Discard = 32, + Apply = 16, + Discard = 32, }; Q_DECLARE_FLAGS(Buttons, Button) + inline uint qHash(LtsWidgets::Button b) { - return ::qHash(static_cast(b)); + return ::qHash(static_cast(b)); } - - -namespace LtsMessageDialog +namespace LtsMessageDialog { - -LTSWIDGETS_EXPORT Button showMessage(QWidget* parent, - const QString &message, - const QString &title = QString(), - const Behaviour behaviour = Behaviour::Modal, - const Buttons buttons = Button::Ok, - const QHash &buttonTexts = QHash()); -LTSWIDGETS_EXPORT Button askApplyDiscardCancel(QWidget *parent); -} - - - - +LTSWIDGETS_EXPORT Button showMessage(QWidget* parent, const QString& message, const QString& title = QString(), + const Behaviour behaviour = Behaviour::Modal, const Buttons buttons = Button::Ok, + const QHash& buttonTexts = QHash()); +LTSWIDGETS_EXPORT Button askApplyDiscardCancel(QWidget* parent); +} // namespace LtsMessageDialog class LTSWIDGETS_EXPORT LtsMessageDialogNew : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit LtsMessageDialogNew(QWidget* parent, - const QString &message, - const QString &title = QString(), - const Behaviour behaviour = Behaviour::Modal, - const Buttons buttons = Button::Ok, - const QHash &buttonTexts = QHash(), - bool deleteOnClose = true ); + public: + explicit LtsMessageDialogNew(QWidget* parent, const QString& message, const QString& title = QString(), + const Behaviour behaviour = Behaviour::Modal, const Buttons buttons = Button::Ok, + const QHash& buttonTexts = QHash(), + bool deleteOnClose = true); -private: - LtsFramelessDialog *m_dialog; + private: + LtsFramelessDialog* m_dialog; - QPushButton *addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent); - - -signals: - void ok(); - void yes(); - void no(); - void apply(); - void discard(); - void cancel(); + QPushButton* addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, + const Button& button, QWidget* parent); + signals: + void ok(); + void yes(); + void no(); + void apply(); + void discard(); + void cancel(); }; -} +} // namespace LtsWidgets Q_DECLARE_OPERATORS_FOR_FLAGS(LtsWidgets::Buttons) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h old mode 100755 new mode 100644 index 0aaf73a4e..0d05b02cd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_message_dialog_helper.h @@ -7,46 +7,39 @@ #include #include - class QPushButton; class QHBoxLayout; - namespace LtsWidgets { - - class LtsMessageDialogHelper : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit LtsMessageDialogHelper(QObject *parent = nullptr); - ~LtsMessageDialogHelper() = default; + public: + explicit LtsMessageDialogHelper(QObject* parent = nullptr); + ~LtsMessageDialogHelper() = default; - Button showMessage(QWidget *parent, - const QString &message, - const QString &title, - Behaviour behaviour, - LtsWidgets::Buttons buttons, - const QHash &buttonTexts); + Button showMessage(QWidget* parent, const QString& message, const QString& title, Behaviour behaviour, + LtsWidgets::Buttons buttons, const QHash& buttonTexts); -private: - QPushButton *addButton(const QString &text, QHBoxLayout *thatLayout, LtsFramelessDialog *dialog, const Button &button, QWidget *parent); + private: + QPushButton* addButton(const QString& text, QHBoxLayout* thatLayout, LtsFramelessDialog* dialog, + const Button& button, QWidget* parent); - Button m_result; - LtsFramelessDialog *m_dialog; + Button m_result; + LtsFramelessDialog* m_dialog; -private slots: - void slotOkay(); - void slotYes(); - void slotNo(); - void slotCancel(); - void slotApply(); - void slotDiscard(); + private slots: + void slotOkay(); + void slotYes(); + void slotNo(); + void slotCancel(); + void slotApply(); + void slotDiscard(); -signals: - void signalQuitEventLoop(); + signals: + void signalQuitEventLoop(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp old mode 100755 new mode 100644 index 8d9316a77..e0a83234f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.cpp @@ -1,114 +1,113 @@ #include "lts_msec_date_time_edit.h" - namespace LtsWidgets { -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(QWidget *parent) - : QDateTimeEdit(parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(QWidget* parent) : QDateTimeEdit(parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDateTime &dt, QWidget *parent) - : QDateTimeEdit(dt, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDateTime& dt, QWidget* parent) : QDateTimeEdit(dt, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDate &d, QWidget *parent) - : QDateTimeEdit(d, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QDate& d, QWidget* parent) : QDateTimeEdit(d, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } -LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QTime &t, QWidget *parent) - : QDateTimeEdit(t, parent) +LtsMSecDateTimeEdit::LtsMSecDateTimeEdit(const QTime& t, QWidget* parent) : QDateTimeEdit(t, parent) { - setWrapping(true); - setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); - connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); + setWrapping(true); + setDisplayFormat(QLatin1String("dd.MM.yy HH:mm:ss.zzz")); + connect(this, &LtsMSecDateTimeEdit::editingFinished, this, &LtsMSecDateTimeEdit::onEditingFinished); } void LtsMSecDateTimeEdit::stepBy(int steps) { - switch (currentSection()) { - case QDateTimeEdit::MonthSection: - QDateTimeEdit::setDateTime(dateTime().addMonths(steps)); - break; - case QDateTimeEdit::YearSection: - QDateTimeEdit::setDateTime(dateTime().addYears(steps)); - break; - case QDateTimeEdit::DaySection: - QDateTimeEdit::setDateTime(dateTime().addDays(steps)); - break; - case QDateTimeEdit::HourSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 3600)); - break; - case QDateTimeEdit::MinuteSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 60)); - break; - case QDateTimeEdit::SecondSection: - QDateTimeEdit::setDateTime(dateTime().addSecs(steps)); - break; - case QDateTimeEdit::MSecSection: - QDateTimeEdit::setDateTime(dateTime().addMSecs(steps * m_msecStepSize)); - break; - case QDateTimeEdit::NoSection: - case QDateTimeEdit::AmPmSection: - case QDateTimeEdit::TimeSections_Mask: - case QDateTimeEdit::DateSections_Mask: - default: - break; - } + switch (currentSection()) + { + case QDateTimeEdit::MonthSection: + QDateTimeEdit::setDateTime(dateTime().addMonths(steps)); + break; + case QDateTimeEdit::YearSection: + QDateTimeEdit::setDateTime(dateTime().addYears(steps)); + break; + case QDateTimeEdit::DaySection: + QDateTimeEdit::setDateTime(dateTime().addDays(steps)); + break; + case QDateTimeEdit::HourSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 3600)); + break; + case QDateTimeEdit::MinuteSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps * 60)); + break; + case QDateTimeEdit::SecondSection: + QDateTimeEdit::setDateTime(dateTime().addSecs(steps)); + break; + case QDateTimeEdit::MSecSection: + QDateTimeEdit::setDateTime(dateTime().addMSecs(steps * m_msecStepSize)); + break; + case QDateTimeEdit::NoSection: + case QDateTimeEdit::AmPmSection: + case QDateTimeEdit::TimeSections_Mask: + case QDateTimeEdit::DateSections_Mask: + default: + break; + } } qint64 LtsMSecDateTimeEdit::msecsSinceEpoch() const { - return dateTime().toMSecsSinceEpoch() - (m_timezoneHoursOffset * 3600 * 1000); + return dateTime().toMSecsSinceEpoch() - (m_timezoneHoursOffset * 3600 * 1000); } void LtsMSecDateTimeEdit::setTimezoneHoursOffset(int timezoneHoursOffset) { - qint64 b4 = msecsSinceEpoch(); - m_timezoneHoursOffset = timezoneHoursOffset; - setMsecsSinceEpoch(b4); + qint64 b4 = msecsSinceEpoch(); + m_timezoneHoursOffset = timezoneHoursOffset; + setMsecsSinceEpoch(b4); } -void LtsMSecDateTimeEdit::setDateTime(const QDateTime &dateTime) +void LtsMSecDateTimeEdit::setDateTime(const QDateTime& dateTime) { - - setMsecsSinceEpoch(QDateTime::fromMSecsSinceEpoch(dateTime.toMSecsSinceEpoch(), Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600).toMSecsSinceEpoch()); + + setMsecsSinceEpoch(QDateTime::fromMSecsSinceEpoch(dateTime.toMSecsSinceEpoch(), Qt::TimeSpec::OffsetFromUTC, + m_timezoneHoursOffset * 3600) + .toMSecsSinceEpoch()); } void LtsMSecDateTimeEdit::setMsecsSinceEpoch(qint64 msecs) { - QDateTimeEdit::setDateTime(QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); + QDateTimeEdit::setDateTime( + QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); } int LtsMSecDateTimeEdit::msecStepSize() const { - return m_msecStepSize; + return m_msecStepSize; } void LtsMSecDateTimeEdit::setMsecStepSize(int msecStepSize) { - m_msecStepSize = msecStepSize; + m_msecStepSize = msecStepSize; } void LtsMSecDateTimeEdit::onEditingFinished() { - qint64 val = msecsSinceEpoch(); - if (val % m_msecStepSize == 0) - return; - val = (val + (m_msecStepSize/2) ) / m_msecStepSize * m_msecStepSize; - setMsecsSinceEpoch(val); + qint64 val = msecsSinceEpoch(); + if (val % m_msecStepSize == 0) + return; + val = (val + (m_msecStepSize / 2)) / m_msecStepSize * m_msecStepSize; + setMsecsSinceEpoch(val); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h old mode 100755 new mode 100644 index aa8e92291..07960390e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_msec_date_time_edit.h @@ -1,42 +1,46 @@ #pragma once -#include - -#include - #include "ltswidgets_export.h" +#include +#include -namespace LtsWidgets { +namespace LtsWidgets +{ class LTSWIDGETS_EXPORT LtsMSecDateTimeEdit : public QDateTimeEdit { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(int msecStepSize READ msecStepSize WRITE setMsecStepSize) + Q_PROPERTY(int msecStepSize READ msecStepSize WRITE setMsecStepSize) -public: - explicit LtsMSecDateTimeEdit(QWidget *parent = nullptr); - explicit LtsMSecDateTimeEdit(const QDateTime &dt, QWidget *parent = nullptr); - explicit LtsMSecDateTimeEdit(const QDate &d, QWidget *parent = nullptr); - explicit LtsMSecDateTimeEdit(const QTime &t, QWidget *parent = nullptr); + public: + explicit LtsMSecDateTimeEdit(QWidget* parent = nullptr); + explicit LtsMSecDateTimeEdit(const QDateTime& dt, QWidget* parent = nullptr); + explicit LtsMSecDateTimeEdit(const QDate& d, QWidget* parent = nullptr); + explicit LtsMSecDateTimeEdit(const QTime& t, QWidget* parent = nullptr); - qint64 msecsSinceEpoch() const; - int timezoneHoursOffset() const { return m_timezoneHoursOffset; } - void stepBy(int steps) override; - int msecStepSize() const; + qint64 msecsSinceEpoch() const; -public slots: - void setDateTime(const QDateTime &dateTime); - void setMsecsSinceEpoch(qint64 msecs); - void setMsecStepSize(int msecStepSize); - void setTimezoneHoursOffset(int timezoneHoursOffset); + int timezoneHoursOffset() const + { + return m_timezoneHoursOffset; + } -private slots: - void onEditingFinished(); + void stepBy(int steps) override; + int msecStepSize() const; -private: - int m_msecStepSize = 10; - int m_timezoneHoursOffset = 0; + public slots: + void setDateTime(const QDateTime& dateTime); + void setMsecsSinceEpoch(qint64 msecs); + void setMsecStepSize(int msecStepSize); + void setTimezoneHoursOffset(int timezoneHoursOffset); + + private slots: + void onEditingFinished(); + + private: + int m_msecStepSize = 10; + int m_timezoneHoursOffset = 0; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp old mode 100755 new mode 100644 index 24799a6ff..d23f06a6d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_multi_range_spinbox.cpp @@ -1,314 +1,261 @@ - #include "lts_multi_range_spinbox.h" -#include #include #include #include +#include namespace LtsWidgets { -LtsMultiRangeSpinBox::LtsMultiRangeSpinBox(QWidget *parent) - : QSpinBox(parent) +LtsMultiRangeSpinBox::LtsMultiRangeSpinBox(QWidget* parent) : QSpinBox(parent) { - m_curVal = minimum(); - + m_curVal = minimum(); } - - - -QValidator::State LtsMultiRangeSpinBox::validate(QString &input, int &pos) const +QValidator::State LtsMultiRangeSpinBox::validate(QString& input, int& pos) const { - - - - - - - - - - - - - - - - return QValidator::Acceptable; + return QValidator::Acceptable; } -void LtsMultiRangeSpinBox::fixup(QString &str) const +void LtsMultiRangeSpinBox::fixup(QString& str) const {} + +QValidator::State LtsMultiRangeSpinBox::validateAll(QString& input, int& pos) { - - - - - - - - - - - - - - - - -} - -QValidator::State LtsMultiRangeSpinBox::validateAll(QString &input, int &pos) -{ - for(QPair range : std::as_const(m_rangesList)) - { - QIntValidator validator(range.first, range.second); - QValidator::State valState = validator.validate(input, pos); - if (valState == QValidator::Acceptable) + for (QPair range : std::as_const(m_rangesList)) { - return valState; + QIntValidator validator(range.first, range.second); + QValidator::State valState = validator.validate(input, pos); + if (valState == QValidator::Acceptable) + { + return valState; + } } - } - return QValidator::Invalid; - - + return QValidator::Invalid; } - -QVector> LtsWidgets::LtsMultiRangeSpinBox::sortRanges(const QVector > &ranges) +QVector> LtsWidgets::LtsMultiRangeSpinBox::sortRanges(const QVector>& ranges) { - QVector> rangesEditable = ranges; - QVector> result; - std::sort(rangesEditable.begin(), rangesEditable.end()); - QVector>::iterator it = rangesEditable.begin(); - QPair current = *(it)++; - while (it != rangesEditable.end()) - { - if (current.second > it->first) - current.second = std::max(current.second, it->second); - else + QVector> rangesEditable = ranges; + QVector> result; + std::sort(rangesEditable.begin(), rangesEditable.end()); + QVector>::iterator it = rangesEditable.begin(); + QPair current = *(it)++; + while (it != rangesEditable.end()) { - result.push_back(current); - current = *(it); + if (current.second > it->first) + current.second = std::max(current.second, it->second); + else + { + result.push_back(current); + current = *(it); + } + ++it; } - ++it; - } - result.push_back(current); - return result; + result.push_back(current); + return result; } -void LtsMultiRangeSpinBox::setRanges(const QVector> &ranges) +void LtsMultiRangeSpinBox::setRanges(const QVector>& ranges) { - if(ranges.empty()) - return; + if (ranges.empty()) + return; - m_rangesList = sortRanges(ranges); + m_rangesList = sortRanges(ranges); - QSpinBox::setMaximum(m_rangesList.last().second); - QSpinBox::setMinimum(m_rangesList.first().first); + QSpinBox::setMaximum(m_rangesList.last().second); + QSpinBox::setMinimum(m_rangesList.first().first); - QStringList rangeStrings; - rangeStrings.reserve(m_rangesList.size()); - for (const QPair &range : std::as_const(m_rangesList)) - rangeStrings << tr("%1-%2%3").arg(range.first).arg(range.second).arg(suffix()); - setToolTip(tr("Ranges:\n%1").arg(rangeStrings.join(QStringLiteral(",\n")))); + QStringList rangeStrings; + rangeStrings.reserve(m_rangesList.size()); + for (const QPair& range : std::as_const(m_rangesList)) + rangeStrings << tr("%1-%2%3").arg(range.first).arg(range.second).arg(suffix()); + setToolTip(tr("Ranges:\n%1").arg(rangeStrings.join(QStringLiteral(",\n")))); } void LtsMultiRangeSpinBox::setRange(int min, int max) { - setRanges({{min,max}}); + setRanges({{min, max}}); } void LtsMultiRangeSpinBox::setMinimum(int min) { - auto ranges = m_rangesList; - ranges.first().first = min; - setRanges(ranges); + auto ranges = m_rangesList; + ranges.first().first = min; + setRanges(ranges); } void LtsMultiRangeSpinBox::setMaximum(int max) { - auto ranges = m_rangesList; - ranges.last().second = max; - setRanges(ranges); + auto ranges = m_rangesList; + ranges.last().second = max; + setRanges(ranges); } int LtsMultiRangeSpinBox::fixupValue(int value) const { - int nearestValue = INT_MAX; - for(QPair range : m_rangesList) - { - if(std::abs(range.first - value) < std::abs(nearestValue - value)) - nearestValue = range.first; - if(std::abs(range.second - value) < std::abs(nearestValue - value)) - nearestValue = range.second; - } - value = nearestValue; - int buffer = value; + int nearestValue = INT_MAX; + for (QPair range : m_rangesList) + { + if (std::abs(range.first - value) < std::abs(nearestValue - value)) + nearestValue = range.first; + if (std::abs(range.second - value) < std::abs(nearestValue - value)) + nearestValue = range.second; + } + value = nearestValue; + int buffer = value; - int remainder = (value - minimum()) % singleStep(); + int remainder = (value - minimum()) % singleStep(); - if (2 * remainder > singleStep()) - { - value += singleStep(); - } - value -= remainder; + if (2 * remainder > singleStep()) + { + value += singleStep(); + } + value -= remainder; - if(buffer + singleStep() > value + singleStep()) - { - value+= singleStep(); - } + if (buffer + singleStep() > value + singleStep()) + { + value += singleStep(); + } - if (value > maximum()) - { - value -= singleStep(); - } + if (value > maximum()) + { + value -= singleStep(); + } - return value; + return value; } int LtsMultiRangeSpinBox::fixupValue(int value, bool higher) const { - int nearestValue = INT_MAX; - for(QPair range : m_rangesList) - { - if(std::abs(range.first - value) < std::abs(nearestValue - value)) + int nearestValue = INT_MAX; + for (QPair range : m_rangesList) { - if(higher) - { - if(range.second < value) - continue; + if (std::abs(range.first - value) < std::abs(nearestValue - value)) + { + if (higher) + { + if (range.second < value) + continue; + } + else if (range.second > value) + continue; - } else - if(range.second > value) - continue; + nearestValue = range.first; + } + if (std::abs(range.second - value) < std::abs(nearestValue - value)) + { + if (higher) + { + if (range.second < value) + continue; + } + else if (range.second > value) + continue; - nearestValue = range.first; + nearestValue = range.second; + } } - if(std::abs(range.second - value) < std::abs(nearestValue - value)) + + value = nearestValue; + int curVal = value; + + int remainder = (value - minimum()) % singleStep(); + + if (2 * remainder > singleStep()) { - if(higher) - { - if(range.second < value) - continue; - - } else - if(range.second > value) - continue; - - nearestValue = range.second; + value += singleStep(); } - } + value -= remainder; - value = nearestValue; - int curVal = value; + if (curVal + singleStep() > value + singleStep()) + { + value += singleStep(); + } + if (value > maximum()) + { + value -= singleStep(); + } - int remainder = (value - minimum()) % singleStep(); - - if (2 * remainder > singleStep()) - { - value += singleStep(); - } - value -= remainder; - - if(curVal + singleStep() > value + singleStep()) - { - value+= singleStep(); - } - if (value > maximum()) - { - value -= singleStep(); - } - - return value; + return value; } - -void LtsMultiRangeSpinBox::focusOutEvent(QFocusEvent *event) +void LtsMultiRangeSpinBox::focusOutEvent(QFocusEvent* event) { - QSpinBox::focusOutEvent(event); - QString value = QString::number(this->value()); - int length = value.length(); - QValidator::State valState = validateAll(value, length); + QSpinBox::focusOutEvent(event); + QString value = QString::number(this->value()); + int length = value.length(); + QValidator::State valState = validateAll(value, length); - if(valState == QValidator::State::Invalid) - { - this->setValue(fixupValue(value.toInt())); - } + if (valState == QValidator::State::Invalid) + { + this->setValue(fixupValue(value.toInt())); + } } -void LtsMultiRangeSpinBox::wheelEvent(QWheelEvent *event) +void LtsMultiRangeSpinBox::wheelEvent(QWheelEvent* event) { - QSpinBox::wheelEvent(event); + QSpinBox::wheelEvent(event); - QString valueStr = QString::number(this->value()); - int length = valueStr.length(); - QValidator::State valState = validateAll(valueStr, length); + QString valueStr = QString::number(this->value()); + int length = valueStr.length(); + QValidator::State valState = validateAll(valueStr, length); - if(valState == QValidator::State::Invalid) - { - - - - if(this->value() < m_curVal) + if (valState == QValidator::State::Invalid) { - m_curVal = fixupValue(this->value(), false); - setValue(m_curVal); + + if (this->value() < m_curVal) + { + m_curVal = fixupValue(this->value(), false); + setValue(m_curVal); + } + else + { + m_curVal = fixupValue(this->value(), true); + setValue(m_curVal); + } } - else - { - m_curVal = fixupValue(this->value(), true); - setValue(m_curVal); - } - } } -void LtsMultiRangeSpinBox::mousePressEvent(QMouseEvent *event) +void LtsMultiRangeSpinBox::mousePressEvent(QMouseEvent* event) { - QSpinBox::mousePressEvent(event); - QString valueStr = QString::number(this->value()); - int length = valueStr.length(); - QValidator::State valState = validateAll(valueStr, length); + QSpinBox::mousePressEvent(event); + QString valueStr = QString::number(this->value()); + int length = valueStr.length(); + QValidator::State valState = validateAll(valueStr, length); - if(valState == QValidator::State::Invalid) - { - - - - - if(this->value() < m_curVal) + if (valState == QValidator::State::Invalid) { - m_curVal = fixupValue(this->value(), false); - setValue(m_curVal); - } - else - { - m_curVal = fixupValue(this->value(), true); - setValue(m_curVal); - } - } - + if (this->value() < m_curVal) + { + m_curVal = fixupValue(this->value(), false); + setValue(m_curVal); + } + else + { + m_curVal = fixupValue(this->value(), true); + setValue(m_curVal); + } + } } -void LtsMultiRangeSpinBox::keyPressEvent(QKeyEvent *event) +void LtsMultiRangeSpinBox::keyPressEvent(QKeyEvent* event) { - QSpinBox::keyPressEvent(event); - QString value = QString::number(this->value()); - int length = value.length(); - QValidator::State valState = validateAll(value, length); + QSpinBox::keyPressEvent(event); + QString value = QString::number(this->value()); + int length = value.length(); + QValidator::State valState = validateAll(value, length); - if(valState == QValidator::State::Invalid) - { - setValue(fixupValue(value.toInt())); - } + if (valState == QValidator::State::Invalid) + { + setValue(fixupValue(value.toInt())); + } } - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h old mode 100755 new mode 100644 index 56d93d0ed..3ecc3dce1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_notification_box.h @@ -1,51 +1,46 @@ #pragma once -#include - #include "ltswidgets_export.h" -#include -#include +#include +#include +#include class QPaintEvent; class QResizeEvent; - namespace Ui { class NotiBox; } - namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsNotificationBox : public QWidget { - Q_OBJECT -public: - enum class MessageType - { - Success, - Error, - Warning, - Info, - }; + Q_OBJECT + public: + enum class MessageType { + Success, + Error, + Warning, + Info, + }; - explicit LtsNotificationBox(QWidget *parent = nullptr); + explicit LtsNotificationBox(QWidget* parent = nullptr); - void message(const QString &title, const QString &text, MessageType type = MessageType::Error); + void message(const QString& title, const QString& text, MessageType type = MessageType::Error); -signals: - void signalClose(); - void signalAck(); - void signalLinkClicked(const QString &link); + signals: + void signalClose(); + void signalAck(); + void signalLinkClicked(const QString& link); -protected: - void paintEvent(QPaintEvent *) override; + protected: + void paintEvent(QPaintEvent*) override; -private: - Ui::NotiBox *m_ui; - QPainterPath roundRectPath; - const static int margin; + private: + Ui::NotiBox* m_ui; + QPainterPath roundRectPath; + const static int margin; }; -} - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp old mode 100755 new mode 100644 index 16e844b6a..469b90584 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.cpp @@ -1,114 +1,105 @@ - #include "lts_operator_menu.h" -#include "ui_lts_operator_menu.h" + #include "lts_info_dialog.h" -#include +#include "ui_lts_operator_menu.h" -#include -#include #include - +#include +#include +#include namespace LtsWidgets { -LtsOperatorMenu::LtsOperatorMenu(const QString &operatorName, const QString &workspaceId, bool debug, int screenCount, QWidget *parent) - : LtsFramelessDialog(parent) - , m_ui(new Ui::LtsOperatorMenu) +LtsOperatorMenu::LtsOperatorMenu(const QString& operatorName, const QString& workspaceId, bool debug, int screenCount, + QWidget* parent) + : LtsFramelessDialog(parent), m_ui(new Ui::LtsOperatorMenu) { - m_ui->setupUi(this); - m_ui->lbOperatorName->setText(operatorName); - m_ui->lbHostName->setText(QHostInfo::localHostName()); + m_ui->setupUi(this); + m_ui->lbOperatorName->setText(operatorName); + m_ui->lbHostName->setText(QHostInfo::localHostName()); - if (screenCount < 2) - m_ui->pbSwap->hide(); + if (screenCount < 2) + m_ui->pbSwap->hide(); - if (debug) - m_ui->lbWorkspaceId->setText(tr("Workspace: >>>%1<<<").arg(workspaceId)); - else - m_ui->lbWorkspaceId->hide(); + if (debug) + m_ui->lbWorkspaceId->setText(tr("Workspace: >>>%1<<<").arg(workspaceId)); + else + m_ui->lbWorkspaceId->hide(); - connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::signalShowOperatorSettings); - connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::onTerminalButtonClicked); - connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbLogout, &QPushButton::clicked, this, &LtsOperatorMenu::signalLogout); - connect(m_ui->pbExit, &QPushButton::clicked, this, &LtsOperatorMenu::signalExit); - connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::signalSwap); - connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::close); - connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::slotShowInfoDialog); - connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::signalShowOperatorSettings); + connect(m_ui->pbOperatorSettings, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::onTerminalButtonClicked); + connect(m_ui->pbWindow, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbLogout, &QPushButton::clicked, this, &LtsOperatorMenu::signalLogout); + connect(m_ui->pbExit, &QPushButton::clicked, this, &LtsOperatorMenu::signalExit); + connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::signalSwap); + connect(m_ui->pbSwap, &QPushButton::clicked, this, &LtsOperatorMenu::close); + connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::slotShowInfoDialog); + connect(m_ui->pbAbout, &QPushButton::clicked, this, &LtsOperatorMenu::close); + if (NGL::translationLocale() == "de_DE") + m_ui->pbGer->setChecked(true); + else + m_ui->pbInt->setChecked(true); - if (NGL::translationLocale() == "de_DE") - m_ui->pbGer->setChecked(true); - else - m_ui->pbInt->setChecked(true); - - connect(m_ui->pbGer, &QPushButton::clicked, - this, &LtsOperatorMenu::onLanguageChange); - connect(m_ui->pbInt, &QPushButton::clicked, - this, &LtsOperatorMenu::onLanguageChange); + connect(m_ui->pbGer, &QPushButton::clicked, this, &LtsOperatorMenu::onLanguageChange); + connect(m_ui->pbInt, &QPushButton::clicked, this, &LtsOperatorMenu::onLanguageChange); #ifndef LTS_DEBUG - m_ui->debugWidget->hide(); + m_ui->debugWidget->hide(); #endif } - LtsOperatorMenu::~LtsOperatorMenu() { - delete m_ui; + delete m_ui; } - void LtsOperatorMenu::slotShowInfoDialog() { - LtsInfoDialog *infoDialog = new LtsInfoDialog(); - infoDialog->setAttribute(Qt::WA_DeleteOnClose); - infoDialog->show(); + LtsInfoDialog* infoDialog = new LtsInfoDialog(); + infoDialog->setAttribute(Qt::WA_DeleteOnClose); + infoDialog->show(); } - void LtsOperatorMenu::onTerminalButtonClicked() { - QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); - QString lang = QString::fromLatin1(NGL::translationLocale()); - lang.append(QStringLiteral(".UTF-8")); - env.insert(QStringLiteral("LANG"), lang); + QString lang = QString::fromLatin1(NGL::translationLocale()); + lang.append(QStringLiteral(".UTF-8")); + env.insert(QStringLiteral("LANG"), lang); - QProcess process; - process.setProcessEnvironment(env); - QStringList args; - args << QStringLiteral("--geometry") << QStringLiteral("800x800+200+100"); + QProcess process; + process.setProcessEnvironment(env); + QStringList args; + args << QStringLiteral("--geometry") << QStringLiteral("800x800+200+100"); - if (QApplication::queryKeyboardModifiers() == Qt::ControlModifier) - process.startDetached(QStringLiteral("xterm"), args); - else - process.startDetached(QStringLiteral("konsole"), args); + if (QApplication::queryKeyboardModifiers() == Qt::ControlModifier) + process.startDetached(QStringLiteral("xterm"), args); + else + process.startDetached(QStringLiteral("konsole"), args); } - void LtsOperatorMenu::setTerminalButton(bool bVisible) { - m_ui->pbWindow->setVisible(bVisible); + m_ui->pbWindow->setVisible(bVisible); } void LtsOperatorMenu::setOperatorSettingsButton(bool bVisible) { - m_ui->pbOperatorSettings->setVisible(bVisible); + m_ui->pbOperatorSettings->setVisible(bVisible); } - void LtsOperatorMenu::onLanguageChange() { - if (m_ui->pbGer->isChecked()) - NGL::setTranslationLocale(QByteArray("de_DE")); + if (m_ui->pbGer->isChecked()) + NGL::setTranslationLocale(QByteArray("de_DE")); - if (m_ui->pbInt->isChecked()) - NGL::setTranslationLocale(QByteArray("en_GB")); + if (m_ui->pbInt->isChecked()) + NGL::setTranslationLocale(QByteArray("en_GB")); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h old mode 100755 new mode 100644 index 18168db62..038bd802c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_operator_menu.h @@ -1,14 +1,13 @@ - #pragma once -#include - #include "lts_frameless_dialog.h" #include "ltswidgets_export.h" +#include -namespace Ui { +namespace Ui +{ class LtsOperatorMenu; } @@ -16,28 +15,29 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsOperatorMenu : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - explicit LtsOperatorMenu(const QString &operatorName, const QString &workspaceId, bool debug, int screenCount, QWidget *parent); - ~LtsOperatorMenu(); + public: + explicit LtsOperatorMenu(const QString& operatorName, const QString& workspaceId, bool debug, int screenCount, + QWidget* parent); + ~LtsOperatorMenu(); - void setTerminalButton(bool bVisible); - void setOperatorSettingsButton(bool bVisible); + void setTerminalButton(bool bVisible); + void setOperatorSettingsButton(bool bVisible); -private: - Ui::LtsOperatorMenu *m_ui; + private: + Ui::LtsOperatorMenu* m_ui; -signals: - void signalLogout(); - void signalExit(); - void signalShowOperatorSettings(); - void signalSwap(); + signals: + void signalLogout(); + void signalExit(); + void signalShowOperatorSettings(); + void signalSwap(); -private slots: - void onTerminalButtonClicked(); - void onLanguageChange(); - void slotShowInfoDialog(); + private slots: + void onTerminalButtonClicked(); + void onLanguageChange(); + void slotShowInfoDialog(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp old mode 100755 new mode 100644 index bd756988b..6c3ee7ab1 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.cpp @@ -1,7 +1,7 @@ - #include "lts_overlay_loading.h" + #include "ui_lts_overlay_loading.h" #include @@ -9,37 +9,29 @@ #include #include - namespace LtsWidgets { -LtsOverlayLoading::LtsOverlayLoading(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::LtsOverlayLoading) +LtsOverlayLoading::LtsOverlayLoading(QWidget* parent) : QWidget(parent), m_ui(new Ui::LtsOverlayLoading) { - m_ui->setupUi(this); - setCancelButtonVisible(false); - connect(m_ui->pbCancel, &QPushButton::clicked, - this, [this](){ setCancelButtonEnabled(false); }); - connect(m_ui->pbCancel, &QPushButton::clicked, - this, &LtsOverlayLoading::cancel); + m_ui->setupUi(this); + setCancelButtonVisible(false); + connect(m_ui->pbCancel, &QPushButton::clicked, this, [this]() { setCancelButtonEnabled(false); }); + connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsOverlayLoading::cancel); } - -void LtsOverlayLoading::setText(const QString &text) +void LtsOverlayLoading::setText(const QString& text) { - m_ui->label->setText(text); + m_ui->label->setText(text); } - void LtsOverlayLoading::setCancelButtonVisible(bool visible) { - m_ui->pbCancel->setVisible(visible); + m_ui->pbCancel->setVisible(visible); } - void LtsOverlayLoading::setCancelButtonEnabled(bool enabled) { - m_ui->pbCancel->setEnabled(enabled); + m_ui->pbCancel->setEnabled(enabled); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h old mode 100755 new mode 100644 index ace18a577..83aa33dd6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_overlay_loading.h @@ -1,35 +1,33 @@ - #pragma once -#include - #include "ltswidgets_export.h" +#include #include - -namespace Ui { class LtsOverlayLoading; } - +namespace Ui +{ +class LtsOverlayLoading; +} namespace LtsWidgets { - class LTSWIDGETS_EXPORT LtsOverlayLoading : public QWidget { - Q_OBJECT -public: - explicit LtsOverlayLoading(QWidget *parent = nullptr); + Q_OBJECT + public: + explicit LtsOverlayLoading(QWidget* parent = nullptr); - void setText(const QString &text); - void setCancelButtonVisible(bool visible); - void setCancelButtonEnabled(bool enabled); + void setText(const QString& text); + void setCancelButtonVisible(bool visible); + void setCancelButtonEnabled(bool enabled); -signals: - void cancel(); + signals: + void cancel(); -private: - Ui::LtsOverlayLoading *m_ui; + private: + Ui::LtsOverlayLoading* m_ui; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp old mode 100755 new mode 100644 index eccdac91a..b39ae38a2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.cpp @@ -1,339 +1,334 @@ - #include "lts_picture_view.h" -#include -#include -#include -#include +#include +#include +#include +#include using namespace LtsWidgets; -LtsPictureView::LtsPictureView(QWidget *parent) - : QGraphicsView(parent) - , m_gsPicture(new QGraphicsScene(this)) - , m_rubberband(new QRubberBand(QRubberBand::Rectangle, this)) - , m_image(nullptr) - , m_origimage(nullptr) +LtsPictureView::LtsPictureView(QWidget* parent) + : QGraphicsView(parent), m_gsPicture(new QGraphicsScene(this)), + m_rubberband(new QRubberBand(QRubberBand::Rectangle, this)), m_image(nullptr), m_origimage(nullptr) { - m_mouseActive = false; - m_moveable = false; - m_aspectRatioEnabled = true; - m_s_inEdit = false; + m_mouseActive = false; + m_moveable = false; + m_aspectRatioEnabled = true; + m_s_inEdit = false; - m_aspectRatio = 1; + m_aspectRatio = 1; - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); } LtsPictureView::~LtsPictureView() { - delete m_rubberband; + delete m_rubberband; } void LtsPictureView::setAspectRatio(double aspectRatio) { - m_aspectRatio = aspectRatio; - newRubberBand(); + m_aspectRatio = aspectRatio; + newRubberBand(); } void LtsPictureView::ratioClicked(bool enabled) { - m_aspectRatioEnabled = enabled; - if (enabled) - newRubberBand(); + m_aspectRatioEnabled = enabled; + if (enabled) + newRubberBand(); } -void LtsPictureView::mousePressEvent(QMouseEvent *event) +void LtsPictureView::mousePressEvent(QMouseEvent* event) { - if (event->button() == Qt::LeftButton) - { - if (m_rubberband->geometry().contains(event->pos())) + if (event->button() == Qt::LeftButton) { - m_bandoffset = event->pos() - m_rubberband->pos(); - m_moveable = true; - m_rubberband->show(); - } - else - { - m_origin = event->pos(); - m_curRectangle = QRect(m_origin.x(), m_origin.y(), 0, 0); - m_rubberband->setGeometry(m_curRectangle); - m_rubberband->show(); - m_mouseActive = true; - } - } - else - { - hideRubberband(); - newRubberBand(); - m_mouseActive = false; - } - QGraphicsView::mousePressEvent(event); -} - -void LtsPictureView::mouseMoveEvent(QMouseEvent *event) -{ - if (m_moveable == true) - { - QPoint newCoord = event->pos() - m_bandoffset; - if (newCoord.x() < 0) - newCoord.setX(0); - if (newCoord.y() < 0) - newCoord.setY(0); - if (m_origimage->pixmap().width() < (newCoord.x() + m_rubberband->width())) - newCoord.setX(m_origimage->pixmap().width() - m_rubberband->width() + 1); - if (m_origimage->pixmap().height() < (newCoord.y() + m_rubberband->height())) - newCoord.setY(m_origimage->pixmap().height() - m_rubberband->height() + 1); - m_rubberband->move(newCoord); - QPoint move = m_rubberband->pos(); - int left = move.x(); - int top = move.y(); - int width = m_rubberband->rect().width(); - int height = m_rubberband->rect().height(); - emit mouseMoved(QRect(left, top, width, height)); - } - else - { - if (m_mouseActive) - { - QRect rect; - - int xMax = event->pos().x(); - int yMax = event->pos().y(); - - if (event->pos().x() > m_origimage->pixmap().width()) - xMax = m_origimage->pixmap().width(); - if (event->pos().x() < 0) - xMax = 0; - if (event->pos().y() > m_origimage->pixmap().height()) - yMax = m_origimage->pixmap().height(); - if (event->pos().y() < 0) - yMax = 0; - - if (m_aspectRatioEnabled) - { - const int xMin = m_origin.x(); - const int yMin = m_origin.y(); - - int xLengthAbs(std::abs(xMax - xMin)); - int yLengthAbs(std::abs(yMax - yMin)); - - QPoint length; - - if (xLengthAbs / m_aspectRatio > yLengthAbs * m_aspectRatio) + if (m_rubberband->geometry().contains(event->pos())) { - length.setX(xLengthAbs); - length.setY(length.x() / m_aspectRatio); + m_bandoffset = event->pos() - m_rubberband->pos(); + m_moveable = true; + m_rubberband->show(); } else { - length.setY(yLengthAbs); - length.setX(length.y() * m_aspectRatio); + m_origin = event->pos(); + m_curRectangle = QRect(m_origin.x(), m_origin.y(), 0, 0); + m_rubberband->setGeometry(m_curRectangle); + m_rubberband->show(); + m_mouseActive = true; } - - if (!(yMax - yMin < 0) && length.y() + m_origin.y() > m_origimage->pixmap().height()) - { - length.setY(m_origimage->pixmap().height() - m_origin.y()); - length.setX(length.y()* m_aspectRatio); - } - if (!(xMax - xMin < 0) && length.x() + m_origin.x() > m_origimage->pixmap().width()) - { - length.setX(m_origimage->pixmap().width() - m_origin.x()); - length.setY(length.x() / m_aspectRatio); - } - - if (xMax - xMin < 0) - { - length.setX(length.x() * -1); - if (length.x() + m_origin.x() < 0) - { - length.setX(0 - m_origin.x()); - length.setY((length.x() / m_aspectRatio) * -1); - } - } - - if (yMax - yMin < 0) - { - length.setY(length.y() * -1); - if (length.y() + m_origin.y() < 0) - { - length.setY(0 - m_origin.y()); - length.setX(length.y() * m_aspectRatio); - if (!(xMax - xMin < 0)) - length.setX(length.x() * -1); - } - } - - length = m_origin + length; - rect.setTopLeft(m_origin); - rect.setBottomRight(length); - } - else - { - rect.setTopLeft(m_origin); - rect.setBottomRight(QPoint(xMax, yMax)); - } - m_curRectangle = rect.normalized(); - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); } - } - QGraphicsView::mouseMoveEvent(event); + else + { + hideRubberband(); + newRubberBand(); + m_mouseActive = false; + } + QGraphicsView::mousePressEvent(event); } -void LtsPictureView::mouseReleaseEvent(QMouseEvent *event) +void LtsPictureView::mouseMoveEvent(QMouseEvent* event) { - m_moveable = false; - QGraphicsView::mouseReleaseEvent(event); + if (m_moveable == true) + { + QPoint newCoord = event->pos() - m_bandoffset; + if (newCoord.x() < 0) + newCoord.setX(0); + if (newCoord.y() < 0) + newCoord.setY(0); + if (m_origimage->pixmap().width() < (newCoord.x() + m_rubberband->width())) + newCoord.setX(m_origimage->pixmap().width() - m_rubberband->width() + 1); + if (m_origimage->pixmap().height() < (newCoord.y() + m_rubberband->height())) + newCoord.setY(m_origimage->pixmap().height() - m_rubberband->height() + 1); + m_rubberband->move(newCoord); + QPoint move = m_rubberband->pos(); + int left = move.x(); + int top = move.y(); + int width = m_rubberband->rect().width(); + int height = m_rubberband->rect().height(); + emit mouseMoved(QRect(left, top, width, height)); + } + else + { + if (m_mouseActive) + { + QRect rect; + + int xMax = event->pos().x(); + int yMax = event->pos().y(); + + if (event->pos().x() > m_origimage->pixmap().width()) + xMax = m_origimage->pixmap().width(); + if (event->pos().x() < 0) + xMax = 0; + if (event->pos().y() > m_origimage->pixmap().height()) + yMax = m_origimage->pixmap().height(); + if (event->pos().y() < 0) + yMax = 0; + + if (m_aspectRatioEnabled) + { + const int xMin = m_origin.x(); + const int yMin = m_origin.y(); + + int xLengthAbs(std::abs(xMax - xMin)); + int yLengthAbs(std::abs(yMax - yMin)); + + QPoint length; + + if (xLengthAbs / m_aspectRatio > yLengthAbs * m_aspectRatio) + { + length.setX(xLengthAbs); + length.setY(length.x() / m_aspectRatio); + } + else + { + length.setY(yLengthAbs); + length.setX(length.y() * m_aspectRatio); + } + + if (!(yMax - yMin < 0) && length.y() + m_origin.y() > m_origimage->pixmap().height()) + { + length.setY(m_origimage->pixmap().height() - m_origin.y()); + length.setX(length.y() * m_aspectRatio); + } + if (!(xMax - xMin < 0) && length.x() + m_origin.x() > m_origimage->pixmap().width()) + { + length.setX(m_origimage->pixmap().width() - m_origin.x()); + length.setY(length.x() / m_aspectRatio); + } + + if (xMax - xMin < 0) + { + length.setX(length.x() * -1); + if (length.x() + m_origin.x() < 0) + { + length.setX(0 - m_origin.x()); + length.setY((length.x() / m_aspectRatio) * -1); + } + } + + if (yMax - yMin < 0) + { + length.setY(length.y() * -1); + if (length.y() + m_origin.y() < 0) + { + length.setY(0 - m_origin.y()); + length.setX(length.y() * m_aspectRatio); + if (!(xMax - xMin < 0)) + length.setX(length.x() * -1); + } + } + + length = m_origin + length; + rect.setTopLeft(m_origin); + rect.setBottomRight(length); + } + else + { + rect.setTopLeft(m_origin); + rect.setBottomRight(QPoint(xMax, yMax)); + } + m_curRectangle = rect.normalized(); + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + } + } + QGraphicsView::mouseMoveEvent(event); +} + +void LtsPictureView::mouseReleaseEvent(QMouseEvent* event) +{ + m_moveable = false; + QGraphicsView::mouseReleaseEvent(event); } void LtsPictureView::hideRubberband() { - m_rubberband->hide(); + m_rubberband->hide(); } void LtsPictureView::newRubberBand() { - delete m_rubberband; - m_rubberband = new QRubberBand(QRubberBand::Rectangle, this); + delete m_rubberband; + m_rubberband = new QRubberBand(QRubberBand::Rectangle, this); } -void LtsPictureView::setPicture(const QImage &image, const QPoint &pos, const bool flag) +void LtsPictureView::setPicture(const QImage& image, const QPoint& pos, const bool flag) { - if (m_image) - { - m_gsPicture->removeItem(m_image); - delete m_image; - } - if (flag) - { - if (m_origimage) + if (m_image) { - m_gsPicture->removeItem(m_origimage); - delete m_origimage; + m_gsPicture->removeItem(m_image); + delete m_image; } - QGraphicsOpacityEffect *opacity = new QGraphicsOpacityEffect; - opacity->setOpacity(0.2); + if (flag) + { + if (m_origimage) + { + m_gsPicture->removeItem(m_origimage); + delete m_origimage; + } + QGraphicsOpacityEffect* opacity = new QGraphicsOpacityEffect; + opacity->setOpacity(0.2); - m_origimage = new QGraphicsPixmapItem(QPixmap::fromImage(image)); - m_origimage->setGraphicsEffect(opacity); + m_origimage = new QGraphicsPixmapItem(QPixmap::fromImage(image)); + m_origimage->setGraphicsEffect(opacity); - m_gsPicture->addItem(m_origimage); + m_gsPicture->addItem(m_origimage); - setMinimumSize(image.size()); - setMaximumSize(image.size()); - emit setLimits(m_origimage->pixmap().size(), true); - } - m_image = new QGraphicsPixmapItem(QPixmap::fromImage(image)); + setMinimumSize(image.size()); + setMaximumSize(image.size()); + emit setLimits(m_origimage->pixmap().size(), true); + } + m_image = new QGraphicsPixmapItem(QPixmap::fromImage(image)); - m_image->setPos(pos); - m_gsPicture->addItem(m_image); - setScene(m_gsPicture); + m_image->setPos(pos); + m_gsPicture->addItem(m_image); + setScene(m_gsPicture); } void LtsPictureView::leftChanged(int left) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setLeft(left); - if(m_aspectRatioEnabled) - { - int newHeight = m_curRectangle.width() / m_aspectRatio; - if (m_origin.y() < m_curRectangle.bottom()) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setLeft(left); + if (m_aspectRatioEnabled) { - m_curRectangle.setHeight(newHeight); + int newHeight = m_curRectangle.width() / m_aspectRatio; + if (m_origin.y() < m_curRectangle.bottom()) + { + m_curRectangle.setHeight(newHeight); + } + else + { + int offset = m_curRectangle.height() - newHeight; + m_curRectangle.setTop(m_curRectangle.top() + offset); + } } - else - { - int offset = m_curRectangle.height() - newHeight; - m_curRectangle.setTop(m_curRectangle.top() + offset); - } - } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::rightChanged(int right) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setRight(right); - if(m_aspectRatioEnabled) - { - int newHeight = m_curRectangle.width() / m_aspectRatio; - if (m_origin.y() < m_curRectangle.bottom()) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setRight(right); + if (m_aspectRatioEnabled) { - m_curRectangle.setHeight(newHeight); + int newHeight = m_curRectangle.width() / m_aspectRatio; + if (m_origin.y() < m_curRectangle.bottom()) + { + m_curRectangle.setHeight(newHeight); + } + else + { + int offset = m_curRectangle.height() - newHeight; + m_curRectangle.setTop(m_curRectangle.top() + offset); + } } - else - { - int offset = m_curRectangle.height() - newHeight; - m_curRectangle.setTop(m_curRectangle.top() + offset); - } - } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::topChanged(int top) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setTop(top); - if(m_aspectRatioEnabled) - { - int newWidth = m_curRectangle.height() * m_aspectRatio; - if (m_origin.x() <= m_curRectangle.left()) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setTop(top); + if (m_aspectRatioEnabled) { - m_curRectangle.setWidth(newWidth); + int newWidth = m_curRectangle.height() * m_aspectRatio; + if (m_origin.x() <= m_curRectangle.left()) + { + m_curRectangle.setWidth(newWidth); + } + else + { + int offset = m_curRectangle.width() - newWidth; + m_curRectangle.setLeft(m_curRectangle.left() + offset); + } } - else - { - int offset = m_curRectangle.width() - newWidth; - m_curRectangle.setLeft(m_curRectangle.left() + offset); - } - } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } void LtsPictureView::bottomChanged(int bottom) { - if (m_s_inEdit || m_mouseActive) - return; - m_s_inEdit = true; - m_curRectangle.setBottom(bottom); - if(m_aspectRatioEnabled) - { - int newWidth = m_curRectangle.height() * m_aspectRatio; - if (m_origin.x() <= m_curRectangle.left()) + if (m_s_inEdit || m_mouseActive) + return; + m_s_inEdit = true; + m_curRectangle.setBottom(bottom); + if (m_aspectRatioEnabled) { - m_curRectangle.setWidth(newWidth); + int newWidth = m_curRectangle.height() * m_aspectRatio; + if (m_origin.x() <= m_curRectangle.left()) + { + m_curRectangle.setWidth(newWidth); + } + else + { + int offset = m_curRectangle.width() - newWidth; + m_curRectangle.setLeft(m_curRectangle.left() + offset); + } } - else - { - int offset = m_curRectangle.width() - newWidth; - m_curRectangle.setLeft(m_curRectangle.left() + offset); - } - } - m_rubberband->setGeometry(m_curRectangle); - emit mouseMoved(m_curRectangle); - m_s_inEdit = false; + m_rubberband->setGeometry(m_curRectangle); + emit mouseMoved(m_curRectangle); + m_s_inEdit = false; } - -QGraphicsPixmapItem *LtsPictureView::getImage() +QGraphicsPixmapItem* LtsPictureView::getImage() { - if (!m_image) - m_image = new QGraphicsPixmapItem; - return m_image; + if (!m_image) + m_image = new QGraphicsPixmapItem; + return m_image; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h old mode 100755 new mode 100644 index a688ffa49..32347a3b5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_picture_view.h @@ -1,11 +1,10 @@ - #pragma once -#include - #include "ltswidgets_export.h" + #include +#include class QRubberBand; @@ -13,49 +12,49 @@ namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsPictureView : public QGraphicsView { - Q_OBJECT + Q_OBJECT -public: - explicit LtsPictureView(QWidget *parent = nullptr); - ~LtsPictureView(); - void hideRubberband(); - void newRubberBand(); - void cutPicture(); - QGraphicsPixmapItem *getImage(); + public: + explicit LtsPictureView(QWidget* parent = nullptr); + ~LtsPictureView(); + void hideRubberband(); + void newRubberBand(); + void cutPicture(); + QGraphicsPixmapItem* getImage(); -protected: - void mousePressEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent *event) override; - void mouseReleaseEvent(QMouseEvent *event) override; + protected: + void mousePressEvent(QMouseEvent* event) override; + void mouseMoveEvent(QMouseEvent* event) override; + void mouseReleaseEvent(QMouseEvent* event) override; -private: - bool m_mouseActive; - bool m_moveable; - bool m_aspectRatioEnabled; - bool m_s_inEdit; + private: + bool m_mouseActive; + bool m_moveable; + bool m_aspectRatioEnabled; + bool m_s_inEdit; - double m_aspectRatio; - QRect m_curRectangle; + double m_aspectRatio; + QRect m_curRectangle; - QGraphicsScene *m_gsPicture; - QRubberBand *m_rubberband; - QGraphicsPixmapItem *m_image; - QGraphicsPixmapItem *m_origimage; + QGraphicsScene* m_gsPicture; + QRubberBand* m_rubberband; + QGraphicsPixmapItem* m_image; + QGraphicsPixmapItem* m_origimage; - QPoint m_origin; - QPoint m_bandoffset; + QPoint m_origin; + QPoint m_bandoffset; -public slots: - void setPicture(const QImage &image, const QPoint &pos, const bool flag); - void setAspectRatio(double aspectRatio); - void ratioClicked(bool enabled); - void leftChanged(int left); - void rightChanged(int right); - void topChanged(int top); - void bottomChanged(int bottom); + public slots: + void setPicture(const QImage& image, const QPoint& pos, const bool flag); + void setAspectRatio(double aspectRatio); + void ratioClicked(bool enabled); + void leftChanged(int left); + void rightChanged(int right); + void topChanged(int top); + void bottomChanged(int bottom); -signals: - void mouseMoved(const QRect &); - void setLimits(const QSize &, bool); + signals: + void mouseMoved(const QRect&); + void setLimits(const QSize&, bool); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h old mode 100755 new mode 100644 index 33cde37a3..be3b2cf90 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_profile_button.h @@ -1,56 +1,55 @@ - #pragma once -#include - #include "ltswidgets_export.h" +#include #include - namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsProfileButton : public QWidget { - Q_OBJECT + Q_OBJECT - Q_PROPERTY( QPixmap pixMap READ pixmap WRITE setPixmap ) - Q_PROPERTY( bool menuEnabled READ menuEnabled WRITE setMenuEnabled ) + Q_PROPERTY(QPixmap pixMap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool menuEnabled READ menuEnabled WRITE setMenuEnabled) -public: - explicit LtsProfileButton(QWidget *parent = nullptr); + public: + explicit LtsProfileButton(QWidget* parent = nullptr); - + void setPixmap(const QPixmap& pixmap); - void setPixmap(const QPixmap &pixmap); + const QPixmap& pixmap() const + { + return m_pixmap; + } - const QPixmap &pixmap() const { return m_pixmap; } + void setMenuEnabled(bool enabled = true) + { + m_menuEnabled = enabled; + } - + bool menuEnabled() const + { + return m_menuEnabled; + } - void setMenuEnabled(bool enabled = true) { m_menuEnabled = enabled; } - bool menuEnabled() const { return m_menuEnabled; } + protected: + void paintEvent(QPaintEvent* event); + void enterEvent(QEvent* event); + void leaveEvent(QEvent* event); + bool event(QEvent* event); + private: + QPixmap m_pixmap; + bool m_isHovered; + bool m_menuEnabled; -protected: - void paintEvent(QPaintEvent *event); - void enterEvent(QEvent *event); - void leaveEvent(QEvent *event); - bool event(QEvent *event); + signals: -private: - QPixmap m_pixmap; - bool m_isHovered; - bool m_menuEnabled; - -signals: - - - void signalClicked(); + void signalClicked(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp old mode 100755 new mode 100644 index 3a64d04f1..91f4dcfe3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.cpp @@ -1,6 +1,5 @@ - #include "lts_progress_dialog_helper.h" #include "lts_frameless_dialog.h" @@ -12,136 +11,118 @@ #include #include - namespace LtsWidgets { -LtsProgressDialogHelper::LtsProgressDialogHelper(QWidget *parent) - : QObject(parent) - , m_waitDlg(nullptr) - , m_parentWidget(parent) - , m_textLabel(nullptr) -{} - +LtsProgressDialogHelper::LtsProgressDialogHelper(QWidget* parent) + : QObject(parent), m_waitDlg(nullptr), m_parentWidget(parent), m_textLabel(nullptr) +{ +} LtsProgressDialogHelper::~LtsProgressDialogHelper() { - delete m_waitDlg; + delete m_waitDlg; } - -void LtsProgressDialogHelper::setCustomText(const QString &customText) +void LtsProgressDialogHelper::setCustomText(const QString& customText) { - if (m_waitDlg == nullptr || m_textLabel == nullptr) - return; + if (m_waitDlg == nullptr || m_textLabel == nullptr) + return; - if (customText.isEmpty()) - m_textLabel->setText(tr("Waiting for server reply...")); - else - m_textLabel->setText(customText); + if (customText.isEmpty()) + m_textLabel->setText(tr("Waiting for server reply...")); + else + m_textLabel->setText(customText); } -void LtsProgressDialogHelper::setParentWidget(QWidget *newParent) +void LtsProgressDialogHelper::setParentWidget(QWidget* newParent) { - m_parentWidget = newParent; - if (m_waitDlg) - { - m_waitDlg->setParent(newParent); - QTimer::singleShot(0, m_waitDlg.data(), &LtsFramelessDialog::onUpdateGeometry); - } + m_parentWidget = newParent; + if (m_waitDlg) + { + m_waitDlg->setParent(newParent); + QTimer::singleShot(0, m_waitDlg.data(), &LtsFramelessDialog::onUpdateGeometry); + } } void LtsProgressDialogHelper::slotShowWaitForReplyWindow() { - if (m_waitDlg) - m_waitDlg->deleteLater(); - m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); + if (m_waitDlg) + m_waitDlg->deleteLater(); + m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); - QHBoxLayout *l = new QHBoxLayout(m_waitDlg); + QHBoxLayout* l = new QHBoxLayout(m_waitDlg); - QProgressBar *pb = new QProgressBar(m_waitDlg); - pb->setMaximum(0); - pb->setValue(-1); + QProgressBar* pb = new QProgressBar(m_waitDlg); + pb->setMaximum(0); + pb->setValue(-1); - l->addWidget(pb); + l->addWidget(pb); - m_textLabel = new QLabel(m_waitDlg); - setCustomText(); - l->addWidget(m_textLabel); + m_textLabel = new QLabel(m_waitDlg); + setCustomText(); + l->addWidget(m_textLabel); - m_waitDlg->setLayout(l); - m_waitDlg->show(); - m_waitDlg->raise(); - - + m_waitDlg->setLayout(l); + m_waitDlg->show(); + m_waitDlg->raise(); } - -void LtsProgressDialogHelper::slotStopWaitForReplyWindow(const ReplyResult &replyResult, const QString &replyString) +void LtsProgressDialogHelper::slotStopWaitForReplyWindow(const ReplyResult& replyResult, const QString& replyString) { - if (m_waitDlg == nullptr) - { - - return; - } - - - m_waitDlg->deleteLater(); - m_waitDlg = nullptr; - - - QString resultText = tr("Unknown result (%1)!").arg((int)replyResult); - - switch (replyResult) - { - case ReplyResult::Close: + if (m_waitDlg == nullptr) { - return; + + return; } - case ReplyResult::Success: + m_waitDlg->deleteLater(); + m_waitDlg = nullptr; + + QString resultText = tr("Unknown result (%1)!").arg((int)replyResult); + + switch (replyResult) { - resultText = tr("Operation was successful"); - break; + case ReplyResult::Close: { + return; + } + + case ReplyResult::Success: { + resultText = tr("Operation was successful"); + break; + } + + case ReplyResult::Failure: { + resultText = tr("Operation has failed!\nReason: '%1'").arg(replyString); + break; + } + + case ReplyResult::TimeOut: { + resultText = tr("Operation has timed out and could not be processed! Please try again later"); + break; + } } - case ReplyResult::Failure: - { - resultText = tr("Operation has failed!\nReason: '%1'").arg(replyString); - break; - } + m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); - case ReplyResult::TimeOut: - { - resultText = tr("Operation has timed out and could not be processed! Please try again later"); - break; - } - } + QVBoxLayout* newLayout = new QVBoxLayout(m_waitDlg); + newLayout->addWidget(new QLabel(resultText, m_waitDlg)); - m_waitDlg = new LtsFramelessDialog(m_parentWidget, Behaviour::Modal); + QPushButton* btn = new QPushButton(tr("OK"), m_waitDlg); + connect(btn, &QPushButton::clicked, this, &LtsProgressDialogHelper::accept); - QVBoxLayout *newLayout = new QVBoxLayout(m_waitDlg); - newLayout->addWidget(new QLabel(resultText, m_waitDlg)); + newLayout->addWidget(btn); - QPushButton *btn = new QPushButton(tr("OK"),m_waitDlg); - connect(btn, &QPushButton::clicked, - this, &LtsProgressDialogHelper::accept); - - newLayout->addWidget(btn); - - m_waitDlg->setLayout(newLayout); - m_waitDlg->show(); - - + m_waitDlg->setLayout(newLayout); + m_waitDlg->show(); } - void LtsProgressDialogHelper::accept() { - m_waitDlg->accept(); - m_waitDlg->deleteLater(); - m_waitDlg = nullptr; - emit accepted(); + m_waitDlg->accept(); + m_waitDlg->deleteLater(); + m_waitDlg = nullptr; + emit accepted(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h old mode 100755 new mode 100644 index de38e064b..7fb6e4ce8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_progress_dialog_helper.h @@ -1,6 +1,5 @@ - #pragma once #include "ltswidgets_export.h" @@ -15,52 +14,49 @@ namespace LtsWidgets { class LtsFramelessDialog; - - class LTSWIDGETS_EXPORT LtsProgressDialogHelper : public QObject { - Q_OBJECT + Q_OBJECT -public: - + public: + enum class ReplyResult { + Close = 0, + Success, + Failure, + TimeOut, + }; - enum class ReplyResult - { - Close = 0, - Success, - Failure, - TimeOut, - }; + explicit LtsProgressDialogHelper(QWidget* parent = nullptr); + ~LtsProgressDialogHelper(); - explicit LtsProgressDialogHelper(QWidget *parent = nullptr); - ~LtsProgressDialogHelper(); - bool isShown() const { return !!m_waitDlg; } - void setCustomText(const QString &customText = QString()); + bool isShown() const + { + return !!m_waitDlg; + } - void setParentWidget(QWidget *newParent); + void setCustomText(const QString& customText = QString()); -public slots: - + void setParentWidget(QWidget* newParent); - void slotShowWaitForReplyWindow(); + public slots: - + void slotShowWaitForReplyWindow(); - void slotStopWaitForReplyWindow(const LtsWidgets::LtsProgressDialogHelper::ReplyResult &replyResult = ReplyResult::Close , - const QString &replyString = QString()); + void + slotStopWaitForReplyWindow(const LtsWidgets::LtsProgressDialogHelper::ReplyResult& replyResult = ReplyResult::Close, + const QString& replyString = QString()); -private: - QPointer m_waitDlg; - QWidget *m_parentWidget; - QPointer m_textLabel; + private: + QPointer m_waitDlg; + QWidget* m_parentWidget; + QPointer m_textLabel; -signals: - + signals: - void accepted(); + void accepted(); -private slots: - void accept(); + private slots: + void accept(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp old mode 100755 new mode 100644 index 89781980f..35abe3b8d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.cpp @@ -1,18 +1,13 @@ - - - - #include "lts_range_slider.h" - #include -#include #include +#include +#include #include #include -#include #include namespace LtsWidgets @@ -20,804 +15,666 @@ namespace LtsWidgets class LtsRangeSliderPrivate { - Q_DECLARE_PUBLIC(LtsRangeSlider) -protected: - LtsRangeSlider *const q_ptr; -public: - - - enum Handle - { - NoHandle = 0x0, - MinimumHandle = 0x1, - MaximumHandle = 0x2 - }; - Q_DECLARE_FLAGS(Handles, Handle) + Q_DECLARE_PUBLIC(LtsRangeSlider) + protected: + LtsRangeSlider* const q_ptr; - explicit LtsRangeSliderPrivate(LtsRangeSlider &object); - void init(); + public: + enum Handle { NoHandle = 0x0, MinimumHandle = 0x1, MaximumHandle = 0x2 }; + Q_DECLARE_FLAGS(Handles, Handle) - - - - - Handle handleAtPos(const QPoint &pos, QRect &handleRect) const; + explicit LtsRangeSliderPrivate(LtsRangeSlider& object); + void init(); - - int pixelPosToRangeValue(int pos) const; - int pixelPosFromRangeValue(int val) const; + Handle handleAtPos(const QPoint& pos, QRect& handleRect) const; - - void drawMinimumSlider(QStylePainter *painter) const; - void drawMaximumSlider(QStylePainter *painter) const; + int pixelPosToRangeValue(int pos) const; + int pixelPosFromRangeValue(int val) const; - - int m_minimumValue = 0; - int m_maximumValue = 100; + void drawMinimumSlider(QStylePainter* painter) const; + void drawMaximumSlider(QStylePainter* painter) const; - - int m_minimumPosition = 0; - int m_maximumPosition = 100; + int m_minimumValue = 0; + int m_maximumValue = 100; - - QStyle::SubControl m_minimumSliderSelected = QStyle::SC_None; - QStyle::SubControl m_maximumSliderSelected = QStyle::SC_None; + int m_minimumPosition = 0; + int m_maximumPosition = 100; - - - int m_subclassClickOffset = 0; + QStyle::SubControl m_minimumSliderSelected = QStyle::SC_None; + QStyle::SubControl m_maximumSliderSelected = QStyle::SC_None; - - - int m_subclassPosition = 0; + int m_subclassClickOffset = 0; - - float m_subclassWidth = 0; + int m_subclassPosition = 0; - LtsRangeSliderPrivate::Handles m_selectedHandles = {}; + float m_subclassWidth = 0; - - - bool m_symmetricMoves = false; + LtsRangeSliderPrivate::Handles m_selectedHandles = {}; - QString m_handleToolTip; + bool m_symmetricMoves = false; -private: - Q_DISABLE_COPY(LtsRangeSliderPrivate) + QString m_handleToolTip; + + private: + Q_DISABLE_COPY(LtsRangeSliderPrivate) }; - -LtsRangeSliderPrivate::LtsRangeSliderPrivate(LtsRangeSlider &object) - : q_ptr(&object) -{} - +LtsRangeSliderPrivate::LtsRangeSliderPrivate(LtsRangeSlider& object) : q_ptr(&object) {} void LtsRangeSliderPrivate::init() { - Q_Q(LtsRangeSlider); - m_minimumValue = q->minimum(); - m_maximumValue = q->maximum(); - m_minimumPosition = q->minimum(); - m_maximumPosition = q->maximum(); - q->connect(q, &LtsRangeSlider::rangeChanged, q, &LtsRangeSlider::onRangeChanged); + Q_Q(LtsRangeSlider); + m_minimumValue = q->minimum(); + m_maximumValue = q->maximum(); + m_minimumPosition = q->minimum(); + m_maximumPosition = q->maximum(); + q->connect(q, &LtsRangeSlider::rangeChanged, q, &LtsRangeSlider::onRangeChanged); } - -LtsRangeSliderPrivate::Handle LtsRangeSliderPrivate::handleAtPos(const QPoint &pos, QRect &handleRect)const +LtsRangeSliderPrivate::Handle LtsRangeSliderPrivate::handleAtPos(const QPoint& pos, QRect& handleRect) const { - Q_Q(const LtsRangeSlider); + Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + QStyleOptionSlider option; + q->initStyleOption(&option); - - - + option.sliderPosition = m_minimumPosition; + option.sliderValue = m_minimumValue; - - option.sliderPosition = m_minimumPosition; - option.sliderValue = m_minimumValue; + QStyle::SubControl minimumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); + QRect minimumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - QStyle::SubControl minimumControl = q->style()->hitTestComplexControl( - QStyle::CC_Slider, &option, pos, q); - QRect minimumHandleRect = q->style()->subControlRect( - QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + option.sliderPosition = m_maximumPosition; + option.sliderValue = m_maximumValue; - - option.sliderPosition = m_maximumPosition; - option.sliderValue = m_maximumValue; + QStyle::SubControl maximumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); + QRect maximumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - QStyle::SubControl maximumControl = q->style()->hitTestComplexControl(QStyle::CC_Slider, &option, pos, q); - QRect maximumHandleRect = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); - - - if (minimumControl == QStyle::SC_SliderHandle && - maximumControl == QStyle::SC_SliderHandle) - { - int minDist = 0; - int maxDist = 0; - if (q->orientation() == Qt::Horizontal) + if (minimumControl == QStyle::SC_SliderHandle && maximumControl == QStyle::SC_SliderHandle) { - minDist = pos.x() - minimumHandleRect.left(); - maxDist = maximumHandleRect.right() - pos.x(); + int minDist = 0; + int maxDist = 0; + if (q->orientation() == Qt::Horizontal) + { + minDist = pos.x() - minimumHandleRect.left(); + maxDist = maximumHandleRect.right() - pos.x(); + } + else + { + minDist = minimumHandleRect.bottom() - pos.y(); + maxDist = pos.y() - maximumHandleRect.top(); + } + Q_ASSERT(minDist >= 0 && maxDist >= 0); + minimumControl = minDist < maxDist ? minimumControl : QStyle::SC_None; } - else + + if (maximumControl == QStyle::SC_SliderHandle) { - minDist = minimumHandleRect.bottom() - pos.y(); - maxDist = pos.y() - maximumHandleRect.top(); + handleRect = maximumHandleRect; + return MaximumHandle; + } + else if (minimumControl == QStyle::SC_SliderHandle) + { + handleRect = minimumHandleRect; + return MinimumHandle; } - Q_ASSERT(minDist >= 0 && maxDist >= 0); - minimumControl = minDist < maxDist ? minimumControl : QStyle::SC_None; - } - if (maximumControl == QStyle::SC_SliderHandle) - { - handleRect = maximumHandleRect; - return MaximumHandle; - } - else if (minimumControl == QStyle::SC_SliderHandle) - { - handleRect = minimumHandleRect; - return MinimumHandle; - } - - handleRect = minimumHandleRect.united(maximumHandleRect); - return NoHandle; + handleRect = minimumHandleRect.united(maximumHandleRect); + return NoHandle; } - - - int LtsRangeSliderPrivate::pixelPosToRangeValue(int pos) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initStyleOption(&option); - QRect gr = q->style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderGroove, - q); - QRect sr = q->style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderHandle, - q); - int sliderMin, sliderMax, sliderLength; - if (option.orientation == Qt::Horizontal) - { - sliderLength = sr.width(); - sliderMin = gr.x(); - sliderMax = gr.right() - sliderLength + 1; - } - else - { - sliderLength = sr.height(); - sliderMin = gr.y(); - sliderMax = gr.bottom() - sliderLength + 1; - } + QRect gr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, q); + QRect sr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + int sliderMin, sliderMax, sliderLength; + if (option.orientation == Qt::Horizontal) + { + sliderLength = sr.width(); + sliderMin = gr.x(); + sliderMax = gr.right() - sliderLength + 1; + } + else + { + sliderLength = sr.height(); + sliderMin = gr.y(); + sliderMax = gr.bottom() - sliderLength + 1; + } - return QStyle::sliderValueFromPosition(q->minimum(), - q->maximum(), - pos - sliderMin, - sliderMax - sliderMin, - option.upsideDown); + return QStyle::sliderValueFromPosition(q->minimum(), q->maximum(), pos - sliderMin, sliderMax - sliderMin, + option.upsideDown); } - int LtsRangeSliderPrivate::pixelPosFromRangeValue(int val) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initStyleOption(&option); - QRect gr = q->style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderGroove, - q); - QRect sr = q->style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderHandle, - q); - int sliderMin, sliderMax, sliderLength; - if (option.orientation == Qt::Horizontal) - { - sliderLength = sr.width(); - sliderMin = gr.x(); - sliderMax = gr.right() - sliderLength + 1; - } - else - { - sliderLength = sr.height(); - sliderMin = gr.y(); - sliderMax = gr.bottom() - sliderLength + 1; - } + QRect gr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, q); + QRect sr = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + int sliderMin, sliderMax, sliderLength; + if (option.orientation == Qt::Horizontal) + { + sliderLength = sr.width(); + sliderMin = gr.x(); + sliderMax = gr.right() - sliderLength + 1; + } + else + { + sliderLength = sr.height(); + sliderMin = gr.y(); + sliderMax = gr.bottom() - sliderLength + 1; + } - return QStyle::sliderPositionFromValue(q->minimum(), - q->maximum(), - val, - sliderMax - sliderMin, - option.upsideDown) + sliderMin; + return QStyle::sliderPositionFromValue(q->minimum(), q->maximum(), val, sliderMax - sliderMin, option.upsideDown) + + sliderMin; } - - -void LtsRangeSliderPrivate::drawMinimumSlider(QStylePainter *painter) const +void LtsRangeSliderPrivate::drawMinimumSlider(QStylePainter* painter) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initMinimumSliderStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initMinimumSliderStyleOption(&option); - option.subControls = QStyle::SC_SliderHandle; - option.sliderValue = m_minimumValue; - option.sliderPosition = m_minimumPosition; - if (q->isMinimumSliderDown()) - { - option.activeSubControls = QStyle::SC_SliderHandle; - option.state |= QStyle::State_Sunken; - } + option.subControls = QStyle::SC_SliderHandle; + option.sliderValue = m_minimumValue; + option.sliderPosition = m_minimumPosition; + if (q->isMinimumSliderDown()) + { + option.activeSubControls = QStyle::SC_SliderHandle; + option.state |= QStyle::State_Sunken; + } #ifdef Q_OS_MAC - - QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, - QStyle::SC_SliderHandle, q); - painter->setClipRect(clip); + + QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + painter->setClipRect(clip); #endif - painter->drawComplexControl(QStyle::CC_Slider, option); + painter->drawComplexControl(QStyle::CC_Slider, option); } - - -void LtsRangeSliderPrivate::drawMaximumSlider(QStylePainter *painter) const +void LtsRangeSliderPrivate::drawMaximumSlider(QStylePainter* painter) const { - Q_Q(const LtsRangeSlider); - QStyleOptionSlider option; - q->initMaximumSliderStyleOption(&option); + Q_Q(const LtsRangeSlider); + QStyleOptionSlider option; + q->initMaximumSliderStyleOption(&option); - option.subControls = QStyle::SC_SliderHandle; - option.sliderValue = m_maximumValue; - option.sliderPosition = m_maximumPosition; - if (q->isMaximumSliderDown()) - { - option.activeSubControls = QStyle::SC_SliderHandle; - option.state |= QStyle::State_Sunken; - } + option.subControls = QStyle::SC_SliderHandle; + option.sliderValue = m_maximumValue; + option.sliderPosition = m_maximumPosition; + if (q->isMaximumSliderDown()) + { + option.activeSubControls = QStyle::SC_SliderHandle; + option.state |= QStyle::State_Sunken; + } #ifdef Q_OS_MAC - - QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, - QStyle::SC_SliderHandle, q); - painter->setClipRect(clip); + + QRect clip = q->style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, q); + painter->setClipRect(clip); #endif - painter->drawComplexControl(QStyle::CC_Slider, option); + painter->drawComplexControl(QStyle::CC_Slider, option); } - -LtsRangeSlider::LtsRangeSlider(Qt::Orientation o, - QWidget *parent) - : QSlider(o, parent) - , d_ptr(new LtsRangeSliderPrivate(*this)) +LtsRangeSlider::LtsRangeSlider(Qt::Orientation o, QWidget* parent) + : QSlider(o, parent), d_ptr(new LtsRangeSliderPrivate(*this)) { - Q_D(LtsRangeSlider); - d->init(); + Q_D(LtsRangeSlider); + d->init(); } - -LtsRangeSlider::LtsRangeSlider(LtsRangeSliderPrivate *impl, Qt::Orientation o, - QWidget *parent) - : QSlider(o, parent) - , d_ptr(impl) -{ - Q_D(LtsRangeSlider); - d->init(); -} - - -LtsRangeSlider::~LtsRangeSlider() +LtsRangeSlider::LtsRangeSlider(LtsRangeSliderPrivate* impl, Qt::Orientation o, QWidget* parent) + : QSlider(o, parent), d_ptr(impl) { + Q_D(LtsRangeSlider); + d->init(); } +LtsRangeSlider::~LtsRangeSlider() {} int LtsRangeSlider::minimumValue() const { - Q_D(const LtsRangeSlider); - return d->m_minimumValue; + Q_D(const LtsRangeSlider); + return d->m_minimumValue; } - void LtsRangeSlider::setMinimumValue(int min) { - Q_D(LtsRangeSlider); - setValues(min, qMax(d->m_maximumValue, min)); + Q_D(LtsRangeSlider); + setValues(min, qMax(d->m_maximumValue, min)); } - int LtsRangeSlider::maximumValue() const { - Q_D(const LtsRangeSlider); - return d->m_maximumValue; + Q_D(const LtsRangeSlider); + return d->m_maximumValue; } - void LtsRangeSlider::setMaximumValue(int max) { - Q_D(LtsRangeSlider); - setValues(qMin(d->m_minimumValue, max), max); + Q_D(LtsRangeSlider); + setValues(qMin(d->m_minimumValue, max), max); } - void LtsRangeSlider::setValues(int min, int max) { - Q_D(LtsRangeSlider); - const int minValue = qBound(minimum(), qMin(min, max), maximum()); - const int maxValue = qBound(minimum(), qMax(min, max), maximum()); - bool emitMinValChanged = (minValue != d->m_minimumValue); - bool emitMaxValChanged = (maxValue != d->m_maximumValue); + Q_D(LtsRangeSlider); + const int minValue = qBound(minimum(), qMin(min, max), maximum()); + const int maxValue = qBound(minimum(), qMax(min, max), maximum()); + bool emitMinValChanged = (minValue != d->m_minimumValue); + bool emitMaxValChanged = (maxValue != d->m_maximumValue); - d->m_minimumValue = minValue; - d->m_maximumValue = maxValue; + d->m_minimumValue = minValue; + d->m_maximumValue = maxValue; - bool emitMinPosChanged = (minValue != d->m_minimumPosition); - bool emitMaxPosChanged = (maxValue != d->m_maximumPosition); - d->m_minimumPosition = minValue; - d->m_maximumPosition = maxValue; + bool emitMinPosChanged = (minValue != d->m_minimumPosition); + bool emitMaxPosChanged = (maxValue != d->m_maximumPosition); + d->m_minimumPosition = minValue; + d->m_maximumPosition = maxValue; - if (isSliderDown()) - { - if (emitMinPosChanged || emitMaxPosChanged) - emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); - if (emitMinPosChanged) - emit minimumPositionChanged(d->m_minimumPosition); - if (emitMaxPosChanged) - emit maximumPositionChanged(d->m_maximumPosition); - } - if (emitMinValChanged || emitMaxValChanged) - emit valuesChanged(d->m_minimumValue, d->m_maximumValue); + if (isSliderDown()) + { + if (emitMinPosChanged || emitMaxPosChanged) + emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); + if (emitMinPosChanged) + emit minimumPositionChanged(d->m_minimumPosition); + if (emitMaxPosChanged) + emit maximumPositionChanged(d->m_maximumPosition); + } + if (emitMinValChanged || emitMaxValChanged) + emit valuesChanged(d->m_minimumValue, d->m_maximumValue); - if (emitMinValChanged) - emit minimumValueChanged(d->m_minimumValue); + if (emitMinValChanged) + emit minimumValueChanged(d->m_minimumValue); - if (emitMaxValChanged) - emit maximumValueChanged(d->m_maximumValue); + if (emitMaxValChanged) + emit maximumValueChanged(d->m_maximumValue); - if (emitMinPosChanged || emitMaxPosChanged || - emitMinValChanged || emitMaxValChanged) - update(); + if (emitMinPosChanged || emitMaxPosChanged || emitMinValChanged || emitMaxValChanged) + update(); } - int LtsRangeSlider::minimumPosition() const { - Q_D(const LtsRangeSlider); - return d->m_minimumPosition; + Q_D(const LtsRangeSlider); + return d->m_minimumPosition; } - int LtsRangeSlider::maximumPosition() const { - Q_D(const LtsRangeSlider); - return d->m_maximumPosition; + Q_D(const LtsRangeSlider); + return d->m_maximumPosition; } - void LtsRangeSlider::setMinimumPosition(int min) { - Q_D(const LtsRangeSlider); - setPositions(min, qMax(min, d->m_maximumPosition)); + Q_D(const LtsRangeSlider); + setPositions(min, qMax(min, d->m_maximumPosition)); } - void LtsRangeSlider::setMaximumPosition(int max) { - Q_D(const LtsRangeSlider); - setPositions(qMin(d->m_minimumPosition, max), max); + Q_D(const LtsRangeSlider); + setPositions(qMin(d->m_minimumPosition, max), max); } - void LtsRangeSlider::setPositions(int min, int max) { - Q_D(LtsRangeSlider); - const int minPosition = qBound(minimum(), qMin(min, max), maximum()); - const int maxPosition = qBound(minimum(), qMax(min, max), maximum()); + Q_D(LtsRangeSlider); + const int minPosition = qBound(minimum(), qMin(min, max), maximum()); + const int maxPosition = qBound(minimum(), qMax(min, max), maximum()); - bool emitMinPosChanged = (minPosition != d->m_minimumPosition); - bool emitMaxPosChanged = (maxPosition != d->m_maximumPosition); + bool emitMinPosChanged = (minPosition != d->m_minimumPosition); + bool emitMaxPosChanged = (maxPosition != d->m_maximumPosition); - if (!emitMinPosChanged && !emitMaxPosChanged) - return; + if (!emitMinPosChanged && !emitMaxPosChanged) + return; - d->m_minimumPosition = minPosition; - d->m_maximumPosition = maxPosition; + d->m_minimumPosition = minPosition; + d->m_maximumPosition = maxPosition; - if (!hasTracking()) - update(); + if (!hasTracking()) + update(); - if (isSliderDown()) - { - if (emitMinPosChanged) - emit minimumPositionChanged(d->m_minimumPosition); - if (emitMaxPosChanged) - emit maximumPositionChanged(d->m_maximumPosition); - if (emitMinPosChanged || emitMaxPosChanged) - emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); - } - if (hasTracking()) - { - triggerAction(SliderMove); - setValues(d->m_minimumPosition, d->m_maximumPosition); - } + if (isSliderDown()) + { + if (emitMinPosChanged) + emit minimumPositionChanged(d->m_minimumPosition); + if (emitMaxPosChanged) + emit maximumPositionChanged(d->m_maximumPosition); + if (emitMinPosChanged || emitMaxPosChanged) + emit positionsChanged(d->m_minimumPosition, d->m_maximumPosition); + } + if (hasTracking()) + { + triggerAction(SliderMove); + setValues(d->m_minimumPosition, d->m_maximumPosition); + } } - void LtsRangeSlider::setSymmetricMoves(bool symmetry) { - Q_D(LtsRangeSlider); - d->m_symmetricMoves = symmetry; + Q_D(LtsRangeSlider); + d->m_symmetricMoves = symmetry; } - bool LtsRangeSlider::symmetricMoves() const { - Q_D(const LtsRangeSlider); - return d->m_symmetricMoves; + Q_D(const LtsRangeSlider); + return d->m_symmetricMoves; } - void LtsRangeSlider::onRangeChanged(int minimum, int maximum) { - Q_UNUSED(minimum); - Q_UNUSED(maximum); - Q_D(LtsRangeSlider); - setValues(d->m_minimumValue, d->m_maximumValue); + Q_UNUSED(minimum); + Q_UNUSED(maximum); + Q_D(LtsRangeSlider); + setValues(d->m_minimumValue, d->m_maximumValue); } - - -void LtsRangeSlider::paintEvent(QPaintEvent *) +void LtsRangeSlider::paintEvent(QPaintEvent*) { - Q_D(LtsRangeSlider); - QStyleOptionSlider option; - initStyleOption(&option); + Q_D(LtsRangeSlider); + QStyleOptionSlider option; + initStyleOption(&option); - QStylePainter painter(this); + QStylePainter painter(this); - - - - painter.setPen(Qt::lightGray); - if (option.orientation == Qt::Horizontal) - { - painter.drawLine(option.rect.left(), option.rect.top(), option.rect.left(), option.rect.bottom()); - painter.drawRect(option.rect.left(), option.rect.center().y() - 1, option.rect.right() - option.rect.left(), 3); - painter.drawLine(option.rect.right(), option.rect.top(), option.rect.right(), option.rect.bottom()); - } - else - { - painter.drawLine(option.rect.left(), option.rect.top(), option.rect.right(), option.rect.top()); - painter.drawRect(option.rect.center().x() - 1, option.rect.top(), 3, option.rect.top() - option.rect.bottom()); - painter.drawLine(option.rect.center().x(), option.rect.top(), option.rect.center().x(), option.rect.bottom()); - painter.drawLine(option.rect.left(), option.rect.bottom(), option.rect.right(), option.rect.bottom()); - } - + painter.setPen(Qt::lightGray); + if (option.orientation == Qt::Horizontal) + { + painter.drawLine(option.rect.left(), option.rect.top(), option.rect.left(), option.rect.bottom()); + painter.drawRect(option.rect.left(), option.rect.center().y() - 1, option.rect.right() - option.rect.left(), 3); + painter.drawLine(option.rect.right(), option.rect.top(), option.rect.right(), option.rect.bottom()); + } + else + { + painter.drawLine(option.rect.left(), option.rect.top(), option.rect.right(), option.rect.top()); + painter.drawRect(option.rect.center().x() - 1, option.rect.top(), 3, option.rect.top() - option.rect.bottom()); + painter.drawLine(option.rect.center().x(), option.rect.top(), option.rect.center().x(), option.rect.bottom()); + painter.drawLine(option.rect.left(), option.rect.bottom(), option.rect.right(), option.rect.bottom()); + } - option.subControls = QStyle::SC_SliderGroove; - - - - option.sliderValue = minimum() - maximum(); - option.sliderPosition = minimum() - maximum(); - option.subControls &= ~QStyle::SC_SliderGroove; - painter.drawComplexControl(QStyle::CC_Slider, option); - option.subControls |= QStyle::SC_SliderGroove; + option.subControls = QStyle::SC_SliderGroove; - option.sliderPosition = d->m_minimumPosition; - const QRect lr = style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderHandle, - this); + option.sliderValue = minimum() - maximum(); + option.sliderPosition = minimum() - maximum(); + option.subControls &= ~QStyle::SC_SliderGroove; + painter.drawComplexControl(QStyle::CC_Slider, option); + option.subControls |= QStyle::SC_SliderGroove; - option.sliderPosition = d->m_maximumPosition; - const QRect ur = style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderHandle, - this); + option.sliderPosition = d->m_minimumPosition; + const QRect lr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); - QRect sr = style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderGroove, - this); - QRect rangeBox; - if (option.orientation == Qt::Horizontal) - { - rangeBox = QRect(QPoint(qMin(lr.center().x(), ur.center().x()), sr.center().y() - 2), - QPoint(qMax(lr.center().x(), ur.center().x()), sr.center().y() + 1)); - } - else - { - rangeBox = QRect(QPoint(sr.center().x() - 2, qMin(lr.center().y(), ur.center().y())), - QPoint(sr.center().x() + 1, qMax(lr.center().y(), ur.center().y()))); - } + option.sliderPosition = d->m_maximumPosition; + const QRect ur = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this); - - - - QRect groove = style()->subControlRect(QStyle::CC_Slider, - &option, - QStyle::SC_SliderGroove, - this); - groove.adjust(0, 0, -1, 0); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + QRect rangeBox; + if (option.orientation == Qt::Horizontal) + { + rangeBox = QRect(QPoint(qMin(lr.center().x(), ur.center().x()), sr.center().y() - 2), + QPoint(qMax(lr.center().x(), ur.center().x()), sr.center().y() + 1)); + } + else + { + rangeBox = QRect(QPoint(sr.center().x() - 2, qMin(lr.center().y(), ur.center().y())), + QPoint(sr.center().x() + 1, qMax(lr.center().y(), ur.center().y()))); + } - - - QColor highlight = palette().color(QPalette::Normal, QPalette::Highlight); - QLinearGradient gradient; - if (option.orientation == Qt::Horizontal) - gradient = QLinearGradient(groove.center().x(), groove.top(), groove.center().x(), groove.bottom()); - else - gradient = QLinearGradient(groove.left(), groove.center().y(), groove.right(), groove.center().y()); + QRect groove = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + groove.adjust(0, 0, -1, 0); - - - + QColor highlight = palette().color(QPalette::Normal, QPalette::Highlight); + QLinearGradient gradient; + if (option.orientation == Qt::Horizontal) + gradient = QLinearGradient(groove.center().x(), groove.top(), groove.center().x(), groove.bottom()); + else + gradient = QLinearGradient(groove.left(), groove.center().y(), groove.right(), groove.center().y()); - gradient.setColorAt(0, highlight.darker(120)); - gradient.setColorAt(1, highlight.lighter(160)); + gradient.setColorAt(0, highlight.darker(120)); + gradient.setColorAt(1, highlight.lighter(160)); - painter.setPen(QPen(highlight.darker(150), 0)); - painter.setBrush(gradient); - painter.drawRect(rangeBox.intersected(groove)); + painter.setPen(QPen(highlight.darker(150), 0)); + painter.setBrush(gradient); + painter.drawRect(rangeBox.intersected(groove)); - - - - if (isMinimumSliderDown()) - { - painter.setClipRect(ur); - d->drawMaximumSlider(&painter); - painter.setClipRect(lr); - d->drawMinimumSlider(&painter); - } - else - { - painter.setClipRect(lr); - d->drawMinimumSlider(&painter); - painter.setClipRect(ur); - d->drawMaximumSlider(&painter); - } + if (isMinimumSliderDown()) + { + painter.setClipRect(ur); + d->drawMaximumSlider(&painter); + painter.setClipRect(lr); + d->drawMinimumSlider(&painter); + } + else + { + painter.setClipRect(lr); + d->drawMinimumSlider(&painter); + painter.setClipRect(ur); + d->drawMaximumSlider(&painter); + } } - - -void LtsRangeSlider::mousePressEvent(QMouseEvent *ev) +void LtsRangeSlider::mousePressEvent(QMouseEvent* ev) { - Q_D(LtsRangeSlider); - if (minimum() == maximum() || (ev->buttons() ^ ev->button())) - { + Q_D(LtsRangeSlider); + if (minimum() == maximum() || (ev->buttons() ^ ev->button())) + { + ev->ignore(); + return; + } + int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); + + QStyleOptionSlider option; + initStyleOption(&option); + + QRect handleRect; + LtsRangeSliderPrivate::Handle handle_ = d->handleAtPos(ev->pos(), handleRect); + + if (handle_ != LtsRangeSliderPrivate::NoHandle) + { + if (ev->buttons() == Qt::RightButton) + { + d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; + d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); + d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; + + setSliderDown(true); + if (!isMinimumSliderDown() || !isMaximumSliderDown()) + { + d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | + QFlags(LtsRangeSliderPrivate::MaximumHandle); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + update(handleRect.united(sr)); + } + ev->accept(); + return; + } + + d->m_subclassPosition = + (handle_ == LtsRangeSliderPrivate::MinimumHandle) ? d->m_minimumPosition : d->m_maximumPosition; + + d->m_subclassClickOffset = mepos - (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); + + setSliderDown(true); + + if (d->m_selectedHandles != handle_) + { + d->m_selectedHandles = handle_; + update(handleRect); + } + + ev->accept(); + return; + } + + QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_Slider, &option, ev->pos(), this); + QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); + int minCenter = (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); + int maxCenter = (orientation() == Qt::Horizontal ? handleRect.right() : handleRect.bottom()); + if (control == QStyle::SC_SliderGroove && mepos > minCenter && mepos < maxCenter) + { + + d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; + d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); + d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; + + setSliderDown(true); + if (!isMinimumSliderDown() || !isMaximumSliderDown()) + { + d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | + QFlags(LtsRangeSliderPrivate::MaximumHandle); + update(handleRect.united(sr)); + } + ev->accept(); + return; + } ev->ignore(); - return; - } - int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); - - QStyleOptionSlider option; - initStyleOption(&option); - - QRect handleRect; - LtsRangeSliderPrivate::Handle handle_ = d->handleAtPos(ev->pos(), handleRect); - - if (handle_ != LtsRangeSliderPrivate::NoHandle) - { - if (ev->buttons() == Qt::RightButton) - { - d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; - d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); - d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; - - setSliderDown(true); - if (!isMinimumSliderDown() || !isMaximumSliderDown()) - { - d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | - QFlags(LtsRangeSliderPrivate::MaximumHandle); - QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - update(handleRect.united(sr)); - } - ev->accept(); - return; - } - - d->m_subclassPosition = (handle_ == LtsRangeSliderPrivate::MinimumHandle) ? d->m_minimumPosition : d->m_maximumPosition; - - - d->m_subclassClickOffset = mepos - (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); - - setSliderDown(true); - - if (d->m_selectedHandles != handle_) - { - d->m_selectedHandles = handle_; - update(handleRect); - } - - ev->accept(); - return; - } - - - - - QStyle::SubControl control = style()->hitTestComplexControl(QStyle::CC_Slider, &option, ev->pos(), this); - QRect sr = style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this); - int minCenter = (orientation() == Qt::Horizontal ? handleRect.left() : handleRect.top()); - int maxCenter = (orientation() == Qt::Horizontal ? handleRect.right() : handleRect.bottom()); - if (control == QStyle::SC_SliderGroove && mepos > minCenter && mepos < maxCenter) - { - - d->m_subclassPosition = (d->m_minimumPosition + d->m_maximumPosition) / 2.; - d->m_subclassClickOffset = mepos - d->pixelPosFromRangeValue(d->m_subclassPosition); - d->m_subclassWidth = (d->m_maximumPosition - d->m_minimumPosition) / 2.; - - setSliderDown(true); - if (!isMinimumSliderDown() || !isMaximumSliderDown()) - { - d->m_selectedHandles = QFlags(LtsRangeSliderPrivate::MinimumHandle) | - QFlags(LtsRangeSliderPrivate::MaximumHandle); - update(handleRect.united(sr)); - } - ev->accept(); - return; - } - ev->ignore(); } - - -void LtsRangeSlider::mouseMoveEvent(QMouseEvent *ev) +void LtsRangeSlider::mouseMoveEvent(QMouseEvent* ev) { - Q_D(LtsRangeSlider); - if (!d->m_selectedHandles) - { - ev->ignore(); - return; - } - int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); - - QStyleOptionSlider option; - initStyleOption(&option); - - - if (isMinimumSliderDown() && isMaximumSliderDown()) - { - int newPosition = d->pixelPosToRangeValue(mepos); - int newMinPosition = newPosition - static_cast(d->m_subclassWidth); - int newMaxPosition = newPosition + static_cast(d->m_subclassWidth + .5); - - if (newMinPosition < minimum()) + Q_D(LtsRangeSlider); + if (!d->m_selectedHandles) { - newMinPosition = minimum(); - newMaxPosition = newMinPosition + (d->m_maximumPosition - d->m_minimumPosition); + ev->ignore(); + return; } - else if (newMaxPosition > maximum()) + int mepos = orientation() == Qt::Horizontal ? ev->pos().x() : ev->pos().y(); + + QStyleOptionSlider option; + initStyleOption(&option); + + if (isMinimumSliderDown() && isMaximumSliderDown()) { - newMaxPosition = maximum(); - newMinPosition = newMaxPosition - (d->m_maximumPosition - d->m_minimumPosition); + int newPosition = d->pixelPosToRangeValue(mepos); + int newMinPosition = newPosition - static_cast(d->m_subclassWidth); + int newMaxPosition = newPosition + static_cast(d->m_subclassWidth + .5); + + if (newMinPosition < minimum()) + { + newMinPosition = minimum(); + newMaxPosition = newMinPosition + (d->m_maximumPosition - d->m_minimumPosition); + } + else if (newMaxPosition > maximum()) + { + newMaxPosition = maximum(); + newMinPosition = newMaxPosition - (d->m_maximumPosition - d->m_minimumPosition); + } + setPositions(newMinPosition, newMaxPosition); + ev->accept(); + return; + } + + const int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &option, this); + + int newPosition = d->pixelPosToRangeValue(mepos - d->m_subclassClickOffset); + + if (m >= 0) + { + const QRect r = rect().adjusted(-m, -m, m, m); + if (!r.contains(ev->pos())) + newPosition = d->m_subclassPosition; + } + + if (isMinimumSliderDown() && !isMaximumSliderDown()) + { + double newMinPos = qMin(newPosition, d->m_maximumPosition); + setPositions(newMinPos, d->m_maximumPosition + (d->m_symmetricMoves ? d->m_minimumPosition - newMinPos : 0)); + } + + else if (isMaximumSliderDown() && !isMinimumSliderDown()) + { + double newMaxPos = qMax(d->m_minimumPosition, newPosition); + setPositions(d->m_minimumPosition - (d->m_symmetricMoves ? newMaxPos - d->m_maximumPosition : 0), newMaxPos); } - setPositions(newMinPosition, newMaxPosition); ev->accept(); - return; - } - - const int m = style()->pixelMetric(QStyle::PM_MaximumDragDistance, &option, this); - - int newPosition = d->pixelPosToRangeValue(mepos - d->m_subclassClickOffset); - - if (m >= 0) - { - const QRect r = rect().adjusted(-m, -m, m, m); - if (!r.contains(ev->pos())) - newPosition = d->m_subclassPosition; - } - - - if (isMinimumSliderDown() && !isMaximumSliderDown()) - { - double newMinPos = qMin(newPosition, d->m_maximumPosition); - setPositions(newMinPos, d->m_maximumPosition + (d->m_symmetricMoves ? d->m_minimumPosition - newMinPos : 0)); - } - - else if (isMaximumSliderDown() && !isMinimumSliderDown()) - { - double newMaxPos = qMax(d->m_minimumPosition, newPosition); - setPositions(d->m_minimumPosition - (d->m_symmetricMoves ? newMaxPos - d->m_maximumPosition : 0), newMaxPos); - } - ev->accept(); } - - -void LtsRangeSlider::mouseReleaseEvent(QMouseEvent *ev) +void LtsRangeSlider::mouseReleaseEvent(QMouseEvent* ev) { - Q_D(LtsRangeSlider); - QSlider::mouseReleaseEvent(ev); + Q_D(LtsRangeSlider); + QSlider::mouseReleaseEvent(ev); - setSliderDown(false); - d->m_selectedHandles = {}; + setSliderDown(false); + d->m_selectedHandles = {}; - update(); + update(); } - bool LtsRangeSlider::isMinimumSliderDown() const { - Q_D(const LtsRangeSlider); - return d->m_selectedHandles & LtsRangeSliderPrivate::MinimumHandle; + Q_D(const LtsRangeSlider); + return d->m_selectedHandles & LtsRangeSliderPrivate::MinimumHandle; } - bool LtsRangeSlider::isMaximumSliderDown() const { - Q_D(const LtsRangeSlider); - return d->m_selectedHandles & LtsRangeSliderPrivate::MaximumHandle; + Q_D(const LtsRangeSlider); + return d->m_selectedHandles & LtsRangeSliderPrivate::MaximumHandle; } - -void LtsRangeSlider::initMinimumSliderStyleOption(QStyleOptionSlider *option) const +void LtsRangeSlider::initMinimumSliderStyleOption(QStyleOptionSlider* option) const { - initStyleOption(option); + initStyleOption(option); } - -void LtsRangeSlider::initMaximumSliderStyleOption(QStyleOptionSlider *option) const +void LtsRangeSlider::initMaximumSliderStyleOption(QStyleOptionSlider* option) const { - initStyleOption(option); + initStyleOption(option); } - -QString LtsRangeSlider::handleToolTip()const +QString LtsRangeSlider::handleToolTip() const { - Q_D(const LtsRangeSlider); - return d->m_handleToolTip; + Q_D(const LtsRangeSlider); + return d->m_handleToolTip; } - -void LtsRangeSlider::setHandleToolTip(const QString &toolTip) +void LtsRangeSlider::setHandleToolTip(const QString& toolTip) { - Q_D(LtsRangeSlider); - d->m_handleToolTip = toolTip; + Q_D(LtsRangeSlider); + d->m_handleToolTip = toolTip; } - -bool LtsRangeSlider::event(QEvent *event) +bool LtsRangeSlider::event(QEvent* event) { - Q_D(LtsRangeSlider); - switch (event->type()) - { - case QEvent::ToolTip: - { - QHelpEvent *helpEvent = static_cast(event); - QStyleOptionSlider opt; - - opt.sliderPosition = d->m_minimumPosition; - opt.sliderValue = d->m_minimumValue; - initStyleOption(&opt); - QStyle::SubControl hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); - if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) + Q_D(LtsRangeSlider); + switch (event->type()) { - QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(minimumValue())); - event->accept(); - return true; + case QEvent::ToolTip: { + QHelpEvent* helpEvent = static_cast(event); + QStyleOptionSlider opt; + + opt.sliderPosition = d->m_minimumPosition; + opt.sliderValue = d->m_minimumValue; + initStyleOption(&opt); + QStyle::SubControl hoveredControl = + style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); + if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) + { + QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(minimumValue())); + event->accept(); + return true; + } + + opt.sliderPosition = d->m_maximumPosition; + opt.sliderValue = d->m_maximumValue; + initStyleOption(&opt); + hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); + if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) + { + QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(maximumValue())); + event->accept(); + return true; + } + } + default: + break; } - - opt.sliderPosition = d->m_maximumPosition; - opt.sliderValue = d->m_maximumValue; - initStyleOption(&opt); - hoveredControl = style()->hitTestComplexControl(QStyle::CC_Slider, &opt, helpEvent->pos(), this); - if (!d->m_handleToolTip.isEmpty() && hoveredControl == QStyle::SC_SliderHandle) - { - QToolTip::showText(helpEvent->globalPos(), d->m_handleToolTip.arg(maximumValue())); - event->accept(); - return true; - } - } - default: - break; - } - return QSlider::event(event); + return QSlider::event(event); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h old mode 100755 new mode 100644 index 29631f0ff..55c465490 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_range_slider.h @@ -1,14 +1,9 @@ - - - #pragma once -#include - #include "ltswidgets_export.h" - +#include #include namespace LtsWidgets @@ -16,180 +11,90 @@ namespace LtsWidgets class LtsRangeSliderPrivate; - - - - - - - - - - - - - - - class LTSWIDGETS_EXPORT LtsRangeSlider : public QSlider { - Q_OBJECT + Q_OBJECT - Q_PROPERTY(int minimumValue READ minimumValue WRITE setMinimumValue) - Q_PROPERTY(int maximumValue READ maximumValue WRITE setMaximumValue) - Q_PROPERTY(int minimumPosition READ minimumPosition WRITE setMinimumPosition) - Q_PROPERTY(int maximumPosition READ maximumPosition WRITE setMaximumPosition) - Q_PROPERTY(bool symmetricMoves READ symmetricMoves WRITE setSymmetricMoves) - Q_PROPERTY(QString handleToolTip READ handleToolTip WRITE setHandleToolTip) + Q_PROPERTY(int minimumValue READ minimumValue WRITE setMinimumValue) + Q_PROPERTY(int maximumValue READ maximumValue WRITE setMaximumValue) + Q_PROPERTY(int minimumPosition READ minimumPosition WRITE setMinimumPosition) + Q_PROPERTY(int maximumPosition READ maximumPosition WRITE setMaximumPosition) + Q_PROPERTY(bool symmetricMoves READ symmetricMoves WRITE setSymmetricMoves) + Q_PROPERTY(QString handleToolTip READ handleToolTip WRITE setHandleToolTip) -public: - - - - explicit LtsRangeSlider(Qt::Orientation o, QWidget *parent = nullptr); - explicit LtsRangeSlider(QWidget *parent = nullptr) - : LtsRangeSlider(Qt::Vertical, parent) - {} - ~LtsRangeSlider(); + public: + explicit LtsRangeSlider(Qt::Orientation o, QWidget* parent = nullptr); - - - - - - int minimumValue() const; + explicit LtsRangeSlider(QWidget* parent = nullptr) : LtsRangeSlider(Qt::Vertical, parent) {} - - - - - - int maximumValue() const; + ~LtsRangeSlider(); - - - - int minimumPosition() const; - void setMinimumPosition(int min); + int minimumValue() const; - - - - int maximumPosition() const; - void setMaximumPosition(int max); + int maximumValue() const; - - - - void setPositions(int min, int max); + int minimumPosition() const; + void setMinimumPosition(int min); - - - - bool symmetricMoves() const; - void setSymmetricMoves(bool symmetry); + int maximumPosition() const; + void setMaximumPosition(int max); - - - - - - QString handleToolTip() const; - void setHandleToolTip(const QString &toolTip); + void setPositions(int min, int max); - - - bool isMinimumSliderDown() const; - - - bool isMaximumSliderDown() const; + bool symmetricMoves() const; + void setSymmetricMoves(bool symmetry); -Q_SIGNALS: - - - - void minimumValueChanged(int min); - - - - void maximumValueChanged(int max); - - - void valuesChanged(int min, int max); + QString handleToolTip() const; + void setHandleToolTip(const QString& toolTip); - - - - - - void minimumPositionChanged(int min); + bool isMinimumSliderDown() const; - - - - - - void maximumPositionChanged(int max); + bool isMaximumSliderDown() const; - - - - void positionsChanged(int min, int max); + Q_SIGNALS: -public Q_SLOTS: - - - - - - - void setMinimumValue(int min); + void minimumValueChanged(int min); - - - - - - - void setMaximumValue(int max); + void maximumValueChanged(int max); - - - - - - - - void setValues(int min, int max); + void valuesChanged(int min, int max); -protected Q_SLOTS: - void onRangeChanged(int minimum, int maximum); + void minimumPositionChanged(int min); -protected: - LtsRangeSlider(LtsRangeSliderPrivate *impl, Qt::Orientation o, QWidget *parent = nullptr); + void maximumPositionChanged(int max); - - - void mousePressEvent(QMouseEvent *ev) override; - void mouseMoveEvent(QMouseEvent *ev) override; - void mouseReleaseEvent(QMouseEvent *ev) override; + void positionsChanged(int min, int max); - - - void paintEvent(QPaintEvent *ev) override; - void initMinimumSliderStyleOption(QStyleOptionSlider *option) const; - void initMaximumSliderStyleOption(QStyleOptionSlider *option) const; + public Q_SLOTS: - - - bool event(QEvent *event) override; + void setMinimumValue(int min); -protected: - QScopedPointer d_ptr; + void setMaximumValue(int max); -private: - Q_DECLARE_PRIVATE(LtsRangeSlider) - Q_DISABLE_COPY(LtsRangeSlider) + void setValues(int min, int max); + + protected Q_SLOTS: + void onRangeChanged(int minimum, int maximum); + + protected: + LtsRangeSlider(LtsRangeSliderPrivate* impl, Qt::Orientation o, QWidget* parent = nullptr); + + void mousePressEvent(QMouseEvent* ev) override; + void mouseMoveEvent(QMouseEvent* ev) override; + void mouseReleaseEvent(QMouseEvent* ev) override; + + void paintEvent(QPaintEvent* ev) override; + void initMinimumSliderStyleOption(QStyleOptionSlider* option) const; + void initMaximumSliderStyleOption(QStyleOptionSlider* option) const; + + bool event(QEvent* event) override; + + protected: + QScopedPointer d_ptr; + + private: + Q_DECLARE_PRIVATE(LtsRangeSlider) + Q_DISABLE_COPY(LtsRangeSlider) }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp old mode 100755 new mode 100644 index ed217150e..ef995f16a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.cpp @@ -1,212 +1,180 @@ - #include "lts_selection_popup.h" -#include "ui_lts_selection_popup.h" -#include "lts_base.h" -#include +#include "lts_base.h" +#include "ui_lts_selection_popup.h" + #include #include #include - +#include #ifdef NEVER -# include -#endif - +#include +#endif namespace LtsWidgets { class RadioButton : public QRadioButton { - Q_OBJECT + Q_OBJECT -public: - explicit RadioButton(int row, const QString &text) - : QRadioButton(text) - , m_row(row) - {} + public: + explicit RadioButton(int row, const QString& text) : QRadioButton(text), m_row(row) {} - int row() const { return m_row; } + int row() const + { + return m_row; + } -signals: - void doubleClickEvent(); + signals: + void doubleClickEvent(); -private: - int m_row; + private: + int m_row; - void mouseDoubleClickEvent(QMouseEvent *) override - { - emit doubleClickEvent(); - } + void mouseDoubleClickEvent(QMouseEvent*) override + { + emit doubleClickEvent(); + } }; - - -LtsSelectionPopup::LtsSelectionPopup(QAbstractItemModel* model, - int currentIndex, - QWidget *parent) - : LtsFramelessDialog(parent, Behaviour::Popup) - , m_ui(new Ui::LtsSelectionPopup) - , m_currentIndex(currentIndex) - , m_firstIndex(currentIndex) - , m_filter(new QSortFilterProxyModel(this)) - , m_valid(false) +LtsSelectionPopup::LtsSelectionPopup(QAbstractItemModel* model, int currentIndex, QWidget* parent) + : LtsFramelessDialog(parent, Behaviour::Popup), m_ui(new Ui::LtsSelectionPopup), m_currentIndex(currentIndex), + m_firstIndex(currentIndex), m_filter(new QSortFilterProxyModel(this)), m_valid(false) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_filter->setSourceModel(model); - m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive); + m_filter->setSourceModel(model); + m_filter->setFilterCaseSensitivity(Qt::CaseInsensitive); - slotFilterChanged(); - #ifdef TABLET_MODE + slotFilterChanged(); +#ifdef TABLET_MODE m_ui->leSearch->setVisible(false); m_ui->label->setVisible(false); - #endif - connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsSelectionPopup::reject); - connect(m_ui->pbSelect, &QPushButton::clicked, this, &LtsSelectionPopup::accept); - connect(m_ui->leSearch, &QLineEdit::textEdited, - this, &LtsSelectionPopup::slotFilterChanged); +#endif + connect(m_ui->pbCancel, &QPushButton::clicked, this, &LtsSelectionPopup::reject); + connect(m_ui->pbSelect, &QPushButton::clicked, this, &LtsSelectionPopup::accept); + connect(m_ui->leSearch, &QLineEdit::textEdited, this, &LtsSelectionPopup::slotFilterChanged); - #ifdef NEVER - +#ifdef NEVER + connect(this, static_cast(&LtsSelectionPopup::currentIndexChanged), this, + [](int idx) { qCritical() << " LtsSelectionPopup: called: currentIndexChanged(int), idx=" << idx; }); + connect(this, static_cast(&LtsSelectionPopup::activated), this, + [](int idx) { qCritical() << " LtsSelectionPopup: called: activated(int), idx=" << idx; }); - - - - connect(this, static_cast(&LtsSelectionPopup::currentIndexChanged), this, [](int idx){ - qCritical() << " LtsSelectionPopup: called: currentIndexChanged(int), idx=" << idx; - }); - - - connect(this, static_cast(&LtsSelectionPopup::activated), this, [](int idx){ - qCritical() << " LtsSelectionPopup: called: activated(int), idx=" << idx; - }); - - #endif +#endif } - LtsSelectionPopup::~LtsSelectionPopup() { - delete m_ui; + delete m_ui; } - void LtsSelectionPopup::slotFilterChanged() { - m_filter->setFilterWildcard(m_ui->leSearch->text().count() ? m_ui->leSearch->text() : QStringLiteral("*") ); - refresh(); + m_filter->setFilterWildcard(m_ui->leSearch->text().count() ? m_ui->leSearch->text() : QStringLiteral("*")); + refresh(); } - void LtsSelectionPopup::refresh() { - m_valid = false; - qDeleteAll(m_ui->itemLayoutWidget->findChildren()); - QLayoutItem *tem = nullptr; - if (m_ui->itemLayoutWidget->layout()->count() > 0) - { - tem = m_ui->itemLayoutWidget->layout()->takeAt(0); - } - - int count = m_filter->rowCount(); - - for (int i = 0; i < count; i++) - { - int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); - - RadioButton *rbItem = new RadioButton(realRow, m_filter->data(m_filter->index(i, 0)).toString()); - int disable = m_filter->data(m_filter->index(i, 0), Qt::UserRole-1).toInt(); - if (disable == 1) - rbItem->setEnabled(false); - m_ui->itemLayoutWidget->layout()->addWidget(rbItem); - - if (realRow == m_currentIndex) + m_valid = false; + qDeleteAll(m_ui->itemLayoutWidget->findChildren()); + QLayoutItem* tem = nullptr; + if (m_ui->itemLayoutWidget->layout()->count() > 0) { - rbItem->setChecked(true); - m_valid = true; + tem = m_ui->itemLayoutWidget->layout()->takeAt(0); } - connect(rbItem, &RadioButton::doubleClickEvent, - this, &LtsSelectionPopup::accept); - connect(rbItem, &RadioButton::toggled, - this, [this](bool checked) + int count = m_filter->rowCount(); + + for (int i = 0; i < count; i++) { - if (checked) - m_ui->pbSelect->setEnabled(true); - }); - } - if (tem) - m_ui->itemLayoutWidget->layout()->addItem(tem); + int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); - if (count == 1) - m_valid = true; + RadioButton* rbItem = new RadioButton(realRow, m_filter->data(m_filter->index(i, 0)).toString()); + int disable = m_filter->data(m_filter->index(i, 0), Qt::UserRole - 1).toInt(); + if (disable == 1) + rbItem->setEnabled(false); + m_ui->itemLayoutWidget->layout()->addWidget(rbItem); - m_ui->pbSelect->setEnabled(m_valid); + if (realRow == m_currentIndex) + { + rbItem->setChecked(true); + m_valid = true; + } + + connect(rbItem, &RadioButton::doubleClickEvent, this, &LtsSelectionPopup::accept); + connect(rbItem, &RadioButton::toggled, this, [this](bool checked) { + if (checked) + m_ui->pbSelect->setEnabled(true); + }); + } + if (tem) + m_ui->itemLayoutWidget->layout()->addItem(tem); + + if (count == 1) + m_valid = true; + + m_ui->pbSelect->setEnabled(m_valid); } - -void LtsSelectionPopup::showEvent(QShowEvent *event) +void LtsSelectionPopup::showEvent(QShowEvent* event) { - LtsFramelessDialog::showEvent(event); - m_ui->leSearch->setFocus(); + LtsFramelessDialog::showEvent(event); + m_ui->leSearch->setFocus(); - resize(sizeHint().width() + m_ui->scrollArea->horizontalScrollBar()->height() , sizeHint().height()); + resize(sizeHint().width() + m_ui->scrollArea->horizontalScrollBar()->height(), sizeHint().height()); } - void LtsSelectionPopup::selectItem(int row, bool bCurrentIndexChanged, bool bActivated) { - - if (bCurrentIndexChanged) - emit currentIndexChanged(row); + if (bCurrentIndexChanged) + emit currentIndexChanged(row); - if (bActivated) - emit activated(row); + if (bActivated) + emit activated(row); - m_ui->pbSelect->setEnabled(true); + m_ui->pbSelect->setEnabled(true); - LtsFramelessDialog::accept(); + LtsFramelessDialog::accept(); } - void LtsSelectionPopup::accept() { - const QList items = m_ui->itemLayoutWidget->findChildren(); + const QList items = m_ui->itemLayoutWidget->findChildren(); - int count = items.count(); + int count = items.count(); - for (int i = 0; i < count; i++) - { - const RadioButton *rb = items.at(i); - - if (rb->isChecked()) + for (int i = 0; i < count; i++) { - int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); + const RadioButton* rb = items.at(i); - bool bCurrentIndexChanged = realRow != m_firstIndex; - bool bActivated = true; - selectItem(realRow, bCurrentIndexChanged, bActivated); - return; + if (rb->isChecked()) + { + int realRow = m_filter->mapToSource(m_filter->index(i, 0)).row(); + + bool bCurrentIndexChanged = realRow != m_firstIndex; + bool bActivated = true; + selectItem(realRow, bCurrentIndexChanged, bActivated); + return; + } } - } - - if (count == 1) - { - const RadioButton *rb = items.at(0); - selectItem(rb->row(), true, true); - return; - } - + if (count == 1) + { + const RadioButton* rb = items.at(0); + selectItem(rb->row(), true, true); + return; + } } -} +} // namespace LtsWidgets #include "lts_selection_popup.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h old mode 100755 new mode 100644 index e9128b524..7809bfac6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_selection_popup.h @@ -1,12 +1,10 @@ - #pragma once -#include - #include "lts_frameless_dialog.h" #include "ltswidgets_export.h" +#include namespace Ui { @@ -19,66 +17,38 @@ class QSortFilterProxyModel; namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsSelectionPopup : public LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - + public: + LtsSelectionPopup(QAbstractItemModel* model, int currentIndex, QWidget* parent = nullptr); + ~LtsSelectionPopup(); - LtsSelectionPopup(QAbstractItemModel *model, - int currentIndex, - QWidget *parent = nullptr); - ~LtsSelectionPopup(); + protected: + void showEvent(QShowEvent* event) override; -protected: - + private: + Ui::LtsSelectionPopup* m_ui; + int m_currentIndex; + int m_firstIndex; + QSortFilterProxyModel* m_filter; + bool m_valid; - void showEvent(QShowEvent *event) override; + void refresh(); -private: - Ui::LtsSelectionPopup *m_ui; - int m_currentIndex; - int m_firstIndex; - QSortFilterProxyModel *m_filter; - bool m_valid; + void selectItem(int row, bool bCurrentIndexChanged, bool bActivated); - + signals: - void refresh(); + void activated(int index); - + void currentIndexChanged(int index); - void selectItem(int row, bool bCurrentIndexChanged, bool bActivated); + public slots: -signals: - - - - - - - - - - - - void activated(int index); - - - - void currentIndexChanged(int index); - -public slots: - - - void accept() override; - - - - void slotFilterChanged(); + void accept() override; + void slotFilterChanged(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp old mode 100755 new mode 100644 index d24161285..4c5bba931 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.cpp @@ -1,6 +1,5 @@ - #include "lts_spinbox.h" #include @@ -8,166 +7,155 @@ namespace LtsWidgets { -LtsSpinBox::LtsSpinBox(QWidget *parent) - : QSpinBox(parent) +LtsSpinBox::LtsSpinBox(QWidget* parent) : QSpinBox(parent) {} + +QValidator::State LtsSpinBox::validate(QString& input, int& pos) const { -} - -QValidator::State LtsSpinBox::validate(QString &input, int &pos) const -{ - QIntValidator validator; - for (auto range : m_validRanges) - { - validator.setBottom(range.first); - validator.setTop(range.second); - QValidator::State state = validator.validate(input, pos); - if (state == QValidator::Invalid || - state == QValidator::Intermediate) - return state; - } - - - int value = input.toInt(); - value -= minimum(); - return (value % singleStep() == 0) ? QValidator::Acceptable : QValidator::Intermediate; -} - -void LtsSpinBox::fixup(QString &str) const -{ - QSpinBox::fixup(str); - - if (singleStep() == 1) - return; - - bool bOk; - int value = str.toInt(&bOk); - if (!bOk) - return; - - int remainder = (value - minimum()) % singleStep(); - - if (2 * remainder > singleStep()) - value += singleStep(); - - value -= remainder; - - if (value > maximum()) - value -= singleStep(); - - str = QString::number(value); -} - -bool LtsSpinBox::setExclusionRanges(const QVector > &exclusionRanges, bool preserveCurrentValues) -{ - bool retVal = true; - - auto newExclusions = exclusionRanges; - - if (preserveCurrentValues) - newExclusions += m_exclusions; - - for (auto &elem : newExclusions) - { - if (elem.first > elem.second) + QIntValidator validator; + for (auto range : m_validRanges) { - int tmp = elem.first; - elem.first= elem.second; - elem.second = tmp; + validator.setBottom(range.first); + validator.setTop(range.second); + QValidator::State state = validator.validate(input, pos); + if (state == QValidator::Invalid || state == QValidator::Intermediate) + return state; } - } - - std::sort(newExclusions.begin(), newExclusions.end(), [](const QPair &a, const QPair &b) { return a.first < b.first; }); - for (int i=0; i= newExclusions[i+1].first) + + int value = input.toInt(); + value -= minimum(); + return (value % singleStep() == 0) ? QValidator::Acceptable : QValidator::Intermediate; +} + +void LtsSpinBox::fixup(QString& str) const +{ + QSpinBox::fixup(str); + + if (singleStep() == 1) + return; + + bool bOk; + int value = str.toInt(&bOk); + if (!bOk) + return; + + int remainder = (value - minimum()) % singleStep(); + + if (2 * remainder > singleStep()) + value += singleStep(); + + value -= remainder; + + if (value > maximum()) + value -= singleStep(); + + str = QString::number(value); +} + +bool LtsSpinBox::setExclusionRanges(const QVector>& exclusionRanges, bool preserveCurrentValues) +{ + bool retVal = true; + + auto newExclusions = exclusionRanges; + + if (preserveCurrentValues) + newExclusions += m_exclusions; + + for (auto& elem : newExclusions) { - retVal = false; - break; + if (elem.first > elem.second) + { + int tmp = elem.first; + elem.first = elem.second; + elem.second = tmp; + } } - } - - if (!retVal || newExclusions[0].first <= minimum() || newExclusions[newExclusions.size()-1].second >= maximum()) - { - - if (!preserveCurrentValues) - m_exclusions.clear(); - return false; - } - - m_exclusions = exclusionRanges; - - m_validRanges.clear(); - if (m_exclusions[0].first - 1 > minimum()) - m_validRanges.append({minimum(), m_exclusions[0].first - 1}); - for (int i=0; i& a, const QPair& b) { return a.first < b.first; }); + for (int i = 0; i < newExclusions.size() - 1; ++i) + { - return true; + if (newExclusions[i].second >= newExclusions[i + 1].first) + { + retVal = false; + break; + } + } + + if (!retVal || newExclusions[0].first <= minimum() || newExclusions[newExclusions.size() - 1].second >= maximum()) + { + + if (!preserveCurrentValues) + m_exclusions.clear(); + return false; + } + + m_exclusions = exclusionRanges; + + m_validRanges.clear(); + if (m_exclusions[0].first - 1 > minimum()) + m_validRanges.append({minimum(), m_exclusions[0].first - 1}); + for (int i = 0; i < m_exclusions.size() - 1; ++i) + { + + if (m_exclusions[i].second + 1 < m_exclusions[i + 1].first - 1) + m_validRanges.append({m_exclusions[i].second + 1, m_exclusions[i + 1].first - 1}); + } + if (m_exclusions[m_exclusions.size() - 1].second + 1 < maximum()) + m_validRanges.append({m_exclusions[0].first - 1, maximum()}); + + return true; } bool LtsSpinBox::addExclusionRange(int min, int max) { - return setExclusionRanges({{min, max}}, true); + return setExclusionRanges({{min, max}}, true); } void LtsSpinBox::clearExclusionRanges() { - m_exclusions.clear(); + m_exclusions.clear(); } +LtsDoubleSpinBox::LtsDoubleSpinBox(QWidget* parent) : QDoubleSpinBox(parent) {} -LtsDoubleSpinBox::LtsDoubleSpinBox(QWidget *parent) - : QDoubleSpinBox(parent) +QValidator::State LtsDoubleSpinBox::validate(QString& input, int& pos) const { + QDoubleValidator validator; + validator.setBottom(minimum()); + validator.setTop(maximum()); + QValidator::State state = validator.validate(input, pos); + if (state == QValidator::Invalid || state == QValidator::Intermediate) + return state; + + double value = input.toDouble(); + value -= minimum(); + return qFuzzyCompare(std::fmod(value, singleStep()), 0.0) ? QValidator::Acceptable : QValidator::Intermediate; } -QValidator::State LtsDoubleSpinBox::validate(QString &input, int &pos) const +void LtsDoubleSpinBox::fixup(QString& str) const { - QDoubleValidator validator; - validator.setBottom(minimum()); - validator.setTop(maximum()); - QValidator::State state = validator.validate(input, pos); - if (state == QValidator::Invalid || - state == QValidator::Intermediate) - return state; + QDoubleSpinBox::fixup(str); - - double value = input.toDouble(); - value -= minimum(); - return qFuzzyCompare(std::fmod(value, singleStep()), 0.0) ? QValidator::Acceptable : QValidator::Intermediate; + if (qFuzzyCompare(singleStep(), pow(10, decimals()))) + return; + + bool bOk; + double value = str.toDouble(&bOk); + if (!bOk) + return; + + double remainder = std::fmod(value - minimum(), singleStep()); + + if (2 * remainder > singleStep()) + value += singleStep(); + + value -= remainder; + + if (value > maximum()) + value -= singleStep(); + + str = QString::number(value, 'f', decimals()); } -void LtsDoubleSpinBox::fixup(QString &str) const -{ - QDoubleSpinBox::fixup(str); - - if (qFuzzyCompare(singleStep(), pow(10, decimals()))) - return; - - bool bOk; - double value = str.toDouble(&bOk); - if (!bOk) - return; - - double remainder = std::fmod(value - minimum(), singleStep()); - - if (2 * remainder > singleStep()) - value += singleStep(); - - value -= remainder; - - if (value > maximum()) - value -= singleStep(); - - str = QString::number(value, 'f', decimals()); -} - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h old mode 100755 new mode 100644 index ce07d7771..c3b916eee --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_spinbox.h @@ -1,11 +1,9 @@ - #pragma once -#include - #include "ltswidgets_export.h" +#include #include namespace LtsWidgets @@ -13,49 +11,62 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsSpinBox : public QSpinBox { - Q_OBJECT + Q_OBJECT -public: - explicit LtsSpinBox(QWidget *parent = nullptr); - ~LtsSpinBox() = default; + public: + explicit LtsSpinBox(QWidget* parent = nullptr); + ~LtsSpinBox() = default; -public slots: - void setValue(int val) { QString valStr = QString::number(val); fixup(valStr); QSpinBox::setValue(valStr.toInt()); } - bool setExclusionRanges(const QVector > &exclusionRanges, bool preserveCurrentValues = false); - bool addExclusionRange(int min, int max); - void clearExclusionRanges(); + public slots: -protected: - QValidator::State validate(QString &input, int &pos) const override; - void fixup(QString &str) const override; + void setValue(int val) + { + QString valStr = QString::number(val); + fixup(valStr); + QSpinBox::setValue(valStr.toInt()); + } -private: + bool setExclusionRanges(const QVector>& exclusionRanges, bool preserveCurrentValues = false); + bool addExclusionRange(int min, int max); + void clearExclusionRanges(); - struct - { - bool operator()(const QPair &a, const QPair &b) const { return a.first < b.first; } - } customless; + protected: + QValidator::State validate(QString& input, int& pos) const override; + void fixup(QString& str) const override; - QVector > m_exclusions; - QVector > m_validRanges; + private: + struct + { + bool operator()(const QPair& a, const QPair& b) const + { + return a.first < b.first; + } + } customless; + QVector> m_exclusions; + QVector> m_validRanges; }; class LTSWIDGETS_EXPORT LtsDoubleSpinBox : public QDoubleSpinBox { - Q_OBJECT + Q_OBJECT -public: - explicit LtsDoubleSpinBox(QWidget *parent = nullptr); - ~LtsDoubleSpinBox() = default; + public: + explicit LtsDoubleSpinBox(QWidget* parent = nullptr); + ~LtsDoubleSpinBox() = default; -public slots: - void setValue(double val) { QString valStr = QString::number(val); fixup(valStr); QDoubleSpinBox::setValue(valStr.toDouble()); } + public slots: -protected: - QValidator::State validate(QString &input, int &pos) const override; - void fixup(QString &str) const override; + void setValue(double val) + { + QString valStr = QString::number(val); + fixup(valStr); + QDoubleSpinBox::setValue(valStr.toDouble()); + } + protected: + QValidator::State validate(QString& input, int& pos) const override; + void fixup(QString& str) const override; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp old mode 100755 new mode 100644 index 341549ab0..5ff73af96 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.cpp @@ -1,81 +1,71 @@ #include "lts_splash.h" #include - #include -#include #include - +#include namespace LtsWidgets { -Splash::Splash() - : QSplashScreen() - , m_done(false) +Splash::Splash() : QSplashScreen(), m_done(false) { - static const auto splashFiles = - { - QStringLiteral(":/project/splash.png"), - QStringLiteral(":/project/splash.jpg"), - }; - for (const QString &f : splashFiles) - { - if (!QFile::exists(f)) - continue; - setPixmap(QPixmap(f)); - break; - } + static const auto splashFiles = { + QStringLiteral(":/project/splash.png"), + QStringLiteral(":/project/splash.jpg"), + }; + for (const QString& f : splashFiles) + { + if (!QFile::exists(f)) + continue; + setPixmap(QPixmap(f)); + break; + } } - -bool Splash::event(QEvent *e) +bool Splash::event(QEvent* e) { - if (e->type() == QEvent::MouseButtonPress || - e->type() == QEvent::MouseButtonRelease || - e->type() == QEvent::MouseButtonDblClick) - { - e->ignore(); - return false; - } + if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease || + e->type() == QEvent::MouseButtonDblClick) + { + e->ignore(); + return false; + } - return QSplashScreen::event(e); + return QSplashScreen::event(e); } - -void Splash::setMessage(const QString &message) +void Splash::setMessage(const QString& message) { - showMessage(message, Qt::AlignRight | Qt::AlignBottom); + showMessage(message, Qt::AlignRight | Qt::AlignBottom); } - void Splash::done() { - if (m_done) - return; - m_done = true; + if (m_done) + return; + m_done = true; - hide(); - LtsWidgets::LtsGlobalWaitDialog::getInstance()->setVisible(true); + hide(); + LtsWidgets::LtsGlobalWaitDialog::getInstance()->setVisible(true); } +static Splash* s_splashInstance = nullptr; -static Splash *s_splashInstance = nullptr; void Splash::cleanupSplashInstance() { - delete s_splashInstance; - s_splashInstance = nullptr; + delete s_splashInstance; + s_splashInstance = nullptr; } - -Splash *Splash::getInstance() +Splash* Splash::getInstance() { - if (!s_splashInstance) - { - s_splashInstance = new Splash; - qAddPostRoutine(&Splash::cleanupSplashInstance); - } - return s_splashInstance; + if (!s_splashInstance) + { + s_splashInstance = new Splash; + qAddPostRoutine(&Splash::cleanupSplashInstance); + } + return s_splashInstance; } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h old mode 100755 new mode 100644 index 32442e9d3..0023770b8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splash.h @@ -2,27 +2,26 @@ #include "ltswidgets_export.h" -#include #include - +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT Splash : public QSplashScreen { - Q_OBJECT -public: - static Splash* getInstance(); + Q_OBJECT + public: + static Splash* getInstance(); - void done(); - void setMessage(const QString &message); + void done(); + void setMessage(const QString& message); -private: - Splash(); - static void cleanupSplashInstance(); + private: + Splash(); + static void cleanupSplashInstance(); - bool event(QEvent *e) override; + bool event(QEvent* e) override; - bool m_done; + bool m_done; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp old mode 100755 new mode 100644 index 46b740cd4..05ed7374c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.cpp @@ -1,57 +1,53 @@ - #include "lts_splitter.h" -#include "lts_splitter_handle.h" +#include "lts_splitter_handle.h" namespace LtsWidgets { -LtsSplitter::LtsSplitter(QWidget *parent) - : QSplitter(parent) +LtsSplitter::LtsSplitter(QWidget* parent) : QSplitter(parent) { - connect(this, &LtsSplitter::sizesChanged, this, &LtsSplitter::changeSizes); + connect(this, &LtsSplitter::sizesChanged, this, &LtsSplitter::changeSizes); } -LtsSplitter::~LtsSplitter() -{ -} +LtsSplitter::~LtsSplitter() {} -QSplitterHandle *LtsSplitter::createHandle() +QSplitterHandle* LtsSplitter::createHandle() { - LtsSplitterHandle *hand = new LtsSplitterHandle(orientation(), this); + LtsSplitterHandle* hand = new LtsSplitterHandle(orientation(), this); #ifdef TABLET_MODE - setHandleWidth(25); + setHandleWidth(25); #else - setHandleWidth(10); + setHandleWidth(10); #endif - return hand; + return hand; } void LtsSplitter::collapseChild(const int index) { - if (children().size() > index) - { - QWidget *widget = static_cast(children().at(index)); - if (widget) + if (children().size() > index) { - QList s = sizes(); - s[index] = 0; - setSizes(s); + QWidget* widget = static_cast(children().at(index)); + if (widget) + { + QList s = sizes(); + s[index] = 0; + setSizes(s); + } } - } } void LtsSplitter::animate(int handleId) { - LtsSplitterHandle *handle = dynamic_cast(this->handle(handleId)); - handle->animate(); + LtsSplitterHandle* handle = dynamic_cast(this->handle(handleId)); + handle->animate(); } -void LtsSplitter::changeSizes(const QList &list) +void LtsSplitter::changeSizes(const QList& list) { - QSplitter::setSizes(list); + QSplitter::setSizes(list); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h old mode 100755 new mode 100644 index c03becbc9..a75305dab --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter.h @@ -1,38 +1,40 @@ - #pragma once -#include - #include "lts_base.h" #include "ltswidgets_export.h" -#include #include - +#include +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsSplitter : public QSplitter { - Q_OBJECT - Q_PROPERTY(QList sizes READ getSizes WRITE setSizes NOTIFY sizesChanged) + Q_OBJECT + Q_PROPERTY(QList sizes READ getSizes WRITE setSizes NOTIFY sizesChanged) -public: - explicit LtsSplitter(QWidget *parent = nullptr); - ~LtsSplitter(); + public: + explicit LtsSplitter(QWidget* parent = nullptr); + ~LtsSplitter(); - QSplitterHandle *createHandle(); - void collapseChild(const int index); - QList getSizes() const { return sizes(); } - void animate(int handleId); + QSplitterHandle* createHandle(); + void collapseChild(const int index); -signals: - void sizesChanged(const QList &newSizes); + QList getSizes() const + { + return sizes(); + } -public slots: - void changeSizes(const QList &list); + void animate(int handleId); + + signals: + void sizesChanged(const QList& newSizes); + + public slots: + void changeSizes(const QList& list); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp old mode 100755 new mode 100644 index 7ddda8f6d..5f8a0186b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.cpp @@ -1,87 +1,83 @@ - #include "lts_splitter_handle.h" -#include -#include + #include +#include #include #include -#include - +#include +#include namespace LtsWidgets { -LtsSplitterHandle::LtsSplitterHandle(Qt::Orientation orientation, QSplitter *parent) - : QSplitterHandle(orientation, parent) +LtsSplitterHandle::LtsSplitterHandle(Qt::Orientation orientation, QSplitter* parent) + : QSplitterHandle(orientation, parent) { - auto bgrole = backgroundRole(); - QPalette p = palette(); - m_endColor = p.color(bgrole); - - m_colorAnimation = new QPropertyAnimation(this, "splittercolor"); - m_colorAnimation->setDuration(1000); - m_colorAnimation->setStartValue(m_currentColor); - m_colorAnimation->setEndValue(m_endColor); - m_colorAnimation->setLoopCount(2); - connect(m_colorAnimation, &QPropertyAnimation::finished, this, [this]{ - m_animate = false; - m_currentColor = m_endColor; - repaint(); - }); + auto bgrole = backgroundRole(); + QPalette p = palette(); + m_endColor = p.color(bgrole); + m_colorAnimation = new QPropertyAnimation(this, "splittercolor"); + m_colorAnimation->setDuration(1000); + m_colorAnimation->setStartValue(m_currentColor); + m_colorAnimation->setEndValue(m_endColor); + m_colorAnimation->setLoopCount(2); + connect(m_colorAnimation, &QPropertyAnimation::finished, this, [this] { + m_animate = false; + m_currentColor = m_endColor; + repaint(); + }); } -LtsSplitterHandle::~LtsSplitterHandle() -{ -} +LtsSplitterHandle::~LtsSplitterHandle() {} -void LtsSplitterHandle::paintEvent(QPaintEvent *event) +void LtsSplitterHandle::paintEvent(QPaintEvent* event) { - if(!m_animate) - { - QSplitterHandle::paintEvent(event); - return; - } - QPainter painter(this); - QLinearGradient gradient; - gradient.setColorAt(0, m_currentColor); - + if (!m_animate) + { + QSplitterHandle::paintEvent(event); + return; + } + QPainter painter(this); + QLinearGradient gradient; + gradient.setColorAt(0, m_currentColor); - if(orientation() == Qt::Horizontal) - { - gradient.setStart(rect().left(), rect().height()/2); - gradient.setFinalStop(rect().height(), rect().height()/2); - }else - { - gradient.setStart(rect().width()/2, rect().top()); - gradient.setFinalStop(rect().width()/2, rect().bottom()/2); - } - painter.fillRect(event->rect(), QBrush(gradient)); + if (orientation() == Qt::Horizontal) + { + gradient.setStart(rect().left(), rect().height() / 2); + gradient.setFinalStop(rect().height(), rect().height() / 2); + } + else + { + gradient.setStart(rect().width() / 2, rect().top()); + gradient.setFinalStop(rect().width() / 2, rect().bottom() / 2); + } + painter.fillRect(event->rect(), QBrush(gradient)); } void LtsSplitterHandle::animate() { - if (m_colorAnimation->state() == QPropertyAnimation::Running) - return; + if (m_colorAnimation->state() == QPropertyAnimation::Running) + return; - m_currentColor = QColor(239,87,50); - m_animate = true; - m_colorAnimation->start(); + m_currentColor = QColor(239, 87, 50); + m_animate = true; + m_colorAnimation->start(); } QColor LtsSplitterHandle::splitterColor() const { - return m_currentColor; + return m_currentColor; } -void LtsSplitterHandle::setCurrentColor(const QColor ¤tcolor) +void LtsSplitterHandle::setCurrentColor(const QColor& currentcolor) { - if (currentcolor == m_currentColor) - return; - m_currentColor = currentcolor; - repaint(); + if (currentcolor == m_currentColor) + return; + m_currentColor = currentcolor; + repaint(); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h old mode 100755 new mode 100644 index 8c4e32263..48188df69 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_splitter_handle.h @@ -1,40 +1,37 @@ - #pragma once -#include - #include "lts_base.h" #include "ltswidgets_export.h" -#include #include +#include #include +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsSplitterHandle : public QSplitterHandle { - Q_OBJECT - Q_PROPERTY(QColor splittercolor READ splitterColor WRITE setCurrentColor DESIGNABLE false) + Q_OBJECT + Q_PROPERTY(QColor splittercolor READ splitterColor WRITE setCurrentColor DESIGNABLE false) -public: - explicit LtsSplitterHandle(Qt::Orientation orientation, QSplitter *parent = nullptr); - ~LtsSplitterHandle(); + public: + explicit LtsSplitterHandle(Qt::Orientation orientation, QSplitter* parent = nullptr); + ~LtsSplitterHandle(); - void paintEvent(QPaintEvent *event) override; - void animate(); + void paintEvent(QPaintEvent* event) override; + void animate(); - QColor splitterColor() const; - void setCurrentColor(const QColor ¤tcolor); - -private: - bool m_animate {false}; - QColor m_endColor {Qt::black}; - QColor m_currentColor{QColor(239,87,50)}; - QPropertyAnimation *m_colorAnimation; + QColor splitterColor() const; + void setCurrentColor(const QColor& currentcolor); + private: + bool m_animate{false}; + QColor m_endColor{Qt::black}; + QColor m_currentColor{QColor(239, 87, 50)}; + QPropertyAnimation* m_colorAnimation; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp old mode 100755 new mode 100644 index 19663a74e..f76e1a82c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.cpp @@ -1,6 +1,5 @@ - #include "lts_tab_bar.h" #include "lts_dialog.h" @@ -8,113 +7,108 @@ #include "lts_events.h" #include "lts_tab_widget.h" -#include #include #include +#include namespace LtsWidgets { -LtsTabBar::LtsTabBar(bool isSecondary, QWidget *parent) - : QTabBar(parent) - , m_secondary(isSecondary) +LtsTabBar::LtsTabBar(bool isSecondary, QWidget* parent) : QTabBar(parent), m_secondary(isSecondary) { - setDocumentMode(true); - setTabsClosable(true); + setDocumentMode(true); + setTabsClosable(true); - connect(this, &LtsTabBar::currentChanged, this, &LtsTabBar::updateCloseButtonColors); + connect(this, &LtsTabBar::currentChanged, this, &LtsTabBar::updateCloseButtonColors); - if (m_secondary) - { - connect(this, &LtsTabBar::customContextMenuRequested, - this, &LtsTabBar::onCustomContextMenuRequested); - setContextMenuPolicy(Qt::CustomContextMenu); - } + if (m_secondary) + { + connect(this, &LtsTabBar::customContextMenuRequested, this, &LtsTabBar::onCustomContextMenuRequested); + setContextMenuPolicy(Qt::CustomContextMenu); + } } - -void LtsTabBar::_internal_closeTab() +void LtsTabBar::_internal_closeTab() { - QObject *object = sender(); - int tabToClose = -1; + QObject* object = sender(); + int tabToClose = -1; - for (int i = 0; i < count(); i++) - { - if (tabButton(i, QTabBar::RightSide) == object) + for (int i = 0; i < count(); i++) { - tabToClose = i; - break; + if (tabButton(i, QTabBar::RightSide) == object) + { + tabToClose = i; + break; + } } - } - if (tabToClose != -1) - emit tabCloseRequested(tabToClose); + if (tabToClose != -1) + emit tabCloseRequested(tabToClose); } - -void LtsTabBar::updateCloseButtonColors(int newIndex) +void LtsTabBar::updateCloseButtonColors(int newIndex) { - - if (newIndex == -1) - newIndex = currentIndex(); - for (int i = 0; i < count(); i++) - { - QWidget *w = tabButton(i, QTabBar::RightSide); - CloseButton *cb = qobject_cast(w); + if (newIndex == -1) + newIndex = currentIndex(); - if (!cb) - continue; - - QColor text; - - bool enabled = isTabEnabled(i); - bool selected = (i == newIndex); - bool secondary = m_secondary; - - if (enabled) + for (int i = 0; i < count(); i++) { - if (selected) - text = (secondary) ? Styles::TabBarTabStyle::secondarySelected : Styles::TabBarTabStyle::primarySelected; - else - text = (secondary) ? Styles::TabBarTabStyle::secondaryNormal : Styles::TabBarTabStyle::primaryNormal; - } - else - text = (secondary) ? Styles::TabBarTabStyle::secondaryDisabled : Styles::TabBarTabStyle::primaryDisabled; + QWidget* w = tabButton(i, QTabBar::RightSide); + CloseButton* cb = qobject_cast(w); - - cb->setFontColor(text); - } + if (!cb) + continue; + + QColor text; + + bool enabled = isTabEnabled(i); + bool selected = (i == newIndex); + bool secondary = m_secondary; + + if (enabled) + { + if (selected) + text = + (secondary) ? Styles::TabBarTabStyle::secondarySelected : Styles::TabBarTabStyle::primarySelected; + else + text = (secondary) ? Styles::TabBarTabStyle::secondaryNormal : Styles::TabBarTabStyle::primaryNormal; + } + else + text = (secondary) ? Styles::TabBarTabStyle::secondaryDisabled : Styles::TabBarTabStyle::primaryDisabled; + + cb->setFontColor(text); + } } void LtsTabBar::onCustomContextMenuRequested(const QPoint pos) { - if (!m_secondary) - return; - QMenu m; - QAction *a = new QAction(tr("Save as image")); - connect(a, &QAction::triggered, this, [this, pos]() { LtsTabBar::onSaveCurrentWidgetAsImage(pos); }); - m.addAction(a); - m.exec(mapToGlobal(pos)); + if (!m_secondary) + return; + QMenu m; + QAction* a = new QAction(tr("Save as image")); + connect(a, &QAction::triggered, this, [this, pos]() { LtsTabBar::onSaveCurrentWidgetAsImage(pos); }); + m.addAction(a); + m.exec(mapToGlobal(pos)); } void LtsTabBar::onSaveCurrentWidgetAsImage(const QPoint pos) { - int curTab = tabAt(pos); - if (curTab < 0) - curTab = currentIndex(); - if (curTab < 0) - return; - LtsTabWidget *tw = qobject_cast(parentWidget()); - QWidget *w = tw ? tw->widget(curTab) : nullptr; - if (!w) - return; - LtsDialogHelper *helper = qobject_cast(w); - if (helper) - w = helper->getDialog(); - SaveImageEvent *ev = new SaveImageEvent(w, w->grab()); - ev->setAccepted(false); - QCoreApplication::postEvent(qApp, ev); + int curTab = tabAt(pos); + if (curTab < 0) + curTab = currentIndex(); + if (curTab < 0) + return; + LtsTabWidget* tw = qobject_cast(parentWidget()); + QWidget* w = tw ? tw->widget(curTab) : nullptr; + if (!w) + return; + LtsDialogHelper* helper = qobject_cast(w); + if (helper) + w = helper->getDialog(); + SaveImageEvent* ev = new SaveImageEvent(w, w->grab()); + ev->setAccepted(false); + QCoreApplication::postEvent(qApp, ev); } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h old mode 100755 new mode 100644 index 1107b848a..5e2e7d7c4 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_bar.h @@ -1,40 +1,33 @@ - #pragma once -#include - -#include #include "ltswidgets_export.h" +#include +#include + namespace LtsWidgets { - - class LTSWIDGETS_EXPORT LtsTabBar : public QTabBar { - Q_OBJECT - Q_PROPERTY(bool secondary MEMBER m_secondary) + Q_OBJECT + Q_PROPERTY(bool secondary MEMBER m_secondary) -public: - + public: + explicit LtsTabBar(bool isSecondary = false, QWidget* parent = nullptr); - explicit LtsTabBar(bool isSecondary = false, QWidget *parent = nullptr); + void _internal_closeTab(); - + protected: + void onCustomContextMenuRequested(const QPoint pos); + void onSaveCurrentWidgetAsImage(const QPoint pos); - void _internal_closeTab(); - -protected: - void onCustomContextMenuRequested(const QPoint pos); - void onSaveCurrentWidgetAsImage(const QPoint pos); -private: - bool m_secondary; - -public slots: - void updateCloseButtonColors(int newIndex = -1); + private: + bool m_secondary; + public slots: + void updateCloseButtonColors(int newIndex = -1); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp old mode 100755 new mode 100644 index 06705f39c..c67681602 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.cpp @@ -2,58 +2,58 @@ #include "lts_tab_sequence_widget.h" +#include #include #include #include -#include namespace LtsWidgets { -LtsTabSequenceWidget::LtsTabSequenceWidget(QWidget *parent) - : LtsAbstractSequenceWidget(parent) - , m_twSequences(new QTabWidget(this)) +LtsTabSequenceWidget::LtsTabSequenceWidget(QWidget* parent) + : LtsAbstractSequenceWidget(parent), m_twSequences(new QTabWidget(this)) { - QHBoxLayout *gridLayout = new QHBoxLayout(this); - gridLayout->addWidget(m_twSequences); - gridLayout->addWidget(pbAddMember(), Qt::AlignTop); + QHBoxLayout* gridLayout = new QHBoxLayout(this); + gridLayout->addWidget(m_twSequences); + gridLayout->addWidget(pbAddMember(), Qt::AlignTop); - m_twSequences->setCornerWidget(pbAddMember()); - pbAddMember()->setFixedSize(m_twSequences->tabBar()->size()); - pbAddMember()->setIconSize(m_twSequences->tabBar()->size()); + m_twSequences->setCornerWidget(pbAddMember()); + pbAddMember()->setFixedSize(m_twSequences->tabBar()->size()); + pbAddMember()->setIconSize(m_twSequences->tabBar()->size()); } LtsTabSequenceWidget::~LtsTabSequenceWidget() { - delete pbAddMember(); - delete m_twSequences; + delete pbAddMember(); + delete m_twSequences; } -void LtsTabSequenceWidget::setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible) +void LtsTabSequenceWidget::setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, + bool isButtonVisible) { - int index = m_twSequences->addTab(child, objectName); - if(isButtonVisible) - m_twSequences->tabBar()->setTabButton(index, QTabBar::RightSide, pbChild); + int index = m_twSequences->addTab(child, objectName); + if (isButtonVisible) + m_twSequences->tabBar()->setTabButton(index, QTabBar::RightSide, pbChild); } QWidget* LtsTabSequenceWidget::getWidget(int index) { - return m_twSequences->widget(index); + return m_twSequences->widget(index); } QWidget* LtsTabSequenceWidget::getCurrentWidget() { - return m_twSequences->currentWidget(); + return m_twSequences->currentWidget(); } int LtsTabSequenceWidget::getCurrentTabIndex() { - return m_twSequences->currentIndex(); + return m_twSequences->currentIndex(); } -void LtsTabSequenceWidget::changeTabName(const QString &name) + +void LtsTabSequenceWidget::changeTabName(const QString& name) { - m_twSequences->setTabText(m_twSequences->currentIndex(), name); + m_twSequences->setTabText(m_twSequences->currentIndex(), name); } - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h old mode 100755 new mode 100644 index 68f9b1e56..a9c68e0ce --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_sequence_widget.h @@ -4,35 +4,36 @@ #define LTS_TAB_SEQUENCE_WIDGET_H #pragma once -#include - #include "lts_abstract_sequence_widget.h" #include "ltswidgets_export.h" +#include + class QTabWidget; namespace LtsWidgets { - class LTSWIDGETS_EXPORT LtsTabSequenceWidget : public LtsAbstractSequenceWidget - { +class LTSWIDGETS_EXPORT LtsTabSequenceWidget : public LtsAbstractSequenceWidget +{ Q_OBJECT public: - LtsTabSequenceWidget(QWidget *parent = nullptr); + LtsTabSequenceWidget(QWidget* parent = nullptr); virtual ~LtsTabSequenceWidget(); QWidget* getWidget(int index); QWidget* getCurrentWidget(); int getCurrentTabIndex(); - void changeTabName(const QString &name); + void changeTabName(const QString& name); protected: - void setupMemberWidget(QWidget *child, QToolButton *pbChild, const QString &objectName, bool isButtonVisible = true) override; + void setupMemberWidget(QWidget* child, QToolButton* pbChild, const QString& objectName, + bool isButtonVisible = true) override; private: - QTabWidget *m_twSequences = nullptr; - }; -} + QTabWidget* m_twSequences = nullptr; +}; +} // namespace LtsWidgets -#endif +#endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h old mode 100755 new mode 100644 index 7df6cbd49..f98ee902e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tab_widget.h @@ -1,164 +1,113 @@ - #pragma once -#include - #include "lts_base.h" #include "ltswidgets_export.h" -#include -#include #include - +#include +#include +#include namespace LtsWidgets { class LtsDialogHelper; class LtsTabBar; - - class LTSWIDGETS_EXPORT LtsTabWidget : public QTabWidget { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit LtsTabWidget(QWidget* parent = nullptr, bool isSecondary = false); + ~LtsTabWidget(); - explicit LtsTabWidget(QWidget *parent = nullptr, bool isSecondary = false); - ~LtsTabWidget(); + void setActuatorTabStyle(bool enable); - + void clearAll(); - void setActuatorTabStyle(bool enable); + void aboutToClose(); - + LtsTabBar* tabBar(); - void clearAll(); + void setTabBar(LtsTabBar* tabbar); + bool focusTab(const QString& menuGroup, const QString& identifier); - void aboutToClose(); + void setSubTabsVisible(bool visible); - + QWidget* getWidget(const QString& menuGroup, const QString& identifier); - LtsTabBar *tabBar(); + static bool hasUnsavedChanges(LtsTabWidget* tabWidget); - + signals: - void setTabBar(LtsTabBar *tabbar); + void signalCheckTabBarVisibility(); - + public slots: - bool focusTab(const QString &menuGroup, const QString &identifier); + void addTab(const QString& menuGroup, const QString& identifier, QWidget* widget, bool setClosable = true, + bool focusNewTab = true); - + bool removeWidget(QWidget* widget); - void setSubTabsVisible(bool visible); + private slots: - + void onRemoveTab(QObject* object); - QWidget *getWidget(const QString &menuGroup, const QString &identifier); + void onCheckTabBarVisibility(); - + void slotTabCloseRequested(int index); - static bool hasUnsavedChanges(LtsTabWidget *tabWidget); + void slotCurrentChanged(int newIdx); + void slotMaximizeButtonClicked(); + private: + void addWidget(const QString& fullName, QWidget* widget, bool setClosable, bool focusNewTab = true); -signals: - + QWidget* getWidget(const QString& fullName); - void signalCheckTabBarVisibility(); + bool focusWidget(const QString& fullName); + void slotWindowTitleChanged(const QString& title); -public slots: - + void closeRequestTabWidget(LtsTabWidget* tabWidget); - void addTab(const QString &menuGroup, const QString &identifier, QWidget *widget, - bool setClosable = true, bool focusNewTab = true); + QPoint startPos; + LtsTabBar* m_tabbar = nullptr; + QPalette m_palette; - + QMap m_tabMap; - bool removeWidget(QWidget * widget); + bool m_hasSubTabs; + bool m_isSecondary; -private slots: - - - - - - - - - - - void onRemoveTab(QObject *object); - - - - void onCheckTabBarVisibility(); - - - - void slotTabCloseRequested(int index); - - void slotCurrentChanged(int newIdx); - - void slotMaximizeButtonClicked(); - -private: - - - void addWidget(const QString &fullName, QWidget *widget, bool setClosable, bool focusNewTab = true); - - - - QWidget *getWidget(const QString &fullName); - - - - bool focusWidget(const QString &fullName); - - - - void slotWindowTitleChanged(const QString &title); - - void closeRequestTabWidget(LtsTabWidget *tabWidget); - - QPoint startPos; - LtsTabBar *m_tabbar = nullptr; - QPalette m_palette; - - - QMap m_tabMap; - - - bool m_hasSubTabs; - bool m_isSecondary; - - QByteArray m_mainSplitterState; + QByteArray m_mainSplitterState; }; - class CloseButton : public QAbstractButton { - Q_OBJECT + Q_OBJECT -public: - using QAbstractButton::QAbstractButton; + public: + using QAbstractButton::QAbstractButton; - void setFontColor(const QColor &fontColor) { m_fontColor = fontColor; } - QRectF cross() const; - QLineF line() const; + void setFontColor(const QColor& fontColor) + { + m_fontColor = fontColor; + } -protected: - void mousePressEvent(QMouseEvent *e) override; - void mouseReleaseEvent(QMouseEvent *e) override; - void paintEvent(QPaintEvent *e) override; - QSize sizeHint() const override; + QRectF cross() const; + QLineF line() const; -private: - QColor m_fontColor; - bool m_isPressed = false; + protected: + void mousePressEvent(QMouseEvent* e) override; + void mouseReleaseEvent(QMouseEvent* e) override; + void paintEvent(QPaintEvent* e) override; + QSize sizeHint() const override; + + private: + QColor m_fontColor; + bool m_isPressed = false; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp old mode 100755 new mode 100644 index 772f99f16..fe5998018 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.cpp @@ -1,7 +1,7 @@ - #include "lts_text_edit_dialog.h" + #include "lts_text_editor.h" #include @@ -15,123 +15,116 @@ namespace LtsWidgets { -LtsTextEditDialog::LtsTextEditDialog(QWidget *parent) - : LtsDialog(parent, ButtonCombination::OkApplyCancel) - #ifdef USE_TEXT_EDITOR - , m_textEditor(new LtsTextEditor(this)) - #else - , m_textEditor2(new LtsTextEditor2(this)) - #endif -{ - QHBoxLayout *hbox = new QHBoxLayout(this); +LtsTextEditDialog::LtsTextEditDialog(QWidget* parent) + : LtsDialog(parent, ButtonCombination::OkApplyCancel) #ifdef USE_TEXT_EDITOR - hbox->addWidget(m_textEditor); - connect(m_textEditor->textEdit(), &QTextEdit::textChanged, this, [this]() { - emit signalTextChanged(this->getHtmlText()); - }); - connect(m_textEditor, &LtsTextEditor::backgroundColorChanged, - this, &LtsTextEditDialog::onBackgroundColorChanged); + , + m_textEditor(new LtsTextEditor(this)) #else - hbox->addWidget(m_textEditor2); - connect(m_textEditor2->textEdit(), &QTextEdit::textChanged, this, [this]() { - emit signalTextChanged(this->getHtmlText()); - }); - connect(m_textEditor2, &LtsTextEditor2::backgroundColorChanged, - this, &LtsTextEditDialog::onBackgroundColorChanged); + , + m_textEditor2(new LtsTextEditor2(this)) +#endif +{ + QHBoxLayout* hbox = new QHBoxLayout(this); +#ifdef USE_TEXT_EDITOR + hbox->addWidget(m_textEditor); + connect(m_textEditor->textEdit(), &QTextEdit::textChanged, this, + [this]() { emit signalTextChanged(this->getHtmlText()); }); + connect(m_textEditor, &LtsTextEditor::backgroundColorChanged, this, &LtsTextEditDialog::onBackgroundColorChanged); +#else + hbox->addWidget(m_textEditor2); + connect(m_textEditor2->textEdit(), &QTextEdit::textChanged, this, + [this]() { emit signalTextChanged(this->getHtmlText()); }); + connect(m_textEditor2, &LtsTextEditor2::backgroundColorChanged, this, &LtsTextEditDialog::onBackgroundColorChanged); #endif - - enableBackgroundColor(false); + enableBackgroundColor(false); } -LtsTextEditDialog::~LtsTextEditDialog() -{} +LtsTextEditDialog::~LtsTextEditDialog() {} void LtsTextEditDialog::enableBackgroundColor(bool onOff) { #ifdef USE_TEXT_EDITOR - m_textEditor->enableBackgroundColor(onOff); + m_textEditor->enableBackgroundColor(onOff); #else - m_textEditor2->enableBackgroundColor(onOff); + m_textEditor2->enableBackgroundColor(onOff); #endif } - - - void LtsTextEditDialog::retranslate() { - - QString name = tr("Edit Text"); - translate(name); + + QString name = tr("Edit Text"); + translate(name); } bool LtsTextEditDialog::apply() { #ifdef USE_TEXT_EDITOR - QString textHtml = m_textEditor->textEdit()->document()->toHtml(); - const QString backGroundColor = QLatin1String("background-color:'%1'; ").arg(m_textEditor->backgroundColor().name()); + QString textHtml = m_textEditor->textEdit()->document()->toHtml(); + const QString backGroundColor = + QLatin1String("background-color:'%1'; ").arg(m_textEditor->backgroundColor().name()); #else - QString textHtml = m_textEditor2->textEdit()->document()->toHtml(); - const QString backGroundColor = QLatin1String("background-color:'%1'; ").arg(m_textEditor2->backgroundColor().name()); + QString textHtml = m_textEditor2->textEdit()->document()->toHtml(); + const QString backGroundColor = + QLatin1String("background-color:'%1'; ").arg(m_textEditor2->backgroundColor().name()); #endif - emit signalTextApplied(textHtml); + emit signalTextApplied(textHtml); - const int insertBackGroundColorIndex = textHtml.indexOf(QLatin1String("font-family")); - textHtml.insert(insertBackGroundColorIndex, backGroundColor); + const int insertBackGroundColorIndex = textHtml.indexOf(QLatin1String("font-family")); + textHtml.insert(insertBackGroundColorIndex, backGroundColor); - emit signalTextAppliedWithBackGroundColor(textHtml); + emit signalTextAppliedWithBackGroundColor(textHtml); - return true; + return true; } -void LtsTextEditDialog::setHtml(const QString &htmlText) +void LtsTextEditDialog::setHtml(const QString& htmlText) { - - + #ifdef USE_TEXT_EDITOR - m_textEditor->textEdit()->document()->setHtml(htmlText); + m_textEditor->textEdit()->document()->setHtml(htmlText); #else - m_textEditor2->textEdit()->document()->setHtml(htmlText); + m_textEditor2->textEdit()->document()->setHtml(htmlText); #endif } QString LtsTextEditDialog::getHtmlText() const { #ifdef USE_TEXT_EDITOR - if(m_textEditor && m_textEditor->textEdit() && m_textEditor->textEdit()->document()) - return m_textEditor->textEdit()->document()->toHtml(); + if (m_textEditor && m_textEditor->textEdit() && m_textEditor->textEdit()->document()) + return m_textEditor->textEdit()->document()->toHtml(); #else - if(m_textEditor2 && m_textEditor2->textEdit() && m_textEditor2->textEdit()->document()) - return m_textEditor2->textEdit()->document()->toHtml(); + if (m_textEditor2 && m_textEditor2->textEdit() && m_textEditor2->textEdit()->document()) + return m_textEditor2->textEdit()->document()->toHtml(); #endif - return {}; + return {}; } -void LtsTextEditDialog::setInitialBackgroundColor(const QColor &bgColor) +void LtsTextEditDialog::setInitialBackgroundColor(const QColor& bgColor) { #ifdef USE_TEXT_EDITOR - if (m_textEditor) - m_textEditor->setInitialBackgroundColor(bgColor); + if (m_textEditor) + m_textEditor->setInitialBackgroundColor(bgColor); #else - if (m_textEditor2) - m_textEditor2->setInitialBackgroundColor(bgColor); + if (m_textEditor2) + m_textEditor2->setInitialBackgroundColor(bgColor); #endif } void LtsTextEditDialog::dialogCanceled() { - emit signalDialogCanceled(); - BaseClass::dialogCanceled(); + emit signalDialogCanceled(); + BaseClass::dialogCanceled(); } -void LtsTextEditDialog::onBackgroundColorChanged(const QColor &backgroundColor) +void LtsTextEditDialog::onBackgroundColorChanged(const QColor& backgroundColor) { - slotChangesMade(); - emit signalBackgroundColorChanged(backgroundColor); + slotChangesMade(); + emit signalBackgroundColorChanged(backgroundColor); } -} - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h old mode 100755 new mode 100644 index a79a76909..ea97d3784 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_edit_dialog.h @@ -1,56 +1,49 @@ #pragma once -#include - #include #include #include - +#include namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsTextEditDialog : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT - using BaseClass = LtsWidgets::LtsDialog; + using BaseClass = LtsWidgets::LtsDialog; -public: - LtsTextEditDialog(QWidget *parent = nullptr); - ~LtsTextEditDialog(); + public: + LtsTextEditDialog(QWidget* parent = nullptr); + ~LtsTextEditDialog(); - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor &bgColor); + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor& bgColor); - void retranslate() override; - bool apply() override; - void setHtml(const QString &htmlText); - QString getHtmlText() const; + void retranslate() override; + bool apply() override; + void setHtml(const QString& htmlText); + QString getHtmlText() const; -protected: - void dialogCanceled() override; + protected: + void dialogCanceled() override; -private: - LtsTextEditor *m_textEditor{nullptr}; - LtsTextEditor2 *m_textEditor2{nullptr}; + private: + LtsTextEditor* m_textEditor{nullptr}; + LtsTextEditor2* m_textEditor2{nullptr}; + protected Q_SLOTS: + void onBackgroundColorChanged(const QColor& backgroundColor); -protected Q_SLOTS: - void onBackgroundColorChanged(const QColor &backgroundColor); - -Q_SIGNALS: - void signalTextChanged(const QString &htmlText); - void signalTextApplied(const QString &htmlText); - void signalTextAppliedWithBackGroundColor(const QString &htmlText); - void signalBackgroundColorChanged(const QColor &bgColor); - void signalDialogApplied(); - void signalDialogCanceled(); - + Q_SIGNALS: + void signalTextChanged(const QString& htmlText); + void signalTextApplied(const QString& htmlText); + void signalTextAppliedWithBackGroundColor(const QString& htmlText); + void signalBackgroundColorChanged(const QColor& bgColor); + void signalDialogApplied(); + void signalDialogCanceled(); }; -} - - - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h old mode 100755 new mode 100644 index b1b3b897e..c683f8662 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor.h @@ -1,11 +1,9 @@ #pragma once -#include - #include "ltswidgets_export.h" +#include #include - namespace Ui { class LtsTextEditor; @@ -14,49 +12,46 @@ class LtsTextEditor; class QTextEdit; class QTextCharFormat; - namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsTextEditor : public QWidget { - Q_OBJECT -public: - LtsTextEditor(QWidget *parent = nullptr); - ~LtsTextEditor(); - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor &bgColor); - QTextEdit *textEdit(); - QColor backgroundColor() const; + Q_OBJECT + public: + LtsTextEditor(QWidget* parent = nullptr); + ~LtsTextEditor(); + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor& bgColor); + QTextEdit* textEdit(); + QColor backgroundColor() const; -Q_SIGNALS: - void backgroundColorChanged(const QColor &bgColor); + Q_SIGNALS: + void backgroundColorChanged(const QColor& bgColor); -private: - Ui::LtsTextEditor *m_ui; - QColor m_backgroundColor{Qt::white}; - QColor m_foregroundColor{Qt::black}; + private: + Ui::LtsTextEditor* m_ui; + QColor m_backgroundColor{Qt::white}; + QColor m_foregroundColor{Qt::black}; -private slots: - void slotCurrentCharFormatChanged(const QTextCharFormat &format); - void slotFontChanged(const QFont &f); - void slotTextColorChanged(const QColor &c); - void slotBackgroundColorChanged(const QColor &bgColor); - void slotAlignmentChanged(); - void slotMergeFormatOnWordOrSelection(const QTextCharFormat &format); - void slotClipboardDataChanged(); - void slotTextColor(); - void slotBackgroundColor(); - void slotTextSize(const QString &p); - void slotTextSizeEditingFinished(); - void slotTextFamily(const QString &f); - void slotTextItalic(); - void slotTextUnderline(); - void slotTextBold(); - - void slotTextAlign(); + private slots: + void slotCurrentCharFormatChanged(const QTextCharFormat& format); + void slotFontChanged(const QFont& f); + void slotTextColorChanged(const QColor& c); + void slotBackgroundColorChanged(const QColor& bgColor); + void slotAlignmentChanged(); + void slotMergeFormatOnWordOrSelection(const QTextCharFormat& format); + void slotClipboardDataChanged(); + void slotTextColor(); + void slotBackgroundColor(); + void slotTextSize(const QString& p); + void slotTextSizeEditingFinished(); + void slotTextFamily(const QString& f); + void slotTextItalic(); + void slotTextUnderline(); + void slotTextBold(); + + void slotTextAlign(); }; -} - - +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h old mode 100755 new mode 100644 index 509a11335..bce9cd24e --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_text_editor2.h @@ -1,18 +1,16 @@ #pragma once -#include - - #include "ltswidgets_export.h" +#include +#include #include #include +#include #include -#include -#include -#include #include +#include QT_BEGIN_NAMESPACE class QAction; @@ -29,108 +27,110 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsTextEditor2 : public QMainWindow { - Q_OBJECT + Q_OBJECT -public: - explicit LtsTextEditor2(QWidget *parent = nullptr); - ~LtsTextEditor2(); + public: + explicit LtsTextEditor2(QWidget* parent = nullptr); + ~LtsTextEditor2(); - static QString rsrcPath(){return (QStringLiteral(":/images/win"));} + static QString rsrcPath() + { + return (QStringLiteral(":/images/win")); + } - QColor m_backgroundColor{Qt::white}; - QColor m_foregroundColor{Qt::black}; + QColor m_backgroundColor{Qt::white}; + QColor m_foregroundColor{Qt::black}; - QTextEdit *textEdit(); - QColor backgroundColor() const; - void enableBackgroundColor(bool onOff); - void setInitialBackgroundColor(const QColor &bgColor); - bool load(const QString &f); + QTextEdit* textEdit(); + QColor backgroundColor() const; + void enableBackgroundColor(bool onOff); + void setInitialBackgroundColor(const QColor& bgColor); + bool load(const QString& f); + Q_SIGNALS: + void backgroundColorChanged(const QColor& bgColor); -Q_SIGNALS: - void backgroundColorChanged(const QColor &bgColor); + public slots: -public slots: + private slots: + void onFileNew(); + void onFileOpen(); + bool onFileSave(); + bool onFileSaveAs(); + void onFilePrint(); + void onFilePrintPreview(); + void onFilePrintPdf(); -private slots: - void onFileNew(); - void onFileOpen(); - bool onFileSave(); - bool onFileSaveAs(); - void onFilePrint(); - void onFilePrintPreview(); - void onFilePrintPdf(); + void onTextBold(); + void onTextUnderline(); + void onTextItalic(); + void onTextFamily(const QString& f); + void onTextSize(const QString& p); + void onTextStyle(int styleIndex); + void onTextColor(); + void onTextAlign(QAction* a); + void setChecked(bool checked); + void indent(); + void unindent(); + void slotBackgroundColorChanged(const QColor& bgColor); + void slotBackgroundColor(); - void onTextBold(); - void onTextUnderline(); - void onTextItalic(); - void onTextFamily(const QString &f); - void onTextSize(const QString &p); - void onTextStyle(int styleIndex); - void onTextColor(); - void onTextAlign(QAction *a); - void setChecked(bool checked); - void indent(); - void unindent(); - void slotBackgroundColorChanged(const QColor &bgColor); - void slotBackgroundColor(); + void currentCharFormatChanged(const QTextCharFormat& format); + void cursorPositionChanged(); - void currentCharFormatChanged(const QTextCharFormat &format); - void cursorPositionChanged(); + void clipboardDataChanged(); + void about(); + void printPreview(QPrinter*); - void clipboardDataChanged(); - void about(); - void printPreview(QPrinter *); + private: + void setupFileActions(); + void setupEditActions(); + void setupTextActions(); + bool maybeSave(); + void setCurrentFileName(const QString& fileName); + void modifyIndentation(int amount); -private: - void setupFileActions(); - void setupEditActions(); - void setupTextActions(); - bool maybeSave(); - void setCurrentFileName(const QString &fileName); - void modifyIndentation(int amount); + void mergeFormatOnWordOrSelection(const QTextCharFormat& format); + void fontChanged(const QFont& f); + void colorChanged(const QColor& c); + void alignmentChanged(Qt::Alignment a); - void mergeFormatOnWordOrSelection(const QTextCharFormat &format); - void fontChanged(const QFont &f); - void colorChanged(const QColor &c); - void alignmentChanged(Qt::Alignment a); - - QAction *m_actionSave; - QAction *m_actionOpen; - QAction *m_actionQuit; - QAction *m_actionSaveAs; - QAction *m_actionNew; - QAction *m_actionPrint; - QAction *m_actionPreview; - QAction *m_actionExport; - QAction *m_actionTextBold; - QAction *m_actionTextUnderline; - QAction *m_actionTextItalic; - QAction *m_actionTextColor; - QAction *m_actionBackgroundColor; - QAction *m_actionAlignLeft; - QAction *m_actionAlignCenter; - QAction *m_actionAlignRight; - QAction *m_actionAlignJustify; - QAction *m_actionIndentLess; - QAction *m_actionIndentMore; - QAction *m_actionToggleCheckState; - QAction *m_actionUndo; - QAction *m_actionRedo; + QAction* m_actionSave; + QAction* m_actionOpen; + QAction* m_actionQuit; + QAction* m_actionSaveAs; + QAction* m_actionNew; + QAction* m_actionPrint; + QAction* m_actionPreview; + QAction* m_actionExport; + QAction* m_actionTextBold; + QAction* m_actionTextUnderline; + QAction* m_actionTextItalic; + QAction* m_actionTextColor; + QAction* m_actionBackgroundColor; + QAction* m_actionAlignLeft; + QAction* m_actionAlignCenter; + QAction* m_actionAlignRight; + QAction* m_actionAlignJustify; + QAction* m_actionIndentLess; + QAction* m_actionIndentMore; + QAction* m_actionToggleCheckState; + QAction* m_actionUndo; + QAction* m_actionRedo; #ifndef QT_NO_CLIPBOARD - QAction *m_actionCut; - QAction *m_actionCopy; - QAction *m_actionPaste; + QAction* m_actionCut; + QAction* m_actionCopy; + QAction* m_actionPaste; #endif - QComboBox *m_comboStyle; - QAction *m_comboStyleAction; - QFontComboBox *m_comboFont; - QComboBox *m_comboSize; + QComboBox* m_comboStyle; + QAction* m_comboStyleAction; + QFontComboBox* m_comboFont; + QComboBox* m_comboSize; - QToolBar *m_tb; - QString m_fileName; - QTextEdit *m_textEdit; + QToolBar* m_tb; + QString m_fileName; + QTextEdit* m_textEdit; }; - } +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h old mode 100755 new mode 100644 index 59436453a..3db6c8480 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_bar_area.h @@ -1,16 +1,13 @@ - #pragma once -#include - #include "ltswidgets_export.h" -#include -#include -#include #include - +#include +#include +#include +#include class QMenu; class QLabel; @@ -26,91 +23,96 @@ class LtsDragIcon; struct ShortCut { - int key = 0; - QShortcut *shortcut = nullptr; - QString name; - QString identifier; - LtsDragIcon *icon = nullptr; - QString keyName() const {return shortcut ? shortcut->key().toString() : QString();} - void clear(); + int key = 0; + QShortcut* shortcut = nullptr; + QString name; + QString identifier; + LtsDragIcon* icon = nullptr; - explicit ShortCut(QWidget *parent = nullptr) - : shortcut(new QShortcut(parent)) - {} - - ~ShortCut() { delete shortcut; } - ShortCut(const ShortCut &o) - : key(o.key) - , name(o.name) - , identifier(o.identifier) - , icon(o.icon) - { - if (o.shortcut) + QString keyName() const { - delete shortcut; - shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, o.shortcut->context()); + return shortcut ? shortcut->key().toString() : QString(); } - } - ShortCut &operator=(const ShortCut &o) - { - if (&o == this) - return *this; + void clear(); - key = o.key; - name = o.name; - identifier = o.identifier; - icon = o.icon; - QWidget *parent = qobject_cast(shortcut->parent()); - delete shortcut; - if (o.shortcut) - shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, o.shortcut->context()); - else - shortcut = new QShortcut(parent); - return *this; - } + explicit ShortCut(QWidget* parent = nullptr) : shortcut(new QShortcut(parent)) {} + + ~ShortCut() + { + delete shortcut; + } + + ShortCut(const ShortCut& o) : key(o.key), name(o.name), identifier(o.identifier), icon(o.icon) + { + if (o.shortcut) + { + delete shortcut; + shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, + o.shortcut->context()); + } + } + + ShortCut& operator=(const ShortCut& o) + { + if (&o == this) + return *this; + + key = o.key; + name = o.name; + identifier = o.identifier; + icon = o.icon; + QWidget* parent = qobject_cast(shortcut->parent()); + delete shortcut; + if (o.shortcut) + shortcut = new QShortcut(o.shortcut->key(), qobject_cast(o.shortcut->parent()), nullptr, nullptr, + o.shortcut->context()); + else + shortcut = new QShortcut(parent); + return *this; + } }; class LTSWIDGETS_EXPORT LtsToolBarArea : public QWidget { - Q_OBJECT -public: - explicit LtsToolBarArea(QWidget *parent = nullptr); - ~LtsToolBarArea(); + Q_OBJECT + public: + explicit LtsToolBarArea(QWidget* parent = nullptr); + ~LtsToolBarArea(); - void addMenuEntry(LtsDragIcon *entry, LtsDragIcon *after = nullptr); - void clearToolBarArea(); + void addMenuEntry(LtsDragIcon* entry, LtsDragIcon* after = nullptr); + void clearToolBarArea(); - void setMenuEntries(const QVector &actions); - QStringList menuEntries() const; + void setMenuEntries(const QVector& actions); + QStringList menuEntries() const; - bool setFunctionKey(int fkey, const QString &action); - QMap functionKeys() const; + bool setFunctionKey(int fkey, const QString& action); + QMap functionKeys() const; - bool removeFunctionKey(const QString &action); - void removeMenuAction(LtsDragIcon *icon); + bool removeFunctionKey(const QString& action); + void removeMenuAction(LtsDragIcon* icon); -public slots: - void showContextMenu(const QPoint &pos); - void functionKeyMenuTriggered(); + public slots: + void showContextMenu(const QPoint& pos); + void functionKeyMenuTriggered(); -protected: - void dragEnterEvent(QDragEnterEvent *event) override; - void dropEvent(QDropEvent *event) override; + protected: + void dragEnterEvent(QDragEnterEvent* event) override; + void dropEvent(QDropEvent* event) override; -private: - QMenu* functionKeyMenu(QWidget *parent); - QString m_currentIdentifierForContextMenue; + private: + QMenu* functionKeyMenu(QWidget* parent); + QString m_currentIdentifierForContextMenue; - QVector m_buttonMap; - QVector m_foreignButtonMap; - QMap m_functionKeys; - QLabel *m_dummyLabel; + QVector m_buttonMap; + QVector m_foreignButtonMap; + QMap m_functionKeys; + QLabel* m_dummyLabel; - Ui::LtsToolBarArea *m_ui; + Ui::LtsToolBarArea* m_ui; - void saveSettings(); + void saveSettings(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp old mode 100755 new mode 100644 index 2095b7070..95a68c0a2 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.cpp @@ -1,85 +1,70 @@ - #include "lts_tool_box.h" #include "lts_drag_icon.h" #include "lts_grid_layout.h" #include -#include #include +#include using namespace LtsWidgets; - -LtsToolBox::LtsToolBox(QWidget *parent) - : QToolBox(parent) +LtsToolBox::LtsToolBox(QWidget* parent) : QToolBox(parent) { - setMinimumSize(17, 200); - setContextMenuPolicy(Qt::CustomContextMenu); - connect(this, &LtsToolBox::customContextMenuRequested, - this, &LtsToolBox::showContextMenu); - - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + setMinimumSize(17, 200); + setContextMenuPolicy(Qt::CustomContextMenu); + connect(this, &LtsToolBox::customContextMenuRequested, this, &LtsToolBox::showContextMenu); + setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } -LtsToolBox::~LtsToolBox() +LtsToolBox::~LtsToolBox() {} + +void LtsToolBox::resizeEvent(QResizeEvent* e) { + emit resized(e); + QToolBox::resizeEvent(e); } -void LtsToolBox::resizeEvent(QResizeEvent *e) +void LtsToolBox::addItem(QWidget* widget, const QString& text) { - emit resized(e); - QToolBox::resizeEvent(e); - + setMinimumSize(120, 100); + QToolBox::addItem(widget, text); } -void LtsToolBox::addItem(QWidget *widget, const QString &text) -{ - setMinimumSize(120, 100); - QToolBox::addItem(widget, text); -} - - -void LtsToolBox::showContextMenu(const QPoint &pos) +void LtsToolBox::showContextMenu(const QPoint& pos) { - - QPoint globalPos = this->mapToGlobal(pos); - - + QPoint globalPos = this->mapToGlobal(pos); - QMenu myMenu; - myMenu.addAction(tr("Icon and Text")); - QAction *to = myMenu.addAction(tr("Text Only")); - QAction *io = myMenu.addAction(tr("Icon Only")); + QMenu myMenu; + myMenu.addAction(tr("Icon and Text")); + QAction* to = myMenu.addAction(tr("Text Only")); + QAction* io = myMenu.addAction(tr("Icon Only")); - - QAction *selectedItem = myMenu.exec(globalPos); - if (selectedItem) - { - ButtonStyle newStyle = ButtonStyle::eTextNextToIcon; - if (selectedItem == to) - newStyle = ButtonStyle::eTextOnly; - if (selectedItem == io) - newStyle = ButtonStyle::eIconOnly; - - for (int i = 0; i < count(); i++) + QAction* selectedItem = myMenu.exec(globalPos); + if (selectedItem) { - const QList list = widget(i)->findChildren(); - for (LtsDragIcon *icon : list) - icon->setButtonStyle(newStyle); - LtsGridLayout *lay = qobject_cast(widget(i)->layout()); - if (lay) - lay->setAutoSize((newStyle == ButtonStyle::eIconOnly)); - } + ButtonStyle newStyle = ButtonStyle::eTextNextToIcon; + if (selectedItem == to) + newStyle = ButtonStyle::eTextOnly; + if (selectedItem == io) + newStyle = ButtonStyle::eIconOnly; - } - else - { - - } + for (int i = 0; i < count(); i++) + { + const QList list = widget(i)->findChildren(); + for (LtsDragIcon* icon : list) + icon->setButtonStyle(newStyle); + LtsGridLayout* lay = qobject_cast(widget(i)->layout()); + if (lay) + lay->setAutoSize((newStyle == ButtonStyle::eIconOnly)); + } + } + else + { + } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h old mode 100755 new mode 100644 index 7f79f41e5..5183bb635 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_tool_box.h @@ -1,12 +1,10 @@ - #pragma once -#include - #include "lts_base.h" #include "ltswidgets_export.h" +#include #include namespace LtsWidgets @@ -14,19 +12,18 @@ namespace LtsWidgets class LTSWIDGETS_EXPORT LtsToolBox : public QToolBox { - Q_OBJECT -public: - explicit LtsToolBox(QWidget *parent = nullptr); - ~LtsToolBox(); - void resizeEvent(QResizeEvent *e) override; - void addItem(QWidget *widget, const QString &text); + Q_OBJECT + public: + explicit LtsToolBox(QWidget* parent = nullptr); + ~LtsToolBox(); + void resizeEvent(QResizeEvent* e) override; + void addItem(QWidget* widget, const QString& text); -signals: - void resized(QResizeEvent *e); - -public slots: - void showContextMenu(const QPoint &pos); + signals: + void resized(QResizeEvent* e); + public slots: + void showContextMenu(const QPoint& pos); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp old mode 100755 new mode 100644 index cb5e3efa3..62be76527 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.cpp @@ -1,17 +1,16 @@ #include "lts_wait_dialog.h" -#include "lts_global_wait_dialog.h" +#include "lts_global_wait_dialog.h" namespace LtsWidgets { -LtsWaitDialog::LtsWaitDialog(const QString &customText) +LtsWaitDialog::LtsWaitDialog(const QString& customText) { - LtsGlobalWaitDialog::getInstance()->wait(customText); + LtsGlobalWaitDialog::getInstance()->wait(customText); } - LtsWaitDialog::~LtsWaitDialog() { - LtsGlobalWaitDialog::getInstance()->done(); -} + LtsGlobalWaitDialog::getInstance()->done(); } +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h old mode 100755 new mode 100644 index 0be84a8f0..b14f4666b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_wait_dialog.h @@ -3,19 +3,17 @@ #include "ltswidgets_export.h" #include - #include - namespace LtsWidgets { class LTSWIDGETS_EXPORT LtsWaitDialog { -public: - LtsWaitDialog(const QString &customText = {}); - ~LtsWaitDialog(); + public: + LtsWaitDialog(const QString& customText = {}); + ~LtsWaitDialog(); }; typedef std::unique_ptr LtsWaitDialogContainer; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h old mode 100755 new mode 100644 index ec9e7223b..221c1b9fb --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/lts_widgets_export.h @@ -5,13 +5,13 @@ #include #ifndef LTSWIDGETS_EXPORT -# ifdef BUILD_STATIC_LIBRARIES -# define LTSWIDGETS_EXPORT -# else -# if defined(MAKE_LTSWIDGETS_LIB) -# define LTSWIDGETS_EXPORT Q_DECL_EXPORT -# else -# define LTSWIDGETS_EXPORT Q_DECL_IMPORT -# endif -# endif +#ifdef BUILD_STATIC_LIBRARIES +#define LTSWIDGETS_EXPORT +#else +#if defined(MAKE_LTSWIDGETS_LIB) +#define LTSWIDGETS_EXPORT Q_DECL_EXPORT +#else +#define LTSWIDGETS_EXPORT Q_DECL_IMPORT +#endif +#endif #endif diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp old mode 100755 new mode 100644 index e31a1b85c..7858bfa3f --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/ltswidgetsplugin.cpp @@ -1,34 +1,33 @@ - -#include -#include -#include +#include "lts_bitfield_widget.h" +#include "lts_combo_box.h" +#include "lts_dialog_button_box.h" +#include "lts_drag_icon.h" +#include "lts_elided_label.h" +#include "lts_frameless_dialog.h" +#include "lts_image_editor.h" +#include "lts_msec_date_time_edit.h" +#include "lts_multi_range_spinbox.h" +#include "lts_picture_view.h" +#include "lts_profile_button.h" +#include "lts_range_slider.h" +#include "lts_spinbox.h" +#include "lts_splitter.h" +#include "lts_tab_bar.h" +#include "lts_tab_sequence_widget.h" +#include "lts_tab_widget.h" +#include "lts_tool_bar.h" +#include "lts_tool_bar_area.h" +#include "lts_tool_box.h" #include #include #include #include -#include "lts_dialog_button_box.h" -#include "lts_elided_label.h" -#include "lts_image_editor.h" -#include "lts_picture_view.h" -#include "lts_profile_button.h" -#include "lts_splitter.h" -#include "lts_tab_bar.h" -#include "lts_tab_widget.h" -#include "lts_tool_bar.h" -#include "lts_tool_bar_area.h" -#include "lts_tool_box.h" -#include "lts_frameless_dialog.h" -#include "lts_drag_icon.h" -#include "lts_combo_box.h" -#include "lts_spinbox.h" -#include "lts_multi_range_spinbox.h" -#include "lts_range_slider.h" -#include "lts_msec_date_time_edit.h" -#include "lts_bitfield_widget.h" -#include "lts_tab_sequence_widget.h" +#include +#include +#include #ifdef TABLET_MODE #include "lts_date_time_edit_touch.h" @@ -36,9 +35,9 @@ #include "lts_date_time_edit.h" #endif -#include "lts_led_widget.h" -#include "lts_base.h" #include "LtsImageCropper/lts_image_cropper.h" +#include "lts_base.h" +#include "lts_led_widget.h" namespace LtsWidgets { @@ -48,35 +47,40 @@ class LtsDesignerCustomWidgetInterface : public QObject, public QDesignerCustomW Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using QObject::QObject; bool isContainer() const override final { return false; } + bool isInitialized() const override final { return mInitialized; } + QIcon icon() const override final { - return QIcon(QStringLiteral(":style/icons/22x22/pushbutton.png")); + return QIcon(QStringLiteral(":style/icons/22x22/pushbutton.png")); } + QString codeTemplate() const override final { return QString(); } + QString group() const override final { return QLatin1String("Lts Widgets"); } - void initialize(QDesignerFormEditorInterface *) override final + + void initialize(QDesignerFormEditorInterface*) override final { mInitialized = true; } -private: + private: bool mInitialized = false; }; @@ -85,65 +89,74 @@ class LtsCoordWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsCoordTrans/lts_coord_widget.h"); } + QString name() const override { return QLatin1String("LtsCoordWidget::LtsCoordWidget"); } + QString toolTip() const override { return QLatin1String("Widget for entering a coordinate"); } + QString whatsThis() const override { return QLatin1String("Widget for entering a coordinate"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsCoordWidget::LtsCoordWidget(parent); } }; - class LtsDialogButtonBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_dialog_button_box.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsDialogButtonBox"); } + QString toolTip() const override { return QLatin1String("Widget for a LTS version of the Button Box"); } + QString whatsThis() const override { return QLatin1String("Widget for a LTS version of the Botton Box"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsDialogButtonBox(parent); } @@ -154,30 +167,35 @@ class LtsElidedLabelPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QStringLiteral("LtsWidgets/lts_elided_label.h"); } + QString name() const override { return QStringLiteral("LtsWidgets::LtsElidedLabel"); } + QString toolTip() const override { return QStringLiteral("A QLabel which automatically elided it's content if needed."); } + QString whatsThis() const override { return toolTip(); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsElidedLabel(parent); } @@ -188,375 +206,419 @@ class LtsImageEditorPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_image_editor.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsImageEditor"); } + QString toolTip() const override { return QLatin1String("Image Editor"); } + QString whatsThis() const override { return QLatin1String("ImageEditor"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsImageEditor(parent); } }; - class LtsPictureViewPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_picture_view.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsPictureView"); } + QString toolTip() const override { return QLatin1String("Picture View Widget"); } + QString whatsThis() const override { return QLatin1String("Picture View Widget"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsPictureView(parent); } }; - class LtsProfileButtonPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_profile_button.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsProfileButton"); } + QString toolTip() const override { return QLatin1String("Profile Button"); } + QString whatsThis() const override { return QLatin1String("Profile Button"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsProfileButton(parent); } }; - class LtsSplitterPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_splitter.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsSplitter"); } + QString toolTip() const override { return QLatin1String("Splitter with sizes property"); } + QString whatsThis() const override { return QLatin1String("Splitter with sizes property"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsSplitter(parent); } }; - class LtsTabBarPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_bar.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsTabBar"); } + QString toolTip() const override { return QLatin1String("Tab Bar"); } + QString whatsThis() const override { return QLatin1String("Tab Bar"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsTabBar(parent); } }; - class LtsTabWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_widget.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsTabWidget"); } + QString toolTip() const override { return QLatin1String("Tab Widget"); } + QString whatsThis() const override { return QLatin1String("Tab Widget"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsTabWidget(parent); } }; - class LtsToolBarPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_bar.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsToolBar"); } + QString toolTip() const override { return QLatin1String("Tool Bar"); } + QString whatsThis() const override { return QLatin1String("Tool Bar"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsToolBar(parent); } }; - class LtsToolBarAreaPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_bar_area.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsToolBarArea"); } + QString toolTip() const override { return QLatin1String("Tool Bar Area"); } + QString whatsThis() const override { return QLatin1String("Tool Bar Area"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsToolBarArea(parent); } }; - class LtsToolBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tool_box.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsToolBox"); } + QString toolTip() const override { return QLatin1String("Tool Box"); } + QString whatsThis() const override { return QLatin1String("Tool Box"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsToolBox(parent); } }; - class LtsDataViewPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsDataView/lts_data_view.h"); } + QString name() const override { return QLatin1String("LtsDataView::LtsDataView"); } + QString toolTip() const override { return QLatin1String("DataView"); } + QString whatsThis() const override { return QLatin1String("DataView"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsDataView::LtsDataView(parent); } }; - class LtsFramelessDialogPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_frameless_dialog.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsFramelessDialog"); } + QString toolTip() const override { return QLatin1String("Enhanced QDialog"); } + QString whatsThis() const override { return QLatin1String("Dialog Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -572,36 +634,40 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsFramelessDialog(parent); } }; - class LtsDragIconPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_drag_icon.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsDragIcon"); } + QString toolTip() const override { return QLatin1String("Class for standard buttons with icons"); } + QString whatsThis() const override { return QLatin1String("Button Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -609,37 +675,41 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsDragIcon *b = new LtsWidgets::LtsDragIcon(parent); + LtsWidgets::LtsDragIcon* b = new LtsWidgets::LtsDragIcon(parent); return b; } }; - class LtsComboBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_combo_box.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsComboBox"); } + QString toolTip() const override { return QLatin1String("Class for standard ComBoBoxes"); } + QString whatsThis() const override { return QLatin1String("ComboBox Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -647,37 +717,41 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsComboBox *b = new LtsWidgets::LtsComboBox(parent); + LtsWidgets::LtsComboBox* b = new LtsWidgets::LtsComboBox(parent); return b; } }; - class LtsSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_spinbox.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsSpinBox"); } + QString toolTip() const override { return QLatin1String("Class for standard SpinBoxes"); } + QString whatsThis() const override { return QLatin1String("SpinBox Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -685,9 +759,10 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsSpinBox *b = new LtsWidgets::LtsSpinBox(parent); + LtsWidgets::LtsSpinBox* b = new LtsWidgets::LtsSpinBox(parent); return b; } }; @@ -696,25 +771,29 @@ class LtsMultiRangeSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_multi_range_spinbox.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsMultiRangeSpinBox"); } + QString toolTip() const override { return QLatin1String("Class for standard SpinBoxes with multiple ranges"); } + QString whatsThis() const override { return QLatin1String("SpinBox Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -722,38 +801,41 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsMultiRangeSpinBox *b = new LtsWidgets::LtsMultiRangeSpinBox(parent); + LtsWidgets::LtsMultiRangeSpinBox* b = new LtsWidgets::LtsMultiRangeSpinBox(parent); return b; } }; - - class LtsDoubleSpinBoxPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_spinbox.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsDoubleSpinBox"); } + QString toolTip() const override { return QLatin1String("Class for standard DoubleSpinBoxes"); } + QString whatsThis() const override { return QLatin1String("DoubleSpinBox Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -761,37 +843,41 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsDoubleSpinBox *b = new LtsWidgets::LtsDoubleSpinBox(parent); + LtsWidgets::LtsDoubleSpinBox* b = new LtsWidgets::LtsDoubleSpinBox(parent); return b; } }; - class LtsDateTimeEditPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_date_time_edit.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsDateTimeEdit"); } + QString toolTip() const override { return QLatin1String("Class for LTS Date Time Edit"); } + QString whatsThis() const override { return QLatin1String("LtsDateTimeEdit Widget"); } + QString domXml() const override { return QLatin1String("\n" @@ -803,9 +889,10 @@ public: " \n" ""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { - LtsWidgets::LtsDateTimeEdit *b = new LtsWidgets::LtsDateTimeEdit(parent); + LtsWidgets::LtsDateTimeEdit* b = new LtsWidgets::LtsDateTimeEdit(parent); return b; } }; @@ -815,30 +902,35 @@ class LtsFileDialogWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsFileDialog/lts_file_dialog.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsFileDialogWidget"); } + QString toolTip() const override { return QLatin1String("File Dialog Widget"); } + QString whatsThis() const override { return QLatin1String("FileDialogWidget"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsFileDialogWidget(parent); } @@ -849,30 +941,35 @@ class LtsFileDialogPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsFileDialog/lts_file_dialog.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsFileDialog"); } + QString toolTip() const override { return QLatin1String("File Dialog Widget"); } + QString whatsThis() const override { return QLatin1String("FileDialog"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsFileDialog(parent); } @@ -883,30 +980,35 @@ class LtsReportDisplayWidgetPlugin final : public LtsDesignerCustomWidgetInterfa Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsReportDisplay/lts_report_display_widget.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsReportDisplayWidget"); } + QString toolTip() const override { return QLatin1String("Report Display Widget"); } + QString whatsThis() const override { return QLatin1String("ReportDisplayWidget"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsReportDisplayWidget(parent); } @@ -916,25 +1018,29 @@ class LtsLedWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_led_widget.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsLedWidget"); } + QString toolTip() const override { return QLatin1String("Class for an LED Widget"); } + QString whatsThis() const override { return QLatin1String("LED Widget"); } + QString domXml() const override { return QLatin1String("\ @@ -942,7 +1048,8 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsLedWidget(parent); } @@ -952,25 +1059,29 @@ class LtsRangeSliderPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_range_slider.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsRangeSlider"); } + QString toolTip() const override { return QLatin1String("Class for an Range Slider"); } + QString whatsThis() const override { return QLatin1String("Range Slider"); } + QString domXml() const override { return QLatin1String("\ @@ -978,7 +1089,8 @@ public: \ "); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsRangeSlider(parent); } @@ -988,29 +1100,34 @@ class LtsImageCropperPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString name() const override { return QLatin1String("LtsWidgets::LtsImageCropper"); } + QString toolTip() const override { return QLatin1String("Class for an Image Cropper Widget"); } + QString whatsThis() const override { return QLatin1String("Image Cropper Widget"); } + QString includeFile() const override { return QLatin1String("LtsWidgets/LtsImageCropper/lts_image_cropper.h"); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsImageCropper(parent); } + QString domXml() const override { return QLatin1String("\n" @@ -1040,29 +1157,34 @@ class LtsMSecDateTimeEditPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString name() const override { return QLatin1String("LtsWidgets::LtsMSecDateTimeEdit"); } + QString toolTip() const override { return QLatin1String("Class for an Date/Time Widget with 40msecs step."); } + QString whatsThis() const override { return QLatin1String("Date/Time Widget with 40msecs step"); } + QString includeFile() const override { return QLatin1String("LtsWidgets/lts_msec_date_time_edit.h"); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsMSecDateTimeEdit(parent); } + QString domXml() const override { return QLatin1String("\n" @@ -1075,91 +1197,97 @@ class LtsBitfieldWidgetPlugin final : public LtsDesignerCustomWidgetInterface Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("lts_bitfield_widget.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsBitfieldWidget"); } + QString toolTip() const override { return QLatin1String("Widget for bitwise displaying and editing of quint8"); } + QString whatsThis() const override { return QLatin1String("Widget for bitwise displaying and editing of quint8"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsBitfieldWidget(parent); } }; - class LtsTabSequenceWidgetPlugin final : public LtsDesignerCustomWidgetInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetInterface) -public: + public: using LtsDesignerCustomWidgetInterface::LtsDesignerCustomWidgetInterface; QString includeFile() const override { return QLatin1String("LtsWidgets/lts_tab_sequence_widget.h"); } + QString name() const override { return QLatin1String("LtsWidgets::LtsTabSequenceWidget"); } + QString toolTip() const override { return QLatin1String("Widget for a Tab Sequence"); } + QString whatsThis() const override { return QLatin1String("Widget for a Tab Sequence"); } + QString domXml() const override { return QStringLiteral(""); } - QWidget *createWidget(QWidget *parent) override + + QWidget* createWidget(QWidget* parent) override { return new LtsWidgets::LtsTabSequenceWidget(parent); } }; - class Plugin final : public QObject, public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_PLUGIN_METADATA(IID "org.rde.sls.ltswidgetsplugin" FILE "ltswidgetsplugin.json") Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) -public: - explicit Plugin(QObject *parent = nullptr); + public: + explicit Plugin(QObject* parent = nullptr); - QList customWidgets() const override + QList customWidgets() const override { return m_plugins; } -private: - QList m_plugins; + private: + QList m_plugins; }; - -Plugin::Plugin(QObject *parent) - : QObject(parent) +Plugin::Plugin(QObject* parent) : QObject(parent) { m_plugins.append(new LtsCoordWidgetPlugin(this)); m_plugins.append(new LtsDialogButtonBoxPlugin(this)); @@ -1192,5 +1320,6 @@ Plugin::Plugin(QObject *parent) m_plugins.append(new LtsTabSequenceWidgetPlugin(this)); } -} +} // namespace LtsWidgets + #include "ltswidgetsplugin.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.cpp old mode 100755 new mode 100644 index 08de3f527..35045e010 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.cpp @@ -1,153 +1,142 @@ - #include "requirement_widget.h" #include - #include #include - namespace LtsWidgets { -UiRequirement::UiRequirement(QLabel *descriptionLabel, const std::function &requirementCheck, const QString &userWarningMessage) - : m_descriptionLabel(descriptionLabel) - , m_requirementCheck(requirementCheck) - , m_lastResult(true) - , m_userWarningMessage(userWarningMessage) +UiRequirement::UiRequirement(QLabel* descriptionLabel, const std::function& requirementCheck, + const QString& userWarningMessage) + : m_descriptionLabel(descriptionLabel), m_requirementCheck(requirementCheck), m_lastResult(true), + m_userWarningMessage(userWarningMessage) { - retranslate(); + retranslate(); } - void UiRequirement::reset() { - if (!isValid()) - return; - m_descriptionLabel->setText(m_originalText); - m_descriptionLabel->setToolTip(m_originalTooltip); + if (!isValid()) + return; + m_descriptionLabel->setText(m_originalText); + m_descriptionLabel->setToolTip(m_originalTooltip); } - void UiRequirement::setTexts() { - if (!isValid()) - return; - if (!m_lastResult) - { - m_descriptionLabel->setText(QStringLiteral("\u2022 %1").arg(m_originalText)); - - if (!m_userWarningMessage.isEmpty()) + if (!isValid()) + return; + if (!m_lastResult) { - m_descriptionLabel->setCursor(Qt::WhatsThisCursor); - m_descriptionLabel->setToolTip(m_userWarningMessage); + m_descriptionLabel->setText( + QStringLiteral("\u2022 %1").arg(m_originalText)); + + if (!m_userWarningMessage.isEmpty()) + { + m_descriptionLabel->setCursor(Qt::WhatsThisCursor); + m_descriptionLabel->setToolTip(m_userWarningMessage); + } } - } - else - { - if (m_originalText.startsWith(QStringLiteral("\u2022 "))) - return; + else + { + if (m_originalText.startsWith(QStringLiteral("\u2022 "))) + return; - m_descriptionLabel->setText(QStringLiteral("\u2022 %1").arg(m_originalText)); - m_descriptionLabel->setCursor(Qt::ArrowCursor); - m_descriptionLabel->setToolTip(m_originalTooltip); - } + m_descriptionLabel->setText(QStringLiteral("\u2022 %1").arg(m_originalText)); + m_descriptionLabel->setCursor(Qt::ArrowCursor); + m_descriptionLabel->setToolTip(m_originalTooltip); + } } - void UiRequirement::retranslate() { - if (!isValid()) - return; + if (!isValid()) + return; - if (m_originalText.startsWith(QStringLiteral("\u2022 "))) - return; + if (m_originalText.startsWith(QStringLiteral("\u2022 "))) + return; - auto x = m_descriptionLabel->text(); - if (x.startsWith(QStringLiteral("\u2022 "))) - return; + auto x = m_descriptionLabel->text(); + if (x.startsWith(QStringLiteral("\u2022 "))) + return; - m_originalText = x; + m_originalText = x; - m_originalTooltip = m_descriptionLabel->toolTip(); - setTexts(); + m_originalTooltip = m_descriptionLabel->toolTip(); + setTexts(); } - bool UiRequirement::checkRequirement() { - if (!isValid()) - return m_lastResult; + if (!isValid()) + return m_lastResult; - m_lastResult = m_requirementCheck(); + m_lastResult = m_requirementCheck(); - if (!m_descriptionLabel->isVisible() && !m_descriptionLabel->property("checkMe").toBool()) - { - return true; - } - - setTexts(); - - return m_lastResult; -} - - -bool UiRequirementList::checkRequirements(QWidget *messageOnThisParent) -{ - bool result = true; - for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) - { - UiRequirement &r = (*i); - - - if (!r.isValid()) - continue; - - if (!r.checkRequirement()) + if (!m_descriptionLabel->isVisible() && !m_descriptionLabel->property("checkMe").toBool()) { - result = false; + return true; } - } - if (!result && messageOnThisParent) - { - LtsWidgets::LtsMessageDialog::showMessage(messageOnThisParent, - QApplication::translate("LtsWidgets::LtsDialog", - "There are elements that have invalid or no value.
" - "Please change values in the elements which are marked with red text."), - QApplication::translate("LtsWidgets::LtsDialog", "Operation not complete")); - } + setTexts(); - return result; + return m_lastResult; } - -void UiRequirementList::addRequirement(const UiRequirement &uiRequirement) +bool UiRequirementList::checkRequirements(QWidget* messageOnThisParent) { - m_requirementList.append(uiRequirement); + bool result = true; + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement& r = (*i); + + if (!r.isValid()) + continue; + + if (!r.checkRequirement()) + { + result = false; + } + } + + if (!result && messageOnThisParent) + { + LtsWidgets::LtsMessageDialog::showMessage( + messageOnThisParent, + QApplication::translate("LtsWidgets::LtsDialog", + "There are elements that have invalid or no value.
" + "Please change values in the elements which are marked with red text."), + QApplication::translate("LtsWidgets::LtsDialog", "Operation not complete")); + } + + return result; } +void UiRequirementList::addRequirement(const UiRequirement& uiRequirement) +{ + m_requirementList.append(uiRequirement); +} void UiRequirementList::clear() { - for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) - { - UiRequirement &uir = *i; - uir.reset(); - } + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement& uir = *i; + uir.reset(); + } - m_requirementList.clear(); + m_requirementList.clear(); } - void UiRequirementList::retranslate() { - for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) - { - UiRequirement &r = (*i); + for (auto i = m_requirementList.begin(); i != m_requirementList.end(); ++i) + { + UiRequirement& r = (*i); - r.retranslate(); - } + r.retranslate(); + } } -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.h old mode 100755 new mode 100644 index 52358733e..38b1f8cbf --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/requirement_widget.h @@ -1,73 +1,62 @@ - #pragma once #include "ltswidgets_export.h" -#include #include +#include #include - class QLabel; - namespace LtsWidgets { - -class LTSWIDGETS_EXPORT UiRequirement +class LTSWIDGETS_EXPORT UiRequirement { -public: - explicit UiRequirement() = default; + public: + explicit UiRequirement() = default; - + UiRequirement(QLabel* descriptionLabel, const std::function& requirementCheck, + const QString& userWarningMessage = QString()); - UiRequirement(QLabel *descriptionLabel, const std::function &requirementCheck, const QString &userWarningMessage = QString()); + void reset(); - void reset(); + bool checkRequirement(); - + bool isValid() const + { + return m_descriptionLabel != nullptr; + } - bool checkRequirement(); + void retranslate(); - bool isValid() const { return m_descriptionLabel != nullptr; } + private: + void setTexts(); - void retranslate(); - -private: - void setTexts(); - - QLabel *m_descriptionLabel; - std::function m_requirementCheck; - QString m_originalText; - QString m_originalTooltip; - bool m_lastResult; - QString m_userWarningMessage; + QLabel* m_descriptionLabel; + std::function m_requirementCheck; + QString m_originalText; + QString m_originalTooltip; + bool m_lastResult; + QString m_userWarningMessage; }; - - - class LTSWIDGETS_EXPORT UiRequirementList { -public: - UiRequirementList() = default; + public: + UiRequirementList() = default; - + bool checkRequirements(QWidget* messageOnThisParent = nullptr); - bool checkRequirements(QWidget *messageOnThisParent = nullptr); + void addRequirement(const UiRequirement& uiRequirement); - + void clear(); - void addRequirement(const UiRequirement &uiRequirement); + void retranslate(); - void clear(); - - void retranslate(); - -private: - QVector m_requirementList; + private: + QVector m_requirementList; }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp old mode 100755 new mode 100644 index fe6471fac..373657a30 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.cpp @@ -1,221 +1,215 @@ - #include "lts_picture_editing.h" -#include "ui_lts_picture_editing.h" -#include "lts_picture_view.h" -#include -#include -#include -#include -#include +#include "lts_picture_view.h" +#include "ui_lts_picture_editing.h" #include +#include +#include +#include +#include +#include #include -LtsPictureEditing::LtsPictureEditing(QWidget *parent) - : QMainWindow(parent) - , m_gvPicture(nullptr) - , m_ui(new Ui::PictureEditing) +LtsPictureEditing::LtsPictureEditing(QWidget* parent) + : QMainWindow(parent), m_gvPicture(nullptr), m_ui(new Ui::PictureEditing) { - m_ui->setupUi(this); - connect(m_ui->actionOpen, &QAction::triggered, this, &LtsPictureEditing::onOpenImage); - connect(m_ui->actionSave, &QAction::triggered, this, &LtsPictureEditing::onSavePicture); - connect(m_ui->actionQuit, &QAction::triggered, this, &LtsPictureEditing::close); - connect(m_ui->pbSetSize, &QPushButton::clicked, this, &LtsPictureEditing::onSetSize); + m_ui->setupUi(this); + connect(m_ui->actionOpen, &QAction::triggered, this, &LtsPictureEditing::onOpenImage); + connect(m_ui->actionSave, &QAction::triggered, this, &LtsPictureEditing::onSavePicture); + connect(m_ui->actionQuit, &QAction::triggered, this, &LtsPictureEditing::close); + connect(m_ui->pbSetSize, &QPushButton::clicked, this, &LtsPictureEditing::onSetSize); - connect(m_ui->sbHeight, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); - connect(m_ui->sbWidth, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); - connect(m_ui->chbRatio, &QPushButton::clicked, this, &LtsPictureEditing::onRatioClicked); + connect(m_ui->sbHeight, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); + connect(m_ui->sbWidth, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRatioChanged); + connect(m_ui->chbRatio, &QPushButton::clicked, this, &LtsPictureEditing::onRatioClicked); - connect(m_ui->sbXMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onLeftChanged); - connect(m_ui->sbXMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRightChanged); - connect(m_ui->sbYMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onTopChanged); - connect(m_ui->sbYMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onBottomChanged); + connect(m_ui->sbXMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onLeftChanged); + connect(m_ui->sbXMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onRightChanged); + connect(m_ui->sbYMin, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onTopChanged); + connect(m_ui->sbYMax, QOverload::of(&QSpinBox::valueChanged), this, &LtsPictureEditing::onBottomChanged); - addViewToFrame(); + addViewToFrame(); - connect(this, &LtsPictureEditing::leftChanged, m_gvPicture, &LtsWidgets::LtsPictureView::leftChanged); - connect(this, &LtsPictureEditing::rightChanged, m_gvPicture, &LtsWidgets::LtsPictureView::rightChanged); - connect(this, &LtsPictureEditing::topChanged, m_gvPicture, &LtsWidgets::LtsPictureView::topChanged); - connect(this, &LtsPictureEditing::bottomChanged, m_gvPicture, &LtsWidgets::LtsPictureView::bottomChanged); + connect(this, &LtsPictureEditing::leftChanged, m_gvPicture, &LtsWidgets::LtsPictureView::leftChanged); + connect(this, &LtsPictureEditing::rightChanged, m_gvPicture, &LtsWidgets::LtsPictureView::rightChanged); + connect(this, &LtsPictureEditing::topChanged, m_gvPicture, &LtsWidgets::LtsPictureView::topChanged); + connect(this, &LtsPictureEditing::bottomChanged, m_gvPicture, &LtsWidgets::LtsPictureView::bottomChanged); - connect(this, &LtsPictureEditing::setAspectRatio, m_gvPicture, &LtsWidgets::LtsPictureView::setAspectRatio); - connect(this, &LtsPictureEditing::ratioClicked, m_gvPicture, &LtsWidgets::LtsPictureView::ratioClicked); + connect(this, &LtsPictureEditing::setAspectRatio, m_gvPicture, &LtsWidgets::LtsPictureView::setAspectRatio); + connect(this, &LtsPictureEditing::ratioClicked, m_gvPicture, &LtsWidgets::LtsPictureView::ratioClicked); - connect(m_gvPicture, &LtsWidgets::LtsPictureView::mouseMoved, this, &LtsPictureEditing::setSpinboxValues); - connect(m_gvPicture, &LtsWidgets::LtsPictureView::setLimits, this, &LtsPictureEditing::setSpinboxLimits); - connect(this, &LtsPictureEditing::setPicture, m_gvPicture, &LtsWidgets::LtsPictureView::setPicture); + connect(m_gvPicture, &LtsWidgets::LtsPictureView::mouseMoved, this, &LtsPictureEditing::setSpinboxValues); + connect(m_gvPicture, &LtsWidgets::LtsPictureView::setLimits, this, &LtsPictureEditing::setSpinboxLimits); + connect(this, &LtsPictureEditing::setPicture, m_gvPicture, &LtsWidgets::LtsPictureView::setPicture); - onRatioChanged(); + onRatioChanged(); } LtsPictureEditing::~LtsPictureEditing() { - delete m_ui; + delete m_ui; } void LtsPictureEditing::addViewToFrame() { - QHBoxLayout *layout(new QHBoxLayout(m_ui->frPicFrame)); - m_gvPicture = new LtsWidgets::LtsPictureView(m_ui->frPicFrame); - layout->addWidget(m_gvPicture); - m_gvPicture->setEnabled(false); + QHBoxLayout* layout(new QHBoxLayout(m_ui->frPicFrame)); + m_gvPicture = new LtsWidgets::LtsPictureView(m_ui->frPicFrame); + layout->addWidget(m_gvPicture); + m_gvPicture->setEnabled(false); } void LtsPictureEditing::onOpenImage() { - const QStringList filter ({ - tr("Images (*.jpg *.jpeg *.png)") - }); - QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), - QStringLiteral("../picture_editing"), - filter.join(QStringLiteral(";;"))); + const QStringList filter({tr("Images (*.jpg *.jpeg *.png)")}); + QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QStringLiteral("../picture_editing"), + filter.join(QStringLiteral(";;"))); - if (fileName.isEmpty()) - return; + if (fileName.isEmpty()) + return; - QFileInfo fi(fileName); - if (!fi.isReadable()) - { - QMessageBox::warning(this, tr("Error!"), tr("An error occurred while loading the file.\n" - "The loaded file is not readable.")); - return; - } + QFileInfo fi(fileName); + if (!fi.isReadable()) + { + QMessageBox::warning(this, tr("Error!"), + tr("An error occurred while loading the file.\n" + "The loaded file is not readable.")); + return; + } - QImage pic; - pic.load(fileName); - if (pic.isNull()) - { - QMessageBox::warning(this, tr("Error!"), tr("An error occurred while loading the file.\n" - "The loaded file is no picture file.\n" - "Please load *.jpg, *.jpeg, *.png files only.")); - return; - } - m_image = pic; - emit setPicture(pic, QPoint(0, 0), true); - m_gvPicture->setEnabled(true); - m_gvPicture->newRubberBand(); + QImage pic; + pic.load(fileName); + if (pic.isNull()) + { + QMessageBox::warning(this, tr("Error!"), + tr("An error occurred while loading the file.\n" + "The loaded file is no picture file.\n" + "Please load *.jpg, *.jpeg, *.png files only.")); + return; + } + m_image = pic; + emit setPicture(pic, QPoint(0, 0), true); + m_gvPicture->setEnabled(true); + m_gvPicture->newRubberBand(); } void LtsPictureEditing::onSetSize() { - if (m_image.isNull()) - return; + if (m_image.isNull()) + return; - m_gvPicture->hideRubberband(); + m_gvPicture->hideRubberband(); - int xMin = m_ui->sbXMin->value() - 1; - int yMin = m_ui->sbYMin->value() - 1; - int xMax = m_ui->sbXMax->value() - 1; - int yMax = m_ui->sbYMax->value() - 1; + int xMin = m_ui->sbXMin->value() - 1; + int yMin = m_ui->sbYMin->value() - 1; + int xMax = m_ui->sbXMax->value() - 1; + int yMax = m_ui->sbYMax->value() - 1; - if (xMax < xMin || yMax < yMin || xMax == xMin || yMax == yMin) - { - clear(); - return; - } + if (xMax < xMin || yMax < yMin || xMax == xMin || yMax == yMin) + { + clear(); + return; + } - QRect picRect(xMin, - yMin, - xMax - xMin, - yMax - yMin); - QImage newPic = m_image.copy(picRect); - emit setPicture(newPic, QPoint(xMin, yMin), false); + QRect picRect(xMin, yMin, xMax - xMin, yMax - yMin); + QImage newPic = m_image.copy(picRect); + emit setPicture(newPic, QPoint(xMin, yMin), false); } void LtsPictureEditing::onSavePicture() { - if (m_gvPicture->getImage()->pixmap().isNull()) - { - QMessageBox::warning(this, tr("Error!"), tr("An error occurred while saving the picture\n" - "Please load a picture before saving it.")); - return; - } - else - { - QString filename = QFileDialog::getSaveFileName(this, tr("Open Image"), QLatin1String("../picture_editing"), - tr("Images (*.jpg *.jpeg *.png)")); - if (filename.isEmpty()) + if (m_gvPicture->getImage()->pixmap().isNull()) { - QMessageBox::warning(this, tr("Error!"), tr("An error occurred while saving the picture.\n" - "Please choose a valid path to save the picture.")); - return; + QMessageBox::warning(this, tr("Error!"), + tr("An error occurred while saving the picture\n" + "Please load a picture before saving it.")); + return; } + else + { + QString filename = QFileDialog::getSaveFileName(this, tr("Open Image"), QLatin1String("../picture_editing"), + tr("Images (*.jpg *.jpeg *.png)")); + if (filename.isEmpty()) + { + QMessageBox::warning(this, tr("Error!"), + tr("An error occurred while saving the picture.\n" + "Please choose a valid path to save the picture.")); + return; + } - m_gvPicture->getImage()->pixmap().save(filename, "PNG"); - } + m_gvPicture->getImage()->pixmap().save(filename, "PNG"); + } } -void LtsPictureEditing::setSpinboxLimits(const QSize &picSize, bool setValues) +void LtsPictureEditing::setSpinboxLimits(const QSize& picSize, bool setValues) { - m_ui->sbXMin->setMaximum(picSize.width()); - m_ui->sbXMax->setMaximum(picSize.width()); - m_ui->sbYMin->setMaximum(picSize.height()); - m_ui->sbYMax->setMaximum(picSize.height()); + m_ui->sbXMin->setMaximum(picSize.width()); + m_ui->sbXMax->setMaximum(picSize.width()); + m_ui->sbYMin->setMaximum(picSize.height()); + m_ui->sbYMax->setMaximum(picSize.height()); - if (setValues) - { - m_ui->sbXMin->setValue(0); - m_ui->sbYMin->setValue(0); - m_ui->sbXMax->setValue(picSize.width() - 1); - m_ui->sbYMax->setValue(picSize.height() - 1); - } + if (setValues) + { + m_ui->sbXMin->setValue(0); + m_ui->sbYMin->setValue(0); + m_ui->sbXMax->setValue(picSize.width() - 1); + m_ui->sbYMax->setValue(picSize.height() - 1); + } } -void LtsPictureEditing::setSpinboxValues(const QRect &picRect) +void LtsPictureEditing::setSpinboxValues(const QRect& picRect) { - m_ui->sbXMin->setValue(picRect.left()); - m_ui->sbYMin->setValue(picRect.top()); - m_ui->sbXMax->setValue(picRect.right()); - m_ui->sbYMax->setValue(picRect.bottom()); + m_ui->sbXMin->setValue(picRect.left()); + m_ui->sbYMin->setValue(picRect.top()); + m_ui->sbXMax->setValue(picRect.right()); + m_ui->sbYMax->setValue(picRect.bottom()); } void LtsPictureEditing::onRatioChanged() { - double ratio = double(m_ui->sbWidth->value()) / double(m_ui->sbHeight->value()); - emit setAspectRatio(ratio); + double ratio = double(m_ui->sbWidth->value()) / double(m_ui->sbHeight->value()); + emit setAspectRatio(ratio); } void LtsPictureEditing::onRatioClicked() { - if (m_ui->chbRatio->isChecked()) - { - m_ui->sbHeight->setEnabled(true); - m_ui->sbWidth->setEnabled(true); - emit ratioClicked(true); - } - else - { - m_ui->sbHeight->setEnabled(false); - m_ui->sbWidth->setEnabled(false); - emit ratioClicked(false); - } + if (m_ui->chbRatio->isChecked()) + { + m_ui->sbHeight->setEnabled(true); + m_ui->sbWidth->setEnabled(true); + emit ratioClicked(true); + } + else + { + m_ui->sbHeight->setEnabled(false); + m_ui->sbWidth->setEnabled(false); + emit ratioClicked(false); + } } void LtsPictureEditing::onLeftChanged(int left) { - emit leftChanged(left); + emit leftChanged(left); } void LtsPictureEditing::onRightChanged(int right) { - emit rightChanged(right); + emit rightChanged(right); } void LtsPictureEditing::onTopChanged(int top) { - emit topChanged(top); + emit topChanged(top); } void LtsPictureEditing::onBottomChanged(int bottom) { - emit bottomChanged(bottom); + emit bottomChanged(bottom); } - void LtsPictureEditing::clear() { - emit setPicture(QImage(), QPoint(), false); + emit setPicture(QImage(), QPoint(), false); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h old mode 100755 new mode 100644 index 596008f41..9f215637a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing.h @@ -1,61 +1,59 @@ - #pragma once -#include - #include +#include namespace Ui { class PictureEditing; } -namespace LtsWidgets{ - class LtsPictureView; +namespace LtsWidgets +{ +class LtsPictureView; } - class LtsPictureEditing : public QMainWindow { - Q_OBJECT + Q_OBJECT -public: - explicit LtsPictureEditing(QWidget *parent = nullptr); - ~LtsPictureEditing(); + public: + explicit LtsPictureEditing(QWidget* parent = nullptr); + ~LtsPictureEditing(); -private: - QImage m_grayImage; - QImage m_image; + private: + QImage m_grayImage; + QImage m_image; - LtsWidgets::LtsPictureView *m_gvPicture; + LtsWidgets::LtsPictureView* m_gvPicture; - Ui::PictureEditing *m_ui; + Ui::PictureEditing* m_ui; -private: - void setSpinboxLimits(const QSize &picSize, bool setValues = true); - void clear(); - void addViewToFrame(); - void initRatio(); + private: + void setSpinboxLimits(const QSize& picSize, bool setValues = true); + void clear(); + void addViewToFrame(); + void initRatio(); -private slots: - void onOpenImage(); - void onSetSize(); - void setSpinboxValues(const QRect &picRect); - void onRatioChanged(); - void onRatioClicked(); - void onSavePicture(); - void onLeftChanged(int left); - void onRightChanged(int right); - void onTopChanged(int top); - void onBottomChanged(int bottom); + private slots: + void onOpenImage(); + void onSetSize(); + void setSpinboxValues(const QRect& picRect); + void onRatioChanged(); + void onRatioClicked(); + void onSavePicture(); + void onLeftChanged(int left); + void onRightChanged(int right); + void onTopChanged(int top); + void onBottomChanged(int bottom); -signals: - void setPicture(const QImage &, const QPoint &, const bool flag); - void setAspectRatio(double ratio); - void ratioClicked(bool enabled); - int leftChanged(int left); - int rightChanged(int right); - int topChanged(int top); - int bottomChanged(int bottom); + signals: + void setPicture(const QImage&, const QPoint&, const bool flag); + void setAspectRatio(double ratio); + void ratioClicked(bool enabled); + int leftChanged(int left); + int rightChanged(int right); + int topChanged(int top); + int bottomChanged(int bottom); }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp old mode 100755 new mode 100644 index 481025873..751290f17 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/lts_picture_editing_main.cpp @@ -1,39 +1,38 @@ - #include "lts_picture_editing.h" + #include #include -static void qtMsgHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) +static void qtMsgHandler(QtMsgType type, const QMessageLogContext&, const QString& msg) { - switch (type) - { - case QtDebugMsg: - std::cout << "DEBUG: " << qPrintable(msg) << std::endl; - break; - case QtInfoMsg: - std::cout << "INFO: " << qPrintable(msg) << std::endl; - break; - case QtWarningMsg: - std::cout << "WARN: " << qPrintable(msg) << std::endl; - break; - case QtCriticalMsg: - std::cerr << "ERROR: " << qPrintable(msg) << std::endl; - break; - case QtFatalMsg: - std::cerr << "FATAL: " << qPrintable(msg) << std::endl; - break; - } + switch (type) + { + case QtDebugMsg: + std::cout << "DEBUG: " << qPrintable(msg) << std::endl; + break; + case QtInfoMsg: + std::cout << "INFO: " << qPrintable(msg) << std::endl; + break; + case QtWarningMsg: + std::cout << "WARN: " << qPrintable(msg) << std::endl; + break; + case QtCriticalMsg: + std::cerr << "ERROR: " << qPrintable(msg) << std::endl; + break; + case QtFatalMsg: + std::cerr << "FATAL: " << qPrintable(msg) << std::endl; + break; + } } - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - QApplication a(argc, argv); - qInstallMessageHandler(&qtMsgHandler); - LtsPictureEditing w; - w.show(); + QApplication a(argc, argv); + qInstallMessageHandler(&qtMsgHandler); + LtsPictureEditing w; + w.show(); - return a.exec(); + return a.exec(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp old mode 100755 new mode 100644 index a9e99005d..210ed2ec5 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/main.cpp @@ -1,31 +1,15 @@ +#include "window.h" + +#include #include -#include "window.h" -#include - - -int main(int argc, char **argv) +int main(int argc, char** argv) { - QApplication app(argc, argv); + QApplication app(argc, argv); + LtsWidgets::LtsDateTimeEdit dte; + dte.activateWindow(); + dte.show(); - - - - - - - LtsWidgets::LtsDateTimeEdit dte; - dte.activateWindow(); - dte.show(); - - - - - - - - - - return app.exec(); + return app.exec(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp old mode 100755 new mode 100644 index da4f78a2e..8c28659fa --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.cpp @@ -1,59 +1,48 @@ #include "window.h" #include - #include #include - namespace LtsWidgets { -Window::Window(QWidget *parent) - : QWidget(parent) +Window::Window(QWidget* parent) : QWidget(parent) { - - setGeometry(x(), y(), 300, 300); + setGeometry(x(), y(), 300, 300); - QHBoxLayout *lay = new QHBoxLayout; + QHBoxLayout* lay = new QHBoxLayout; - lay->setMargin(0); - + lay->setMargin(0); + auto x1 = new LtsWidgets::LtsNotificationBox; + lay->addWidget(x1); - auto x1 = new LtsWidgets::LtsNotificationBox; - lay->addWidget(x1); + if (qApp->arguments().count() < 2) + abort(); + LtsNotificationBox::MessageType type; - if (qApp->arguments().count() < 2) - abort(); + if (qApp->arguments().at(1) == QStringLiteral("e")) + type = LtsNotificationBox::MessageType::Error; + else if (qApp->arguments().at(1) == QStringLiteral("w")) + type = LtsNotificationBox::MessageType::Warning; + else if (qApp->arguments().at(1) == QStringLiteral("i")) + type = LtsNotificationBox::MessageType::Info; + else if (qApp->arguments().at(1) == QStringLiteral("s")) + type = LtsNotificationBox::MessageType::Success; + else + abort(); + x1->message(QStringLiteral("Title Message"), + QStringLiteral("A text that consists of a lot of characters and also even has
two lines."), type); + connect(x1, &LtsNotificationBox::signalClose, this, &QWidget::close); - LtsNotificationBox::MessageType type; + setLayout(lay); - if (qApp->arguments().at(1) == QStringLiteral("e")) - type = LtsNotificationBox::MessageType::Error; - else if (qApp->arguments().at(1) == QStringLiteral("w")) - type = LtsNotificationBox::MessageType::Warning; - else if (qApp->arguments().at(1) == QStringLiteral("i")) - type = LtsNotificationBox::MessageType::Info; - else if (qApp->arguments().at(1) == QStringLiteral("s")) - type = LtsNotificationBox::MessageType::Success; - else - abort(); - - x1->message(QStringLiteral("Title Message"), QStringLiteral("A text that consists of a lot of characters and also even has
two lines."), type); - connect(x1, &LtsNotificationBox::signalClose, this, &QWidget::close); - - setLayout(lay); - - setAttribute(Qt::WA_TranslucentBackground); + setAttribute(Qt::WA_TranslucentBackground); } +Window::~Window() {} -Window::~Window() -{ - -} - -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h old mode 100755 new mode 100644 index c01805855..43859df41 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/LtsWidgets/tests/window.h @@ -1,17 +1,14 @@ #pragma once #include - #include - namespace LtsWidgets { class Window : public QWidget { - Q_OBJECT -public: - Window(QWidget *parent = nullptr); - ~Window(); - + Q_OBJECT + public: + Window(QWidget* parent = nullptr); + ~Window(); }; -} +} // namespace LtsWidgets diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h old mode 100755 new mode 100644 index 7a267d835..9c5399dc8 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/data_plugin_interface.h @@ -1,18 +1,16 @@ - #pragma once #include - #include #include - namespace NGL { class INGLLogger; } + namespace LtsSession { class LtsSessionDataDds; @@ -21,27 +19,24 @@ class LtsSessionDataDds; namespace DataPluginBase { - class Interface { -public: - Interface() = default; - virtual ~Interface() = default; + public: + Interface() = default; + virtual ~Interface() = default; }; - - class Plugin { -public: - Plugin() = default; - virtual ~Plugin() = default; + public: + Plugin() = default; + virtual ~Plugin() = default; - virtual QString pluginName() const = 0; - virtual std::shared_ptr createDataInterface(LtsSession::LtsSessionDataDds *session) = 0; - virtual bool availableInPartition(IDL::PartitionType partition) const = 0; + virtual QString pluginName() const = 0; + virtual std::shared_ptr createDataInterface(LtsSession::LtsSessionDataDds* session) = 0; + virtual bool availableInPartition(IDL::PartitionType partition) const = 0; }; -} +} // namespace DataPluginBase Q_DECLARE_INTERFACE(DataPluginBase::Plugin, "data:") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h old mode 100755 new mode 100644 index 526dfb7f8..590f7ab2b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/gui_plugin_interface.h @@ -1,19 +1,16 @@ - #pragma once -#include -#include #include #include - +#include +#include +#include #include #include -#include #include - namespace NGL { class INGLLogger; @@ -23,7 +20,8 @@ namespace LtsWidgets { class LtsBackgroundWidget; class LtsBaseLayoutWidget; -} +} // namespace LtsWidgets + namespace LtsSession { class LtsSession; @@ -33,65 +31,113 @@ namespace GuiPluginBase { class Interface; - -class Plugin +class Plugin { -public: - Plugin() = default; - virtual ~Plugin() = default; + public: + Plugin() = default; + virtual ~Plugin() = default; - virtual QString pluginName() = 0; - virtual std::shared_ptr createGuiInterface(LtsSession::LtsSession *session) = 0; - virtual bool availableInPartition(IDL::PartitionType partition) const = 0; + virtual QString pluginName() = 0; + virtual std::shared_ptr createGuiInterface(LtsSession::LtsSession* session) = 0; + virtual bool availableInPartition(IDL::PartitionType partition) const = 0; }; - - class Interface { -public: - Interface(LtsSession::LtsSession *session, NGL::INGLLogger &logger) - : m_hasInit(true) - , m_session(session) - , m_logger(logger) - , m_appId(LtsAppDescriptor::App::Login) - {} - virtual ~Interface() = default; + public: + Interface(LtsSession::LtsSession* session, NGL::INGLLogger& logger) + : m_hasInit(true), m_session(session), m_logger(logger), m_appId(LtsAppDescriptor::App::Login) + { + } - void setFlags(const QFlags &flags) { m_flags = flags; } - const QFlags &getFlags() const { return m_flags; } - void setOptions(const QStringList &options) { m_options = options; } - const QStringList &getOptions() const { return m_options; } - void setAppId(LtsAppDescriptor::App appId) { m_appId = appId; } - LtsAppDescriptor::App appId() const { return m_appId; } + virtual ~Interface() = default; - virtual QVector getActions() { return QVector(); } - - virtual bool fetchInterfaces() { return true; } - virtual void clearInterfaces() {} - virtual QString menuGroup() const { return {}; } - virtual LtsUtils::LtsTranslatableIdentifier menuGroupIdentifier() const { m_hasMenuGroupIdentifier = false; return {}; } - virtual bool availableInPartition(IDL::PartitionType partition) const { Q_UNUSED(partition); return true; } - virtual void init() { m_hasInit = false; } + void setFlags(const QFlags& flags) + { + m_flags = flags; + } - - virtual void executePayload(LtsWidgets::LtsBackgroundWidget *mainBackground) { (void)mainBackground; } - virtual int executionPriority() const { return -1; } + const QFlags& getFlags() const + { + return m_flags; + } - + void setOptions(const QStringList& options) + { + m_options = options; + } - bool m_hasInit; - mutable bool m_hasMenuGroupIdentifier = true; + const QStringList& getOptions() const + { + return m_options; + } -protected: - LtsSession::LtsSession *m_session; -private: - QFlags m_flags; - QStringList m_options; - LtsAppDescriptor::App m_appId; - + void setAppId(LtsAppDescriptor::App appId) + { + m_appId = appId; + } + + LtsAppDescriptor::App appId() const + { + return m_appId; + } + + virtual QVector getActions() + { + return QVector(); + } + + virtual bool fetchInterfaces() + { + return true; + } + + virtual void clearInterfaces() {} + + virtual QString menuGroup() const + { + return {}; + } + + virtual LtsUtils::LtsTranslatableIdentifier menuGroupIdentifier() const + { + m_hasMenuGroupIdentifier = false; + return {}; + } + + virtual bool availableInPartition(IDL::PartitionType partition) const + { + Q_UNUSED(partition); + return true; + } + + virtual void init() + { + m_hasInit = false; + } + + virtual void executePayload(LtsWidgets::LtsBackgroundWidget* mainBackground) + { + (void)mainBackground; + } + + virtual int executionPriority() const + { + return -1; + } + + bool m_hasInit; + mutable bool m_hasMenuGroupIdentifier = true; + + protected: + LtsSession::LtsSession* m_session; + + private: + QFlags m_flags; + QStringList m_options; + LtsAppDescriptor::App m_appId; }; -} +} // namespace GuiPluginBase Q_DECLARE_INTERFACE(GuiPluginBase::Plugin, "gui") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h old mode 100755 new mode 100644 index fffe29e13..40536c355 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/project_plugin_interface.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,11 +8,11 @@ namespace ProjectPlugin { class Plugin { -public: - Plugin() = default; - virtual ~Plugin() = default; + public: + Plugin() = default; + virtual ~Plugin() = default; }; -} +} // namespace ProjectPlugin Q_DECLARE_INTERFACE(ProjectPlugin::Plugin, "project") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h old mode 100755 new mode 100644 index 614ed712f..ed05c37e0 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/record_replay_plugin.h @@ -1,13 +1,12 @@ - #pragma once -#include -#include +#include #include #include -#include +#include +#include namespace DDSConnector { @@ -15,90 +14,66 @@ class DdsConnector; } class NSqlQuery; + namespace RecordReplay { class RecordReplayPlugin { -public: - RecordReplayPlugin() = default; - virtual ~RecordReplayPlugin() = default; + public: + RecordReplayPlugin() = default; + virtual ~RecordReplayPlugin() = default; - virtual QString pluginName() const = 0; + virtual QString pluginName() const = 0; - + virtual bool initDtc(const std::shared_ptr& ddsConnector, int exerciseId) = 0; - virtual bool initDtc(const std::shared_ptr &ddsConnector, - int exerciseId) = 0; - + virtual bool initDts(const std::shared_ptr& ddsConnector, int exerciseId, + bool bCanHandleSchemas, NSqlQuery& query) = 0; - virtual bool initDts(const std::shared_ptr &ddsConnector, - int exerciseId, - bool bCanHandleSchemas, - NSqlQuery &query) = 0; + virtual bool initCopy(int exerciseId, bool bCanHandleSchemasRead, bool bCanHandleSchemasWrite) = 0; - + virtual bool copyData(NSqlQuery& queryFrom, NSqlQuery& queryTo, qint64 fromTime, qint64 toTime) = 0; - virtual bool initCopy(int exerciseId, bool bCanHandleSchemasRead, bool bCanHandleSchemasWrite) = 0; + virtual QString svcShortName() const = 0; - + virtual bool ddsTopicsToDatabase(NSqlQuery& query, QHash& minRecordSampleTimes) = 0; - virtual bool copyData(NSqlQuery &queryFrom, NSqlQuery &queryTo, qint64 fromTime, qint64 toTime) = 0; + virtual bool setReplayStartTime(NSqlQuery& query, qint64 startTime) = 0; - + virtual bool ddsTopicsFromDatabase(NSqlQuery& query, qint64 fromTime, qint64 toTime) = 0; - virtual QString svcShortName() const = 0; + virtual bool publishData(qint64 desiredTime) = 0; - - + virtual bool waitForAsyncOperations(qint64 desiredTime) + { + Q_UNUSED(desiredTime); + return true; + } - virtual bool ddsTopicsToDatabase(NSqlQuery &query, QHash &minRecordSampleTimes) = 0; - - + virtual void clearData() = 0; - virtual bool setReplayStartTime(NSqlQuery &query, qint64 startTime) = 0; - + struct RecSnapshot + { + qint64 timeStamp = 0; + std::map recIdArray; + RecSnapshot() = default; - virtual bool ddsTopicsFromDatabase(NSqlQuery &query, qint64 fromTime, qint64 toTime) = 0; - + RecSnapshot(qint64 timeStamp_, const std::map& recIdArray_) + : timeStamp(timeStamp_), recIdArray(recIdArray_) + { + } + }; - virtual bool publishData(qint64 desiredTime) = 0; - + virtual std::map> + getSnapshotTimes(NSqlQuery& query, qint64 toTime, qint64 interval, + const QHash& minRecordedSampleTimes) = 0; - virtual bool waitForAsyncOperations(qint64 desiredTime) { Q_UNUSED(desiredTime); return true; } - + virtual QVector getRecordTopicNames() const = 0; - virtual void clearData() = 0; + virtual QVector getRecordTableNames() const = 0; - - struct RecSnapshot - { - qint64 timeStamp = 0; - std::map recIdArray; - RecSnapshot() = default; - RecSnapshot(qint64 timeStamp_, const std::map &recIdArray_) - : timeStamp(timeStamp_) - , recIdArray(recIdArray_) - {} - }; - - - virtual std::map> getSnapshotTimes(NSqlQuery &query, - qint64 toTime, - qint64 interval, - const QHash &minRecordedSampleTimes) = 0; - - - - virtual QVector getRecordTopicNames() const = 0; - - - - virtual QVector getRecordTableNames() const = 0; - - - - virtual qint64 getMinimumSampleTime(NSqlQuery &q, const QString &topicName, qint64 defaultValue) const = 0; + virtual qint64 getMinimumSampleTime(NSqlQuery& q, const QString& topicName, qint64 defaultValue) const = 0; }; -} +} // namespace RecordReplay Q_DECLARE_INTERFACE(RecordReplay::RecordReplayPlugin, "special:3:recordreplay") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h old mode 100755 new mode 100644 index 64c49c213..1ef779022 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/style_plugin_interface.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,14 +8,14 @@ namespace StylePlugin { class Plugin { -public: - Plugin() = default; - virtual ~Plugin() = default; + public: + Plugin() = default; + virtual ~Plugin() = default; - virtual void loadStyle(bool highDpi) = 0; - virtual void unloadStyle() = 0; + virtual void loadStyle(bool highDpi) = 0; + virtual void unloadStyle() = 0; }; -} +} // namespace StylePlugin Q_DECLARE_INTERFACE(StylePlugin::Plugin, "style") diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h old mode 100755 new mode 100644 index 46e02de9d..2767bed0b --- a/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/PluginInterfaces/topic_replay_interface.h @@ -1,124 +1,131 @@ - #pragma once -#include - #include #include - +#include class QWidget; -namespace TopicEditorBase { class ExportNotifier; } - +namespace TopicEditorBase +{ +class ExportNotifier; +} namespace TopicReplay { - - class Interface { -public: - static QJsonObject timeRange(qint64 start, qint64 end) - { - return { {QStringLiteral("start"), start}, {QStringLiteral("end"), end} }; - } - - struct SituationReplayTime - { - int id = 0; - - qint64 topicStart_s = -1; - qint64 topicEnd_s = -1; - - qint64 replayStart_ms = -1; - qint64 replayEnd_ms = -1; - double replaySpeedFactor = 1; - - QJsonObject toReplayInformation() const + public: + static QJsonObject timeRange(qint64 start, qint64 end) { - return { - {QStringLiteral("id"), id}, - {QStringLiteral("timeInPresentation"), timeRange(topicStart_s * 1000, topicEnd_s * 1000)}, - }; + return {{QStringLiteral("start"), start}, {QStringLiteral("end"), end}}; } - QJsonObject toPlaybackTime(double max) const + + struct SituationReplayTime { - QJsonObject ret = timeRange(replayStart_ms, std::min(replayEnd_ms * replaySpeedFactor, max)); - ret[QStringLiteral("replaySpeedFactor")] = replaySpeedFactor; - return ret; - } - QJsonObject toJson(double maxReplayEndMs) const + int id = 0; + + qint64 topicStart_s = -1; + qint64 topicEnd_s = -1; + + qint64 replayStart_ms = -1; + qint64 replayEnd_ms = -1; + double replaySpeedFactor = 1; + + QJsonObject toReplayInformation() const + { + return { + {QStringLiteral("id"), id}, + {QStringLiteral("timeInPresentation"), timeRange(topicStart_s * 1000, topicEnd_s * 1000)}, + }; + } + + QJsonObject toPlaybackTime(double max) const + { + QJsonObject ret = timeRange(replayStart_ms, std::min(replayEnd_ms * replaySpeedFactor, max)); + ret[QStringLiteral("replaySpeedFactor")] = replaySpeedFactor; + return ret; + } + + QJsonObject toJson(double maxReplayEndMs) const + { + return { + {QStringLiteral("playbackTime"), toPlaybackTime(maxReplayEndMs)}, + {QStringLiteral("replayInformation"), toReplayInformation()}, + }; + } + }; + + Interface() = default; + virtual ~Interface() = default; + + virtual QWidget* createWidget() { - return { - {QStringLiteral("playbackTime"), toPlaybackTime(maxReplayEndMs)}, - {QStringLiteral("replayInformation"), toReplayInformation()}, - }; + return nullptr; } - }; - Interface() = default; - virtual ~Interface() = default; + virtual bool playbackInit(const QJsonObject& attributes) + { + Q_UNUSED(attributes); + return true; + } - + virtual bool playbackStart(int secondsOffset) + { + Q_UNUSED(secondsOffset); + return true; + } - virtual QWidget *createWidget() { return nullptr; } + virtual bool playbackPause() + { + return true; + } - - + virtual bool playbackStop() + { + return true; + } - virtual bool playbackInit(const QJsonObject &attributes) { Q_UNUSED(attributes); return true; } + virtual void setExportPlaybackTimes(qint64 startTimeSec, qint64 durationSec, + const QVector& sitReplayTimes) + { + Q_UNUSED(startTimeSec); + Q_UNUSED(durationSec); + Q_UNUSED(sitReplayTimes); + } - - virtual bool playbackStart(int secondsOffset) { Q_UNUSED(secondsOffset); return true; } - virtual bool playbackPause() { return true; } - virtual bool playbackStop() { return true; } + virtual bool exportTopic(const QJsonObject& attributes, const QString& strFolderPath, + TopicEditorBase::ExportNotifier* pExportNotifier) = 0; - + virtual QVector additionalTrackEntries(const QJsonObject& attributes) const + { + Q_UNUSED(attributes); + return {}; + } - virtual void setExportPlaybackTimes( - qint64 startTimeSec, qint64 durationSec, const QVector &sitReplayTimes - ) - { - Q_UNUSED(startTimeSec); - Q_UNUSED(durationSec); - Q_UNUSED(sitReplayTimes); - } - virtual bool exportTopic( - const QJsonObject &attributes, const QString &strFolderPath, TopicEditorBase::ExportNotifier *pExportNotifier - ) = 0; - - - virtual QVector additionalTrackEntries(const QJsonObject &attributes) const - { - Q_UNUSED(attributes); - return {}; - } - - virtual QVector additionalTrackEntries(const QJsonObject &attributes, bool &keepOriginalTopic) const - { - keepOriginalTopic = true; - return additionalTrackEntries(attributes); - } - - virtual void setBasePath(const QString &basePath) { Q_UNUSED(basePath); } + virtual QVector additionalTrackEntries(const QJsonObject& attributes, + bool& keepOriginalTopic) const + { + keepOriginalTopic = true; + return additionalTrackEntries(attributes); + } + virtual void setBasePath(const QString& basePath) + { + Q_UNUSED(basePath); + } }; - - - class Factory { -public: - virtual ~Factory() = default; - virtual Interface *createInterface(TopicEditorBase::TopicType topicType) = 0; - + public: + virtual ~Factory() = default; + virtual Interface* createInterface(TopicEditorBase::TopicType topicType) = 0; }; -} +} // namespace TopicReplay diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h b/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h old mode 100755 new mode 100644 index 2c7bcb3fc..a88ffc33d --- a/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/ProjectConfig/project_defines.h @@ -1,73 +1,66 @@ - #pragma once -#include #include +#include namespace IDL { -enum class PartitionType -{ - Any, - Global, - Exercise, - AllExercises, - Replay, +enum class PartitionType { + Any, + Global, + Exercise, + AllExercises, + Replay, }; inline std::string toStdString(PartitionType pt) { - switch (pt) - { - case PartitionType::Any: - return "Any"; - case PartitionType::Global: - return "Global"; - case PartitionType::Exercise: - return "Exercise"; - case PartitionType::AllExercises: - return "AllExercises"; - case PartitionType::Replay: - return "Replay"; - } - return std::string("invalid:") + std::to_string(static_cast(pt)); + switch (pt) + { + case PartitionType::Any: + return "Any"; + case PartitionType::Global: + return "Global"; + case PartitionType::Exercise: + return "Exercise"; + case PartitionType::AllExercises: + return "AllExercises"; + case PartitionType::Replay: + return "Replay"; + } + return std::string("invalid:") + std::to_string(static_cast(pt)); } -inline std::ostream& operator <<(std::ostream &o, PartitionType pt) +inline std::ostream& operator<<(std::ostream& o, PartitionType pt) { - switch (pt) - { - case PartitionType::Any: - case PartitionType::Global: - case PartitionType::Exercise: - case PartitionType::AllExercises: - case PartitionType::Replay: - return o << std::string("PartitionType::") + toStdString(pt); - default: - return o << std::to_string(static_cast(pt)); - } + switch (pt) + { + case PartitionType::Any: + case PartitionType::Global: + case PartitionType::Exercise: + case PartitionType::AllExercises: + case PartitionType::Replay: + return o << std::string("PartitionType::") + toStdString(pt); + default: + return o << std::to_string(static_cast(pt)); + } } - - inline std::string exercisePartition(int exerciseId) { - if (exerciseId < 0) - return { "ex_*" }; - return std::string("ex_") + std::to_string(exerciseId); + if (exerciseId < 0) + return {"ex_*"}; + return std::string("ex_") + std::to_string(exerciseId); } - - inline std::string replayPartition(int partitionId) { - if (partitionId < 0) - return { "srp_*" }; - return std::string("srp_") + std::to_string(partitionId); + if (partitionId < 0) + return {"srp_*"}; + return std::string("srp_") + std::to_string(partitionId); } -} - +} // namespace IDL diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.cpp old mode 100755 new mode 100644 index 3c08c136e..39c4abd86 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.cpp @@ -1,122 +1,100 @@ - #include "topic_editor_base.h" + #include "topic_preview_widget.h" #include - -#include #include - +#include namespace TopicEditorBase { -TopicEditor::TopicEditor(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_previewWidget(nullptr) +TopicEditor::TopicEditor(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_previewWidget(nullptr) { - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); } - - - -void TopicEditor::setTopicData(const TopicEditorBase::TopicData &data) +void TopicEditor::setTopicData(const TopicEditorBase::TopicData& data) { - m_topicData = data; - m_topicDuration = data.duration; + m_topicData = data; + m_topicDuration = data.duration; - if (m_previewWidget == nullptr) - { - QMessageBox::critical( - nullptr, QStringLiteral("An den Entwickler!"), - QStringLiteral("!! STOP !! - Dieser Topic Editor hatte 'init()' vorher nicht aufgerufen!") - ); - - return; - } + if (m_previewWidget == nullptr) + { + QMessageBox::critical( + nullptr, QStringLiteral("An den Entwickler!"), + QStringLiteral("!! STOP !! - Dieser Topic Editor hatte 'init()' vorher nicht aufgerufen!")); - m_previewWidget->setTopicData(m_topicData); + return; + } - bool isAlreadyUnchangeable = unchangeable(); - if (!isAlreadyUnchangeable) - setUnchangeable(true); + m_previewWidget->setTopicData(m_topicData); - updateInternalData(); + bool isAlreadyUnchangeable = unchangeable(); + if (!isAlreadyUnchangeable) + setUnchangeable(true); - if (!isAlreadyUnchangeable) - setUnchangeable(false); + updateInternalData(); + + if (!isAlreadyUnchangeable) + setUnchangeable(false); } - void TopicEditor::setDuration(int duration) { - m_topicData.duration = duration; - updateInternalLength(); + m_topicData.duration = duration; + updateInternalLength(); } - - - -void TopicEditor::init(TopicPreviewWidget *widget) +void TopicEditor::init(TopicPreviewWidget* widget) { - m_previewWidget = widget; - connect(m_previewWidget, &TopicPreviewWidget::deleteMe, - this, &TopicEditor::deleteLater); + m_previewWidget = widget; + connect(m_previewWidget, &TopicPreviewWidget::deleteMe, this, &TopicEditor::deleteLater); - - m_previewWidget->setTopicEnabled(false); - connect(this, &TopicEditor::signalChangesMade, this, [this]() - { m_previewWidget->setTopicEnabled(false); - }); + connect(this, &TopicEditor::signalChangesMade, this, [this]() { m_previewWidget->setTopicEnabled(false); }); } - -void TopicEditor::setTopicDataProperty(const QString &key, const QJsonValue &value) +void TopicEditor::setTopicDataProperty(const QString& key, const QJsonValue& value) { - m_topicData.properties[key] = value; - emit signalChangesMade(); + m_topicData.properties[key] = value; + emit signalChangesMade(); } - void TopicEditor::applied() { - m_previewWidget->setTopicEnabled(true); - emit topicDataChanged(); + m_previewWidget->setTopicEnabled(true); + emit topicDataChanged(); } void TopicEditor::setIsPlaying(bool isPlaying) { - m_isPlaying = isPlaying; + m_isPlaying = isPlaying; } - - - bool TopicEditor::apply() { - if (m_previewWidget == nullptr) - { - QMessageBox::critical( - nullptr, QStringLiteral("An den Entwickler!"), - QStringLiteral("!! STOP !! - Dieser Topic Editor hatte 'init()' vorher nicht aufgerufen!") - ); - - return false; - } - if (m_isPlaying) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Please Stop Playback first")); - return false; - } + if (m_previewWidget == nullptr) + { + QMessageBox::critical( + nullptr, QStringLiteral("An den Entwickler!"), + QStringLiteral("!! STOP !! - Dieser Topic Editor hatte 'init()' vorher nicht aufgerufen!")); - bool result = apply2(); - if (result) - applied(); - return result; + return false; + } + if (m_isPlaying) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Please Stop Playback first")); + return false; + } + + bool result = apply2(); + if (result) + applied(); + return result; } -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.h b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.h old mode 100755 new mode 100644 index 398449802..789085a77 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_base.h @@ -1,125 +1,161 @@ - #pragma once -#include - #include "topic_editor_utils.h" - #include "topiceditorbase_export.h" -#include + #include +#include #include #include +#include - -namespace LtsUtils { class Promise; } - +namespace LtsUtils +{ +class Promise; +} namespace TopicEditorBase { class TopicPreviewWidget; - -class TOPICEDITORBASE_EXPORT ExportNotifier : public QObject +class TOPICEDITORBASE_EXPORT ExportNotifier : public QObject { - Q_OBJECT + Q_OBJECT -public: - ExportNotifier(QObject *parent) - : QObject(parent) - {} + public: + ExportNotifier(QObject* parent) : QObject(parent) {} - bool isSuccessful = false; - QString successMessage; + bool isSuccessful = false; + QString successMessage; - void setExportSuccessful(const QString &message) - { - isSuccessful = true; - successMessage = message; - emit exportSuccessful(message); - emit exportFinished(); - } + void setExportSuccessful(const QString& message) + { + isSuccessful = true; + successMessage = message; + emit exportSuccessful(message); + emit exportFinished(); + } - void setExportFailed() - { - isSuccessful = false; - successMessage = QString(); - emit exportFailed(); - emit exportFinished(); - } + void setExportFailed() + { + isSuccessful = false; + successMessage = QString(); + emit exportFailed(); + emit exportFinished(); + } -signals: - void stillAlive(); - void exportSuccessful(const QString &); - void exportFailed(); - void exportFinished(); + signals: + void stillAlive(); + void exportSuccessful(const QString&); + void exportFailed(); + void exportFinished(); }; - -class TOPICEDITORBASE_EXPORT TopicEditor: public LtsWidgets::LtsDialog +class TOPICEDITORBASE_EXPORT TopicEditor : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit TopicEditor(QWidget *parent = nullptr); - virtual ~TopicEditor() = default; + public: + explicit TopicEditor(QWidget* parent = nullptr); + virtual ~TopicEditor() = default; - TopicData &topicData() { return m_topicData; } - void setTopicData(const TopicData &data); + TopicData& topicData() + { + return m_topicData; + } - int topicId() const { return m_topicData.id; } + void setTopicData(const TopicData& data); - int startTime() const { return m_topicData.startTime; } - void setStartTime(int start) { m_topicData.startTime = start; } + int topicId() const + { + return m_topicData.id; + } - int duration() const { return m_topicData.duration; } - void setDuration(int duration); + int startTime() const + { + return m_topicData.startTime; + } - QString description() const { return m_topicData.description; } - void setDescription(const QString &description) { m_topicData.description = description; } + void setStartTime(int start) + { + m_topicData.startTime = start; + } - TopicPreviewWidget *topicPreviewWidget() { return m_previewWidget; } + int duration() const + { + return m_topicData.duration; + } -protected: - void init(TopicPreviewWidget *widget); + void setDuration(int duration); - + QString description() const + { + return m_topicData.description; + } - virtual void updateInternalData() = 0; - virtual void updateInternalLength() {} + void setDescription(const QString& description) + { + m_topicData.description = description; + } - TopicType topicType() const { return m_topicData.topicType; } - QJsonValue getTopicDataValue(const QString &key) const { return m_topicData.properties.value(key); } - QJsonArray getTopicVDataAsArray(const QString &key) const { return m_topicData.properties.value(key).toArray(); } + TopicPreviewWidget* topicPreviewWidget() + { + return m_previewWidget; + } - bool hasTopicDataProperties() const { return !m_topicData.properties.isEmpty(); } - void setTopicDataProperty(const QString &key, const QJsonValue &value); + protected: + void init(TopicPreviewWidget* widget); - void applied(); + virtual void updateInternalData() = 0; -public slots: - virtual bool apply2() = 0; - void setIsPlaying(bool isPlaying); + virtual void updateInternalLength() {} -private slots: - bool apply() override final; + TopicType topicType() const + { + return m_topicData.topicType; + } -signals: - void topicDataChanged(); - void topicEditorRequested(const TopicData &); - void durationCheckRequested(int duration, LtsUtils::Promise *promise); - void signalSetTopicPosition(QWidget *widget, int ignoreTopicForReplay); - void changesSaved(const TopicData &data); + QJsonValue getTopicDataValue(const QString& key) const + { + return m_topicData.properties.value(key); + } -protected: - TopicData m_topicData; - int m_topicDuration{-1}; - bool m_isPlaying {false}; + QJsonArray getTopicVDataAsArray(const QString& key) const + { + return m_topicData.properties.value(key).toArray(); + } - TopicPreviewWidget *m_previewWidget{nullptr}; + bool hasTopicDataProperties() const + { + return !m_topicData.properties.isEmpty(); + } + void setTopicDataProperty(const QString& key, const QJsonValue& value); + + void applied(); + + public slots: + virtual bool apply2() = 0; + void setIsPlaying(bool isPlaying); + + private slots: + bool apply() override final; + + signals: + void topicDataChanged(); + void topicEditorRequested(const TopicData&); + void durationCheckRequested(int duration, LtsUtils::Promise* promise); + void signalSetTopicPosition(QWidget* widget, int ignoreTopicForReplay); + void changesSaved(const TopicData& data); + + protected: + TopicData m_topicData; + int m_topicDuration{-1}; + bool m_isPlaying{false}; + + TopicPreviewWidget* m_previewWidget{nullptr}; }; -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_interface.h old mode 100755 new mode 100644 index 96d0d13d4..8d961ba61 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_interface.h @@ -1,12 +1,10 @@ - #pragma once #include "topic_editor_utils.h" - -namespace TopicEditorBase +namespace TopicEditorBase { class TopicEditor; @@ -14,15 +12,17 @@ class TopicEditor; class Interface { -public: - virtual ~Interface() = default; + public: + virtual ~Interface() = default; - + virtual TopicEditor* createTopicEditor(const TopicData&) = 0; - virtual TopicEditor *createTopicEditor(const TopicData &) = 0; - virtual bool initTopicEditor() { return true; } - virtual void finishTopicEditor() {} + virtual bool initTopicEditor() + { + return true; + } + virtual void finishTopicEditor() {} }; -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.cpp old mode 100755 new mode 100644 index b2e495100..8e30cc87c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.cpp @@ -8,311 +8,288 @@ #include #include - namespace TopicEditorBase { QString topicTypeTranslation(TopicType topicType) { - switch (topicType) - { - case TopicType::SituationMap: - return QLabel::tr("SituationMap"); - case TopicType::SituationReplay: - return QLabel::tr("SituationReplay"); - case TopicType::Image: - return QLabel::tr("Image"); - case TopicType::Text: - return QLabel::tr("Text"); - case TopicType::Pdf: - return QLabel::tr("Pdf"); - case TopicType::Xml: - return QLabel::tr("Xml"); - case TopicType::TacticalPlan: - return QLabel::tr("TacticalPlan"); - case TopicType::MSOffice: - return QLabel::tr("MSOffice"); - case TopicType::OpenOffice: - return QLabel::tr("OpenOffice"); - case TopicType::Audio: - return QLabel::tr("Audio"); - case TopicType::Video: - return QLabel::tr("Video"); - case TopicType::Building: - return QLabel::tr("Building"); - case TopicType::SituationMapFilter: - return QLabel::tr("SituationMapFilter"); - case TopicType::Snapshot: - return QLabel::tr("Snapshot"); - case TopicType::Evaluation: - return QLabel::tr("Evaluation"); - case TopicType::Report: - return QLabel::tr("Report"); - case TopicType::Situation: - return QLabel::tr("Situation"); - case TopicType::Invalid: - default: - return QLabel::tr("Invalid"); - } - Q_UNREACHABLE(); - + switch (topicType) + { + case TopicType::SituationMap: + return QLabel::tr("SituationMap"); + case TopicType::SituationReplay: + return QLabel::tr("SituationReplay"); + case TopicType::Image: + return QLabel::tr("Image"); + case TopicType::Text: + return QLabel::tr("Text"); + case TopicType::Pdf: + return QLabel::tr("Pdf"); + case TopicType::Xml: + return QLabel::tr("Xml"); + case TopicType::TacticalPlan: + return QLabel::tr("TacticalPlan"); + case TopicType::MSOffice: + return QLabel::tr("MSOffice"); + case TopicType::OpenOffice: + return QLabel::tr("OpenOffice"); + case TopicType::Audio: + return QLabel::tr("Audio"); + case TopicType::Video: + return QLabel::tr("Video"); + case TopicType::Building: + return QLabel::tr("Building"); + case TopicType::SituationMapFilter: + return QLabel::tr("SituationMapFilter"); + case TopicType::Snapshot: + return QLabel::tr("Snapshot"); + case TopicType::Evaluation: + return QLabel::tr("Evaluation"); + case TopicType::Report: + return QLabel::tr("Report"); + case TopicType::Situation: + return QLabel::tr("Situation"); + case TopicType::Invalid: + default: + return QLabel::tr("Invalid"); + } + Q_UNREACHABLE(); } QString topicTypeString(TopicType topicType) { - switch (topicType) - { - case TopicType::SituationMap: - return QStringLiteral("SituationMap"); - case TopicType::SituationReplay: - return QStringLiteral("SituationReplay"); - case TopicType::Image: - return QStringLiteral("Image"); - case TopicType::Text: - return QStringLiteral("Text"); - case TopicType::Pdf: - return QStringLiteral("Pdf"); - case TopicType::Xml: - return QStringLiteral("Xml"); - case TopicType::TacticalPlan: - return QStringLiteral("TacticalPlan"); - case TopicType::MSOffice: - return QStringLiteral("MSOffice"); - case TopicType::OpenOffice: - return QStringLiteral("OpenOffice"); - case TopicType::Audio: - return QStringLiteral("Audio"); - case TopicType::Video: - return QStringLiteral("Video"); - case TopicType::Building: - return QStringLiteral("Building"); - case TopicType::SituationMapFilter: - return QStringLiteral("SituationMapFilter"); - case TopicType::Snapshot: - return QStringLiteral("Snapshot"); - case TopicType::Evaluation: - return QStringLiteral("Evaluation"); - case TopicType::Report: - return QStringLiteral("Report"); - case TopicType::Situation: - return QStringLiteral("Situation"); - case TopicType::Invalid: - default: - return QStringLiteral("Invalid"); - } - Q_UNREACHABLE(); + switch (topicType) + { + case TopicType::SituationMap: + return QStringLiteral("SituationMap"); + case TopicType::SituationReplay: + return QStringLiteral("SituationReplay"); + case TopicType::Image: + return QStringLiteral("Image"); + case TopicType::Text: + return QStringLiteral("Text"); + case TopicType::Pdf: + return QStringLiteral("Pdf"); + case TopicType::Xml: + return QStringLiteral("Xml"); + case TopicType::TacticalPlan: + return QStringLiteral("TacticalPlan"); + case TopicType::MSOffice: + return QStringLiteral("MSOffice"); + case TopicType::OpenOffice: + return QStringLiteral("OpenOffice"); + case TopicType::Audio: + return QStringLiteral("Audio"); + case TopicType::Video: + return QStringLiteral("Video"); + case TopicType::Building: + return QStringLiteral("Building"); + case TopicType::SituationMapFilter: + return QStringLiteral("SituationMapFilter"); + case TopicType::Snapshot: + return QStringLiteral("Snapshot"); + case TopicType::Evaluation: + return QStringLiteral("Evaluation"); + case TopicType::Report: + return QStringLiteral("Report"); + case TopicType::Situation: + return QStringLiteral("Situation"); + case TopicType::Invalid: + default: + return QStringLiteral("Invalid"); + } + Q_UNREACHABLE(); } -TopicType topicTypeFromString(const QString &topicName) +TopicType topicTypeFromString(const QString& topicName) { - static const QHash topics = - { - { QStringLiteral("Invalid"), TopicType::Invalid }, - { QStringLiteral("SituationMap"), TopicType::SituationMap }, - { QStringLiteral("SituationReplay"), TopicType::SituationReplay }, - { QStringLiteral("Image"), TopicType::Image }, - { QStringLiteral("Text"), TopicType::Text }, - { QStringLiteral("Pdf"), TopicType::Pdf }, - { QStringLiteral("Xml"), TopicType::Xml }, - { QStringLiteral("TacticalPlan"), TopicType::TacticalPlan }, - { QStringLiteral("MSOffice"), TopicType::MSOffice }, - { QStringLiteral("OpenOffice"), TopicType::OpenOffice }, - { QStringLiteral("Audio"), TopicType::Audio }, - { QStringLiteral("Video"), TopicType::Video }, - { QStringLiteral("Building"), TopicType::Building }, - { QStringLiteral("SituationMapFilter"), TopicType::SituationMapFilter }, - { QStringLiteral("Snapshot"), TopicType::Snapshot }, - { QStringLiteral("Evaluation"), TopicType::Evaluation }, - { QStringLiteral("Report"), TopicType::Report }, - { QStringLiteral("Situation"), TopicType::Situation }, - }; - return topics.contains(topicName) ? topics.value(topicName) : TopicType::Invalid; + static const QHash topics = { + {QStringLiteral("Invalid"), TopicType::Invalid}, + {QStringLiteral("SituationMap"), TopicType::SituationMap}, + {QStringLiteral("SituationReplay"), TopicType::SituationReplay}, + {QStringLiteral("Image"), TopicType::Image}, + {QStringLiteral("Text"), TopicType::Text}, + {QStringLiteral("Pdf"), TopicType::Pdf}, + {QStringLiteral("Xml"), TopicType::Xml}, + {QStringLiteral("TacticalPlan"), TopicType::TacticalPlan}, + {QStringLiteral("MSOffice"), TopicType::MSOffice}, + {QStringLiteral("OpenOffice"), TopicType::OpenOffice}, + {QStringLiteral("Audio"), TopicType::Audio}, + {QStringLiteral("Video"), TopicType::Video}, + {QStringLiteral("Building"), TopicType::Building}, + {QStringLiteral("SituationMapFilter"), TopicType::SituationMapFilter}, + {QStringLiteral("Snapshot"), TopicType::Snapshot}, + {QStringLiteral("Evaluation"), TopicType::Evaluation}, + {QStringLiteral("Report"), TopicType::Report}, + {QStringLiteral("Situation"), TopicType::Situation}, + }; + return topics.contains(topicName) ? topics.value(topicName) : TopicType::Invalid; } QIcon topicIcon(const TopicType topicType) { - switch (topicType) - { - case TopicType::SituationMap: - return QIcon(QLatin1String("icon:add_situation.svg")); - case TopicType::Situation: - return QIcon(QLatin1String("icon:add_situation_combined.svg")); - case TopicType::SituationReplay: - return QIcon(QLatin1String("icon:add_restart.svg")); - case TopicType::Image: - return QIcon(QLatin1String("icon:create_image_topic.svg")); - case TopicType::Text: - return QIcon(QLatin1String("icon:document-new-txt.svg")); - case TopicType::Pdf: - return QIcon(QLatin1String("icon:create_pdf_topic.svg")); - case TopicType::Xml: - return QIcon(QLatin1String("icon:document-new-xml.svg")); - case TopicType::TacticalPlan: - return QIcon(QLatin1String("icon:tactical_organization.svg")); - case TopicType::MSOffice: - return QIcon(QLatin1String("icon:ms_office.svg")); - case TopicType::OpenOffice: - return QIcon(QLatin1String("icon:documents.svg")); - case TopicType::Audio: - return QIcon(QLatin1String("icon:create_lecture_topic.svg")); - case TopicType::Video: - return QIcon(QLatin1String("icon:add_video_menu.svg")); - case TopicType::Building: - return QIcon(QLatin1String("icon:configure_buildings.svg")); - case TopicType::SituationMapFilter: - return QIcon(QLatin1String("icon:filter_player.svg")); - case TopicType::Snapshot: - return QIcon(QLatin1String("icon:create_snapshot.svg")); - case TopicType::Evaluation: - return QIcon(QLatin1String("icon:add_evaluation_elements.svg")); - case TopicType::Report: - return QIcon(QLatin1String("icon:add_reports_display.svg")); - case TopicType::Invalid: - default: - return QIcon(); - } - Q_UNREACHABLE(); + switch (topicType) + { + case TopicType::SituationMap: + return QIcon(QLatin1String("icon:add_situation.svg")); + case TopicType::Situation: + return QIcon(QLatin1String("icon:add_situation_combined.svg")); + case TopicType::SituationReplay: + return QIcon(QLatin1String("icon:add_restart.svg")); + case TopicType::Image: + return QIcon(QLatin1String("icon:create_image_topic.svg")); + case TopicType::Text: + return QIcon(QLatin1String("icon:document-new-txt.svg")); + case TopicType::Pdf: + return QIcon(QLatin1String("icon:create_pdf_topic.svg")); + case TopicType::Xml: + return QIcon(QLatin1String("icon:document-new-xml.svg")); + case TopicType::TacticalPlan: + return QIcon(QLatin1String("icon:tactical_organization.svg")); + case TopicType::MSOffice: + return QIcon(QLatin1String("icon:ms_office.svg")); + case TopicType::OpenOffice: + return QIcon(QLatin1String("icon:documents.svg")); + case TopicType::Audio: + return QIcon(QLatin1String("icon:create_lecture_topic.svg")); + case TopicType::Video: + return QIcon(QLatin1String("icon:add_video_menu.svg")); + case TopicType::Building: + return QIcon(QLatin1String("icon:configure_buildings.svg")); + case TopicType::SituationMapFilter: + return QIcon(QLatin1String("icon:filter_player.svg")); + case TopicType::Snapshot: + return QIcon(QLatin1String("icon:create_snapshot.svg")); + case TopicType::Evaluation: + return QIcon(QLatin1String("icon:add_evaluation_elements.svg")); + case TopicType::Report: + return QIcon(QLatin1String("icon:add_reports_display.svg")); + case TopicType::Invalid: + default: + return QIcon(); + } + Q_UNREACHABLE(); } QColor topicTypeColor(TopicType topicType) { - switch (topicType) - { - case TopicType::SituationMap: - return QRgb(0xb1cbbb); - case TopicType::SituationReplay: - return QRgb(0xc94c4c); - case TopicType::Image: - return QRgb(0xfefbd8); - case TopicType::Text: - return QRgb(0x92a8d1); - case TopicType::Pdf: - return QRgb(0x80ced6); - case TopicType::Xml: - return QRgb(0xeea29a); - case TopicType::TacticalPlan: - return QRgb(0xdac292); - case TopicType::MSOffice: - return QRgb(0xf7cac9); - case TopicType::OpenOffice: - return QRgb(0xb2b2b2); - case TopicType::Audio: - return QRgb(0x034f84); - case TopicType::Video: - return QRgb(0x618685); - case TopicType::Building: - return QRgb(0xc6bcb6); - case TopicType::SituationMapFilter: - return QRgb(0x36486b); - case TopicType::Snapshot: - return QRgb(0xf18973); - case TopicType::Evaluation: - return QRgb(0xd6cbd3); - case TopicType::Report: - return QRgb(0xfeb236); - case TopicType::Situation: - return QRgb(0xb1c1cb); - case TopicType::Invalid: - default: - return Qt::black; - } - Q_UNREACHABLE(); - return {}; + switch (topicType) + { + case TopicType::SituationMap: + return QRgb(0xb1cbbb); + case TopicType::SituationReplay: + return QRgb(0xc94c4c); + case TopicType::Image: + return QRgb(0xfefbd8); + case TopicType::Text: + return QRgb(0x92a8d1); + case TopicType::Pdf: + return QRgb(0x80ced6); + case TopicType::Xml: + return QRgb(0xeea29a); + case TopicType::TacticalPlan: + return QRgb(0xdac292); + case TopicType::MSOffice: + return QRgb(0xf7cac9); + case TopicType::OpenOffice: + return QRgb(0xb2b2b2); + case TopicType::Audio: + return QRgb(0x034f84); + case TopicType::Video: + return QRgb(0x618685); + case TopicType::Building: + return QRgb(0xc6bcb6); + case TopicType::SituationMapFilter: + return QRgb(0x36486b); + case TopicType::Snapshot: + return QRgb(0xf18973); + case TopicType::Evaluation: + return QRgb(0xd6cbd3); + case TopicType::Report: + return QRgb(0xfeb236); + case TopicType::Situation: + return QRgb(0xb1c1cb); + case TopicType::Invalid: + default: + return Qt::black; + } + Q_UNREACHABLE(); + return {}; } std::ostream& operator<<(std::ostream& stream, TopicType topicType) { - stream << "TopicType::" << topicTypeString(topicType).toStdString().c_str(); - return stream; + stream << "TopicType::" << topicTypeString(topicType).toStdString().c_str(); + return stream; } - - - - const QString TopicData::mime = QStringLiteral("application/rheinmetall.topiceditorbase.topicdata"); +TopicData::TopicData(TopicType topicType) : topicType(topicType) {} -TopicData::TopicData(TopicType topicType) - : topicType(topicType) -{} +TopicData::TopicData(TopicType topicType, int duration) : topicType(topicType), duration(duration) {} -TopicData::TopicData(TopicType topicType, int duration) - : topicType(topicType) - , duration(duration) -{} - -TopicData::TopicData( - int id, TopicType topicType, int startTime, int duration, const QString &description, const QString &channel, - const QJsonObject &properties -) - : topicType(topicType) - , id(id) - , startTime(startTime) - , duration(duration) - , properties(properties) - , description(description) - , channel(channel) -{} - - -void TopicData::fromJson(const QJsonObject &obj) +TopicData::TopicData(int id, TopicType topicType, int startTime, int duration, const QString& description, + const QString& channel, const QJsonObject& properties) + : topicType(topicType), id(id), startTime(startTime), duration(duration), properties(properties), + description(description), channel(channel) { - id = obj[QStringLiteral("topicId")].toInt(); - topicType = static_cast(obj[QStringLiteral("type")].toInt()); - startTime = obj[QStringLiteral("startTime")].toInt(-1); - duration = obj[QStringLiteral("length")].toInt(-1); - state = obj[QStringLiteral("isSet")].toBool(); - index = obj[QStringLiteral("index")].toInt(); - properties = obj[QStringLiteral("detailData")].toObject(); - description = obj[QStringLiteral("description")].toString(); - channel = obj[QStringLiteral("channelName")].toString(); - parentChannel = obj[QStringLiteral("filterParentChannel")].toString(); - x = obj[QStringLiteral("x")].toDouble(); - y = obj[QStringLiteral("y")].toDouble(); - w = obj[QStringLiteral("w")].toDouble(); - h = obj[QStringLiteral("h")].toDouble(); } +void TopicData::fromJson(const QJsonObject& obj) +{ + id = obj[QStringLiteral("topicId")].toInt(); + topicType = static_cast(obj[QStringLiteral("type")].toInt()); + startTime = obj[QStringLiteral("startTime")].toInt(-1); + duration = obj[QStringLiteral("length")].toInt(-1); + state = obj[QStringLiteral("isSet")].toBool(); + index = obj[QStringLiteral("index")].toInt(); + properties = obj[QStringLiteral("detailData")].toObject(); + description = obj[QStringLiteral("description")].toString(); + channel = obj[QStringLiteral("channelName")].toString(); + parentChannel = obj[QStringLiteral("filterParentChannel")].toString(); + x = obj[QStringLiteral("x")].toDouble(); + y = obj[QStringLiteral("y")].toDouble(); + w = obj[QStringLiteral("w")].toDouble(); + h = obj[QStringLiteral("h")].toDouble(); +} QJsonObject TopicData::toJson() const { - return QJsonObject({ - { QStringLiteral("topicId"), id }, - { QStringLiteral("startTime"), startTime }, - { QStringLiteral("length"), duration }, - { QStringLiteral("type"), static_cast(topicType) }, - { QStringLiteral("isSet"), state }, - { QStringLiteral("index"), index }, - { QStringLiteral("detailData"), properties }, - { QStringLiteral("description"), description }, - { QStringLiteral("channelName"), channel }, - { QStringLiteral("filterParentChannel"), parentChannel }, - { QStringLiteral("x"), x }, - { QStringLiteral("y"), y }, - { QStringLiteral("w"), w }, - { QStringLiteral("h"), h } - }); + return QJsonObject({{QStringLiteral("topicId"), id}, + {QStringLiteral("startTime"), startTime}, + {QStringLiteral("length"), duration}, + {QStringLiteral("type"), static_cast(topicType)}, + {QStringLiteral("isSet"), state}, + {QStringLiteral("index"), index}, + {QStringLiteral("detailData"), properties}, + {QStringLiteral("description"), description}, + {QStringLiteral("channelName"), channel}, + {QStringLiteral("filterParentChannel"), parentChannel}, + {QStringLiteral("x"), x}, + {QStringLiteral("y"), y}, + {QStringLiteral("w"), w}, + {QStringLiteral("h"), h}}); } - -QDataStream &operator<<(QDataStream &stream, const TopicData &data) +QDataStream& operator<<(QDataStream& stream, const TopicData& data) { - const QByteArray properties = QJsonDocument(data.properties).toBinaryData(); - stream << data.id << static_cast(data.topicType) << data.startTime << data.duration << data.state << data.index - << properties << data.description << data.channel << data.parentChannel << data.x << data.y << data.w << data.h; - return stream; + const QByteArray properties = QJsonDocument(data.properties).toBinaryData(); + stream << data.id << static_cast(data.topicType) << data.startTime << data.duration << data.state + << data.index << properties << data.description << data.channel << data.parentChannel << data.x << data.y + << data.w << data.h; + return stream; } -QDataStream &operator >>(QDataStream &stream, TopicData &data) +QDataStream& operator>>(QDataStream& stream, TopicData& data) { - QByteArray properties; - quint8 topicType; - stream >> data.id >> topicType >> data.startTime >> data.duration >> data.state >> data.index >> properties - >> data.description >> data.channel >> data.parentChannel >> data.x >> data.y >> data.w >> data.h; - data.topicType = static_cast(topicType); - data.properties = QJsonDocument::fromBinaryData(properties).object(); - return stream; + QByteArray properties; + quint8 topicType; + stream >> data.id >> topicType >> data.startTime >> data.duration >> data.state >> data.index >> properties >> + data.description >> data.channel >> data.parentChannel >> data.x >> data.y >> data.w >> data.h; + data.topicType = static_cast(topicType); + data.properties = QJsonDocument::fromBinaryData(properties).object(); + return stream; } -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.h b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.h old mode 100755 new mode 100644 index 6cb1f100a..ff0f8b958 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_editor_utils.h @@ -3,36 +3,32 @@ #include "topiceditorbase_export.h" #include - #include - class QColor; - namespace TopicEditorBase { -enum class TopicType -{ - Invalid, - SituationMap, - SituationReplay, - Image, - Text, - Pdf, - Xml, - TacticalPlan, - MSOffice, - OpenOffice, - Audio, - Video, - Building, - SituationMapFilter, - Snapshot, - Evaluation, - Report, - Situation +enum class TopicType { + Invalid, + SituationMap, + SituationReplay, + Image, + Text, + Pdf, + Xml, + TacticalPlan, + MSOffice, + OpenOffice, + Audio, + Video, + Building, + SituationMapFilter, + Snapshot, + Evaluation, + Report, + Situation }; typedef QVector TopicTypes; @@ -40,7 +36,7 @@ TOPICEDITORBASE_EXPORT QString topicTypeTranslation(TopicType topicType); TOPICEDITORBASE_EXPORT QString topicTypeString(TopicType topicType); -TOPICEDITORBASE_EXPORT TopicType topicTypeFromString(const QString &topicName); +TOPICEDITORBASE_EXPORT TopicType topicTypeFromString(const QString& topicName); TOPICEDITORBASE_EXPORT QIcon topicIcon(TopicType topicType); @@ -48,44 +44,40 @@ TOPICEDITORBASE_EXPORT QColor topicTypeColor(TopicType topicType); TOPICEDITORBASE_EXPORT std::ostream& operator<<(std::ostream& stream, TopicType topicType); - struct TOPICEDITORBASE_EXPORT TopicData { - static const QString mime; + static const QString mime; - TopicType topicType{TopicType::Invalid}; - int id{-1}; - int startTime{-1}; - int duration{0}; + TopicType topicType{TopicType::Invalid}; + int id{-1}; + int startTime{-1}; + int duration{0}; - bool state{false}; - int index{-1}; + bool state{false}; + int index{-1}; - QJsonObject properties; - QString description; - QString channel; - QString parentChannel; + QJsonObject properties; + QString description; + QString channel; + QString parentChannel; - - double x{0.}; - double y{0.}; - double h{0.}; - double w{0.}; + double x{0.}; + double y{0.}; + double h{0.}; + double w{0.}; - TopicData() = default; - TopicData(const TopicData &data) = default; - explicit TopicData(TopicType topicType); - explicit TopicData(TopicType topicType, int duration); - explicit TopicData( - int id, TopicType topicType, int startTime, int duration, const QString &description, const QString &channel, - const QJsonObject &properties - ); + TopicData() = default; + TopicData(const TopicData& data) = default; + explicit TopicData(TopicType topicType); + explicit TopicData(TopicType topicType, int duration); + explicit TopicData(int id, TopicType topicType, int startTime, int duration, const QString& description, + const QString& channel, const QJsonObject& properties); - void fromJson(const QJsonObject &obj); - QJsonObject toJson() const; + void fromJson(const QJsonObject& obj); + QJsonObject toJson() const; }; -TOPICEDITORBASE_EXPORT QDataStream &operator<<(QDataStream &stream, const TopicData &data); -TOPICEDITORBASE_EXPORT QDataStream &operator>>(QDataStream &stream, TopicData &data); +TOPICEDITORBASE_EXPORT QDataStream& operator<<(QDataStream& stream, const TopicData& data); +TOPICEDITORBASE_EXPORT QDataStream& operator>>(QDataStream& stream, TopicData& data); -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.cpp old mode 100755 new mode 100644 index ec7deb282..72d88a6af --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.cpp @@ -1,126 +1,103 @@ #include "topic_preview_widget.h" -#include "ui_topic_preview_widget.h" + #include "topic_previewer.h" +#include "ui_topic_preview_widget.h" #include #include - #include #include #include #include - namespace TopicEditorBase { -TopicPreviewWidget::TopicPreviewWidget(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::TopicPreviewWidget) +TopicPreviewWidget::TopicPreviewWidget(QWidget* parent) : QWidget(parent), m_ui(new Ui::TopicPreviewWidget) { - m_ui->setupUi(this); + m_ui->setupUi(this); #ifndef LTS_DEBUG - m_ui->lbxTopicId->hide(); - m_ui->lblTopicId->hide(); + m_ui->lbxTopicId->hide(); + m_ui->lblTopicId->hide(); - m_ui->lbxDuration->hide(); - m_ui->lblDuration->hide(); + m_ui->lbxDuration->hide(); + m_ui->lblDuration->hide(); #endif - connect(m_ui->widget, &TopicPreviewer::deleteMe, - this, &TopicPreviewWidget::deleteMe); + connect(m_ui->widget, &TopicPreviewer::deleteMe, this, &TopicPreviewWidget::deleteMe); - - connect(m_ui->widget, &TopicPreviewer::startDragMe, - this, &TopicPreviewWidget::startDragMe); - connect(m_ui->widget, &TopicPreviewer::stopDragMe, - this, &TopicPreviewWidget::stopDragMe); + connect(m_ui->widget, &TopicPreviewer::startDragMe, this, &TopicPreviewWidget::startDragMe); + connect(m_ui->widget, &TopicPreviewer::stopDragMe, this, &TopicPreviewWidget::stopDragMe); } TopicPreviewWidget::~TopicPreviewWidget() { - delete m_ui; + delete m_ui; } - - - void TopicPreviewWidget::setTopicEnabled(bool enabled) { - m_ui->widget->setEnabled(enabled); + m_ui->widget->setEnabled(enabled); } - -void TopicPreviewWidget::setTopicData(const TopicData &data) +void TopicPreviewWidget::setTopicData(const TopicData& data) { - m_ui->lbxDragAndDrop->setVisible(!data.state); - m_ui->widget->setVisible(!data.state); + m_ui->lbxDragAndDrop->setVisible(!data.state); + m_ui->widget->setVisible(!data.state); - m_ui->leDescription->setText(data.description); - m_ui->lblTopicId->setText(QString::number(data.id)); - m_ui->lblDuration->setText(QString::number(data.duration)); - m_ui->widget->setTopicData(data); + m_ui->leDescription->setText(data.description); + m_ui->lblTopicId->setText(QString::number(data.id)); + m_ui->lblDuration->setText(QString::number(data.duration)); + m_ui->widget->setTopicData(data); } - QString TopicPreviewWidget::description() const { - return m_ui->leDescription->text(); + return m_ui->leDescription->text(); } - -void TopicPreviewWidget::setDescription(const QString &description) +void TopicPreviewWidget::setDescription(const QString& description) { - m_ui->leDescription->setText(description); + m_ui->leDescription->setText(description); } - -TopicPreviewer *TopicPreviewWidget::previewer() +TopicPreviewer* TopicPreviewWidget::previewer() { - return m_ui->widget; + return m_ui->widget; } - - - -void TopicPreviewWidget::contextMenuEvent(QContextMenuEvent *event) +void TopicPreviewWidget::contextMenuEvent(QContextMenuEvent* event) { #ifndef LTS_DEBUG - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("TopicPreviewWidget.DebugMenu")) == QVariant(true)) + if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("TopicPreviewWidget.DebugMenu")) == + QVariant(true)) #endif - { - QMenu *menu = new QMenu(this); - menu->setAttribute(Qt::WA_DeleteOnClose); - - QPoint p = mapToGlobal(menu->pos()); - menu->setGeometry(QRect(p, QPoint(event->x(), event->y()))); - menu->addAction(QStringLiteral("enable"), this, [this]() { - setTopicEnabled(true); - }); + QMenu* menu = new QMenu(this); + menu->setAttribute(Qt::WA_DeleteOnClose); - menu->addAction(QStringLiteral("disable"), this, [this]() - { - setTopicEnabled(false); - }); - menu->addAction(QStringLiteral("show properties"), this, [this]() - { - TopicData data = m_ui->widget->topicData(); - if (data.properties.isEmpty()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("no properties available")); - return; - } + QPoint p = mapToGlobal(menu->pos()); + menu->setGeometry(QRect(p, QPoint(event->x(), event->y()))); + menu->addAction(QStringLiteral("enable"), this, [this]() { setTopicEnabled(true); }); - QTextEdit *ted = new QTextEdit(nullptr); - ted->setAttribute(Qt::WA_DeleteOnClose); - ted->setWindowTitle(QStringLiteral("Track Entry #%1 - Detail Data string").arg(data.id)); - ted->setText(QString::fromUtf8(QJsonDocument(data.properties).toJson())); - ted->setReadOnly(true); - ted->show(); - }); + menu->addAction(QStringLiteral("disable"), this, [this]() { setTopicEnabled(false); }); + menu->addAction(QStringLiteral("show properties"), this, [this]() { + TopicData data = m_ui->widget->topicData(); + if (data.properties.isEmpty()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("no properties available")); + return; + } - menu->show(); - } + QTextEdit* ted = new QTextEdit(nullptr); + ted->setAttribute(Qt::WA_DeleteOnClose); + ted->setWindowTitle(QStringLiteral("Track Entry #%1 - Detail Data string").arg(data.id)); + ted->setText(QString::fromUtf8(QJsonDocument(data.properties).toJson())); + ted->setReadOnly(true); + ted->show(); + }); + + menu->show(); + } } -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.h b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.h old mode 100755 new mode 100644 index 3066ad629..53c98fbb3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_preview_widget.h @@ -1,49 +1,46 @@ #pragma once -#include - #include "topic_editor_utils.h" - #include "topiceditorbase_export.h" +#include #include - -namespace Ui { class TopicPreviewWidget; } - +namespace Ui +{ +class TopicPreviewWidget; +} namespace TopicEditorBase { class TopicPreviewer; - class TOPICEDITORBASE_EXPORT TopicPreviewWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TopicPreviewWidget(QWidget *parent = nullptr); - ~TopicPreviewWidget(); + public: + explicit TopicPreviewWidget(QWidget* parent = nullptr); + ~TopicPreviewWidget(); - void setTopicData(const TopicData &data); - void setTopicEnabled(bool enabled); + void setTopicData(const TopicData& data); + void setTopicEnabled(bool enabled); - QString description() const; - void setDescription(const QString &description); + QString description() const; + void setDescription(const QString& description); - TopicPreviewer *previewer(); + TopicPreviewer* previewer(); -private: - void contextMenuEvent(QContextMenuEvent *event); + private: + void contextMenuEvent(QContextMenuEvent* event); -signals: - void startDragMe(); - void stopDragMe(); - void deleteMe(); - -private: - Ui::TopicPreviewWidget *m_ui{nullptr}; + signals: + void startDragMe(); + void stopDragMe(); + void deleteMe(); + private: + Ui::TopicPreviewWidget* m_ui{nullptr}; }; -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.cpp old mode 100755 new mode 100644 index 0dd78e0ca..e0869c8dd --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.cpp @@ -6,78 +6,66 @@ #include #include - namespace TopicEditorBase { -TopicPreviewer::TopicPreviewer(QWidget *parent) - : QWidget(parent) +TopicPreviewer::TopicPreviewer(QWidget* parent) : QWidget(parent) { - - setVisible(false); + setVisible(false); } -TopicPreviewer::~TopicPreviewer() -{} +TopicPreviewer::~TopicPreviewer() {} - - - -void TopicPreviewer::setTopicData(const TopicData &data) +void TopicPreviewer::setTopicData(const TopicData& data) { - m_topicData = data; + m_topicData = data; - if (m_topicData.state) - return; + if (m_topicData.state) + return; } - - - -void TopicPreviewer::mousePressEvent(QMouseEvent *event) +void TopicPreviewer::mousePressEvent(QMouseEvent* event) { - - if (m_topicData.topicType == TopicType::Invalid || m_topicData.duration < 1 || event->buttons() != Qt::LeftButton) - return; - m_topicData.state = true; - QByteArray byteArray; - QDataStream dataStream(&byteArray, QIODevice::WriteOnly); - dataStream << m_topicData; - m_topicData.state = false; - QMimeData *mimeData = new QMimeData; - mimeData->setData(TopicData::mime, byteArray); - QDrag *drag = new QDrag(this); - drag->setDragCursor(QPixmap(), Qt::CopyAction); - drag->setMimeData(mimeData); - emit startDragMe(); - if (drag->exec(Qt::CopyAction) == Qt::CopyAction) - emit deleteMe(); - emit stopDragMe(); + if (m_topicData.topicType == TopicType::Invalid || m_topicData.duration < 1 || event->buttons() != Qt::LeftButton) + return; + + m_topicData.state = true; + QByteArray byteArray; + QDataStream dataStream(&byteArray, QIODevice::WriteOnly); + dataStream << m_topicData; + m_topicData.state = false; + QMimeData* mimeData = new QMimeData; + mimeData->setData(TopicData::mime, byteArray); + QDrag* drag = new QDrag(this); + drag->setDragCursor(QPixmap(), Qt::CopyAction); + drag->setMimeData(mimeData); + emit startDragMe(); + if (drag->exec(Qt::CopyAction) == Qt::CopyAction) + emit deleteMe(); + emit stopDragMe(); } - -void TopicPreviewer::paintEvent(QPaintEvent *event) +void TopicPreviewer::paintEvent(QPaintEvent* event) { - QWidget::paintEvent(event); + QWidget::paintEvent(event); - if (m_topicData.topicType == TopicType::Invalid) - return; + if (m_topicData.topicType == TopicType::Invalid) + return; - QPainter painter(this); - painter.setClipping(true); - painter.setClipRect(rect(), Qt::ReplaceClip); - painter.setPen(isEnabled() ? Qt::black : Qt::lightGray); - painter.setBrush(QBrush(topicTypeColor(m_topicData.topicType))); - painter.drawRect(rect().adjusted(0, 0, -1, -1)); - painter.drawText(rect().adjusted(3, 16, -1, -1), m_topicData.description); - if (!isEnabled()) - { - painter.setBrush(QBrush(QColor(255, 255, 255, 204))); + QPainter painter(this); + painter.setClipping(true); + painter.setClipRect(rect(), Qt::ReplaceClip); + painter.setPen(isEnabled() ? Qt::black : Qt::lightGray); + painter.setBrush(QBrush(topicTypeColor(m_topicData.topicType))); painter.drawRect(rect().adjusted(0, 0, -1, -1)); - } - + painter.drawText(rect().adjusted(3, 16, -1, -1), m_topicData.description); + if (!isEnabled()) + { + painter.setBrush(QBrush(QColor(255, 255, 255, 204))); + painter.drawRect(rect().adjusted(0, 0, -1, -1)); + } } -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.h b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.h old mode 100755 new mode 100644 index f3cd2fc4c..77e54061c --- a/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/TopicEditorBase/topic_previewer.h @@ -1,39 +1,39 @@ #pragma once -#include - #include "topic_editor_utils.h" - #include "topiceditorbase_export.h" +#include #include - namespace TopicEditorBase { class TOPICEDITORBASE_EXPORT TopicPreviewer : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit TopicPreviewer(QWidget *parent = nullptr); - ~TopicPreviewer(); + public: + explicit TopicPreviewer(QWidget* parent = nullptr); + ~TopicPreviewer(); - void setTopicData(const TopicData &data); - TopicData topicData() const { return m_topicData; } + void setTopicData(const TopicData& data); -protected: - void mousePressEvent(QMouseEvent *event) override; - void paintEvent(QPaintEvent *event) override; + TopicData topicData() const + { + return m_topicData; + } -signals: - void startDragMe(); - void stopDragMe(); - void deleteMe(); + protected: + void mousePressEvent(QMouseEvent* event) override; + void paintEvent(QPaintEvent* event) override; -private: - TopicData m_topicData; + signals: + void startDragMe(); + void stopDragMe(); + void deleteMe(); + private: + TopicData m_topicData; }; -} +} // namespace TopicEditorBase diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp old mode 100755 new mode 100644 index 9e5658cf7..c117ffe66 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/AbstractServer.cpp @@ -1,91 +1,78 @@ +#include +#include +#include #include #include #include -#include -#include -#include - - namespace httq { -AbstractServer::AbstractServer(QObject *parent) - : QObject(parent) - , mSvr(new QTcpServer(this)) - , mLoggerFactory(nullptr) - , mLogger(nullptr) -{} - - -LoggerFactory *AbstractServer::createLoggerFactory() +AbstractServer::AbstractServer(QObject* parent) + : QObject(parent), mSvr(new QTcpServer(this)), mLoggerFactory(nullptr), mLogger(nullptr) { - return new LoggerFactory(this); } - -LoggerFactory *AbstractServer::getLoggerFactory() +LoggerFactory* AbstractServer::createLoggerFactory() { - if (mLoggerFactory == nullptr) - mLoggerFactory = createLoggerFactory(); - return mLoggerFactory; + return new LoggerFactory(this); } +LoggerFactory* AbstractServer::getLoggerFactory() +{ + if (mLoggerFactory == nullptr) + mLoggerFactory = createLoggerFactory(); + return mLoggerFactory; +} void AbstractServer::slotNewConnection() { - mLogger->debug(QStringLiteral("newConnection")); + mLogger->debug(QStringLiteral("newConnection")); - while (QTcpSocket *cli = mSvr->nextPendingConnection()) - { - mLogger->debug(QStringLiteral("nextPendingConnection")); - - if (cli == nullptr) + while (QTcpSocket* cli = mSvr->nextPendingConnection()) { - mLogger->debug(QStringLiteral("invalid tcp client")); - return; + mLogger->debug(QStringLiteral("nextPendingConnection")); + + if (cli == nullptr) + { + mLogger->debug(QStringLiteral("invalid tcp client")); + return; + } + + HttpRequest* req = new HttpRequest(cli, this); + + connect(req, &HttpRequest::signalUpgrade, this, [this, req](QTcpSocket* sock) { + mLogger->debug(QStringLiteral("signalUpgrade")); + + QWebSocketServer* wsSvr = webSocketServer(); + + if (wsSvr == nullptr) + { + mLogger->debug(QStringLiteral("no websocket server available for websocket upgrade")); + sock->close(); + sock->deleteLater(); + return; + } + + wsSvr->handleConnection(sock); + emit sock->readyRead(); + }); + + connect(req, &HttpRequest::signalReady, this, [this, req]() { + mLogger->debug(QStringLiteral("signalReady")); + newHttpConnection(req); + }); } - - HttpRequest *req = new HttpRequest(cli, this); - - connect(req, &HttpRequest::signalUpgrade, - this, [this, req](QTcpSocket *sock) - { - mLogger->debug(QStringLiteral("signalUpgrade")); - - QWebSocketServer *wsSvr = webSocketServer(); - - if (wsSvr == nullptr) - { - mLogger->debug(QStringLiteral("no websocket server available for websocket upgrade")); - sock->close(); - sock->deleteLater(); - return; - } - - wsSvr->handleConnection(sock); - emit sock->readyRead(); - }); - - connect(req, &HttpRequest::signalReady, - this, [this, req]() - { - mLogger->debug(QStringLiteral("signalReady")); - newHttpConnection(req); - }); - } } - -bool AbstractServer::listen(qint16 port, const QHostAddress &host) +bool AbstractServer::listen(qint16 port, const QHostAddress& host) { - mLoggerFactory = createLoggerFactory(); - mLogger = mLoggerFactory->createLogger(this); + mLoggerFactory = createLoggerFactory(); + mLogger = mLoggerFactory->createLogger(this); - mLogger->debug(QStringLiteral("listen")); + mLogger->debug(QStringLiteral("listen")); - connect(mSvr, &QTcpServer::newConnection, - this, &AbstractServer::slotNewConnection); + connect(mSvr, &QTcpServer::newConnection, this, &AbstractServer::slotNewConnection); - return mSvr->listen(host, port); -} + return mSvr->listen(host, port); } +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp old mode 100755 new mode 100644 index 967379c20..2029d751a --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/DataStream.cpp @@ -1,262 +1,209 @@ -#include -#include - +#include +#include #include #include -#include -#include #include -#include +#include +#include +#include #ifdef Q_OS_UNIX #include #endif - namespace httq { -DataStream::DataStream(QIODevice *from, QIODevice *to, const QByteArray &bodyPartial, - qint64 fileLength, size_t bufferSize, LoggerFactory *loggerFactory, - QObject *parent) - : QObject(parent) - , mBodyPartial(bodyPartial) - , mFrom(from) - , mTo(to) - , mBufferSize(bufferSize) - , mFileLength(fileLength) - , mLogger(loggerFactory->createLogger(this)) +DataStream::DataStream(QIODevice* from, QIODevice* to, const QByteArray& bodyPartial, qint64 fileLength, + size_t bufferSize, LoggerFactory* loggerFactory, QObject* parent) + : QObject(parent), mBodyPartial(bodyPartial), mFrom(from), mTo(to), mBufferSize(bufferSize), + mFileLength(fileLength), mLogger(loggerFactory->createLogger(this)) { #ifdef SAVE_PARTIAL_BODY - { - QTemporaryFile f; - f.open(); - f.write(mBodyPartial); - f.setAutoRemove(false); - qWarning() << "partial:" << f.fileName(); - } + { + QTemporaryFile f; + f.open(); + f.write(mBodyPartial); + f.setAutoRemove(false); + qWarning() << "partial:" << f.fileName(); + } #endif - - if (mFileLength == 0) - { - mLogger->warning(QStringLiteral("file size = 0 - done")); - QTimer::singleShot(1, this, [this]() { emit signalDone(); deleteLater(); } ); - return; - } - - mLogger->debug(QStringLiteral("DataStream c_tor")); - - - - mBuffer.reserve(bufferSize); - - - - mFromSupportsSignals = (qobject_cast(mFrom) == nullptr); - mToSupportsSignals = (qobject_cast(mTo) == nullptr); - mLogger->debug(QStringLiteral("signal support - from: %1 - to: %2").arg(mFromSupportsSignals).arg(mToSupportsSignals)); - - - - - auto sock = qobject_cast(mFrom); - qWarning() << "######################### SOCK" << sock; - connect(sock, &QTcpSocket::readyRead, - this, [this]() + if (mFileLength == 0) { - mLogger->debug(QStringLiteral(">> DataStream readyRead")); + mLogger->warning(QStringLiteral("file size = 0 - done")); + QTimer::singleShot(1, this, [this]() { + emit signalDone(); + deleteLater(); + }); + return; + } - - QTimer::singleShot(1, this, [this]() { readNext(); } ); + mLogger->debug(QStringLiteral("DataStream c_tor")); + + mBuffer.reserve(bufferSize); + + mFromSupportsSignals = (qobject_cast(mFrom) == nullptr); + mToSupportsSignals = (qobject_cast(mTo) == nullptr); + mLogger->debug( + QStringLiteral("signal support - from: %1 - to: %2").arg(mFromSupportsSignals).arg(mToSupportsSignals)); + + auto sock = qobject_cast(mFrom); + qWarning() << "######################### SOCK" << sock; + connect(sock, &QTcpSocket::readyRead, this, [this]() { + mLogger->debug(QStringLiteral(">> DataStream readyRead")); + + QTimer::singleShot(1, this, [this]() { readNext(); }); }); + if (mToSupportsSignals) + connect(mTo, &QIODevice::bytesWritten, this, [this]() { + mLogger->debug(QStringLiteral(">> DataStream write")); - if (mToSupportsSignals) - connect(mTo, &QIODevice::bytesWritten, - this, [this]() - { - mLogger->debug(QStringLiteral(">> DataStream write")); + mReadyWrite = true; + QTimer::singleShot(1, this, [this]() { readNext(); }); + }); - mReadyWrite = true; - QTimer::singleShot(1, this, [this]() { readNext(); } ); - }); - - - QTimer::singleShot(1, this, [this]() { readNext(); } ); + QTimer::singleShot(1, this, [this]() { readNext(); }); } - DataStream::~DataStream() { - mLogger->debug(QStringLiteral("~DataStream")); + mLogger->debug(QStringLiteral("~DataStream")); } - void DataStream::readNext() { #if defined(DEBUG_SLOW) && defined(Q_OS_UNIX) - mLogger->debug(QStringLiteral("read: slowing down.....")); - usleep(2 * 1000 * 1000); + mLogger->debug(QStringLiteral("read: slowing down.....")); + usleep(2 * 1000 * 1000); #endif - mLogger->debug(QStringLiteral("read: readNext: %1").arg(mBuffer.size())); + mLogger->debug(QStringLiteral("read: readNext: %1").arg(mBuffer.size())); + if (mBuffer.size() > 0) + { + mLogger->debug(QStringLiteral("read: ignoring read until buffer was written")); + return; + } - if (mBuffer.size() > 0) - { - mLogger->debug(QStringLiteral("read: ignoring read until buffer was written")); - return; - } + if (mToSupportsSignals && !mReadyWrite) + { + mLogger->debug(QStringLiteral("read: won't read until write is ready!")); + return; + } + if (!mBodyPartial.isEmpty()) + { + mBuffer = mBodyPartial; - if (mToSupportsSignals && !mReadyWrite) - { - mLogger->debug(QStringLiteral("read: won't read until write is ready!")); - return; - } - - - if (!mBodyPartial.isEmpty()) - { - mBuffer = mBodyPartial; - + alreadyRead += mBuffer.size(); + mLogger->debug(QStringLiteral("read: prebody size: %1").arg(mBuffer.size())); + mBodyPartial.clear(); + mLogger->debug(QStringLiteral("read: queueing writeNext after prebody read")); + QTimer::singleShot(1, this, [this]() { writeNext(); }); + return; + } + if ((mFrom->bytesAvailable() < 1)) + { + mLogger->debug(QStringLiteral("read: no bytes available and not ready read")); + QTimer::singleShot(1000, this, [this]() { readNext(); }); + return; + } + mBuffer = mFrom->read(mBufferSize); + mLogger->debug(QStringLiteral("read: mPos is now %1").arg(mBuffer.size())); alreadyRead += mBuffer.size(); - mLogger->debug(QStringLiteral("read: prebody size: %1").arg(mBuffer.size())); + mLogger->debug(QStringLiteral("read: alreadyRead = %1").arg(alreadyRead)); - mBodyPartial.clear(); + if (mBuffer.size() < 1) + { + mLogger->debug(QStringLiteral("read: cannot read anything")); + deleteLater(); + return; + } - - mLogger->debug(QStringLiteral("read: queueing writeNext after prebody read")); - QTimer::singleShot(1, this, [this]() { writeNext(); } ); - return; - } - - - if ( (mFrom->bytesAvailable() < 1 )) - { - - - mLogger->debug(QStringLiteral("read: no bytes available and not ready read")); - - - - - - - - - - QTimer::singleShot(1000, this, [this]() { readNext(); } ); - - - - - - - - - return; - } - - - - - mBuffer = mFrom->read(mBufferSize); - mLogger->debug(QStringLiteral("read: mPos is now %1").arg(mBuffer.size())); - - - - - alreadyRead += mBuffer.size(); - mLogger->debug(QStringLiteral("read: alreadyRead = %1").arg(alreadyRead)); - - if (mBuffer.size() < 1) - { - mLogger->debug(QStringLiteral("read: cannot read anything")); - deleteLater(); - return; - } - - mLogger->debug(QStringLiteral("read: queueing writeNext")); - QTimer::singleShot(1, this, [this]() { writeNext(); } ); + mLogger->debug(QStringLiteral("read: queueing writeNext")); + QTimer::singleShot(1, this, [this]() { writeNext(); }); } - void DataStream::writeNext() { - mLogger->debug(QStringLiteral("write: writeNext: %1").arg(mBuffer.size())); + mLogger->debug(QStringLiteral("write: writeNext: %1").arg(mBuffer.size())); - if (mBuffer.size() < 1) - { - mLogger->debug(QStringLiteral("write: nothing to write")); - QTimer::singleShot(1, this, [this]() { readNext(); } ); - return; - } + if (mBuffer.size() < 1) + { + mLogger->debug(QStringLiteral("write: nothing to write")); + QTimer::singleShot(1, this, [this]() { readNext(); }); + return; + } - - if (!mTo->isOpen() || !mTo->isWritable()) - { - mLogger->debug(QStringLiteral("write: file error: open? %1 - writable? %2").arg(mTo->isOpen()).arg(mTo->isWritable())); - deleteLater(); - return; - } + if (!mTo->isOpen() || !mTo->isWritable()) + { + mLogger->debug( + QStringLiteral("write: file error: open? %1 - writable? %2").arg(mTo->isOpen()).arg(mTo->isWritable())); + deleteLater(); + return; + } - if (mToSupportsSignals && !mReadyWrite ) - { - mLogger->debug(QStringLiteral("write: !mReadyWrite")); - - return; - } + if (mToSupportsSignals && !mReadyWrite) + { + mLogger->debug(QStringLiteral("write: !mReadyWrite")); - if (mToSupportsSignals) - mReadyWrite = false; + return; + } - const qint64 size = mTo->write(mBuffer); - mLogger->debug(QStringLiteral("write: wrote to buffer %1 bytes").arg(size)); + if (mToSupportsSignals) + mReadyWrite = false; - mLogger->debug(QStringLiteral("write: %1 / %2 bytes done (%3 bytes left until DataStream done)").arg(alreadyRead).arg(mFileLength).arg(mFileLength - alreadyRead)); + const qint64 size = mTo->write(mBuffer); + mLogger->debug(QStringLiteral("write: wrote to buffer %1 bytes").arg(size)); - if (size < mBuffer.size()) - { - mLogger->warning(QStringLiteral("write: cannot write all bytes: %1 / %2 bytes").arg(mBuffer.size()).arg(size)); - deleteLater(); - return; - } + mLogger->debug(QStringLiteral("write: %1 / %2 bytes done (%3 bytes left until DataStream done)") + .arg(alreadyRead) + .arg(mFileLength) + .arg(mFileLength - alreadyRead)); - mLogger->debug(QStringLiteral("write: mPos is now %1 and was set to zero now!!").arg(mBuffer.size())); - mBuffer.clear(); + if (size < mBuffer.size()) + { + mLogger->warning(QStringLiteral("write: cannot write all bytes: %1 / %2 bytes").arg(mBuffer.size()).arg(size)); + deleteLater(); + return; + } - if (alreadyRead == mFileLength) - { - mLogger->debug(QStringLiteral("write: DONE!")); - emit signalDone(); - deleteLater(); - return; - } + mLogger->debug(QStringLiteral("write: mPos is now %1 and was set to zero now!!").arg(mBuffer.size())); + mBuffer.clear(); - if (alreadyRead > mFileLength) - { - mLogger->debug(QStringLiteral("write: oops... we read too much!! data may be corrupt!! already read %1 bytes, but content length is only %2 (%1 / %2)").arg(alreadyRead).arg(mFileLength)); - emit signalDone(); - deleteLater(); - return; - } + if (alreadyRead == mFileLength) + { + mLogger->debug(QStringLiteral("write: DONE!")); + emit signalDone(); + deleteLater(); + return; + } + if (alreadyRead > mFileLength) + { + mLogger->debug(QStringLiteral("write: oops... we read too much!! data may be corrupt!! already read %1 bytes, " + "but content length is only %2 (%1 / %2)") + .arg(alreadyRead) + .arg(mFileLength)); + emit signalDone(); + deleteLater(); + return; + } - - if (mToSupportsSignals) - mLogger->debug(QStringLiteral("write: waiting for bytes written to be triggered...")); + if (mToSupportsSignals) + mLogger->debug(QStringLiteral("write: waiting for bytes written to be triggered...")); - mLogger->debug(QStringLiteral("write: queueing writeNext again")); - QTimer::singleShot(1, this, [this]() { writeNext(); } ); -} + mLogger->debug(QStringLiteral("write: queueing writeNext again")); + QTimer::singleShot(1, this, [this]() { writeNext(); }); } +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp old mode 100755 new mode 100644 index d607c85e4..1767a70b3 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/HttpRequest.cpp @@ -1,415 +1,357 @@ -#include -#include -#include - -#include -#include - +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include - +#include +#include +#include +#include +#include namespace httq { -HttpRequest::HttpRequest(QTcpSocket *cli, AbstractServer *parent) - : QObject(parent) - , mCli(cli) - , mLogger(parent->getLoggerFactory()->createLogger(this)) +HttpRequest::HttpRequest(QTcpSocket* cli, AbstractServer* parent) + : QObject(parent), mCli(cli), mLogger(parent->getLoggerFactory()->createLogger(this)) { - mLogger->debug(QStringLiteral("HttpRequest c_tor")); + mLogger->debug(QStringLiteral("HttpRequest c_tor")); - + http_parser_init(&mParser, HTTP_REQUEST); + mData.mHttpRquest = this; + mParser.data = static_cast(&mData); - - http_parser_init(&mParser, HTTP_REQUEST); - mData.mHttpRquest = this; - mParser.data = static_cast(&mData); + connect(cli, &QTcpSocket::readyRead, this, &HttpRequest::slotReadyRead); + connect(cli, &QTcpSocket::disconnected, this, [this]() { qWarning() << "Client disconnected himself!!"; }); + connect(cli, &QTcpSocket::disconnected, this, &HttpRequest::deleteLater); - connect(cli, &QTcpSocket::readyRead, - this, &HttpRequest::slotReadyRead); - connect(cli, &QTcpSocket::disconnected, - this, [this]() - { - qWarning() << "Client disconnected himself!!"; - }); - connect(cli, &QTcpSocket::disconnected, - this, &HttpRequest::deleteLater); - - - - - - - mParserSettings.on_message_begin = &HttpRequest::on_message_begin; - mParserSettings.on_url = &HttpRequest::on_url; - mParserSettings.on_status = &HttpRequest::on_status; - mParserSettings.on_header_field = &HttpRequest::on_header_field; - mParserSettings.on_header_value = &HttpRequest::on_header_value; - mParserSettings.on_headers_complete = &HttpRequest::on_headers_complete; - mParserSettings.on_body = &HttpRequest::on_body; - mParserSettings.on_message_complete = &HttpRequest::on_message_complete; - mParserSettings.on_chunk_header = &HttpRequest::on_chunk_header; - mParserSettings.on_chunk_complete = &HttpRequest::on_chunk_complete; + mParserSettings.on_message_begin = &HttpRequest::on_message_begin; + mParserSettings.on_url = &HttpRequest::on_url; + mParserSettings.on_status = &HttpRequest::on_status; + mParserSettings.on_header_field = &HttpRequest::on_header_field; + mParserSettings.on_header_value = &HttpRequest::on_header_value; + mParserSettings.on_headers_complete = &HttpRequest::on_headers_complete; + mParserSettings.on_body = &HttpRequest::on_body; + mParserSettings.on_message_complete = &HttpRequest::on_message_complete; + mParserSettings.on_chunk_header = &HttpRequest::on_chunk_header; + mParserSettings.on_chunk_complete = &HttpRequest::on_chunk_complete; } - HttpRequest::~HttpRequest() { - mLogger->debug(QStringLiteral("~HttpRequest")); + mLogger->debug(QStringLiteral("~HttpRequest")); - if (mCli == nullptr) - return; + if (mCli == nullptr) + return; - mLogger->debug(QStringLiteral("mCli flush & close")); - mCli->flush(); - + mLogger->debug(QStringLiteral("mCli flush & close")); + mCli->flush(); } - QString HttpRequest::toString() const { - return QStringLiteral("HttpRequest(url = '%1', method = %2)").arg(url().toString()).arg(methodString()); + return QStringLiteral("HttpRequest(url = '%1', method = %2)").arg(url().toString()).arg(methodString()); } - -int HttpRequest::on_message_begin(http_parser *parser) +int HttpRequest::on_message_begin(http_parser* parser) { - dataLogger(parser)->debug(QStringLiteral("on_message_begin")); - return 0; + dataLogger(parser)->debug(QStringLiteral("on_message_begin")); + return 0; } - -int HttpRequest::on_url(http_parser *parser, const char *at, size_t length) +int HttpRequest::on_url(http_parser* parser, const char* at, size_t length) { - dataLogger(parser)->debug(QStringLiteral("on_url '%1'").arg(QString::fromUtf8(at, length))); + dataLogger(parser)->debug(QStringLiteral("on_url '%1'").arg(QString::fromUtf8(at, length))); - - - - http_parser_url parserUrl; - if (http_parser_parse_url(at, length, false, &parserUrl) != 0) - { - dataLogger(parser)->debug(QStringLiteral("could not determine url! %1").arg(QString::fromUtf8(at, length))); - return 1; - } - - QUrl url; - -#define isUrlFieldSet(field) parserUrl.field_set & (1 << field) - if (isUrlFieldSet(UF_SCHEMA)) - url.setScheme(QString::fromUtf8(at + parserUrl.field_data[UF_SCHEMA].off, parserUrl.field_data[UF_SCHEMA].len)); - - if (parserUrl.field_set & (1 << UF_HOST)) - url.setHost(QString::fromUtf8(at + parserUrl.field_data[UF_HOST].off, parserUrl.field_data[UF_HOST].len)); - - if (parserUrl.field_set & (1 << UF_PORT)) - { - bool k = false; - QString portString(QString::fromUtf8(at + parserUrl.field_data[UF_PORT].off, parserUrl.field_data[UF_PORT].len)); - qint16 port = portString.toShort(&k); - - if (!k) + http_parser_url parserUrl; + if (http_parser_parse_url(at, length, false, &parserUrl) != 0) { - dataLogger(parser)->warning(QStringLiteral("could not determine port! %1").arg(portString)); - return 1; + dataLogger(parser)->debug(QStringLiteral("could not determine url! %1").arg(QString::fromUtf8(at, length))); + return 1; } - url.setPort(static_cast(port)); - } + QUrl url; - if (parserUrl.field_set & (1 << UF_PATH)) - url.setPath(QString::fromUtf8(at + parserUrl.field_data[UF_PATH].off, parserUrl.field_data[UF_PATH].len)); +#define isUrlFieldSet(field) parserUrl.field_set&(1 << field) + if (isUrlFieldSet(UF_SCHEMA)) + url.setScheme(QString::fromUtf8(at + parserUrl.field_data[UF_SCHEMA].off, parserUrl.field_data[UF_SCHEMA].len)); - HttpRequestData *reqData = data(parser); - if (isUrlFieldSet(UF_QUERY)) - { - - QUrlQuery q(QString::fromUtf8(at + parserUrl.field_data[UF_QUERY].off, parserUrl.field_data[UF_QUERY].len)); - url.setQuery(q); - reqData->mQuery = q; - } + if (parserUrl.field_set & (1 << UF_HOST)) + url.setHost(QString::fromUtf8(at + parserUrl.field_data[UF_HOST].off, parserUrl.field_data[UF_HOST].len)); + if (parserUrl.field_set & (1 << UF_PORT)) + { + bool k = false; + QString portString( + QString::fromUtf8(at + parserUrl.field_data[UF_PORT].off, parserUrl.field_data[UF_PORT].len)); + qint16 port = portString.toShort(&k); + if (!k) + { + dataLogger(parser)->warning(QStringLiteral("could not determine port! %1").arg(portString)); + return 1; + } + url.setPort(static_cast(port)); + } - if (isUrlFieldSet(UF_USERINFO)) - url.setUserInfo(QString::fromUtf8(at + parserUrl.field_data[UF_USERINFO].off, parserUrl.field_data[UF_USERINFO].len)); + if (parserUrl.field_set & (1 << UF_PATH)) + url.setPath(QString::fromUtf8(at + parserUrl.field_data[UF_PATH].off, parserUrl.field_data[UF_PATH].len)); + + HttpRequestData* reqData = data(parser); + if (isUrlFieldSet(UF_QUERY)) + { + + QUrlQuery q(QString::fromUtf8(at + parserUrl.field_data[UF_QUERY].off, parserUrl.field_data[UF_QUERY].len)); + url.setQuery(q); + reqData->mQuery = q; + } + + if (isUrlFieldSet(UF_USERINFO)) + url.setUserInfo( + QString::fromUtf8(at + parserUrl.field_data[UF_USERINFO].off, parserUrl.field_data[UF_USERINFO].len)); #undef isUrlFieldSet + dataLogger(parser)->debug(QStringLiteral("final url = %1").arg(url.toString())); + reqData->mUrl = url; - dataLogger(parser)->debug(QStringLiteral("final url = %1").arg(url.toString())); - reqData->mUrl = url; - - - return 0; + return 0; } - -int HttpRequest::on_status(http_parser *parser, const char *, size_t ) +int HttpRequest::on_status(http_parser* parser, const char*, size_t) { - dataLogger(parser)->debug(QStringLiteral("on_status")); - return 0; + dataLogger(parser)->debug(QStringLiteral("on_status")); + return 0; } - -int HttpRequest::on_header_field(http_parser *parser, const char *at, size_t length) +int HttpRequest::on_header_field(http_parser* parser, const char* at, size_t length) { - dataLogger(parser)->debug(QStringLiteral("on_header_field")); + dataLogger(parser)->debug(QStringLiteral("on_header_field")); - data(parser)->mCurrentHeaderField = QString::fromUtf8(at, length); + data(parser)->mCurrentHeaderField = QString::fromUtf8(at, length); - return 0; + return 0; } - -int HttpRequest::on_header_value(http_parser *parser, const char *at, size_t length) +int HttpRequest::on_header_value(http_parser* parser, const char* at, size_t length) { - dataLogger(parser)->debug(QStringLiteral("on_header_value")); + dataLogger(parser)->debug(QStringLiteral("on_header_value")); - QString value(QString::fromUtf8(at, length)); - HttpRequestData *reqdata = data(parser); + QString value(QString::fromUtf8(at, length)); + HttpRequestData* reqdata = data(parser); - reqdata->mHeaders.insert(reqdata->mCurrentHeaderField, value); + reqdata->mHeaders.insert(reqdata->mCurrentHeaderField, value); - dataLogger(parser)->debug(QStringLiteral("added header: %1 = %2").arg(reqdata->mCurrentHeaderField).arg(value)); + dataLogger(parser)->debug(QStringLiteral("added header: %1 = %2").arg(reqdata->mCurrentHeaderField).arg(value)); - reqdata->mCurrentHeaderField.clear(); + reqdata->mCurrentHeaderField.clear(); - return 0; + return 0; } - -int HttpRequest::on_headers_complete(http_parser *parser) +int HttpRequest::on_headers_complete(http_parser* parser) { - dataLogger(parser)->debug(QStringLiteral("on_headers_complete")); - return 0; + dataLogger(parser)->debug(QStringLiteral("on_headers_complete")); + return 0; } - -int HttpRequest::on_body(http_parser *parser, const char *at, size_t length) +int HttpRequest::on_body(http_parser* parser, const char* at, size_t length) { - dataLogger(parser)->debug(QStringLiteral("on_body")); - data(parser)->mBodyPartial = QByteArray(at, length); + dataLogger(parser)->debug(QStringLiteral("on_body")); + data(parser)->mBodyPartial = QByteArray(at, length); - + data(parser)->mDone = true; - data(parser)->mDone = true; - - return 0; + return 0; } - -int HttpRequest::on_message_complete(http_parser *parser) +int HttpRequest::on_message_complete(http_parser* parser) { - dataLogger(parser)->debug(QStringLiteral("on_message_complete")); + dataLogger(parser)->debug(QStringLiteral("on_message_complete")); - data(parser)->mDone = true; + data(parser)->mDone = true; - return 0; + return 0; } - -int HttpRequest::on_chunk_header(http_parser *parser) +int HttpRequest::on_chunk_header(http_parser* parser) { - dataLogger(parser)->debug(QStringLiteral("on_chunk_header")); - return 0; + dataLogger(parser)->debug(QStringLiteral("on_chunk_header")); + return 0; } - -int HttpRequest::on_chunk_complete(http_parser *parser) +int HttpRequest::on_chunk_complete(http_parser* parser) { - dataLogger(parser)->debug(QStringLiteral("on_chunk_complete")); - return 0; + dataLogger(parser)->debug(QStringLiteral("on_chunk_complete")); + return 0; } - qint64 HttpRequest::availableBytes() const { - return (mContentLength - alreadyRead); + return (mContentLength - alreadyRead); } - -DataStream *HttpRequest::createDataStreamToClient(int status, const QString &contentType, QIODevice *from, qint64 fileSize, qint64 bufferSize) +DataStream* HttpRequest::createDataStreamToClient(int status, const QString& contentType, QIODevice* from, + qint64 fileSize, qint64 bufferSize) { - mLogger->debug(QStringLiteral("createDataStreamToClient")); + mLogger->debug(QStringLiteral("createDataStreamToClient")); - writeStatusHeader(status); - addHeader(QStringLiteral("Content-Type"), contentType); - addHeader(QStringLiteral("Content-Length"), QString::number(fileSize)); - writeHeaders(); - mCli->write("\r\n"); + writeStatusHeader(status); + addHeader(QStringLiteral("Content-Type"), contentType); + addHeader(QStringLiteral("Content-Length"), QString::number(fileSize)); + writeHeaders(); + mCli->write("\r\n"); - return new DataStream(from, mCli, {}, fileSize, bufferSize, mLogger->getLoggerFactory(), this); + return new DataStream(from, mCli, {}, fileSize, bufferSize, mLogger->getLoggerFactory(), this); } - -DataStream *HttpRequest::createDataStreamFromClient(QIODevice *to, qint64 fileSize, qint64 bufferSize) +DataStream* HttpRequest::createDataStreamFromClient(QIODevice* to, qint64 fileSize, qint64 bufferSize) { - mLogger->debug(QStringLiteral("createDataStreamFromClient")); + mLogger->debug(QStringLiteral("createDataStreamFromClient")); - return new DataStream(mCli, to, mData.mBodyPartial, fileSize, bufferSize, mLogger->getLoggerFactory(), this); + return new DataStream(mCli, to, mData.mBodyPartial, fileSize, bufferSize, mLogger->getLoggerFactory(), this); } - - - - - - - -void HttpRequest::write(int status, const QJsonValue &jsonValue) +void HttpRequest::write(int status, const QJsonValue& jsonValue) { - QJsonDocument doc; + QJsonDocument doc; - if (jsonValue.isArray()) - doc = QJsonDocument(jsonValue.toArray()); - else - doc = QJsonDocument(jsonValue.toObject()); + if (jsonValue.isArray()) + doc = QJsonDocument(jsonValue.toArray()); + else + doc = QJsonDocument(jsonValue.toObject()); - write(status, doc.toJson(), QStringLiteral("application/json")); + write(status, doc.toJson(), QStringLiteral("application/json")); } - -void HttpRequest::write(int status, const QByteArray &data, const QString &contentType) +void HttpRequest::write(int status, const QByteArray& data, const QString& contentType) { - mLogger->debug(QStringLiteral("write to client: status = %1, data (size) = %2, contentType = %3").arg(status).arg(data.size()).arg(contentType)); - writeStatusHeader(status); + mLogger->debug(QStringLiteral("write to client: status = %1, data (size) = %2, contentType = %3") + .arg(status) + .arg(data.size()) + .arg(contentType)); + writeStatusHeader(status); - addHeader(QStringLiteral("Content-Type"), contentType); - addHeader(QStringLiteral("Content-Length"), QString::number(data.size())); + addHeader(QStringLiteral("Content-Type"), contentType); + addHeader(QStringLiteral("Content-Length"), QString::number(data.size())); - writeHeaders(); - mCli->write("\r\n"); + writeHeaders(); + mCli->write("\r\n"); - mCli->write(data); + mCli->write(data); } - void HttpRequest::writeStatusHeader(int status) { - QString header(QStringLiteral("HTTP/1.1 %1 %2\r\n").arg(status).arg(QStringLiteral("OK") )); - mLogger->debug(QStringLiteral("write to client: header = %1").arg(header)); - mCli->write(header.toUtf8()); + QString header(QStringLiteral("HTTP/1.1 %1 %2\r\n").arg(status).arg(QStringLiteral("OK"))); + mLogger->debug(QStringLiteral("write to client: header = %1").arg(header)); + mCli->write(header.toUtf8()); } - -void HttpRequest::addHeader(const QString &key, const QString &value) +void HttpRequest::addHeader(const QString& key, const QString& value) { - mHeaders.insert(key, value); + mHeaders.insert(key, value); } - void HttpRequest::writeHeaders() { - QString headers; + QString headers; - QMapIterator it(mHeaders); - while (it.hasNext()) - { - it.next(); - headers += QStringLiteral("%1: %2\r\n").arg(it.key(), it.value()); - } + QMapIterator it(mHeaders); + while (it.hasNext()) + { + it.next(); + headers += QStringLiteral("%1: %2\r\n").arg(it.key(), it.value()); + } - mLogger->debug(QStringLiteral("write to client: headers = %1").arg(headers)); - mCli->write(headers.toUtf8()); + mLogger->debug(QStringLiteral("write to client: headers = %1").arg(headers)); + mCli->write(headers.toUtf8()); } - void HttpRequest::slotReadyRead() { - - mLogger->debug(QStringLiteral("slotReadyRead")); - if (mDone) - { - mLogger->debug(QStringLiteral("slotReadyRead: already marked as done")); - return; - } + mLogger->debug(QStringLiteral("slotReadyRead")); - mCli->startTransaction(); - - - while (mCli->bytesAvailable() && !mData.mDone) - { - mLogger->debug(QStringLiteral("slotReadyRead: bytes available")); - const QByteArray data(mCli->read(10000)); - - - int dataSize = data.size(); - - size_t size = http_parser_execute(&mParser, &mParserSettings, data.constData(), static_cast(dataSize)); - - if (size < static_cast(dataSize)) + if (mDone) { - mLogger->error(QStringLiteral("http parser error: %1").arg(QString::fromUtf8(http_errno_name(HTTP_PARSER_ERRNO(&mParser))))); - mCli->commitTransaction(); - deleteLater(); - return; - } - } - - - if (mData.mDone) - { - mLogger->debug(QStringLiteral("slotReadyRead: now marked as done")); - - mDone = true; - - - mLogger->debug(QStringLiteral("slotReadyRead: method = %1").arg(methodString())); - - - - auto it = mData.mHeaders.constFind(QStringLiteral("Upgrade")); - - if (it != mData.mHeaders.constEnd() && (*it).toLower() == QStringLiteral("websocket")) - { - mLogger->debug(QStringLiteral("slotReadyRead: Upgrade: %1").arg(*it)); - disconnect(mCli, &QTcpSocket::readyRead, nullptr, nullptr); - - mCli->rollbackTransaction(); - mCli->setParent(nullptr); - auto cli = mCli; - mCli = nullptr; - emit signalUpgrade(cli); - - deleteLater(); - return; - } - - - - it = mData.mHeaders.constFind(QStringLiteral("Content-Length")); - - if (it != mData.mHeaders.constEnd()) - { - bool k = false; - mContentLength = (*it).toLongLong(&k); - - if (!k) - { - mLogger->error(QStringLiteral("slotReadyRead: invalid content length: ").arg(*it)); - deleteLater(); + mLogger->debug(QStringLiteral("slotReadyRead: already marked as done")); return; - } } + mCli->startTransaction(); - alreadyRead = mData.mBodyPartial.size(); + while (mCli->bytesAvailable() && !mData.mDone) + { + mLogger->debug(QStringLiteral("slotReadyRead: bytes available")); + const QByteArray data(mCli->read(10000)); - mLogger->debug(QStringLiteral("slotReadyRead: already read %1 / %2 bytes").arg(alreadyRead).arg(contentLength())); + int dataSize = data.size(); - mCli->commitTransaction(); - emit signalReady(); - return; - } + size_t size = http_parser_execute(&mParser, &mParserSettings, data.constData(), static_cast(dataSize)); - mLogger->debug(QStringLiteral("slotReadyRead: commit transaction")); - mCli->commitTransaction(); -} + if (size < static_cast(dataSize)) + { + mLogger->error(QStringLiteral("http parser error: %1") + .arg(QString::fromUtf8(http_errno_name(HTTP_PARSER_ERRNO(&mParser))))); + mCli->commitTransaction(); + deleteLater(); + return; + } + } + + if (mData.mDone) + { + mLogger->debug(QStringLiteral("slotReadyRead: now marked as done")); + + mDone = true; + + mLogger->debug(QStringLiteral("slotReadyRead: method = %1").arg(methodString())); + + auto it = mData.mHeaders.constFind(QStringLiteral("Upgrade")); + + if (it != mData.mHeaders.constEnd() && (*it).toLower() == QStringLiteral("websocket")) + { + mLogger->debug(QStringLiteral("slotReadyRead: Upgrade: %1").arg(*it)); + disconnect(mCli, &QTcpSocket::readyRead, nullptr, nullptr); + + mCli->rollbackTransaction(); + mCli->setParent(nullptr); + auto cli = mCli; + mCli = nullptr; + emit signalUpgrade(cli); + + deleteLater(); + return; + } + + it = mData.mHeaders.constFind(QStringLiteral("Content-Length")); + + if (it != mData.mHeaders.constEnd()) + { + bool k = false; + mContentLength = (*it).toLongLong(&k); + + if (!k) + { + mLogger->error(QStringLiteral("slotReadyRead: invalid content length: ").arg(*it)); + deleteLater(); + return; + } + } + + alreadyRead = mData.mBodyPartial.size(); + + mLogger->debug( + QStringLiteral("slotReadyRead: already read %1 / %2 bytes").arg(alreadyRead).arg(contentLength())); + + mCli->commitTransaction(); + emit signalReady(); + return; + } + + mLogger->debug(QStringLiteral("slotReadyRead: commit transaction")); + mCli->commitTransaction(); } +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp old mode 100755 new mode 100644 index 04e5140f2..34868a923 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/Logger.cpp @@ -1,71 +1,48 @@ -#include - #include #include - +#include namespace httq { -Logger *LoggerFactory::createLogger(QObject *parent) +Logger* LoggerFactory::createLogger(QObject* parent) { - return new Logger(this, parent); + return new Logger(this, parent); } - - -Logger::Logger(LoggerFactory *loggerFactory, QObject *parent) - : QObject(parent) - , mLoggerFactory(loggerFactory) +Logger::Logger(LoggerFactory* loggerFactory, QObject* parent) : QObject(parent), mLoggerFactory(loggerFactory) { - if (parent == nullptr) - { - - mPath = QStringLiteral("Global"); - } - else - { - mPath = QString::fromUtf8(parent->metaObject()->className()); + if (parent == nullptr) + { - - - - - - - - - - - - - } + mPath = QStringLiteral("Global"); + } + else + { + mPath = QString::fromUtf8(parent->metaObject()->className()); + } } - -void Logger::debug(const QString &message) +void Logger::debug(const QString& message) { - - qtLogger(QStringLiteral("DEBUG"), qWarning()) << message; + + qtLogger(QStringLiteral("DEBUG"), qWarning()) << message; } - -void Logger::warning(const QString &message) +void Logger::warning(const QString& message) { - qtLogger(QStringLiteral("WARNING"), qWarning()) << message; + qtLogger(QStringLiteral("WARNING"), qWarning()) << message; } - -void Logger::error(const QString &message) +void Logger::error(const QString& message) { - qtLogger(QStringLiteral("ERROR"), qCritical()) << message; + qtLogger(QStringLiteral("ERROR"), qCritical()) << message; } - -QDebug Logger::qtLogger(const QString &type, QDebug logger) +QDebug Logger::qtLogger(const QString& type, QDebug logger) { - QDebug d(logger.noquote()); - d << type << mPath << ":"; - return d; -} + QDebug d(logger.noquote()); + d << type << mPath << ":"; + return d; } +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h index da4356bd2..040a72554 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/http_parser.h @@ -8,8 +8,7 @@ #define HTTP_PARSER_VERSION_PATCH 4 #include -#if defined(_WIN32) && !defined(__MINGW32__) && \ - (!defined(_MSC_VER) || _MSC_VER < 1600) && !defined(__WINE__) +#if defined(_WIN32) && !defined(__MINGW32__) && (!defined(_MSC_VER) || _MSC_VER < 1600) && !defined(__WINE__) #include typedef __int8 int8_t; typedef unsigned __int8 uint8_t; @@ -42,273 +41,277 @@ struct http_parser_settings; typedef struct http_parser http_parser; typedef struct http_parser_settings http_parser_settings; -typedef int (*http_data_cb)(http_parser *, const char *, size_t); -typedef int (*http_cb)(http_parser *); +typedef int (*http_data_cb)(http_parser*, const char*, size_t); +typedef int (*http_cb)(http_parser*); -#define HTTP_STATUS_MAP(XX) \ - XX(100, CONTINUE, Continue) \ - XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ - XX(102, PROCESSING, Processing) \ - XX(200, OK, OK) \ - XX(201, CREATED, Created) \ - XX(202, ACCEPTED, Accepted) \ - XX(203, NON_AUTHORITATIVE_INFORMATION, Non - Authoritative Information) \ - XX(204, NO_CONTENT, No Content) \ - XX(205, RESET_CONTENT, Reset Content) \ - XX(206, PARTIAL_CONTENT, Partial Content) \ - XX(207, MULTI_STATUS, Multi - Status) \ - XX(208, ALREADY_REPORTED, Already Reported) \ - XX(226, IM_USED, IM Used) \ - XX(300, MULTIPLE_CHOICES, Multiple Choices) \ - XX(301, MOVED_PERMANENTLY, Moved Permanently) \ - XX(302, FOUND, Found) \ - XX(303, SEE_OTHER, See Other) \ - XX(304, NOT_MODIFIED, Not Modified) \ - XX(305, USE_PROXY, Use Proxy) \ - XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ - XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ - XX(400, BAD_REQUEST, Bad Request) \ - XX(401, UNAUTHORIZED, Unauthorized) \ - XX(402, PAYMENT_REQUIRED, Payment Required) \ - XX(403, FORBIDDEN, Forbidden) \ - XX(404, NOT_FOUND, Not Found) \ - XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ - XX(406, NOT_ACCEPTABLE, Not Acceptable) \ - XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ - XX(408, REQUEST_TIMEOUT, Request Timeout) \ - XX(409, CONFLICT, Conflict) \ - XX(410, GONE, Gone) \ - XX(411, LENGTH_REQUIRED, Length Required) \ - XX(412, PRECONDITION_FAILED, Precondition Failed) \ - XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ - XX(414, URI_TOO_LONG, URI Too Long) \ - XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ - XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ - XX(417, EXPECTATION_FAILED, Expectation Failed) \ - XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ - XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ - XX(423, LOCKED, Locked) \ - XX(424, FAILED_DEPENDENCY, Failed Dependency) \ - XX(426, UPGRADE_REQUIRED, Upgrade Required) \ - XX(428, PRECONDITION_REQUIRED, Precondition Required) \ - XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ - XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ - XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ - XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ - XX(501, NOT_IMPLEMENTED, Not Implemented) \ - XX(502, BAD_GATEWAY, Bad Gateway) \ - XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ - XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ - XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ - XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ - XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ - XX(508, LOOP_DETECTED, Loop Detected) \ - XX(510, NOT_EXTENDED, Not Extended) \ - XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) +#define HTTP_STATUS_MAP(XX) \ + XX(100, CONTINUE, Continue) \ + XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ + XX(102, PROCESSING, Processing) \ + XX(200, OK, OK) \ + XX(201, CREATED, Created) \ + XX(202, ACCEPTED, Accepted) \ + XX(203, NON_AUTHORITATIVE_INFORMATION, Non - Authoritative Information) \ + XX(204, NO_CONTENT, No Content) \ + XX(205, RESET_CONTENT, Reset Content) \ + XX(206, PARTIAL_CONTENT, Partial Content) \ + XX(207, MULTI_STATUS, Multi - Status) \ + XX(208, ALREADY_REPORTED, Already Reported) \ + XX(226, IM_USED, IM Used) \ + XX(300, MULTIPLE_CHOICES, Multiple Choices) \ + XX(301, MOVED_PERMANENTLY, Moved Permanently) \ + XX(302, FOUND, Found) \ + XX(303, SEE_OTHER, See Other) \ + XX(304, NOT_MODIFIED, Not Modified) \ + XX(305, USE_PROXY, Use Proxy) \ + XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ + XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ + XX(400, BAD_REQUEST, Bad Request) \ + XX(401, UNAUTHORIZED, Unauthorized) \ + XX(402, PAYMENT_REQUIRED, Payment Required) \ + XX(403, FORBIDDEN, Forbidden) \ + XX(404, NOT_FOUND, Not Found) \ + XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ + XX(406, NOT_ACCEPTABLE, Not Acceptable) \ + XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ + XX(408, REQUEST_TIMEOUT, Request Timeout) \ + XX(409, CONFLICT, Conflict) \ + XX(410, GONE, Gone) \ + XX(411, LENGTH_REQUIRED, Length Required) \ + XX(412, PRECONDITION_FAILED, Precondition Failed) \ + XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ + XX(414, URI_TOO_LONG, URI Too Long) \ + XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ + XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ + XX(417, EXPECTATION_FAILED, Expectation Failed) \ + XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ + XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ + XX(423, LOCKED, Locked) \ + XX(424, FAILED_DEPENDENCY, Failed Dependency) \ + XX(426, UPGRADE_REQUIRED, Upgrade Required) \ + XX(428, PRECONDITION_REQUIRED, Precondition Required) \ + XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ + XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ + XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ + XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ + XX(501, NOT_IMPLEMENTED, Not Implemented) \ + XX(502, BAD_GATEWAY, Bad Gateway) \ + XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ + XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ + XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ + XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ + XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ + XX(508, LOOP_DETECTED, Loop Detected) \ + XX(510, NOT_EXTENDED, Not Extended) \ + XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) enum http_status { + #define XX(num, name, string) HTTP_STATUS_##name = num, - HTTP_STATUS_MAP(XX) + HTTP_STATUS_MAP(XX) #undef XX }; -#define HTTP_METHOD_MAP(XX) \ - XX(0, DELETE, DELETE) \ - XX(1, GET, GET) \ - XX(2, HEAD, HEAD) \ - XX(3, POST, POST) \ - XX(4, PUT, PUT) \ - \ - XX(5, CONNECT, CONNECT) \ - XX(6, OPTIONS, OPTIONS) \ - XX(7, TRACE, TRACE) \ - \ - XX(8, COPY, COPY) \ - XX(9, LOCK, LOCK) \ - XX(10, MKCOL, MKCOL) \ - XX(11, MOVE, MOVE) \ - XX(12, PROPFIND, PROPFIND) \ - XX(13, PROPPATCH, PROPPATCH) \ - XX(14, SEARCH, SEARCH) \ - XX(15, UNLOCK, UNLOCK) \ - XX(16, BIND, BIND) \ - XX(17, REBIND, REBIND) \ - XX(18, UNBIND, UNBIND) \ - XX(19, ACL, ACL) \ - \ - XX(20, REPORT, REPORT) \ - XX(21, MKACTIVITY, MKACTIVITY) \ - XX(22, CHECKOUT, CHECKOUT) \ - XX(23, MERGE, MERGE) \ - \ - XX(24, MSEARCH, M - SEARCH) \ - XX(25, NOTIFY, NOTIFY) \ - XX(26, SUBSCRIBE, SUBSCRIBE) \ - XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ - \ - XX(28, PATCH, PATCH) \ - XX(29, PURGE, PURGE) \ - \ - XX(30, MKCALENDAR, MKCALENDAR) \ - \ - XX(31, LINK, LINK) \ - XX(32, UNLINK, UNLINK) \ - \ - XX(33, SOURCE, SOURCE) +#define HTTP_METHOD_MAP(XX) \ + XX(0, DELETE, DELETE) \ + XX(1, GET, GET) \ + XX(2, HEAD, HEAD) \ + XX(3, POST, POST) \ + XX(4, PUT, PUT) \ + \ + XX(5, CONNECT, CONNECT) \ + XX(6, OPTIONS, OPTIONS) \ + XX(7, TRACE, TRACE) \ + \ + XX(8, COPY, COPY) \ + XX(9, LOCK, LOCK) \ + XX(10, MKCOL, MKCOL) \ + XX(11, MOVE, MOVE) \ + XX(12, PROPFIND, PROPFIND) \ + XX(13, PROPPATCH, PROPPATCH) \ + XX(14, SEARCH, SEARCH) \ + XX(15, UNLOCK, UNLOCK) \ + XX(16, BIND, BIND) \ + XX(17, REBIND, REBIND) \ + XX(18, UNBIND, UNBIND) \ + XX(19, ACL, ACL) \ + \ + XX(20, REPORT, REPORT) \ + XX(21, MKACTIVITY, MKACTIVITY) \ + XX(22, CHECKOUT, CHECKOUT) \ + XX(23, MERGE, MERGE) \ + \ + XX(24, MSEARCH, M - SEARCH) \ + XX(25, NOTIFY, NOTIFY) \ + XX(26, SUBSCRIBE, SUBSCRIBE) \ + XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ + \ + XX(28, PATCH, PATCH) \ + XX(29, PURGE, PURGE) \ + \ + XX(30, MKCALENDAR, MKCALENDAR) \ + \ + XX(31, LINK, LINK) \ + XX(32, UNLINK, UNLINK) \ + \ + XX(33, SOURCE, SOURCE) enum http_method { + #define XX(num, name, string) HTTP_##name = num, - HTTP_METHOD_MAP(XX) + HTTP_METHOD_MAP(XX) #undef XX }; enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; enum flags { - F_CHUNKED = 1 << 0, - F_CONNECTION_KEEP_ALIVE = 1 << 1, - F_CONNECTION_CLOSE = 1 << 2, - F_CONNECTION_UPGRADE = 1 << 3, - F_TRAILING = 1 << 4, - F_UPGRADE = 1 << 5, - F_SKIPBODY = 1 << 6, - F_CONTENTLENGTH = 1 << 7, - F_TRANSFER_ENCODING = 1 << 8 + F_CHUNKED = 1 << 0, + F_CONNECTION_KEEP_ALIVE = 1 << 1, + F_CONNECTION_CLOSE = 1 << 2, + F_CONNECTION_UPGRADE = 1 << 3, + F_TRAILING = 1 << 4, + F_UPGRADE = 1 << 5, + F_SKIPBODY = 1 << 6, + F_CONTENTLENGTH = 1 << 7, + F_TRANSFER_ENCODING = 1 << 8 }; -#define HTTP_ERRNO_MAP(XX) \ - \ - XX(OK, "success") \ - \ - XX(CB_message_begin, "the on_message_begin callback failed") \ - XX(CB_url, "the on_url callback failed") \ - XX(CB_header_field, "the on_header_field callback failed") \ - XX(CB_header_value, "the on_header_value callback failed") \ - XX(CB_headers_complete, "the on_headers_complete callback failed") \ - XX(CB_body, "the on_body callback failed") \ - XX(CB_message_complete, "the on_message_complete callback failed") \ - XX(CB_status, "the on_status callback failed") \ - XX(CB_chunk_header, "the on_chunk_header callback failed") \ - XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ - \ - XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ - XX(HEADER_OVERFLOW, "too many header bytes seen; overflow detected") \ - XX(CLOSED_CONNECTION, \ - "data received after completed connection: close message") \ - XX(INVALID_VERSION, "invalid HTTP version") \ - XX(INVALID_STATUS, "invalid HTTP status code") \ - XX(INVALID_METHOD, "invalid HTTP method") \ - XX(INVALID_URL, "invalid URL") \ - XX(INVALID_HOST, "invalid host") \ - XX(INVALID_PORT, "invalid port") \ - XX(INVALID_PATH, "invalid path") \ - XX(INVALID_QUERY_STRING, "invalid query string") \ - XX(INVALID_FRAGMENT, "invalid fragment") \ - XX(LF_EXPECTED, "LF character expected") \ - XX(INVALID_HEADER_TOKEN, "invalid character in header") \ - XX(INVALID_CONTENT_LENGTH, "invalid character in content-length header") \ - XX(UNEXPECTED_CONTENT_LENGTH, "unexpected content-length header") \ - XX(INVALID_CHUNK_SIZE, "invalid character in chunk size header") \ - XX(INVALID_CONSTANT, "invalid constant string") \ - XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state") \ - XX(STRICT, "strict mode assertion failed") \ - XX(PAUSED, "parser is paused") \ - XX(UNKNOWN, "an unknown error occurred") \ - XX(INVALID_TRANSFER_ENCODING, "request has invalid transfer-encoding") +#define HTTP_ERRNO_MAP(XX) \ + \ + XX(OK, "success") \ + \ + XX(CB_message_begin, "the on_message_begin callback failed") \ + XX(CB_url, "the on_url callback failed") \ + XX(CB_header_field, "the on_header_field callback failed") \ + XX(CB_header_value, "the on_header_value callback failed") \ + XX(CB_headers_complete, "the on_headers_complete callback failed") \ + XX(CB_body, "the on_body callback failed") \ + XX(CB_message_complete, "the on_message_complete callback failed") \ + XX(CB_status, "the on_status callback failed") \ + XX(CB_chunk_header, "the on_chunk_header callback failed") \ + XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ + \ + XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ + XX(HEADER_OVERFLOW, "too many header bytes seen; overflow detected") \ + XX(CLOSED_CONNECTION, "data received after completed connection: close message") \ + XX(INVALID_VERSION, "invalid HTTP version") \ + XX(INVALID_STATUS, "invalid HTTP status code") \ + XX(INVALID_METHOD, "invalid HTTP method") \ + XX(INVALID_URL, "invalid URL") \ + XX(INVALID_HOST, "invalid host") \ + XX(INVALID_PORT, "invalid port") \ + XX(INVALID_PATH, "invalid path") \ + XX(INVALID_QUERY_STRING, "invalid query string") \ + XX(INVALID_FRAGMENT, "invalid fragment") \ + XX(LF_EXPECTED, "LF character expected") \ + XX(INVALID_HEADER_TOKEN, "invalid character in header") \ + XX(INVALID_CONTENT_LENGTH, "invalid character in content-length header") \ + XX(UNEXPECTED_CONTENT_LENGTH, "unexpected content-length header") \ + XX(INVALID_CHUNK_SIZE, "invalid character in chunk size header") \ + XX(INVALID_CONSTANT, "invalid constant string") \ + XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state") \ + XX(STRICT, "strict mode assertion failed") \ + XX(PAUSED, "parser is paused") \ + XX(UNKNOWN, "an unknown error occurred") \ + XX(INVALID_TRANSFER_ENCODING, "request has invalid transfer-encoding") #define HTTP_ERRNO_GEN(n, s) HPE_##n, + enum http_errno { HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) }; + #undef HTTP_ERRNO_GEN #define HTTP_PARSER_ERRNO(p) ((enum http_errno)(p)->http_errno) -struct http_parser { +struct http_parser +{ - unsigned int type : 2; - unsigned int flags : 8; - unsigned int state : 7; - unsigned int header_state : 7; - unsigned int index : 5; - unsigned int extra_flags : 2; - unsigned int lenient_http_headers : 1; + unsigned int type : 2; + unsigned int flags : 8; + unsigned int state : 7; + unsigned int header_state : 7; + unsigned int index : 5; + unsigned int extra_flags : 2; + unsigned int lenient_http_headers : 1; - uint32_t nread; - uint64_t content_length; + uint32_t nread; + uint64_t content_length; - unsigned short http_major; - unsigned short http_minor; - unsigned int status_code : 16; - unsigned int method : 8; - unsigned int http_errno : 7; + unsigned short http_major; + unsigned short http_minor; + unsigned int status_code : 16; + unsigned int method : 8; + unsigned int http_errno : 7; - unsigned int upgrade : 1; + unsigned int upgrade : 1; - void *data; + void* data; }; -struct http_parser_settings { - http_cb on_message_begin; - http_data_cb on_url; - http_data_cb on_status; - http_data_cb on_header_field; - http_data_cb on_header_value; - http_cb on_headers_complete; - http_data_cb on_body; - http_cb on_message_complete; +struct http_parser_settings +{ + http_cb on_message_begin; + http_data_cb on_url; + http_data_cb on_status; + http_data_cb on_header_field; + http_data_cb on_header_value; + http_cb on_headers_complete; + http_data_cb on_body; + http_cb on_message_complete; - http_cb on_chunk_header; - http_cb on_chunk_complete; + http_cb on_chunk_header; + http_cb on_chunk_complete; }; enum http_parser_url_fields { - UF_SCHEMA = 0, - UF_HOST = 1, - UF_PORT = 2, - UF_PATH = 3, - UF_QUERY = 4, - UF_FRAGMENT = 5, - UF_USERINFO = 6, - UF_MAX = 7 + UF_SCHEMA = 0, + UF_HOST = 1, + UF_PORT = 2, + UF_PATH = 3, + UF_QUERY = 4, + UF_FRAGMENT = 5, + UF_USERINFO = 6, + UF_MAX = 7 }; -struct http_parser_url { - uint16_t field_set; - uint16_t port; +struct http_parser_url +{ + uint16_t field_set; + uint16_t port; - struct { - uint16_t off; - uint16_t len; - } field_data[UF_MAX]; + struct + { + uint16_t off; + uint16_t len; + } field_data[UF_MAX]; }; unsigned long http_parser_version(void); -void http_parser_init(http_parser *parser, enum http_parser_type type); +void http_parser_init(http_parser* parser, enum http_parser_type type); -void http_parser_settings_init(http_parser_settings *settings); +void http_parser_settings_init(http_parser_settings* settings); -size_t http_parser_execute(http_parser *parser, - const http_parser_settings *settings, - const char *data, size_t len); +size_t http_parser_execute(http_parser* parser, const http_parser_settings* settings, const char* data, size_t len); -int http_should_keep_alive(const http_parser *parser); +int http_should_keep_alive(const http_parser* parser); -const char *http_method_str(enum http_method m); +const char* http_method_str(enum http_method m); -const char *http_status_str(enum http_status s); +const char* http_status_str(enum http_status s); -const char *http_errno_name(enum http_errno err); +const char* http_errno_name(enum http_errno err); -const char *http_errno_description(enum http_errno err); +const char* http_errno_description(enum http_errno err); -void http_parser_url_init(struct http_parser_url *u); +void http_parser_url_init(struct http_parser_url* u); -int http_parser_parse_url(const char *buf, size_t buflen, int is_connect, - struct http_parser_url *u); +int http_parser_parse_url(const char* buf, size_t buflen, int is_connect, struct http_parser_url* u); -void http_parser_pause(http_parser *parser, int paused); +void http_parser_pause(http_parser* parser, int paused); -int http_body_is_final(const http_parser *parser); +int http_body_is_final(const http_parser* parser); void http_parser_set_max_header_size(uint32_t size); diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h old mode 100755 new mode 100644 index 3341d7cd3..96ad858b6 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/AbstractServer.h @@ -2,39 +2,41 @@ #include "httq_export.h" -#include #include - +#include class QTcpServer; class QWebSocketServer; - namespace httq { class HttpRequest; class LoggerFactory; class Logger; - class HTTQ_EXPORT AbstractServer : public QObject { - Q_OBJECT -public: - explicit AbstractServer(QObject *parent = nullptr); + Q_OBJECT + public: + explicit AbstractServer(QObject* parent = nullptr); - virtual bool newHttpConnection(HttpRequest *request) = 0; - virtual QWebSocketServer *webSocketServer() const { return nullptr; } - virtual LoggerFactory *createLoggerFactory(); - LoggerFactory *getLoggerFactory(); - bool listen(qint16 port, const QHostAddress &host = QHostAddress::Any); + virtual bool newHttpConnection(HttpRequest* request) = 0; -private slots: - void slotNewConnection(); + virtual QWebSocketServer* webSocketServer() const + { + return nullptr; + } -private: - QTcpServer *mSvr; - LoggerFactory *mLoggerFactory { nullptr }; - Logger *mLogger; + virtual LoggerFactory* createLoggerFactory(); + LoggerFactory* getLoggerFactory(); + bool listen(qint16 port, const QHostAddress& host = QHostAddress::Any); + + private slots: + void slotNewConnection(); + + private: + QTcpServer* mSvr; + LoggerFactory* mLoggerFactory{nullptr}; + Logger* mLogger; }; -} +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h old mode 100755 new mode 100644 index 025cf1c3c..28e46d5dc --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/DataStream.h @@ -1,53 +1,49 @@ #pragma once #include "httq_export.h" -#include #include #include - +#include class QIODevice; - namespace httq { class HttpRequest; class HTTQ_EXPORT DataStream : public QObject { - Q_OBJECT + Q_OBJECT -private: - explicit DataStream(QIODevice *from, QIODevice *to, const QByteArray &bodyPartial, - qint64 fileLength, size_t bufferSize, LoggerFactory *loggerFactory, - QObject *parent = nullptr); + private: + explicit DataStream(QIODevice* from, QIODevice* to, const QByteArray& bodyPartial, qint64 fileLength, + size_t bufferSize, LoggerFactory* loggerFactory, QObject* parent = nullptr); -public: - ~DataStream(); + public: + ~DataStream(); -private: - friend class HttpRequest; + private: + friend class HttpRequest; - void readNext(); - void writeNext(); + void readNext(); + void writeNext(); - bool mReadyWrite { true }; - - QByteArray mBuffer; - QByteArray mBodyPartial; - QIODevice *mFrom; - QIODevice *mTo; - - qint64 mBufferSize; - qint64 alreadyRead { 0 }; - qint64 mFileLength; - bool mFromSupportsSignals { false }; - bool mToSupportsSignals { false }; - QScopedPointer mLogger; + bool mReadyWrite{true}; -signals: - void signalDone(); + QByteArray mBuffer; + QByteArray mBodyPartial; + QIODevice* mFrom; + QIODevice* mTo; + qint64 mBufferSize; + qint64 alreadyRead{0}; + qint64 mFileLength; + bool mFromSupportsSignals{false}; + bool mToSupportsSignals{false}; + QScopedPointer mLogger; + + signals: + void signalDone(); }; -} +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h old mode 100755 new mode 100644 index 10f76f27d..9a7a90054 --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/HttpRequest.h @@ -1,20 +1,18 @@ #pragma once #include "httq_export.h" -#include -#include #include -#include #include +#include #include +#include #include - +#include class QTcpSocket; class QIODevice; - namespace httq { class AbstractServer; @@ -22,91 +20,118 @@ class Logger; class DataStream; class HttpRequest; - struct HttpRequestData { - QByteArray mData; - QUrl mUrl; - QString mCurrentHeaderField; - QMap mHeaders; - bool mDone { false }; - QByteArray mBodyPartial; - QUrlQuery mQuery; - HttpRequest *mHttpRquest; + QByteArray mData; + QUrl mUrl; + QString mCurrentHeaderField; + QMap mHeaders; + bool mDone{false}; + QByteArray mBodyPartial; + QUrlQuery mQuery; + HttpRequest* mHttpRquest; }; - class HTTQ_EXPORT HttpRequest : public QObject { - Q_OBJECT + Q_OBJECT -private: - explicit HttpRequest(QTcpSocket *cli, AbstractServer *parent = nullptr); -public: - ~HttpRequest(); + private: + explicit HttpRequest(QTcpSocket* cli, AbstractServer* parent = nullptr); - qint64 availableBytes() const; - http_method method() const { return (enum http_method)mParser.method; } - QString methodString() const { return QString::fromUtf8(http_method_str(method())); } - const QUrl &url() const { return mData.mUrl; } - const QUrlQuery &query() const { return mData.mQuery; } - qint64 contentLength() const { return mContentLength; } - const QMap &requestHeaders() const { return mData.mHeaders; } - - - Logger *logger() { return mLogger; } - QString toString() const; + public: + ~HttpRequest(); - - void addHeader(const QString &key, const QString &value); - void write(int status, const QByteArray &data, const QString &contentType); - void write(int status, const QJsonValue &jsonValue); - DataStream *createDataStreamFromClient(QIODevice *to, qint64 fileSize, qint64 bufferSize = 1024 * 1024); - DataStream *createDataStreamToClient(int status, const QString &contentType, QIODevice *from, qint64 fileSize, qint64 bufferSize = 1024 * 1024); + qint64 availableBytes() const; - friend class DataStream; + http_method method() const + { + return (enum http_method)mParser.method; + } + QString methodString() const + { + return QString::fromUtf8(http_method_str(method())); + } -private: - friend class AbstractServer; + const QUrl& url() const + { + return mData.mUrl; + } - - void writeStatusHeader(int status); - void writeHeaders(); + const QUrlQuery& query() const + { + return mData.mQuery; + } - static int on_message_begin(http_parser *parser); - static int on_url(http_parser *parser, const char *at, size_t length); - static int on_status(http_parser *parser, const char *at, size_t length); - static int on_header_field(http_parser *parser, const char *at, size_t length); - static int on_header_value(http_parser *parser, const char *at, size_t length); - static int on_headers_complete(http_parser *parser); - static int on_body(http_parser *parser, const char *at, size_t length); - static int on_message_complete(http_parser *parser); - static int on_chunk_header(http_parser *parser); - static int on_chunk_complete(http_parser *parser); + qint64 contentLength() const + { + return mContentLength; + } - static HttpRequestData *data(http_parser *parser) { return static_cast(parser->data); } - static Logger *dataLogger(http_parser *parser) { return static_cast(parser->data)->mHttpRquest->logger(); } + const QMap& requestHeaders() const + { + return mData.mHeaders; + } + Logger* logger() + { + return mLogger; + } - QTcpSocket *mCli; - http_parser mParser; - http_parser_settings mParserSettings; - HttpRequestData mData; - bool mDone { false }; - qint64 mContentLength { 0 }; - qint64 alreadyRead { 0 }; - QMap mHeaders; - Logger *mLogger; + QString toString() const; + void addHeader(const QString& key, const QString& value); + void write(int status, const QByteArray& data, const QString& contentType); + void write(int status, const QJsonValue& jsonValue); + DataStream* createDataStreamFromClient(QIODevice* to, qint64 fileSize, qint64 bufferSize = 1024 * 1024); + DataStream* createDataStreamToClient(int status, const QString& contentType, QIODevice* from, qint64 fileSize, + qint64 bufferSize = 1024 * 1024); -private slots: - void slotReadyRead(); + friend class DataStream; + private: + friend class AbstractServer; -signals: - void signalUpgrade(QTcpSocket *sock); - void signalReady(); + void writeStatusHeader(int status); + void writeHeaders(); + static int on_message_begin(http_parser* parser); + static int on_url(http_parser* parser, const char* at, size_t length); + static int on_status(http_parser* parser, const char* at, size_t length); + static int on_header_field(http_parser* parser, const char* at, size_t length); + static int on_header_value(http_parser* parser, const char* at, size_t length); + static int on_headers_complete(http_parser* parser); + static int on_body(http_parser* parser, const char* at, size_t length); + static int on_message_complete(http_parser* parser); + static int on_chunk_header(http_parser* parser); + static int on_chunk_complete(http_parser* parser); + + static HttpRequestData* data(http_parser* parser) + { + return static_cast(parser->data); + } + + static Logger* dataLogger(http_parser* parser) + { + return static_cast(parser->data)->mHttpRquest->logger(); + } + + QTcpSocket* mCli; + http_parser mParser; + http_parser_settings mParserSettings; + HttpRequestData mData; + bool mDone{false}; + qint64 mContentLength{0}; + qint64 alreadyRead{0}; + QMap mHeaders; + Logger* mLogger; + + private slots: + void slotReadyRead(); + + signals: + void signalUpgrade(QTcpSocket* sock); + void signalReady(); }; -} +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h old mode 100755 new mode 100644 index 3e0b8440d..22712d0ba --- a/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Common/httq/include/httq/Logger.h @@ -3,50 +3,45 @@ #include "httq_export.h" #include -#include #include - +#include namespace httq { class Logger; - class HTTQ_EXPORT LoggerFactory : public QObject { - Q_OBJECT + Q_OBJECT -public: - LoggerFactory(QObject *parent) - : QObject(parent) - {} + public: + LoggerFactory(QObject* parent) : QObject(parent) {} - virtual Logger *createLogger(QObject *parent); + virtual Logger* createLogger(QObject* parent); }; - class HTTQ_EXPORT Logger : public QObject { - Q_OBJECT -public: - Logger(LoggerFactory *loggerFactory, QObject *parent); + Q_OBJECT + public: + Logger(LoggerFactory* loggerFactory, QObject* parent); - virtual void debug(const QString &message); - virtual void warning(const QString &message); - virtual void error(const QString &message); + virtual void debug(const QString& message); + virtual void warning(const QString& message); + virtual void error(const QString& message); - virtual LoggerFactory *getLoggerFactory() const - { - Q_ASSERT(mLoggerFactory); - return mLoggerFactory; - } + virtual LoggerFactory* getLoggerFactory() const + { + Q_ASSERT(mLoggerFactory); + return mLoggerFactory; + } -protected: - QPointer mLoggerFactory; + protected: + QPointer mLoggerFactory; -private: - QDebug qtLogger(const QString &type, QDebug debug); + private: + QDebug qtLogger(const QString& type, QDebug debug); - QString mPath; + QString mPath; }; -} +} // namespace httq diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.cpp old mode 100755 new mode 100644 index 1e3cad565..5e61f53f9 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.cpp @@ -1,15 +1,14 @@ - #include "pacemaker.h" +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include namespace Core { @@ -17,101 +16,96 @@ Pacemaker::Pacemaker(DDSConnector::DdsConnector *ddsConnector) : QObject(nullptr) .getNGLLogger("Core.Pacemaker")) { - init(ddsConnector); + init(ddsConnector); } Pacemaker::~Pacemaker() { - m_paceThread->requestInterruption(); - m_paceThread->quit(); - m_paceThread->wait(); - delete m_paceThread; - m_publishTimer->deleteLater(); - delete m_dtsCurrentRunningState; + m_paceThread->requestInterruption(); + m_paceThread->quit(); + m_paceThread->wait(); + delete m_paceThread; + m_publishTimer->deleteLater(); + delete m_dtsCurrentRunningState; } - -void Pacemaker::setNewState(Core::RunningState newState, const QString &errorString) +void Pacemaker::setNewState(Core::RunningState newState, const QString& errorString) { - if (QThread::currentThread() == this->thread()) - setNewStateInternal(newState, errorString); - else - QTimer::singleShot(0, this, [this, newState, errorString]() { setNewStateInternal(newState, errorString); }); + if (QThread::currentThread() == this->thread()) + setNewStateInternal(newState, errorString); + else + QTimer::singleShot(0, this, [this, newState, errorString]() { setNewStateInternal(newState, errorString); }); } -void Pacemaker::setNewStateInternal(Core::RunningState newState, const QString &errorString) +void Pacemaker::setNewStateInternal(Core::RunningState newState, const QString& errorString) { - m_state.runningState(newState); - if (errorString.isEmpty()) - m_state.errorString().reset(); - else - m_state.errorString(errorString.toStdString()); - publishState(); + m_state.runningState(newState); + if (errorString.isEmpty()) + m_state.errorString().reset(); + else + m_state.errorString(errorString.toStdString()); + publishState(); } -void Pacemaker::addPort(unsigned short number, Core::PortType portType, const QString &properties) +void Pacemaker::addPort(unsigned short number, Core::PortType portType, const QString& properties) { - if (QThread::currentThread() == this->thread()) - addPortInternal(number, portType, properties); - else - QTimer::singleShot(0, this, [this, number, portType, properties]() { addPortInternal(number, portType, properties); }); + if (QThread::currentThread() == this->thread()) + addPortInternal(number, portType, properties); + else + QTimer::singleShot(0, this, + [this, number, portType, properties]() { addPortInternal(number, portType, properties); }); } -void Pacemaker::addPortInternal(unsigned short number, Core::PortType portType,const QString &properties) +void Pacemaker::addPortInternal(unsigned short number, Core::PortType portType, const QString& properties) { - if (!m_state.ports().is_set()) - m_state.ports() = std::vector(); - m_state.ports().get().push_back(Core::PortInformation(number, portType, properties.toStdString())); + if (!m_state.ports().is_set()) + m_state.ports() = std::vector(); + m_state.ports().get().push_back(Core::PortInformation(number, portType, properties.toStdString())); - publishState(); + publishState(); } void Pacemaker::publishState() { - if (!m_dtsCurrentRunningState) - return; - m_dtsCurrentRunningState->write(m_state); + if (!m_dtsCurrentRunningState) + return; + m_dtsCurrentRunningState->write(m_state); } -void Pacemaker::init(DDSConnector::DdsConnector *ddsConnector) +void Pacemaker::init(DDSConnector::DdsConnector* ddsConnector) { - m_dtsCurrentRunningState = ddsConnector->createDTS(); - if (!m_dtsCurrentRunningState) - { - WARNING_LOG(m_logger) << "Can not initialize DTS::CurrentRunningState!"; - return; - } - m_state.pid(QCoreApplication::applicationPid()); - m_state.runningState(Core::RunningState::Starting); + m_dtsCurrentRunningState = ddsConnector->createDTS(); + if (!m_dtsCurrentRunningState) + { + WARNING_LOG(m_logger) << "Can not initialize DTS::CurrentRunningState!"; + return; + } + m_state.pid(QCoreApplication::applicationPid()); + m_state.runningState(Core::RunningState::Starting); - m_paceThread = new QThread; - this->moveToThread(m_paceThread); + m_paceThread = new QThread; + this->moveToThread(m_paceThread); - startTimer(); - publishState(); + startTimer(); + publishState(); } void Pacemaker::startTimer() { - if (m_publishTimer) - return; + if (m_publishTimer) + return; - m_publishTimer = new QTimer(); + m_publishTimer = new QTimer(); + m_publishTimer->moveToThread(m_paceThread); - m_publishTimer->moveToThread(m_paceThread); + connect(m_publishTimer, &QTimer::timeout, this, &Pacemaker::publishState); - connect(m_publishTimer, &QTimer::timeout, - this, &Pacemaker::publishState); + m_publishTimer->setSingleShot(false); + m_publishTimer->setInterval(m_publishTimerDelay); + connect(m_paceThread, &QThread::started, this, [this]() { m_publishTimer->start(); }); - m_publishTimer->setSingleShot(false); - m_publishTimer->setInterval(m_publishTimerDelay); - connect(m_paceThread, &QThread::started, this, [this](){ - m_publishTimer->start(); - }); - - - m_paceThread->start(); + m_paceThread->start(); } -} +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.h old mode 100755 new mode 100644 index 62441675a..8ff17bd8f --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Core/pacemaker.h @@ -1,18 +1,19 @@ - #pragma once +#include "svccoreclient_export.h" + +#include #include #include -#include -#include "svccoreclient_export.h" namespace DDSConnector { class DdsConnector; } class QTimer; + namespace NGL { class INGLLogger; @@ -22,37 +23,38 @@ namespace Core { class CORE_CLIENT_EXPORT Pacemaker final : public QObject { - Q_OBJECT -public: - explicit Pacemaker(const std::shared_ptr &ddsConnector) - : Pacemaker(ddsConnector.get()) - {} + Q_OBJECT + public: + explicit Pacemaker(const std::shared_ptr& ddsConnector) : Pacemaker(ddsConnector.get()) + { + } - explicit Pacemaker(DDSConnector::DdsConnector *ddsConnector); - ~Pacemaker(); + explicit Pacemaker(DDSConnector::DdsConnector* ddsConnector); + ~Pacemaker(); - void startTimer(); + void startTimer(); -public Q_SLOTS: - void setNewState(Core::RunningState newState, const QString &errorString = QString()); - void addPort(unsigned short number, Core::PortType portType, const QString &properties = QStringLiteral("")); + public Q_SLOTS: + void setNewState(Core::RunningState newState, const QString& errorString = QString()); + void addPort(unsigned short number, Core::PortType portType, const QString& properties = QStringLiteral("")); - - void publishState(); + void publishState(); -private: - NGL::INGLLogger &m_logger; - void init(DDSConnector::DdsConnector *ddsConnector); - void setNewStateInternal(Core::RunningState newState, const QString &errorString = QString()); - void addPortInternal(unsigned short number, Core::PortType portType, const QString &properties = QStringLiteral("")); -private: - NGL::INGLLogger &m_logger; - static constexpr const int m_publishTimerDelay = 3000; + private: + NGL::INGLLogger& m_logger; + void init(DDSConnector::DdsConnector* ddsConnector); + void setNewStateInternal(Core::RunningState newState, const QString& errorString = QString()); + void addPortInternal(unsigned short number, Core::PortType portType, + const QString& properties = QStringLiteral("")); - CurrentRunningState m_state; - QTimer *m_publishTimer = nullptr; - QThread *m_paceThread = nullptr; + private: + NGL::INGLLogger& m_logger; + static constexpr const int m_publishTimerDelay = 3000; - DTS::CurrentRunningStateImpl *m_dtsCurrentRunningState; + CurrentRunningState m_state; + QTimer* m_publishTimer = nullptr; + QThread* m_paceThread = nullptr; + + DTS::CurrentRunningStateImpl* m_dtsCurrentRunningState; }; -} +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.cpp old mode 100755 new mode 100644 index 0f87098c8..eb2c0f5df --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.cpp @@ -1,13 +1,13 @@ - #include "dds_connector.h" + #include "publisher.h" #include "subscriber.h" -#include -#include #include +#include +#include #include namespace DDSConnector @@ -32,252 +32,221 @@ DdsConnector::DdsConnector(int domainId, , m_wsHandler(nullptr) .getNGLLogger("Common.DDSConnector")) { - initInternal(); - DEBUG_LOG(m_logger) << "DdsConnector ctor: " << m_domainId << "," << m_partitionId << ","<< m_exerciseId << "," << static_cast(m_defaultPartitionType); + initInternal(); + DEBUG_LOG(m_logger) << "DdsConnector ctor: " << m_domainId << "," << m_partitionId << "," << m_exerciseId << "," + << static_cast(m_defaultPartitionType); } -DdsConnector::DdsConnector(int domainId, - IDL::PartitionType defaultPartitionType, - int partitionId, int exerciseId, - const QUrl &tcpConnectionUrl) - : DdsConnector(domainId, - nullptr, - defaultPartitionType, - partitionId, - exerciseId, - DDS::QosProfile::ConnectionType::Server, - tcpConnectionUrl) -{} - -DdsConnector::DdsConnector(const dds::domain::DomainParticipant &domainParticipant, - IDL::PartitionType defaultPartitionType, - int partitionId, int exerciseId, - const QUrl &tcpConnectionUrl) - : DdsConnector(domainParticipant.domain_id(), - domainParticipant, - defaultPartitionType, - partitionId, - exerciseId, - DDS::QosProfile::ConnectionType::Server, - tcpConnectionUrl) -{} - - -DdsConnector::DdsConnector(const dds::domain::DomainParticipant &domainParticipant, - IDL::PartitionType defaultPartitionType, - DDS::QosProfile::ConnectionType connectionType, - int partitionId, - int exerciseId - ) - : DdsConnector(domainParticipant.domain_id(), - domainParticipant, - defaultPartitionType, - partitionId, - exerciseId, - connectionType, - QUrl()) -{} - -DdsConnector::DdsConnector(int domainId, - IDL::PartitionType defaultPartitionType, - int partitionId, int exerciseId, - DDS::QosProfile::ConnectionType connectionType) - : DdsConnector(domainId, - nullptr, - defaultPartitionType, - partitionId, - exerciseId, - connectionType, - QUrl()) +DdsConnector::DdsConnector(int domainId, IDL::PartitionType defaultPartitionType, int partitionId, int exerciseId, + const QUrl& tcpConnectionUrl) + : DdsConnector(domainId, nullptr, defaultPartitionType, partitionId, exerciseId, + DDS::QosProfile::ConnectionType::Server, tcpConnectionUrl) { - Q_ASSERT(connectionType != DDS::QosProfile::ConnectionType::Tcp); } +DdsConnector::DdsConnector(const dds::domain::DomainParticipant& domainParticipant, + IDL::PartitionType defaultPartitionType, int partitionId, int exerciseId, + const QUrl& tcpConnectionUrl) + : DdsConnector(domainParticipant.domain_id(), domainParticipant, defaultPartitionType, partitionId, exerciseId, + DDS::QosProfile::ConnectionType::Server, tcpConnectionUrl) +{ +} + +DdsConnector::DdsConnector(const dds::domain::DomainParticipant& domainParticipant, + IDL::PartitionType defaultPartitionType, DDS::QosProfile::ConnectionType connectionType, + int partitionId, int exerciseId) + : DdsConnector(domainParticipant.domain_id(), domainParticipant, defaultPartitionType, partitionId, exerciseId, + connectionType, QUrl()) +{ +} + +DdsConnector::DdsConnector(int domainId, IDL::PartitionType defaultPartitionType, int partitionId, int exerciseId, + DDS::QosProfile::ConnectionType connectionType) + : DdsConnector(domainId, nullptr, defaultPartitionType, partitionId, exerciseId, connectionType, QUrl()) +{ + Q_ASSERT(connectionType != DDS::QosProfile::ConnectionType::Tcp); +} DdsConnector::~DdsConnector() { - delete m_subscriber; - delete m_publisher; - delete m_wsHandler; + delete m_subscriber; + delete m_publisher; + delete m_wsHandler; } -bool DdsConnector::init(const QStringList &qosFileList) +bool DdsConnector::init(const QStringList& qosFileList) { - return DDS::QosProfile::setDefault(qosFileList); + return DDS::QosProfile::setDefault(qosFileList); } QUrl DdsConnector::getTcpConnectionUrl() const { - DEBUG_LOG(m_logger) << this << " gettcpConnectionUrl: " << m_tcpConnectionUrl.toString(); - return m_tcpConnectionUrl; + DEBUG_LOG(m_logger) << this << " gettcpConnectionUrl: " << m_tcpConnectionUrl.toString(); + return m_tcpConnectionUrl; } dds::pub::Publisher DdsConnector::getDdsPublisher() const { - return m_publisher ? m_publisher->getDdsPublisher() : nullptr; + return m_publisher ? m_publisher->getDdsPublisher() : nullptr; } dds::sub::Subscriber DdsConnector::getDdsSubscriber() const { - return m_subscriber ? m_subscriber->getDdsSubscriber() : nullptr; + return m_subscriber ? m_subscriber->getDdsSubscriber() : nullptr; } -DDSGeneric::SubscriberListener *DdsConnector::getSubscriberListener() +DDSGeneric::SubscriberListener* DdsConnector::getSubscriberListener() { - return m_subscriber ? m_subscriber->getSubscriberListener() : nullptr; + return m_subscriber ? m_subscriber->getSubscriberListener() : nullptr; } void DdsConnector::initPublisherSubscriber() { - initSubscriber(); - initPublisher(); + initSubscriber(); + initPublisher(); } void DdsConnector::initPublisher() { - if (m_publisher) - return; - initDomainParticipant(); - - setPublisher(new DDSConnector::Publisher(m_domainParticipant, getDefaultPartition())); + if (m_publisher) + return; + initDomainParticipant(); + + setPublisher(new DDSConnector::Publisher(m_domainParticipant, getDefaultPartition())); } void DdsConnector::initSubscriber() { - if (m_subscriber) - return; - initDomainParticipant(); - - setSubscriber(new DDSConnector::Subscriber(m_domainParticipant, getDefaultPartition())); + if (m_subscriber) + return; + initDomainParticipant(); + + setSubscriber(new DDSConnector::Subscriber(m_domainParticipant, getDefaultPartition())); } void DdsConnector::initDomainParticipant() { - if (m_domainParticipant == nullptr) - setDomainParticipant(dds::domain::DomainParticipant(m_domainId, - DDS::QosProfile::domainParticipantDefault(m_connectionType, m_tcpConnectionUrl))); + if (m_domainParticipant == nullptr) + setDomainParticipant(dds::domain::DomainParticipant( + m_domainId, DDS::QosProfile::domainParticipantDefault(m_connectionType, m_tcpConnectionUrl))); } - std::string DdsConnector::getDefaultPartition() const { - return getPartitionString(m_defaultPartitionType, m_partitionId); + return getPartitionString(m_defaultPartitionType, m_partitionId); } std::string DdsConnector::getPartitionString(IDL::PartitionType pt, int partitionId) { - switch (pt) - { - case IDL::PartitionType::Any: - return "*"; - case IDL::PartitionType::Global: - return IDL::exercisePartition(0); - case IDL::PartitionType::Exercise: - case IDL::PartitionType::AllExercises: - return IDL::exercisePartition(partitionId); - case IDL::PartitionType::Replay: - return IDL::replayPartition(partitionId); - } + switch (pt) + { + case IDL::PartitionType::Any: + return "*"; + case IDL::PartitionType::Global: + return IDL::exercisePartition(0); + case IDL::PartitionType::Exercise: + case IDL::PartitionType::AllExercises: + return IDL::exercisePartition(partitionId); + case IDL::PartitionType::Replay: + return IDL::replayPartition(partitionId); + } - NGL::INGLLogger &m_logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Common.DDSConnector"); - ERROR_LOG(m_logger) << "Invalid partition type: " << static_cast(pt); - return std::string(); + NGL::INGLLogger& m_logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("Common.DDSConnector"); + ERROR_LOG(m_logger) << "Invalid partition type: " << static_cast(pt); + return std::string(); } -void DdsConnector::setDomainParticipant(const dds::domain::DomainParticipant &participant) +void DdsConnector::setDomainParticipant(const dds::domain::DomainParticipant& participant) { - m_domainParticipant = participant; - if (m_domainParticipant == nullptr) - return; + m_domainParticipant = participant; + if (m_domainParticipant == nullptr) + return; - try - { - - dds::domain::qos::DomainParticipantQos dpQos(m_domainParticipant.qos()); - DDS::QosProfile::print(dpQos, m_logger); - rti::core::policy::EntityName entityName; - entityName.name(qAppName().toStdString() + (" - DP ") + std::to_string(m_domainId)); - dpQos << entityName; - m_domainParticipant.qos(dpQos); - m_domainParticipant->default_datareader_qos(DDS::QosProfile::dataReaderDefault(m_connectionType)); - m_domainParticipant.enable(); - } - catch (const dds::core::Exception &ex) - { - WARNING_LOG(m_logger) << "Could not enable DomainParticipant: " << ex.what(); - exit(1); - } + try + { + + dds::domain::qos::DomainParticipantQos dpQos(m_domainParticipant.qos()); + DDS::QosProfile::print(dpQos, m_logger); + rti::core::policy::EntityName entityName; + entityName.name(qAppName().toStdString() + (" - DP ") + std::to_string(m_domainId)); + dpQos << entityName; + m_domainParticipant.qos(dpQos); + m_domainParticipant->default_datareader_qos(DDS::QosProfile::dataReaderDefault(m_connectionType)); + m_domainParticipant.enable(); + } + catch (const dds::core::Exception& ex) + { + WARNING_LOG(m_logger) << "Could not enable DomainParticipant: " << ex.what(); + exit(1); + } } -void DdsConnector::setPublisher(Publisher *publisher) +void DdsConnector::setPublisher(Publisher* publisher) { - if (m_publisher && publisher != m_publisher) - { - WARNING_LOG(m_logger) << "Trying to set publisher but there is already a publisher set - overwriting!"; - delete m_publisher; - } - m_publisher = publisher; - if (m_publisher) - DDS::QosProfile::print(m_publisher->getDdsPublisher().default_datawriter_qos(), m_logger); + if (m_publisher && publisher != m_publisher) + { + WARNING_LOG(m_logger) << "Trying to set publisher but there is already a publisher set - overwriting!"; + delete m_publisher; + } + m_publisher = publisher; + if (m_publisher) + DDS::QosProfile::print(m_publisher->getDdsPublisher().default_datawriter_qos(), m_logger); } void DdsConnector::enableBatchedWriter(bool bEnable) { - if (m_publisher) - m_publisher->enableBatchedWriter(bEnable); + if (m_publisher) + m_publisher->enableBatchedWriter(bEnable); } - -void DdsConnector::setSubscriber(Subscriber *subscriber) +void DdsConnector::setSubscriber(Subscriber* subscriber) { - if (m_subscriber && subscriber != m_subscriber) - { - WARNING_LOG(m_logger) << "Trying to set subscriber but there is already a subscriber set - overwriting!"; - delete m_subscriber; - } - m_subscriber = subscriber; - if (m_subscriber) - DDS::QosProfile::print(m_subscriber->getDdsSubscriber().default_datareader_qos(), m_logger); + if (m_subscriber && subscriber != m_subscriber) + { + WARNING_LOG(m_logger) << "Trying to set subscriber but there is already a subscriber set - overwriting!"; + delete m_subscriber; + } + m_subscriber = subscriber; + if (m_subscriber) + DDS::QosProfile::print(m_subscriber->getDdsSubscriber().default_datareader_qos(), m_logger); } void DdsConnector::initInternal() { - if (m_tcpConnectionUrl.isValid()) - { - m_connectionType = DDS::QosProfile::ConnectionType::Tcp; - } - else - { - m_tcpConnectionUrl.clear(); - if (m_connectionType == DDS::QosProfile::ConnectionType::Tcp) - m_connectionType = DDS::QosProfile::ConnectionType::ShmUdp; - } + if (m_tcpConnectionUrl.isValid()) + { + m_connectionType = DDS::QosProfile::ConnectionType::Tcp; + } + else + { + m_tcpConnectionUrl.clear(); + if (m_connectionType == DDS::QosProfile::ConnectionType::Tcp) + m_connectionType = DDS::QosProfile::ConnectionType::ShmUdp; + } - if (m_defaultPartitionType == IDL::PartitionType::Any || - m_defaultPartitionType == IDL::PartitionType::AllExercises) - m_partitionId = -1; - if (m_defaultPartitionType == IDL::PartitionType::Exercise && m_partitionId < 0) - WARNING_LOG(m_logger) << "Want to subscribe to an exercise, but no exercise Id is given!"; - if (m_defaultPartitionType == IDL::PartitionType::Global) - { - m_partitionId = 0; - m_exerciseId = 0; - } - INFO_LOG(m_logger) << "DDSConnector(" << m_domainId << ") for partition: " << m_partitionId - << " with partition type " << static_cast(m_defaultPartitionType); + if (m_defaultPartitionType == IDL::PartitionType::Any || m_defaultPartitionType == IDL::PartitionType::AllExercises) + m_partitionId = -1; + if (m_defaultPartitionType == IDL::PartitionType::Exercise && m_partitionId < 0) + WARNING_LOG(m_logger) << "Want to subscribe to an exercise, but no exercise Id is given!"; + if (m_defaultPartitionType == IDL::PartitionType::Global) + { + m_partitionId = 0; + m_exerciseId = 0; + } + INFO_LOG(m_logger) << "DDSConnector(" << m_domainId << ") for partition: " << m_partitionId + << " with partition type " << static_cast(m_defaultPartitionType); - - dds::domain::qos::DomainParticipantFactoryQos domainParticipantFactoryQos = dds::domain::DomainParticipant::participant_factory_qos(); - - domainParticipantFactoryQos << dds::core::policy::EntityFactory::ManuallyEnable(); - dds::domain::DomainParticipant::participant_factory_qos(domainParticipantFactoryQos); + dds::domain::qos::DomainParticipantFactoryQos domainParticipantFactoryQos = + dds::domain::DomainParticipant::participant_factory_qos(); + + domainParticipantFactoryQos << dds::core::policy::EntityFactory::ManuallyEnable(); + dds::domain::DomainParticipant::participant_factory_qos(domainParticipantFactoryQos); } - void DdsConnector::createWaitSetHandler() { - if (!m_wsHandler) - m_wsHandler = new DDSGeneric::WaitSetHandler; + if (!m_wsHandler) + m_wsHandler = new DDSGeneric::WaitSetHandler; } -} +} // namespace DDSConnector diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.h old mode 100755 new mode 100644 index 2fcbd7199..7bdc436c0 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/dds_connector.h @@ -2,33 +2,36 @@ #pragma once +#include +#include +#include +#include #include #include #include - -#include -#include #include -#include -#include class QObject; + namespace DDS { namespace QosProfile { enum class ConnectionType; } -} +} // namespace DDS + namespace NGL { class INGLLogger; } + namespace DDSGeneric { class WaitSetHandler; class SubscriberListener; -} +} // namespace DDSGeneric + namespace DDSConnector { class Publisher; @@ -36,181 +39,167 @@ class Subscriber; class DDSCONNECTOR_EXPORT DdsConnector { - DdsConnector(int domainId, - const dds::domain::DomainParticipant &domainParticipant, - IDL::PartitionType defaultPartitionType, - int partitionId, - int exerciseId, - DDS::QosProfile::ConnectionType connectionType, - const QUrl &tcpConnectionUrl); -public: - DdsConnector(const DdsConnector &) = delete; - DdsConnector &operator=(const DdsConnector &) = delete; + DdsConnector(int domainId, const dds::domain::DomainParticipant& domainParticipant, + IDL::PartitionType defaultPartitionType, int partitionId, int exerciseId, + DDS::QosProfile::ConnectionType connectionType, const QUrl& tcpConnectionUrl); - + public: + DdsConnector(const DdsConnector&) = delete; + DdsConnector& operator=(const DdsConnector&) = delete; - DdsConnector(int domainId, - IDL::PartitionType defaultPartitionType, - int partitionId = 0, - int exerciseId = 0, - const QUrl &tcpConnectionUrl = QUrl()); - + DdsConnector(int domainId, IDL::PartitionType defaultPartitionType, int partitionId = 0, int exerciseId = 0, + const QUrl& tcpConnectionUrl = QUrl()); - DdsConnector(const dds::domain::DomainParticipant &domainParticipant, - IDL::PartitionType defaultPartitionType, - int partitionId = 0, - int exerciseId = 0, - const QUrl &tcpConnectionUrl = QUrl()); + DdsConnector(const dds::domain::DomainParticipant& domainParticipant, IDL::PartitionType defaultPartitionType, + int partitionId = 0, int exerciseId = 0, const QUrl& tcpConnectionUrl = QUrl()); - DdsConnector(const dds::domain::DomainParticipant &domainParticipant, - IDL::PartitionType defaultPartitionType, - DDS::QosProfile::ConnectionType connectionType, - int partitionId = 0, - int exerciseId = 0); + DdsConnector(const dds::domain::DomainParticipant& domainParticipant, IDL::PartitionType defaultPartitionType, + DDS::QosProfile::ConnectionType connectionType, int partitionId = 0, int exerciseId = 0); - DdsConnector(int domainId, - IDL::PartitionType defaultPartitionType, - int partitionId, - int exerciseId, - DDS::QosProfile::ConnectionType connectionType); + DdsConnector(int domainId, IDL::PartitionType defaultPartitionType, int partitionId, int exerciseId, + DDS::QosProfile::ConnectionType connectionType); - virtual ~DdsConnector(); + virtual ~DdsConnector(); - + virtual bool init(const QStringList& qosFileList = QStringList()); - virtual bool init(const QStringList &qosFileList = QStringList()); + dds::domain::DomainParticipant getDomainParticipant() const + { + return m_domainParticipant; + } - dds::domain::DomainParticipant getDomainParticipant() const { return m_domainParticipant; } - void setDomainParticipant(const dds::domain::DomainParticipant &participant); + void setDomainParticipant(const dds::domain::DomainParticipant& participant); - Publisher *getPublisher() { return m_publisher; } - dds::pub::Publisher getDdsPublisher() const; - void setPublisher(Publisher *publisher); - void enableBatchedWriter(bool bEnable); + Publisher* getPublisher() + { + return m_publisher; + } - Subscriber *getSubscriber() { return m_subscriber; } - dds::sub::Subscriber getDdsSubscriber() const; - void setSubscriber(Subscriber *subscriber); - DDSGeneric::SubscriberListener *getSubscriberListener(); + dds::pub::Publisher getDdsPublisher() const; + void setPublisher(Publisher* publisher); + void enableBatchedWriter(bool bEnable); - const DDSGeneric::WaitSetHandler *getWaitSetHandler() const { return m_wsHandler; } + Subscriber* getSubscriber() + { + return m_subscriber; + } - int getDomainId() const { return m_domainId; } - IDL::PartitionType getPartitionType() const { return m_defaultPartitionType; } - int getPartitionId() const { return m_partitionId; } - int getExerciseId() const { return m_exerciseId; } - std::string getDefaultPartition() const; - QUrl getTcpConnectionUrl() const; - static std::string getPartitionString(IDL::PartitionType pt, int partitionId = -1); + dds::sub::Subscriber getDdsSubscriber() const; + void setSubscriber(Subscriber* subscriber); + DDSGeneric::SubscriberListener* getSubscriberListener(); - + const DDSGeneric::WaitSetHandler* getWaitSetHandler() const + { + return m_wsHandler; + } - void initPublisherSubscriber(); - void initPublisher(); - void initSubscriber(); - void initDomainParticipant(); + int getDomainId() const + { + return m_domainId; + } - template - T *createDTS(const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - { - if (getDomainParticipant() == nullptr || - getDdsPublisher() == nullptr) - return nullptr; - T *dts = new T(getDomainParticipant(), - getDdsPublisher(), - topicName); - return dts; - } + IDL::PartitionType getPartitionType() const + { + return m_defaultPartitionType; + } - template - T *createDTC(const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - { - if (getDomainParticipant() == nullptr || - getDdsSubscriber() == nullptr) - return nullptr; - T *dtc = new T(getDomainParticipant(), - getDdsSubscriber(), - getSubscriberListener(), - topicName); - return dtc; - } + int getPartitionId() const + { + return m_partitionId; + } - template - T *createDTC(const dds::topic::Filter &filter, - const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - { - if (getDomainParticipant() == nullptr || - getDdsSubscriber() == nullptr) - return nullptr; - T *dtc = new T(getDomainParticipant(), - getDdsSubscriber(), - getSubscriberListener(), - filter, - topicName); - return dtc; - } + int getExerciseId() const + { + return m_exerciseId; + } - template - T *createFTS() - { - if (getDomainParticipant() == nullptr || - getDdsPublisher() == nullptr || - getDdsSubscriber() == nullptr) - return nullptr; - createWaitSetHandler(); - T *fts = new T(getDomainParticipant(), - getDdsPublisher(), - getDdsSubscriber(), - m_wsHandler); - return fts; - } + std::string getDefaultPartition() const; + QUrl getTcpConnectionUrl() const; + static std::string getPartitionString(IDL::PartitionType pt, int partitionId = -1); - template - T *createFTC(QObject *objToInform) - { - if (getDomainParticipant() == nullptr || - getDdsPublisher() == nullptr || - getDdsSubscriber() == nullptr) - return nullptr; - T *ftc = new T(getDomainParticipant(), - getDdsPublisher(), - getDdsSubscriber(), - objToInform, - IDL::toStdString(m_defaultPartitionType), - m_partitionId); - return ftc; - } + void initPublisherSubscriber(); + void initPublisher(); + void initSubscriber(); + void initDomainParticipant(); -private: - NGL::INGLLogger &m_logger; - void initInternal(); - void createWaitSetHandler(); -private: - NGL::INGLLogger &m_logger; - int m_domainId; - IDL::PartitionType m_defaultPartitionType; - int m_partitionId; - int m_exerciseId; + template + T* createDTS(const std::string& topicName = + DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) + { + if (getDomainParticipant() == nullptr || getDdsPublisher() == nullptr) + return nullptr; + T* dts = new T(getDomainParticipant(), getDdsPublisher(), topicName); + return dts; + } - QUrl m_tcpConnectionUrl; - DDS::QosProfile::ConnectionType m_connectionType; - dds::domain::DomainParticipant m_domainParticipant; - DDSConnector::Publisher *m_publisher; - DDSConnector::Subscriber *m_subscriber; - DDSGeneric::WaitSetHandler *m_wsHandler; + template + T* createDTC(const std::string& topicName = + DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) + { + if (getDomainParticipant() == nullptr || getDdsSubscriber() == nullptr) + return nullptr; + T* dtc = new T(getDomainParticipant(), getDdsSubscriber(), getSubscriberListener(), topicName); + return dtc; + } + + template + T* createDTC(const dds::topic::Filter& filter, const std::string& topicName = DDS::Helper::getShortTopicName( + DDS::topic_type_name::value())) + { + if (getDomainParticipant() == nullptr || getDdsSubscriber() == nullptr) + return nullptr; + T* dtc = new T(getDomainParticipant(), getDdsSubscriber(), getSubscriberListener(), filter, topicName); + return dtc; + } + + template T* createFTS() + { + if (getDomainParticipant() == nullptr || getDdsPublisher() == nullptr || getDdsSubscriber() == nullptr) + return nullptr; + createWaitSetHandler(); + T* fts = new T(getDomainParticipant(), getDdsPublisher(), getDdsSubscriber(), m_wsHandler); + return fts; + } + + template T* createFTC(QObject* objToInform) + { + if (getDomainParticipant() == nullptr || getDdsPublisher() == nullptr || getDdsSubscriber() == nullptr) + return nullptr; + T* ftc = new T(getDomainParticipant(), getDdsPublisher(), getDdsSubscriber(), objToInform, + IDL::toStdString(m_defaultPartitionType), m_partitionId); + return ftc; + } + + private: + NGL::INGLLogger& m_logger; + void initInternal(); + void createWaitSetHandler(); + + private: + NGL::INGLLogger& m_logger; + int m_domainId; + IDL::PartitionType m_defaultPartitionType; + int m_partitionId; + int m_exerciseId; + + QUrl m_tcpConnectionUrl; + DDS::QosProfile::ConnectionType m_connectionType; + dds::domain::DomainParticipant m_domainParticipant; + DDSConnector::Publisher* m_publisher; + DDSConnector::Subscriber* m_subscriber; + DDSGeneric::WaitSetHandler* m_wsHandler; }; - - class CoherentSet { -public: - explicit CoherentSet(const std::shared_ptr &connector) - : m_coherentSet(connector->getDdsPublisher()) - {} -private: - NGL::INGLLogger &m_logger; - dds::pub::CoherentSet m_coherentSet; + public: + explicit CoherentSet(const std::shared_ptr& connector) : m_coherentSet(connector->getDdsPublisher()) + { + } + + private: + NGL::INGLLogger& m_logger; + dds::pub::CoherentSet m_coherentSet; }; -} +} // namespace DDSConnector diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/pub_sub_base.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/pub_sub_base.h old mode 100755 new mode 100644 index 2816ce0e7..43c585dc3 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/pub_sub_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DDSConnector/pub_sub_base.h @@ -2,11 +2,10 @@ #pragma once +#include #include - #include #include -#include namespace NGL { @@ -17,23 +16,29 @@ namespace DDSConnector { class DDSCONNECTOR_EXPORT PubSubBase { -protected: -NGL::INGLLogger &m_logger; - PubSubBase(const dds::domain::DomainParticipant &domainParticipant, - const std::string &partition, - const char *loggerName); -public: - virtual ~PubSubBase() = default; + protected: + NGL::INGLLogger& m_logger; + PubSubBase(const dds::domain::DomainParticipant& domainParticipant, const std::string& partition, + const char* loggerName); - void setDomainParticipant(const dds::domain::DomainParticipant &domainParticipant) { m_domainParticipant = domainParticipant; } - const dds::domain::DomainParticipant &getDomainParticipant() const { return m_domainParticipant; } + public: + virtual ~PubSubBase() = default; -protected: - template - void updatePartitionQoS(P &pubSub); + void setDomainParticipant(const dds::domain::DomainParticipant& domainParticipant) + { + m_domainParticipant = domainParticipant; + } -protected: - dds::domain::DomainParticipant m_domainParticipant; - std::vector m_partitions; + const dds::domain::DomainParticipant& getDomainParticipant() const + { + return m_domainParticipant; + } + + protected: + template void updatePartitionQoS(P& pubSub); + + protected: + dds::domain::DomainParticipant m_domainParticipant; + std::vector m_partitions; }; -} +} // namespace DDSConnector diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc.h old mode 100755 new mode 100644 index 3bdd80003..19edb0906 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc.h @@ -1,9 +1,7 @@ - #pragma once #include - #include namespace NGLLogger @@ -15,52 +13,49 @@ namespace DTC { class SubscriberListener; -template -class GenericDtcSC +template class GenericDtcSC { -public: - using DataReaderObject = DRO_OBJECT; - using SubscriberCallback = SC; - using TopicType = typename DRO_OBJECT::TopicType; + public: + using DataReaderObject = DRO_OBJECT; + using SubscriberCallback = SC; + using TopicType = typename DRO_OBJECT::TopicType; - GenericDtcSC() = default; - virtual ~GenericDtcSC() = default; + GenericDtcSC() = default; + virtual ~GenericDtcSC() = default; - virtual bool setSubscriberCallback(const SubscriberCallback &subscriberCallback) = 0; - virtual dds::sub::LoanedSamples readAlive() const = 0; - virtual dds::sub::LoanedSamples takeAlive() const = 0; - virtual dds::sub::LoanedSamples takeDisposed() const = 0; - virtual bool hasSamples() const = 0; - virtual DataReaderObject *dataReader() const = 0; - virtual bool waitForHistoricalData(int timeoutMSec) = 0; + virtual bool setSubscriberCallback(const SubscriberCallback& subscriberCallback) = 0; + virtual dds::sub::LoanedSamples readAlive() const = 0; + virtual dds::sub::LoanedSamples takeAlive() const = 0; + virtual dds::sub::LoanedSamples takeDisposed() const = 0; + virtual bool hasSamples() const = 0; + virtual DataReaderObject* dataReader() const = 0; + virtual bool waitForHistoricalData(int timeoutMSec) = 0; }; - - -template +template class GenericDtc - : public GenericDtcSC > -{}; + : public GenericDtcSC> +{ +}; - -template +template class GenericDtcSampleInfo : public GenericDtcSC > -{}; + std::function> +{ +}; - -template +template class Ddtc - : public GenericDtcSC > -{}; + : public GenericDtcSC< + DRO_OBJECT, std::function> +{ +}; - -template +template class DdtcSampleInfo - : public GenericDtcSC > -{}; -} + : public GenericDtcSC> +{ +}; +} // namespace DTC diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc_impl.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc_impl.h old mode 100755 new mode 100644 index 47a793190..5055d3d7f --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTC/generic_dtc_impl.h @@ -1,311 +1,294 @@ - #pragma once +#include "generic_dtc.h" + #include #include #include - #include #include -#include "generic_dtc.h" - - namespace DDSGeneric { class DynamicDataReader; } + namespace DTC { -template +template class GenericDtcImplSubscriberTemplate : public DDSGeneric::SubscriberListenerCallback, public SuperClass { -public: - using DataReaderObject = typename SuperClass::DataReaderObject; - using SubscriberCallback = typename SuperClass::SubscriberCallback; - using TopicTypeRead = typename DataReaderObject::TopicType; - using TopicTypeSubscribe = typename DataReaderObject::TopicType; - using DataReader = typename DataReaderObject::DataReader; + public: + using DataReaderObject = typename SuperClass::DataReaderObject; + using SubscriberCallback = typename SuperClass::SubscriberCallback; + using TopicTypeRead = typename DataReaderObject::TopicType; + using TopicTypeSubscribe = typename DataReaderObject::TopicType; + using DataReader = typename DataReaderObject::DataReader; - GenericDtcImplSubscriberTemplate(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - DDSGeneric::SubscriberListener *subscriberListener, - const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - : m_subscriberListener(subscriberListener) - , m_dataReaderObject(new DataReaderObject) - , m_subscriberCallback(nullptr) - , m_writerState(0) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) - { - createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName)); - } - - GenericDtcImplSubscriberTemplate(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - DDSGeneric::SubscriberListener *subscriberListener, - const dds::topic::Filter &filter, - const std::string &topicName) - : m_subscriberListener(subscriberListener) - , m_dataReaderObject(new DataReaderObject) - , m_subscriberCallback(nullptr) - , m_writerState(0) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) - { - createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName, filter)); - } - - GenericDtcImplSubscriberTemplate(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - DDSGeneric::SubscriberListener *subscriberListener, - const dds::core::xtypes::StructType &structType, - const std::string &topicName) - : m_subscriberListener(subscriberListener) - , m_dataReaderObject(new DataReaderObject) - , m_subscriberCallback(nullptr) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) - { - createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName, structType)); - } - - ~GenericDtcImplSubscriberTemplate() - { - if (m_dataReaderObject && m_subscriberCallback) - m_subscriberListener->removeCallback(m_dataReaderObject->getDataReader(), this); - delete m_dataReaderObject; - } - - bool setSubscriberCallback(const SubscriberCallback &subscriberCallback) override final - { - if (m_subscriberCallback) + GenericDtcImplSubscriberTemplate( + const dds::domain::DomainParticipant& domainParticipant, const dds::sub::Subscriber& ddsSubscriber, + DDSGeneric::SubscriberListener* subscriberListener, + const std::string& topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) + : m_subscriberListener(subscriberListener), m_dataReaderObject(new DataReaderObject), + m_subscriberCallback(nullptr), m_writerState(0), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) { - WARNING_LOG(m_logger) << "Can not set subscriber callback - already set ..."; - return false; - } - if (!m_subscriberListener) - { - WARNING_LOG(m_logger) << "Can not set subscriber callback - no subscriber listener ..."; - return false; + createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName)); } - m_subscriberCallback = subscriberCallback; - - if (!m_dataReaderObject) + GenericDtcImplSubscriberTemplate(const dds::domain::DomainParticipant& domainParticipant, + const dds::sub::Subscriber& ddsSubscriber, + DDSGeneric::SubscriberListener* subscriberListener, + const dds::topic::Filter& filter, const std::string& topicName) + : m_subscriberListener(subscriberListener), m_dataReaderObject(new DataReaderObject), + m_subscriberCallback(nullptr), m_writerState(0), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) { - WARNING_LOG(m_logger) << "Can not set subscriber callback - no data reader object ..."; - return false; + createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName, filter)); } - m_dataReaderObject->setHaveSubscriberCallback(m_subscriberCallback != nullptr); - - return true; - } - - dds::sub::LoanedSamples readAlive() const override final - { - if (!m_dataReaderObject) - return dds::sub::LoanedSamples(); - - bool bSeenUnreadSamples = false; - auto ret = m_dataReaderObject->readAlive(bSeenUnreadSamples); - if (bSeenUnreadSamples) - QTimer::singleShot(0, this, &GenericDtcImplSubscriberTemplate::unreadSamplesDuringRead); - - return ret; - } - - dds::sub::LoanedSamples takeAlive() const override final - { - if (!m_dataReaderObject) - return dds::sub::LoanedSamples(); - - bool bSeenUnreadSamples = false; - auto ret = m_dataReaderObject->takeAlive(bSeenUnreadSamples); - if (bSeenUnreadSamples) - QTimer::singleShot(0, this, &GenericDtcImplSubscriberTemplate::unreadSamplesDuringRead); - - return ret; - } - - dds::sub::LoanedSamples takeDisposed() const override final - { - if (!m_dataReaderObject) - return dds::sub::LoanedSamples(); - - return m_dataReaderObject->takeDisposed(); - } - - bool hasSamples() const override final - { - if (!m_dataReaderObject) - return false; - - return m_dataReaderObject->hasSamples(); - } - - DataReaderObject *dataReader() const override final - { - return m_dataReaderObject; - } - - bool waitForHistoricalData(int timeoutMSec) override - { - if (m_dataReaderObject == nullptr || - m_dataReaderObject->getDataReader() == nullptr) - return false; - - const bool bWaitForever = (timeoutMSec < 0); - auto dr = m_dataReaderObject->getDataReader(); - try + GenericDtcImplSubscriberTemplate(const dds::domain::DomainParticipant& domainParticipant, + const dds::sub::Subscriber& ddsSubscriber, + DDSGeneric::SubscriberListener* subscriberListener, + const dds::core::xtypes::StructType& structType, const std::string& topicName) + : m_subscriberListener(subscriberListener), m_dataReaderObject(new DataReaderObject), + m_subscriberCallback(nullptr), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_CLIENT)) { - if (dr.subscription_matched_status().current_count() == 0) - { - dds::core::cond::WaitSet ws; - dds::core::cond::StatusCondition cond(dr); - cond.enabled_statuses(dds::core::status::StatusMask::subscription_matched()); - ws.attach_condition(cond); - const dds::core::Duration waitTimeout(bWaitForever ? dds::core::Duration::infinite() : dds::core::Duration::from_millisecs(timeoutMSec)); - const dds::core::cond::WaitSet::ConditionSeq seq(ws.wait(waitTimeout)); - - if (seq.empty()) - return false; - } - dr.wait_for_historical_data(dds::core::Duration(1)); - } - catch (const dds::core::Exception &) - { - - return false; - } - return true; - } - -protected: - void unreadSamplesDuringRead() - { - droDataAvailable(DDS::topic_type_name::value(), m_dataReaderObject->topicName()); - } - - void droDataAvailable(const std::string &topicType, const std::string &topicName) override final - { - Q_UNUSED(topicType); - if (m_writerState.testAndSetRelaxed(1, 0)) - { - DEBUG_LOG(m_logger) << "Recreate Reader for topic " << topicName - << ", type name " << DDS::topic_type_name::value(); - if (m_subscriberListener) - m_subscriberListener->removeCallback(m_dataReaderObject->getDataReader(), this); - m_dataReaderObject->recreateReader(); - if (m_subscriberListener) - m_subscriberListener->addCallback(m_dataReaderObject->getDataReader(), this); + createInternal(m_dataReaderObject->create(domainParticipant, ddsSubscriber, topicName, structType)); } - DEBUG_LOG(m_logger) << "IN droDataAvailable(), topic name: " << topicName - << ", type name " << DDS::topic_type_name::value() - << ", this: " << this - << ", m_dataReaderObject: " << m_dataReaderObject - << ", hasSamples: " << (m_dataReaderObject ? m_dataReaderObject->hasSamples() : -1); - - if (m_subscriberListener) - m_subscriberListener->enableCallback(m_dataReaderObject->getDataReader(), this); - - if (!m_dataReaderObject || !m_subscriberCallback) - return; - - m_dataReaderObject->read(m_subscriberCallback); - } - - void noWriterAnymore(const std::string &topicType, const std::string &topicName) override - { - Q_UNUSED(topicType); - Q_UNUSED(topicName); - m_writerState = -1; - } - - void writerAvailable(const std::string &topicType, const std::string &topicName) override - { - Q_UNUSED(topicType); - Q_UNUSED(topicName); - m_writerState.testAndSetRelaxed(-1, 1); - } - - bool createInternal(bool droInitOk) - { - if (!droInitOk) + ~GenericDtcImplSubscriberTemplate() { - ERROR_LOG(m_logger) << "Error initializing DRO for type " << DDS::topic_type_name::value(); - delete m_dataReaderObject; - m_dataReaderObject = nullptr; - return false; + if (m_dataReaderObject && m_subscriberCallback) + m_subscriberListener->removeCallback(m_dataReaderObject->getDataReader(), this); + delete m_dataReaderObject; } - if (m_subscriberListener) + bool setSubscriberCallback(const SubscriberCallback& subscriberCallback) override final { - DEBUG_LOG(m_logger) << "subscriberListener exists, adding type " - << DDS::topic_type_name::value(); - m_subscriberListener->addCallback(m_dataReaderObject->getDataReader(), this); + if (m_subscriberCallback) + { + WARNING_LOG(m_logger) << "Can not set subscriber callback - already set ..."; + return false; + } + if (!m_subscriberListener) + { + WARNING_LOG(m_logger) << "Can not set subscriber callback - no subscriber listener ..."; + return false; + } + + m_subscriberCallback = subscriberCallback; + + if (!m_dataReaderObject) + { + WARNING_LOG(m_logger) << "Can not set subscriber callback - no data reader object ..."; + return false; + } + + m_dataReaderObject->setHaveSubscriberCallback(m_subscriberCallback != nullptr); + + return true; } - else + + dds::sub::LoanedSamples readAlive() const override final { - DEBUG_LOG(m_logger) << "Cannot add DTC to subscriberListener callback - type: " - << DDS::topic_type_name::value(); + if (!m_dataReaderObject) + return dds::sub::LoanedSamples(); + + bool bSeenUnreadSamples = false; + auto ret = m_dataReaderObject->readAlive(bSeenUnreadSamples); + if (bSeenUnreadSamples) + QTimer::singleShot(0, this, &GenericDtcImplSubscriberTemplate::unreadSamplesDuringRead); + + return ret; } - m_dataReaderObject->setHaveSubscriberCallback(m_subscriberListener != nullptr); - return true; - } -private: - DDSGeneric::SubscriberListener *m_subscriberListener; + dds::sub::LoanedSamples takeAlive() const override final + { + if (!m_dataReaderObject) + return dds::sub::LoanedSamples(); - - DataReaderObject *m_dataReaderObject; + bool bSeenUnreadSamples = false; + auto ret = m_dataReaderObject->takeAlive(bSeenUnreadSamples); + if (bSeenUnreadSamples) + QTimer::singleShot(0, this, &GenericDtcImplSubscriberTemplate::unreadSamplesDuringRead); - - SubscriberCallback m_subscriberCallback; + return ret; + } - QAtomicInt m_writerState; + dds::sub::LoanedSamples takeDisposed() const override final + { + if (!m_dataReaderObject) + return dds::sub::LoanedSamples(); + + return m_dataReaderObject->takeDisposed(); + } + + bool hasSamples() const override final + { + if (!m_dataReaderObject) + return false; + + return m_dataReaderObject->hasSamples(); + } + + DataReaderObject* dataReader() const override final + { + return m_dataReaderObject; + } + + bool waitForHistoricalData(int timeoutMSec) override + { + if (m_dataReaderObject == nullptr || m_dataReaderObject->getDataReader() == nullptr) + return false; + + const bool bWaitForever = (timeoutMSec < 0); + auto dr = m_dataReaderObject->getDataReader(); + try + { + if (dr.subscription_matched_status().current_count() == 0) + { + dds::core::cond::WaitSet ws; + dds::core::cond::StatusCondition cond(dr); + cond.enabled_statuses(dds::core::status::StatusMask::subscription_matched()); + ws.attach_condition(cond); + const dds::core::Duration waitTimeout(bWaitForever ? dds::core::Duration::infinite() + : dds::core::Duration::from_millisecs(timeoutMSec)); + const dds::core::cond::WaitSet::ConditionSeq seq(ws.wait(waitTimeout)); + + if (seq.empty()) + return false; + } + dr.wait_for_historical_data(dds::core::Duration(1)); + } + catch (const dds::core::Exception&) + { + + return false; + } + return true; + } + + protected: + void unreadSamplesDuringRead() + { + droDataAvailable(DDS::topic_type_name::value(), m_dataReaderObject->topicName()); + } + + void droDataAvailable(const std::string& topicType, const std::string& topicName) override final + { + Q_UNUSED(topicType); + if (m_writerState.testAndSetRelaxed(1, 0)) + { + DEBUG_LOG(m_logger) << "Recreate Reader for topic " << topicName << ", type name " + << DDS::topic_type_name::value(); + if (m_subscriberListener) + m_subscriberListener->removeCallback(m_dataReaderObject->getDataReader(), this); + m_dataReaderObject->recreateReader(); + if (m_subscriberListener) + m_subscriberListener->addCallback(m_dataReaderObject->getDataReader(), this); + } + + DEBUG_LOG(m_logger) << "IN droDataAvailable(), topic name: " << topicName << ", type name " + << DDS::topic_type_name::value() << ", this: " << this + << ", m_dataReaderObject: " << m_dataReaderObject + << ", hasSamples: " << (m_dataReaderObject ? m_dataReaderObject->hasSamples() : -1); + + if (m_subscriberListener) + m_subscriberListener->enableCallback(m_dataReaderObject->getDataReader(), this); + + if (!m_dataReaderObject || !m_subscriberCallback) + return; + + m_dataReaderObject->read(m_subscriberCallback); + } + + void noWriterAnymore(const std::string& topicType, const std::string& topicName) override + { + Q_UNUSED(topicType); + Q_UNUSED(topicName); + m_writerState = -1; + } + + void writerAvailable(const std::string& topicType, const std::string& topicName) override + { + Q_UNUSED(topicType); + Q_UNUSED(topicName); + m_writerState.testAndSetRelaxed(-1, 1); + } + + bool createInternal(bool droInitOk) + { + if (!droInitOk) + { + ERROR_LOG(m_logger) << "Error initializing DRO for type " << DDS::topic_type_name::value(); + delete m_dataReaderObject; + m_dataReaderObject = nullptr; + return false; + } + + if (m_subscriberListener) + { + DEBUG_LOG(m_logger) << "subscriberListener exists, adding type " + << DDS::topic_type_name::value(); + m_subscriberListener->addCallback(m_dataReaderObject->getDataReader(), this); + } + else + { + DEBUG_LOG(m_logger) << "Cannot add DTC to subscriberListener callback - type: " + << DDS::topic_type_name::value(); + } + m_dataReaderObject->setHaveSubscriberCallback(m_subscriberListener != nullptr); + return true; + } + + private: + DDSGeneric::SubscriberListener* m_subscriberListener; + + DataReaderObject* m_dataReaderObject; + + SubscriberCallback m_subscriberCallback; + + QAtomicInt m_writerState; }; - -template -class GenericDtcImpl final - : public GenericDtcImplSubscriberTemplate> +template +class GenericDtcImpl final : public GenericDtcImplSubscriberTemplate> { - using BaseClass = GenericDtcImplSubscriberTemplate>; -public: - using BaseClass::BaseClass; + using BaseClass = GenericDtcImplSubscriberTemplate>; + + public: + using BaseClass::BaseClass; }; - -template -class GenericDtcImplSampleInfo final - : public GenericDtcImplSubscriberTemplate> +template +class GenericDtcImplSampleInfo final : public GenericDtcImplSubscriberTemplate> { - using BaseClass = GenericDtcImplSubscriberTemplate>; -public: - using BaseClass::BaseClass; + using BaseClass = GenericDtcImplSubscriberTemplate>; + + public: + using BaseClass::BaseClass; }; - -template -class DdtcImpl final - : public GenericDtcImplSubscriberTemplate> +template class DdtcImpl final : public GenericDtcImplSubscriberTemplate> { - using BaseClass = GenericDtcImplSubscriberTemplate>; -public: - using BaseClass::BaseClass; + using BaseClass = GenericDtcImplSubscriberTemplate>; + + public: + using BaseClass::BaseClass; }; - -template -class DdtcImplSampleInfo final - : public GenericDtcImplSubscriberTemplate> +template +class DdtcImplSampleInfo final : public GenericDtcImplSubscriberTemplate> { - using BaseClass = GenericDtcImplSubscriberTemplate>; -public: - using BaseClass::BaseClass; + using BaseClass = GenericDtcImplSubscriberTemplate>; + + public: + using BaseClass::BaseClass; }; -} +} // namespace DTC diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTS/generic_dts_impl.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTS/generic_dts_impl.h old mode 100755 new mode 100644 index f6d6b156d..67d6afea0 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DTS/generic_dts_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DTS/generic_dts_impl.h @@ -3,85 +3,74 @@ #pragma once #include "generic_dts.h" + #include #include namespace DTS { - template - class GenericDtsImpl final : public GenericDts - { +template class GenericDtsImpl final : public GenericDts +{ public: using DataWriterObject = DWO_OBJECT; - using TopicType = typename DWO_OBJECT::TopicType; - using DataWriter = typename dds::pub::DataWriter; + using TopicType = typename DWO_OBJECT::TopicType; + using DataWriter = typename dds::pub::DataWriter; - GenericDtsImpl(const dds::domain::DomainParticipant &domainParticipant, - const dds::pub::Publisher &ddsPublisher, - const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - : m_dataWriterObject(new DataWriterObject()) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_SERVER)) + GenericDtsImpl( + const dds::domain::DomainParticipant& domainParticipant, const dds::pub::Publisher& ddsPublisher, + const std::string& topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) + : m_dataWriterObject(new DataWriterObject()), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_TOPIC_SERVER)) { - Q_ASSERT(domainParticipant != nullptr); - Q_ASSERT(ddsPublisher != nullptr); + Q_ASSERT(domainParticipant != nullptr); + Q_ASSERT(ddsPublisher != nullptr); - m_dataWriterObject->create(domainParticipant, ddsPublisher, topicName); + m_dataWriterObject->create(domainParticipant, ddsPublisher, topicName); } ~GenericDtsImpl() { - delete m_dataWriterObject; + delete m_dataWriterObject; } - bool write(const TopicType &data, - const dds::core::optional &si = dds::core::optional()) override final + bool write(const TopicType& data, const dds::core::optional& si = + dds::core::optional()) override final { - DEBUG_LOG(m_logger) << "IN write (" - << DDS::topic_type_name::value() - << ")"; + DEBUG_LOG(m_logger) << "IN write (" << DDS::topic_type_name::value() << ")"; - if (!m_dataWriterObject) - return false; + if (!m_dataWriterObject) + return false; - if (!m_dataWriterObject->write(data, si)) - { - ERROR_LOG(m_logger) << "Error writing for " - << DDS::topic_type_name::value(); - return false; - } - DEBUG_LOG(m_logger) << "TopicData (" - << DDS::topic_type_name::value() - << ") written"; + if (!m_dataWriterObject->write(data, si)) + { + ERROR_LOG(m_logger) << "Error writing for " << DDS::topic_type_name::value(); + return false; + } + DEBUG_LOG(m_logger) << "TopicData (" << DDS::topic_type_name::value() << ") written"; - return true; + return true; } - bool remove(const TopicType &data, bool errorMsgIfNotExists = true) override final + bool remove(const TopicType& data, bool errorMsgIfNotExists = true) override final { - DEBUG_LOG(m_logger) << "IN remove (" - << DDS::topic_type_name::value() - << ")"; + DEBUG_LOG(m_logger) << "IN remove (" << DDS::topic_type_name::value() << ")"; - if (!m_dataWriterObject) - return false; + if (!m_dataWriterObject) + return false; - if (!m_dataWriterObject->remove(data, errorMsgIfNotExists)) - { - if (errorMsgIfNotExists) - ERROR_LOG(m_logger) << "Error removing for " - << DDS::topic_type_name::value(); - return false; - } - DEBUG_LOG(m_logger) << "TopicData (" - << DDS::topic_type_name::value() - << ") removed"; + if (!m_dataWriterObject->remove(data, errorMsgIfNotExists)) + { + if (errorMsgIfNotExists) + ERROR_LOG(m_logger) << "Error removing for " << DDS::topic_type_name::value(); + return false; + } + DEBUG_LOG(m_logger) << "TopicData (" << DDS::topic_type_name::value() << ") removed"; - return true; + return true; } private: - - DataWriterObject *m_dataWriterObject; - }; + DataWriterObject* m_dataWriterObject; +}; -} +} // namespace DTS diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.cpp old mode 100755 new mode 100644 index 174766ff6..8e046ec17 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.cpp @@ -1,19 +1,15 @@ - #include "data_topic_tests.h" -#include - -#include -#include #include +#include +#include #include - -#include -#include +#include #include - +#include +#include DataTopicTests::DataTopicTests() : m_domainParticipantPub(nullptr) , m_domainParticipantSub(nullptr) @@ -26,129 +22,109 @@ DataTopicTests::DataTopicTests() : m_domainParticipantPub(nullptr) , m_dtcTestPart(nullptr) , m_mainThreadId(QThread::currentThreadId()) .getNGLLogger("UnitTests.DataTopicTests")), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - if (!DDS::QosProfile::setDefault()) - ERROR_LOG(m_logger) << "Error setting default QoS from xml-file "; + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + if (!DDS::QosProfile::setDefault()) + ERROR_LOG(m_logger) << "Error setting default QoS from xml-file "; - DEBUG_LOG(m_logger) << "Main thread ID is " << m_mainThreadId; + DEBUG_LOG(m_logger) << "Main thread ID is " << m_mainThreadId; } DataTopicTests::~DataTopicTests() { - - delete m_testPart; - - delete m_dtcTestPart; + delete m_testPart; - - - delete m_subscriberListener; + delete m_dtcTestPart; + + delete m_subscriberListener; } - - - bool DataTopicTests::initPublisher() { - m_domainParticipantPub = - dds::domain::DomainParticipant(m_domainId, - DDS::QosProfile::domainParticipantShm()); + m_domainParticipantPub = dds::domain::DomainParticipant(m_domainId, DDS::QosProfile::domainParticipantShm()); - dds::pub::qos::PublisherQos publisherQos = m_domainParticipantPub.default_publisher_qos(); + dds::pub::qos::PublisherQos publisherQos = m_domainParticipantPub.default_publisher_qos(); - - QString partition = QString::fromStdString(IDL::exercisePartition(m_partitionId)); + QString partition = QString::fromStdString(IDL::exercisePartition(m_partitionId)); - dds::core::policy::Partition partitionQos; - partitionQos.name( { partition.toStdString() } ); - publisherQos << partitionQos; + dds::core::policy::Partition partitionQos; + partitionQos.name({partition.toStdString()}); + publisherQos << partitionQos; - DEBUG_LOG(m_logger) << "Publish on partition " << partition; + DEBUG_LOG(m_logger) << "Publish on partition " << partition; - m_ddsPublisher = dds::pub::Publisher(m_domainParticipantPub, publisherQos); - m_testPart = new DTS::TestParticipantImpl(m_domainParticipantPub, m_ddsPublisher); + m_ddsPublisher = dds::pub::Publisher(m_domainParticipantPub, publisherQos); + m_testPart = new DTS::TestParticipantImpl(m_domainParticipantPub, m_ddsPublisher); - return true; + return true; } -bool DataTopicTests::write(const DdsUnitTests::TestParticipant &data) +bool DataTopicTests::write(const DdsUnitTests::TestParticipant& data) { - INFO_LOG(m_logger) << "Publish topic TestParticipant "; - DEBUG_LOG(m_logger) << "ParticipantId: " << data.location().participantId() - << ", equipNo = " << data.location().equipNo(); + INFO_LOG(m_logger) << "Publish topic TestParticipant "; + DEBUG_LOG(m_logger) << "ParticipantId: " << data.location().participantId() + << ", equipNo = " << data.location().equipNo(); - return m_testPart->write(data); + return m_testPart->write(data); } - - - - bool DataTopicTests::initSubscriber() { - DEBUG_LOG(m_logger) << "Initialisation DDS (Subscriber/Reader)"; + DEBUG_LOG(m_logger) << "Initialisation DDS (Subscriber/Reader)"; - m_domainParticipantSub = - dds::domain::DomainParticipant(m_domainId, - DDS::QosProfile::domainParticipantShm()); + m_domainParticipantSub = dds::domain::DomainParticipant(m_domainId, DDS::QosProfile::domainParticipantShm()); - dds::sub::qos::SubscriberQos subscriberQos = m_domainParticipantSub.default_subscriber_qos(); + dds::sub::qos::SubscriberQos subscriberQos = m_domainParticipantSub.default_subscriber_qos(); - - dds::core::StringSeq partitions; - partitions.reserve(1); - for(int partitionId : { 1 } ) - { - partitions.push_back(IDL::exercisePartition(partitionId)); - } + dds::core::StringSeq partitions; + partitions.reserve(1); + for (int partitionId : {1}) + { + partitions.push_back(IDL::exercisePartition(partitionId)); + } - dds::core::policy::Partition partitionQos; - partitionQos.name( partitions ); - subscriberQos << partitionQos; + dds::core::policy::Partition partitionQos; + partitionQos.name(partitions); + subscriberQos << partitionQos; - DEBUG_LOG(m_logger) << "Initialise DTC::SubscriberListener"; - m_subscriberListener = new DDSGeneric::SubscriberListener(); - m_ddsSubscriber = dds::sub::Subscriber(m_domainParticipantSub, - subscriberQos, - m_subscriberListener, - DDSGeneric::SubscriberListener::mask()); + DEBUG_LOG(m_logger) << "Initialise DTC::SubscriberListener"; + m_subscriberListener = new DDSGeneric::SubscriberListener(); + m_ddsSubscriber = dds::sub::Subscriber(m_domainParticipantSub, subscriberQos, m_subscriberListener, + DDSGeneric::SubscriberListener::mask()); - - m_dtcTestPart = new DTC::SampleInfo::TestParticipantImpl(m_domainParticipantSub, - m_ddsSubscriber, - m_subscriberListener); + m_dtcTestPart = + new DTC::SampleInfo::TestParticipantImpl(m_domainParticipantSub, m_ddsSubscriber, m_subscriberListener); - m_dtcTestPart->setSubscriberCallback([this](const DdsUnitTests::TestParticipant &data, const dds::sub::SampleInfo &si) { processData(data, si); } ); + m_dtcTestPart->setSubscriberCallback( + [this](const DdsUnitTests::TestParticipant& data, const dds::sub::SampleInfo& si) { processData(data, si); }); - return true; + return true; } void DataTopicTests::deleteDTC() { - delete m_dtcTestPart; - m_dtcTestPart = nullptr; + delete m_dtcTestPart; + m_dtcTestPart = nullptr; } void DataTopicTests::deleteSubscriber() { - m_ddsSubscriber = nullptr; - delete m_subscriberListener; - m_subscriberListener = nullptr; + m_ddsSubscriber = nullptr; + delete m_subscriberListener; + m_subscriberListener = nullptr; } - - -void DataTopicTests::processData(const DdsUnitTests::TestParticipant &instance, const dds::sub::SampleInfo &si) +void DataTopicTests::processData(const DdsUnitTests::TestParticipant& instance, const dds::sub::SampleInfo& si) { - INFO_LOG(m_logger) << "process data in topic TestParticipant, Sampleinfo: " << si.source_timestamp().sec(); + INFO_LOG(m_logger) << "process data in topic TestParticipant, Sampleinfo: " << si.source_timestamp().sec(); - DEBUG_LOG(m_logger) << "participantId: " << instance.location().participantId(); - DEBUG_LOG(m_logger) << "equipNo: " << instance.location().equipNo(); + DEBUG_LOG(m_logger) << "participantId: " << instance.location().participantId(); + DEBUG_LOG(m_logger) << "equipNo: " << instance.location().equipNo(); - m_receivedParticipantData = instance; + m_receivedParticipantData = instance; - QCOMPARE(m_mainThreadId, QThread::currentThreadId()); + QCOMPARE(m_mainThreadId, QThread::currentThreadId()); - emit testParticipantDataArrived(); + emit testParticipantDataArrived(); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.h old mode 100755 new mode 100644 index 1f1dbbacf..466d3c480 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests.h @@ -2,64 +2,58 @@ #pragma once -#include #include - #include #include +#include - -namespace NGL { - class INGLLogger; +namespace NGL +{ +class INGLLogger; } class DataTopicTests : public QObject { - Q_OBJECT -public: - DataTopicTests(); - virtual ~DataTopicTests(); + Q_OBJECT + public: + DataTopicTests(); + virtual ~DataTopicTests(); - - bool initPublisher(); - bool initSubscriber(); + bool initPublisher(); + bool initSubscriber(); - - bool write(const DdsUnitTests::TestParticipant &data); + bool write(const DdsUnitTests::TestParticipant& data); - - DdsUnitTests::TestParticipant getReceivedParticipantData() const { return m_receivedParticipantData; } - void deleteDTC(); - void deleteSubscriber(); + DdsUnitTests::TestParticipant getReceivedParticipantData() const + { + return m_receivedParticipantData; + } -protected: - - NGL::INGLLogger &m_logger; - void processData(const DdsUnitTests::TestParticipant &instance, const dds::sub::SampleInfo &si); + void deleteDTC(); + void deleteSubscriber(); -Q_SIGNALS: - void testParticipantDataArrived(); + protected: + NGL::INGLLogger& m_logger; + void processData(const DdsUnitTests::TestParticipant& instance, const dds::sub::SampleInfo& si); -private: - dds::domain::DomainParticipant m_domainParticipantPub; - dds::domain::DomainParticipant m_domainParticipantSub; - int m_domainId; - int m_partitionId; + Q_SIGNALS: + void testParticipantDataArrived(); - - dds::pub::Publisher m_ddsPublisher; - DTS::TestParticipant *m_testPart; + private: + dds::domain::DomainParticipant m_domainParticipantPub; + dds::domain::DomainParticipant m_domainParticipantSub; + int m_domainId; + int m_partitionId; - - dds::sub::Subscriber m_ddsSubscriber; - DDSGeneric::SubscriberListener *m_subscriberListener; + dds::pub::Publisher m_ddsPublisher; + DTS::TestParticipant* m_testPart; - DTC::SampleInfo::TestParticipant *m_dtcTestPart; + dds::sub::Subscriber m_ddsSubscriber; + DDSGeneric::SubscriberListener* m_subscriberListener; - Qt::HANDLE m_mainThreadId; - - DdsUnitTests::TestParticipant m_receivedParticipantData; + DTC::SampleInfo::TestParticipant* m_dtcTestPart; + + Qt::HANDLE m_mainThreadId; + + DdsUnitTests::TestParticipant m_receivedParticipantData; }; - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.cpp old mode 100755 new mode 100644 index 364035cf1..b4d6e286a --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.cpp @@ -1,102 +1,96 @@ - #include "data_topic_tests_main.h" + #include "data_topic_tests.h" + #include - -#include - -#include #include +#include +#include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - NGLCoreApplication app(argc, argv); - app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); + NGLCoreApplication app(argc, argv); + app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); - DataTopicTestsMain *tc = new DataTopicTestsMain; + DataTopicTestsMain* tc = new DataTopicTestsMain; - int retCode = QTest::qExec(tc, argc, argv); + int retCode = QTest::qExec(tc, argc, argv); - delete tc; + delete tc; - return retCode; + return retCode; } DataTopicTestsMain::DataTopicTestsMain() - : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTests.DataTopicTestsMain")) + : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTests.DataTopicTestsMain")) { } - void DataTopicTestsMain::initTestCase() { - DEBUG_LOG(m_logger) <<"DataTopicTestsMain: initTestCase"; + DEBUG_LOG(m_logger) << "DataTopicTestsMain: initTestCase"; - m_dtTest = new DataTopicTests(); - QVERIFY2(m_dtTest, "Initialisation of DataTopicTest failed"); - QVERIFY2(m_dtTest->initPublisher(), "Initialisation Publisher failed"); - QVERIFY2(m_dtTest->initSubscriber(), "Initialisation Subscriber failed"); + m_dtTest = new DataTopicTests(); + QVERIFY2(m_dtTest, "Initialisation of DataTopicTest failed"); + QVERIFY2(m_dtTest->initPublisher(), "Initialisation Publisher failed"); + QVERIFY2(m_dtTest->initSubscriber(), "Initialisation Subscriber failed"); - m_participantDataArrivedSpy = new QSignalSpy(m_dtTest, &DataTopicTests::testParticipantDataArrived); + m_participantDataArrivedSpy = new QSignalSpy(m_dtTest, &DataTopicTests::testParticipantDataArrived); } - void DataTopicTestsMain::publishTestCase() -{ - DEBUG_LOG(m_logger) <<"DataTopicTestsMain: publish TestParticipant"; - - m_sentParticipantData.location().participantId(100); - m_sentParticipantData.location().equipNo(1010); - m_sentParticipantData.testId(100); - QVERIFY2(m_dtTest->write(m_sentParticipantData), "Publishing Topic TestParticipant failed"); +{ + DEBUG_LOG(m_logger) << "DataTopicTestsMain: publish TestParticipant"; - DEBUG_LOG(m_logger) <<"DataTopicTestsMain: publish ready"; + m_sentParticipantData.location().participantId(100); + m_sentParticipantData.location().equipNo(1010); + m_sentParticipantData.testId(100); + QVERIFY2(m_dtTest->write(m_sentParticipantData), "Publishing Topic TestParticipant failed"); + + DEBUG_LOG(m_logger) << "DataTopicTestsMain: publish ready"; } - void DataTopicTestsMain::subscribeTestCase() { - DEBUG_LOG(m_logger) << "IN subscribeTestCase"; + DEBUG_LOG(m_logger) << "IN subscribeTestCase"; - QTRY_COMPARE(m_participantDataArrivedSpy->count(), 1); + QTRY_COMPARE(m_participantDataArrivedSpy->count(), 1); - DdsUnitTests::TestParticipant recvPartiticpant = m_dtTest->getReceivedParticipantData(); + DdsUnitTests::TestParticipant recvPartiticpant = m_dtTest->getReceivedParticipantData(); - QCOMPARE(recvPartiticpant.location().participantId(), m_sentParticipantData.location().participantId()); - QCOMPARE(recvPartiticpant.location().equipNo(), m_sentParticipantData.location().equipNo()); + QCOMPARE(recvPartiticpant.location().participantId(), m_sentParticipantData.location().participantId()); + QCOMPARE(recvPartiticpant.location().equipNo(), m_sentParticipantData.location().equipNo()); } - void DataTopicTestsMain::deleteDataReaderTestCase() { - DdsUnitTests::TestParticipant data; - for (int i = 0; i < 1000; ++i) - { - m_sentParticipantData.id(i); - m_dtTest->write(m_sentParticipantData); - } - m_dtTest->deleteDTC(); - for (int i = 0; i < 1000; ++i) - { - m_sentParticipantData.id(i); - m_dtTest->write(m_sentParticipantData); - } - m_dtTest->deleteSubscriber(); - for (int i = 0; i < 1000; ++i) - { - m_sentParticipantData.id(i); - m_dtTest->write(m_sentParticipantData); - } + DdsUnitTests::TestParticipant data; + for (int i = 0; i < 1000; ++i) + { + m_sentParticipantData.id(i); + m_dtTest->write(m_sentParticipantData); + } + m_dtTest->deleteDTC(); + for (int i = 0; i < 1000; ++i) + { + m_sentParticipantData.id(i); + m_dtTest->write(m_sentParticipantData); + } + m_dtTest->deleteSubscriber(); + for (int i = 0; i < 1000; ++i) + { + m_sentParticipantData.id(i); + m_dtTest->write(m_sentParticipantData); + } } - void DataTopicTestsMain::cleanupTestCase() { - DEBUG_LOG(m_logger) <<"DataTopicTestsMain: cleanupTestCase"; - delete m_dtTest; m_dtTest = nullptr; - delete m_participantDataArrivedSpy; m_participantDataArrivedSpy = nullptr; + DEBUG_LOG(m_logger) << "DataTopicTestsMain: cleanupTestCase"; + delete m_dtTest; + m_dtTest = nullptr; + delete m_participantDataArrivedSpy; + m_participantDataArrivedSpy = nullptr; } - diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.h old mode 100755 new mode 100644 index 0a2d2dd16..bf1b90650 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/data_topic_tests_main.h @@ -2,37 +2,36 @@ #pragma once +#include #include #include -#include namespace NGL { - class INGLLogger; +class INGLLogger; } class DataTopicTests; - class DataTopicTestsMain : public QObject { - Q_OBJECT + Q_OBJECT -public: - DataTopicTestsMain(); + public: + DataTopicTestsMain(); -private Q_SLOTS: - void initTestCase(); - void publishTestCase(); - void subscribeTestCase(); - void deleteDataReaderTestCase(); - void cleanupTestCase(); + private Q_SLOTS: + void initTestCase(); + void publishTestCase(); + void subscribeTestCase(); + void deleteDataReaderTestCase(); + void cleanupTestCase(); -protected: + protected: + NGL::INGLLogger& m_logger; - NGL::INGLLogger &m_logger; -private: - DdsUnitTests::TestParticipant m_sentParticipantData; - QSignalSpy *m_participantDataArrivedSpy = nullptr; - DataTopicTests *m_dtTest = nullptr; + private: + DdsUnitTests::TestParticipant m_sentParticipantData; + QSignalSpy* m_participantDataArrivedSpy = nullptr; + DataTopicTests* m_dtTest = nullptr; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.cpp old mode 100755 new mode 100644 index 4ccce30e7..05bf15496 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.cpp @@ -1,256 +1,240 @@ - #include "function_topic_tests.h" -#include -#include + #include - -#include - -#include +#include +#include #include +#include +#include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - NGLCoreApplication app(argc, argv); - app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); + NGLCoreApplication app(argc, argv); + app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); - FunctionTopicTests *tc = new FunctionTopicTests; + FunctionTopicTests* tc = new FunctionTopicTests; - int retCode = QTest::qExec(tc, argc, argv); + int retCode = QTest::qExec(tc, argc, argv); - delete tc; + delete tc; - return retCode; + return retCode; } - FunctionTopicTests::FunctionTopicTests() : m_mainThreadId(QThread::currentThreadId()) .getNGLLogger("UnitTests.FunctionTopicTests")), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - qRegisterMetaType("DdsUnitTests::FunctionReply"); - qRegisterMetaType("DdsUnitTests::FunctionReplyWithState"); + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + qRegisterMetaType("DdsUnitTests::FunctionReply"); + qRegisterMetaType("DdsUnitTests::FunctionReplyWithState"); } - void FunctionTopicTests::initTestCase() { - DEBUG_LOG(m_logger) <<"FunctionTopicTests: initTestCase"; + DEBUG_LOG(m_logger) << "FunctionTopicTests: initTestCase"; - const int domainId = 0; + const int domainId = 0; - m_ddsConnectorClient = std::make_shared(domainId, IDL::PartitionType::Global); - QVERIFY2(m_ddsConnectorClient->init(), "Initialisation of ddsconnector (Client) failed"); - m_ddsConnectorClient->initSubscriber(); - QVERIFY2(m_ddsConnectorClient->getSubscriber(), "Initialisation of Subscriber (DdsConnectorClient) failed"); - m_ddsConnectorClient->initPublisher(); - QVERIFY2(m_ddsConnectorClient->getPublisher(), "Initialisation of Publisher (DdsConnectorClient) failed"); + m_ddsConnectorClient = std::make_shared(domainId, IDL::PartitionType::Global); + QVERIFY2(m_ddsConnectorClient->init(), "Initialisation of ddsconnector (Client) failed"); + m_ddsConnectorClient->initSubscriber(); + QVERIFY2(m_ddsConnectorClient->getSubscriber(), "Initialisation of Subscriber (DdsConnectorClient) failed"); + m_ddsConnectorClient->initPublisher(); + QVERIFY2(m_ddsConnectorClient->getPublisher(), "Initialisation of Publisher (DdsConnectorClient) failed"); - m_ddsConnectorServer = std::make_shared(domainId, IDL::PartitionType::Global); - QVERIFY2(m_ddsConnectorServer->init(), "Initialisation of ddsconnector (Server) failed"); - m_ddsConnectorServer->initSubscriber(); - QVERIFY2(m_ddsConnectorServer->getSubscriber(), "Initialisation of Subscriber (DdsConnectorServer) failed"); - m_ddsConnectorServer->initPublisher(); - QVERIFY2(m_ddsConnectorServer->getPublisher(), "Initialisation of Publisher (DdsConnectorServer) failed"); + m_ddsConnectorServer = std::make_shared(domainId, IDL::PartitionType::Global); + QVERIFY2(m_ddsConnectorServer->init(), "Initialisation of ddsconnector (Server) failed"); + m_ddsConnectorServer->initSubscriber(); + QVERIFY2(m_ddsConnectorServer->getSubscriber(), "Initialisation of Subscriber (DdsConnectorServer) failed"); + m_ddsConnectorServer->initPublisher(); + QVERIFY2(m_ddsConnectorServer->getPublisher(), "Initialisation of Publisher (DdsConnectorServer) failed"); } - void FunctionTopicTests::initFTSTestCase() { - m_fts.reset(m_ddsConnectorServer->createFTS()); - QVERIFY2(m_fts.get(), "Initialisation of FTS Replier failed"); - m_fts->setSubscriberCallback([this](const rti::core::SampleIdentity &identity, const DdsUnitTests::FunctionRequest &request) { this->onFunctionTopicRequest(identity, request);}); - - m_ftsWS.reset(m_ddsConnectorServer->createFTS()); - QVERIFY2(m_ftsWS.get(), "Initialisation of FTS Replier failed"); - m_ftsWS->setSubscriberCallback([this](const rti::core::SampleIdentity &identity, const DdsUnitTests::FunctionRequestWithState &request) { this->onFunctionTopicRequest(identity, request);}); + m_fts.reset(m_ddsConnectorServer->createFTS()); + QVERIFY2(m_fts.get(), "Initialisation of FTS Replier failed"); + m_fts->setSubscriberCallback( + [this](const rti::core::SampleIdentity& identity, const DdsUnitTests::FunctionRequest& request) { + this->onFunctionTopicRequest(identity, request); + }); + m_ftsWS.reset(m_ddsConnectorServer->createFTS()); + QVERIFY2(m_ftsWS.get(), "Initialisation of FTS Replier failed"); + m_ftsWS->setSubscriberCallback( + [this](const rti::core::SampleIdentity& identity, const DdsUnitTests::FunctionRequestWithState& request) { + this->onFunctionTopicRequest(identity, request); + }); } void FunctionTopicTests::initFTCTestCase() { - m_ftc.reset(m_ddsConnectorClient->createFTC(this)); - QVERIFY2(m_ftc.get(), "Initialisation of FTC Requester failed"); - m_ftcWS.reset(m_ddsConnectorClient->createFTC(this)); - QVERIFY2(m_ftc.get(), "Initialisation of FTC Requester failed"); + m_ftc.reset(m_ddsConnectorClient->createFTC(this)); + QVERIFY2(m_ftc.get(), "Initialisation of FTC Requester failed"); + m_ftcWS.reset(m_ddsConnectorClient->createFTC(this)); + QVERIFY2(m_ftc.get(), "Initialisation of FTC Requester failed"); } - void FunctionTopicTests::requestTestCase1() { - - requestWithState(); - - QCOMPARE(m_ddsConnectorServer->getWaitSetHandler()->attachedConditionCount(), 3); - requestWithState(); - - QCOMPARE(m_ddsConnectorServer->getWaitSetHandler()->attachedConditionCount(), 3); -} + requestWithState(); + + QCOMPARE(m_ddsConnectorServer->getWaitSetHandler()->attachedConditionCount(), 3); + requestWithState(); + + QCOMPARE(m_ddsConnectorServer->getWaitSetHandler()->attachedConditionCount(), 3); +} void FunctionTopicTests::requestWithState() { - - QSignalSpy spyRequest(this, &FunctionTopicTests::functionTopicRequestFinished); - QSignalSpy spyReply(this, &FunctionTopicTests::functionTopicReply); - DEBUG_LOG(m_logger) <<"FunctionTopicTests: request"; + QSignalSpy spyRequest(this, &FunctionTopicTests::functionTopicRequestFinished); + QSignalSpy spyReply(this, &FunctionTopicTests::functionTopicReply); - - DdsUnitTests::FunctionRequestWithState data; + DEBUG_LOG(m_logger) << "FunctionTopicTests: request"; - data.id(1); - data.info(std::string("Test request")); - data.value(1000.0); + DdsUnitTests::FunctionRequestWithState data; - int uniqueId = 0; - bool bRet = m_ftcWS->requestDataClassic(data, - SLOT(slotRequestedData(DdsUnitTests::FunctionTopicTestWithStateReply,int,bool)), - SLOT(slotRequestedDataError(int,int,int)), - uniqueId); + data.id(1); + data.info(std::string("Test request")); + data.value(1000.0); - QVERIFY2(bRet, "Could not request data!"); + int uniqueId = 0; + bool bRet = m_ftcWS->requestDataClassic( + data, SLOT(slotRequestedData(DdsUnitTests::FunctionTopicTestWithStateReply, int, bool)), + SLOT(slotRequestedDataError(int, int, int)), uniqueId); - QTRY_COMPARE(spyRequest.count(), 1); - QTRY_COMPARE(spyReply.count(), 2); + QVERIFY2(bRet, "Could not request data!"); + + QTRY_COMPARE(spyRequest.count(), 1); + QTRY_COMPARE(spyReply.count(), 2); } - void FunctionTopicTests::requestTestCase2() { - - QSignalSpy spyRequest(this, &FunctionTopicTests::functionTopicRequestFinished); - QSignalSpy spyReply(this, &FunctionTopicTests::functionTopicReply); - DEBUG_LOG(m_logger) <<"FunctionTopicTests: request"; + QSignalSpy spyRequest(this, &FunctionTopicTests::functionTopicRequestFinished); + QSignalSpy spyReply(this, &FunctionTopicTests::functionTopicReply); - - DdsUnitTests::FunctionRequest data; + DEBUG_LOG(m_logger) << "FunctionTopicTests: request"; - data.id(1); - data.info(std::string("Test request")); - data.value(1000.0); + DdsUnitTests::FunctionRequest data; - int uniqueId = 0; - bool bRet = m_ftc->requestDataClassic(data, - SLOT(slotRequestedData(DdsUnitTests::FunctionTopicTestReply,int,bool)), - SLOT(slotRequestedDataError(int,int,int)), - uniqueId); + data.id(1); + data.info(std::string("Test request")); + data.value(1000.0); - QVERIFY2(bRet, "Could not request data!"); + int uniqueId = 0; + bool bRet = + m_ftc->requestDataClassic(data, SLOT(slotRequestedData(DdsUnitTests::FunctionTopicTestReply, int, bool)), + SLOT(slotRequestedDataError(int, int, int)), uniqueId); - QTRY_COMPARE(spyRequest.count(), 1); - QTRY_COMPARE(spyReply.count(), 1); + QVERIFY2(bRet, "Could not request data!"); + + QTRY_COMPARE(spyRequest.count(), 1); + QTRY_COMPARE(spyReply.count(), 1); } - void FunctionTopicTests::cleanupTestCase() { - DEBUG_LOG(m_logger) <<"FunctionTopicTests: cleanupTestCase"; + DEBUG_LOG(m_logger) << "FunctionTopicTests: cleanupTestCase"; - m_fts = nullptr; - m_ftc = nullptr; - m_ftsWS = nullptr; - m_ftcWS = nullptr; - m_ddsConnectorServer = nullptr; - m_ddsConnectorClient = nullptr; + m_fts = nullptr; + m_ftc = nullptr; + m_ftsWS = nullptr; + m_ftcWS = nullptr; + m_ddsConnectorServer = nullptr; + m_ddsConnectorClient = nullptr; } - -void FunctionTopicTests::onFunctionTopicRequest(const rti::core::SampleIdentity &sampleId, - const DdsUnitTests::FunctionRequestWithState &request) +void FunctionTopicTests::onFunctionTopicRequest(const rti::core::SampleIdentity& sampleId, + const DdsUnitTests::FunctionRequestWithState& request) { - QCOMPARE(m_mainThreadId, QThread::currentThreadId()); + QCOMPARE(m_mainThreadId, QThread::currentThreadId()); - INFO_LOG(m_logger) << "Got function topic request (with status member)"; - m_requestTopicWithState = request; - QCOMPARE(m_requestTopicWithState.id(), 1); - QCOMPARE(m_requestTopicWithState.info().get(), std::string("Test request")); - QCOMPARE(m_requestTopicWithState.value(), 1000.0); + INFO_LOG(m_logger) << "Got function topic request (with status member)"; + m_requestTopicWithState = request; + QCOMPARE(m_requestTopicWithState.id(), 1); + QCOMPARE(m_requestTopicWithState.info().get(), std::string("Test request")); + QCOMPARE(m_requestTopicWithState.value(), 1000.0); - DdsUnitTests::FunctionReplyWithState reply; + DdsUnitTests::FunctionReplyWithState reply; - DEBUG_LOG(m_logger) << "Send sample with status REPLY_COMPLETED"; - reply.id(1); - reply.errorString("Hello"); - reply.replyState(Core::FtReplyState::Completed); + DEBUG_LOG(m_logger) << "Send sample with status REPLY_COMPLETED"; + reply.id(1); + reply.errorString("Hello"); + reply.replyState(Core::FtReplyState::Completed); - bool bRet = m_ftsWS->sendReply(sampleId, reply); - QVERIFY2(bRet, "Sending Reply failed"); + bool bRet = m_ftsWS->sendReply(sampleId, reply); + QVERIFY2(bRet, "Sending Reply failed"); - emit functionTopicRequestFinished(); + emit functionTopicRequestFinished(); } - - -void FunctionTopicTests::onFunctionTopicRequest(const rti::core::SampleIdentity &sampleId, - const DdsUnitTests::FunctionRequest &request) +void FunctionTopicTests::onFunctionTopicRequest(const rti::core::SampleIdentity& sampleId, + const DdsUnitTests::FunctionRequest& request) { - QCOMPARE(m_mainThreadId, QThread::currentThreadId()); + QCOMPARE(m_mainThreadId, QThread::currentThreadId()); - INFO_LOG(m_logger) << "Got function topic request (without status member)"; + INFO_LOG(m_logger) << "Got function topic request (without status member)"; - m_requestTopic = request; + m_requestTopic = request; - DdsUnitTests::FunctionReply reply; + DdsUnitTests::FunctionReply reply; - reply.id(2); - reply.errorString("What?"); + reply.id(2); + reply.errorString("What?"); - bool bRet = m_fts->sendReply(sampleId, reply); - QVERIFY2(bRet, "Sending Reply failed"); + bool bRet = m_fts->sendReply(sampleId, reply); + QVERIFY2(bRet, "Sending Reply failed"); - emit functionTopicRequestFinished(); + emit functionTopicRequestFinished(); } - - -void FunctionTopicTests::slotRequestedData(const DdsUnitTests::FunctionTopicTestWithStateReply &reply, - int seqNo, bool bFinished) +void FunctionTopicTests::slotRequestedData(const DdsUnitTests::FunctionTopicTestWithStateReply& reply, int seqNo, + bool bFinished) { - Q_UNUSED(seqNo); - QCOMPARE(m_mainThreadId, QThread::currentThreadId()); + Q_UNUSED(seqNo); + QCOMPARE(m_mainThreadId, QThread::currentThreadId()); - INFO_LOG(m_logger) << "Got reply from FTS: " << reply.replyState(); + INFO_LOG(m_logger) << "Got reply from FTS: " << reply.replyState(); - m_replyTopicWithState = reply; + m_replyTopicWithState = reply; - if (m_replyTopicWithState.replyState() == Core::FtReplyState::InProgress) - { - QVERIFY(!bFinished); - QCOMPARE(m_replyTopicWithState.id(), 0); - } - else - { + if (m_replyTopicWithState.replyState() == Core::FtReplyState::InProgress) + { + QVERIFY(!bFinished); + QCOMPARE(m_replyTopicWithState.id(), 0); + } + else + { + QVERIFY(bFinished); + QCOMPARE(m_replyTopicWithState.id(), 1); + QCOMPARE(m_replyTopicWithState.errorString(), std::string("Hello")); + QCOMPARE(m_replyTopicWithState.replyState().underlying(), Core::FtReplyState::Completed); + } + emit functionTopicReply(); +} + +void FunctionTopicTests::slotRequestedData(const DdsUnitTests::FunctionTopicTestReply& reply, int seqNo, bool bFinished) +{ + Q_UNUSED(seqNo); QVERIFY(bFinished); - QCOMPARE(m_replyTopicWithState.id(), 1); - QCOMPARE(m_replyTopicWithState.errorString(), std::string("Hello")); - QCOMPARE(m_replyTopicWithState.replyState().underlying(), Core::FtReplyState::Completed); - } - emit functionTopicReply(); + QCOMPARE(m_mainThreadId, QThread::currentThreadId()); + + m_replyTopic = reply; + QCOMPARE(m_replyTopic.id(), 2); + QCOMPARE(m_replyTopic.errorString(), std::string("What?")); + + emit functionTopicReply(); } -void FunctionTopicTests::slotRequestedData(const DdsUnitTests::FunctionTopicTestReply &reply, - int seqNo, bool bFinished) -{ - Q_UNUSED(seqNo); - QVERIFY(bFinished); - QCOMPARE(m_mainThreadId, QThread::currentThreadId()); - - m_replyTopic = reply; - QCOMPARE(m_replyTopic.id(), 2); - QCOMPARE(m_replyTopic.errorString(), std::string("What?")); - - emit functionTopicReply(); -} - - - void FunctionTopicTests::slotRequestedDataError(int reason, int seqNo, int requestId) { - Q_UNUSED(seqNo); - Q_UNUSED(requestId); - QFAIL(qPrintable(QStringLiteral("Error when trying to request data: %1").arg(reason))); + Q_UNUSED(seqNo); + Q_UNUSED(requestId); + QFAIL(qPrintable(QStringLiteral("Error when trying to request data: %1").arg(reason))); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.h old mode 100755 new mode 100644 index 214c9fe25..b5f21670e --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/function_topic_tests.h @@ -2,72 +2,70 @@ #pragma once +#include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include - namespace NGL { - class INGLLogger; +class INGLLogger; } class FunctionTopicTests : public QObject { - Q_OBJECT + Q_OBJECT -public: - FunctionTopicTests(); + public: + FunctionTopicTests(); -private Q_SLOTS: - void initTestCase(); - void initFTSTestCase(); - void initFTCTestCase(); - void requestTestCase1(); - void requestTestCase2(); - void cleanupTestCase(); + private Q_SLOTS: + void initTestCase(); + void initFTSTestCase(); + void initFTCTestCase(); + void requestTestCase1(); + void requestTestCase2(); + void cleanupTestCase(); -Q_SIGNALS: - void functionTopicRequestFinished(); - void functionTopicReply(); -protected Q_SLOTS: - - void slotRequestedData(const DdsUnitTests::FunctionTopicTestReply &reply, int seqNo, bool bFinished); - void slotRequestedData(const DdsUnitTests::FunctionTopicTestWithStateReply &reply, int seqNo, bool bFinished); - void slotRequestedDataError(int reason, int seqNo, int requestId); - - void onFunctionTopicRequest(const rti::core::SampleIdentity &sampleId, - const DdsUnitTests::FunctionRequest &request); - void onFunctionTopicRequest(const rti::core::SampleIdentity &sampleId, - const DdsUnitTests::FunctionRequestWithState &request); + Q_SIGNALS: + void functionTopicRequestFinished(); + void functionTopicReply(); + protected Q_SLOTS: -private: - NGL::INGLLogger &m_logger; - void requestWithState(); -private: - - NGL::INGLLogger &m_logger; - std::unique_ptr m_fts; - std::unique_ptr m_ftsWS; - - std::unique_ptr m_ftc; - std::unique_ptr m_ftcWS; + void slotRequestedData(const DdsUnitTests::FunctionTopicTestReply& reply, int seqNo, bool bFinished); + void slotRequestedData(const DdsUnitTests::FunctionTopicTestWithStateReply& reply, int seqNo, bool bFinished); + void slotRequestedDataError(int reason, int seqNo, int requestId); - std::shared_ptr m_ddsConnectorClient; - std::shared_ptr m_ddsConnectorServer; + void onFunctionTopicRequest(const rti::core::SampleIdentity& sampleId, + const DdsUnitTests::FunctionRequest& request); + void onFunctionTopicRequest(const rti::core::SampleIdentity& sampleId, + const DdsUnitTests::FunctionRequestWithState& request); + private: + NGL::INGLLogger& m_logger; + void requestWithState(); - DdsUnitTests::FunctionRequest m_requestTopic; - DdsUnitTests::FunctionReply m_replyTopic; + private: + NGL::INGLLogger& m_logger; + std::unique_ptr m_fts; + std::unique_ptr m_ftsWS; - DdsUnitTests::FunctionRequestWithState m_requestTopicWithState; - DdsUnitTests::FunctionReplyWithState m_replyTopicWithState; + std::unique_ptr m_ftc; + std::unique_ptr m_ftcWS; - Qt::HANDLE m_mainThreadId; + std::shared_ptr m_ddsConnectorClient; + std::shared_ptr m_ddsConnectorServer; + + DdsUnitTests::FunctionRequest m_requestTopic; + DdsUnitTests::FunctionReply m_replyTopic; + + DdsUnitTests::FunctionRequestWithState m_requestTopicWithState; + DdsUnitTests::FunctionReplyWithState m_replyTopicWithState; + + Qt::HANDLE m_mainThreadId; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.cpp old mode 100755 new mode 100644 index c471f69b2..c4537acab --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.cpp @@ -1,226 +1,219 @@ - #include "generic_data_tests.h" -#include + #include #include - -#include - -#include +#include #include +#include +#include - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { - NGLCoreApplication app(argc, argv); - app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); + NGLCoreApplication app(argc, argv); + app.createLogger("UnitTests", "log4cxx_ddsUnitTests.props"); - GenericDataTests *tc = new GenericDataTests; + GenericDataTests* tc = new GenericDataTests; - int retCode = QTest::qExec(tc, argc, argv); + int retCode = QTest::qExec(tc, argc, argv); - delete tc; + delete tc; - return retCode; + return retCode; } GenericDataTests::GenericDataTests() - : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTests.GenericDataTests")) + : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("UnitTests.GenericDataTests")) { - m_spatialData.equipNo(0); - m_testPart.location().equipNo(0); - m_testPart.location().participantId(0); + m_spatialData.equipNo(0); + m_testPart.location().equipNo(0); + m_testPart.location().participantId(0); } - - void GenericDataTests::initTestCase() { - DEBUG_LOG(m_logger) <<"GenericDataTests: initTestCase"; + DEBUG_LOG(m_logger) << "GenericDataTests: initTestCase"; - m_init = new Initialisation(); + m_init = new Initialisation(); - int domainId = 0; - int exerciseId = 2; + int domainId = 0; + int exerciseId = 2; - QVERIFY2(m_init, "Initialisation failed"); - QVERIFY2(m_init->initDDS(domainId, exerciseId, Initialisation::USE_PUBLISHER), "Initialisation (Publisher) failed"); - QVERIFY2(m_init->initDDS(domainId, exerciseId, Initialisation::USE_SUBSCRIBER), "Initialisation (Subscriber) failed"); + QVERIFY2(m_init, "Initialisation failed"); + QVERIFY2(m_init->initDDS(domainId, exerciseId, Initialisation::USE_PUBLISHER), "Initialisation (Publisher) failed"); + QVERIFY2(m_init->initDDS(domainId, exerciseId, Initialisation::USE_SUBSCRIBER), + "Initialisation (Subscriber) failed"); - - QVERIFY2(m_init->getSubscriberListener(), "Initialisation SubscriberListener failed"); + QVERIFY2(m_init->getSubscriberListener(), "Initialisation SubscriberListener failed"); } void GenericDataTests::initDRTestCase() { - m_dataReader = new DTC::DroTestParticipant; - QVERIFY2(m_dataReader, "Initialisation of GenericDataReader(TestParticipant) failed"); - QVERIFY2(m_dataReader->create(m_init->getDomainParticipantSub(), m_init->getDDSSubscriber()), "Creating DataReader (TestParticipant) failed"); - m_init->getSubscriberListener()->addCallback(m_dataReader->getDataReader(), this); + m_dataReader = new DTC::DroTestParticipant; + QVERIFY2(m_dataReader, "Initialisation of GenericDataReader(TestParticipant) failed"); + QVERIFY2(m_dataReader->create(m_init->getDomainParticipantSub(), m_init->getDDSSubscriber()), + "Creating DataReader (TestParticipant) failed"); + m_init->getSubscriberListener()->addCallback(m_dataReader->getDataReader(), this); - m_dataReaderSd = new DTC::DroSpatialData; - QVERIFY2(m_dataReaderSd, "Initialisation of GenericDataReader(SpatialData) failed"); - QVERIFY2(m_dataReaderSd->create(m_init->getDomainParticipantSub(), m_init->getDDSSubscriber()), "Creating DataReader (SpatialData) failed"); - m_init->getSubscriberListener()->addCallback(m_dataReaderSd->getDataReader(), this); + m_dataReaderSd = new DTC::DroSpatialData; + QVERIFY2(m_dataReaderSd, "Initialisation of GenericDataReader(SpatialData) failed"); + QVERIFY2(m_dataReaderSd->create(m_init->getDomainParticipantSub(), m_init->getDDSSubscriber()), + "Creating DataReader (SpatialData) failed"); + m_init->getSubscriberListener()->addCallback(m_dataReaderSd->getDataReader(), this); } void GenericDataTests::initDWTestCase() { - m_dataWriter = new DTS::DwoTestParticipant(); - QVERIFY2(m_dataWriter, "Initialisation of GenericDataWriter(TestParticipant) failed"); - QVERIFY2(m_dataWriter->create(m_init->getDomainParticipant(), m_init->getDDSPublisher()), "Creating DataWriter (TestParticipant) failed"); + m_dataWriter = new DTS::DwoTestParticipant(); + QVERIFY2(m_dataWriter, "Initialisation of GenericDataWriter(TestParticipant) failed"); + QVERIFY2(m_dataWriter->create(m_init->getDomainParticipant(), m_init->getDDSPublisher()), + "Creating DataWriter (TestParticipant) failed"); - m_dataWriterSd = new DTS::DwoSpatialData(); - QVERIFY2(m_dataWriterSd, "Initialisation of GenericDataWriter(SpatialData) failed"); - QVERIFY2(m_dataWriterSd->create(m_init->getDomainParticipant(), m_init->getDDSPublisher()), "Creating DataWriter (SpatialData) failed"); + m_dataWriterSd = new DTS::DwoSpatialData(); + QVERIFY2(m_dataWriterSd, "Initialisation of GenericDataWriter(SpatialData) failed"); + QVERIFY2(m_dataWriterSd->create(m_init->getDomainParticipant(), m_init->getDDSPublisher()), + "Creating DataWriter (SpatialData) failed"); } - - void GenericDataTests::dataWriterTestCase() { - DEBUG_LOG(m_logger) <<"GenericDataTests: dataWriter"; + DEBUG_LOG(m_logger) << "GenericDataTests: dataWriter"; - - DdsUnitTests::SpatialData data; + DdsUnitTests::SpatialData data; - data.participantId(100); - data.equipNo(999); - data.gpsPosition().lon(70000); - data.gpsPosition().lat(90000); - data.gpsPosition().z(10); + data.participantId(100); + data.equipNo(999); + data.gpsPosition().lon(70000); + data.gpsPosition().lat(90000); + data.gpsPosition().z(10); - data.orientation().heave(10); - data.orientation().pitch(10); - data.orientation().roll(10); + data.orientation().heave(10); + data.orientation().pitch(10); + data.orientation().roll(10); - data.velocity().x(10); - data.velocity().y(2); - data.velocity().z(1); + data.velocity().x(10); + data.velocity().y(2); + data.velocity().z(1); - data.changedAt(11111); + data.changedAt(11111); - QVERIFY2(m_dataWriterSd->write(data), "Publishing Topic (SpatialData) failed"); + QVERIFY2(m_dataWriterSd->write(data), "Publishing Topic (SpatialData) failed"); - DdsUnitTests::TestParticipant allData; + DdsUnitTests::TestParticipant allData; - allData.name("************************ Name of TestParticpant ***********************"); - allData.location() = data; - allData.id(10000); - QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); - allData.id(11000); - QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); - allData.id(11100); - QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); - allData.id(11110); - QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); + allData.name("************************ Name of TestParticpant ***********************"); + allData.location() = data; + allData.id(10000); + QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); + allData.id(11000); + QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); + allData.id(11100); + QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); + allData.id(11110); + QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); - allData.id(11111); + allData.id(11111); - QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); + QVERIFY2(m_dataWriter->write(allData), "Publishing Topic (TestParticipant) failed"); } - void GenericDataTests::dataReaderTestCase() { - DEBUG_LOG(m_logger) << "GenericDataTests: dataReader"; + DEBUG_LOG(m_logger) << "GenericDataTests: dataReader"; - - QTRY_COMPARE(m_spatialData.equipNo(), 999); - QCOMPARE(m_spatialData.changedAt(), 11111); - - QTRY_COMPARE(m_testPart.location().equipNo(), 999); - QCOMPARE(m_testPart.location().participantId(), 100); + QTRY_COMPARE(m_spatialData.equipNo(), 999); + QCOMPARE(m_spatialData.changedAt(), 11111); - bool bSeenUnreadSamples = false; - dds::sub::LoanedSamples vecTp = m_dataReader->readAlive(bSeenUnreadSamples); - INFO_LOG(m_logger) <<"vecTp size: " << vecTp.length(); - QCOMPARE(vecTp.length(), static_cast(5)); - QCOMPARE(vecTp[0].data().id(), 10000); - QCOMPARE(vecTp[1].data().id(), 11000); - QCOMPARE(vecTp[2].data().id(), 11100); - QCOMPARE(vecTp[3].data().id(), 11110); - QCOMPARE(vecTp[4].data().id(), 11111); + QTRY_COMPARE(m_testPart.location().equipNo(), 999); + QCOMPARE(m_testPart.location().participantId(), 100); - dds::sub::LoanedSamples vecTpLoaned = m_dataReader->takeAlive(bSeenUnreadSamples); - INFO_LOG(m_logger) <<"vecTpLoaned size: " << vecTp.length(); - QCOMPARE(vecTpLoaned.length(), static_cast(5)); - QCOMPARE(vecTpLoaned[0].data().id(), 10000); - QCOMPARE(vecTpLoaned[1].data().id(), 11000); - QCOMPARE(vecTpLoaned[2].data().id(), 11100); - QCOMPARE(vecTpLoaned[3].data().id(), 11110); - QCOMPARE(vecTpLoaned[4].data().id(), 11111); + bool bSeenUnreadSamples = false; + dds::sub::LoanedSamples vecTp = m_dataReader->readAlive(bSeenUnreadSamples); + INFO_LOG(m_logger) << "vecTp size: " << vecTp.length(); + QCOMPARE(vecTp.length(), static_cast(5)); + QCOMPARE(vecTp[0].data().id(), 10000); + QCOMPARE(vecTp[1].data().id(), 11000); + QCOMPARE(vecTp[2].data().id(), 11100); + QCOMPARE(vecTp[3].data().id(), 11110); + QCOMPARE(vecTp[4].data().id(), 11111); + + dds::sub::LoanedSamples vecTpLoaned = m_dataReader->takeAlive(bSeenUnreadSamples); + INFO_LOG(m_logger) << "vecTpLoaned size: " << vecTp.length(); + QCOMPARE(vecTpLoaned.length(), static_cast(5)); + QCOMPARE(vecTpLoaned[0].data().id(), 10000); + QCOMPARE(vecTpLoaned[1].data().id(), 11000); + QCOMPARE(vecTpLoaned[2].data().id(), 11100); + QCOMPARE(vecTpLoaned[3].data().id(), 11110); + QCOMPARE(vecTpLoaned[4].data().id(), 11111); } - void GenericDataTests::deleteDataReaderTestCase() { - DdsUnitTests::TestParticipant data; - for (int i = 0; i < 1000; ++i) - { - data.id(i); - m_dataWriter->write(data); - } - m_init->getSubscriberListener()->removeCallback(m_dataReader->getDataReader(), this); - delete m_dataReader; - m_dataReader = nullptr; - for(int i = 0; i < 1000; ++i) - { - data.id(i); - m_dataWriter->write(data); - } + DdsUnitTests::TestParticipant data; + for (int i = 0; i < 1000; ++i) + { + data.id(i); + m_dataWriter->write(data); + } + m_init->getSubscriberListener()->removeCallback(m_dataReader->getDataReader(), this); + delete m_dataReader; + m_dataReader = nullptr; + for (int i = 0; i < 1000; ++i) + { + data.id(i); + m_dataWriter->write(data); + } } - - void GenericDataTests::cleanupTestCase() { - DEBUG_LOG(m_logger) <<"GenericDataTests: cleanupTestCase"; - if (m_dataReader) - { - m_init->getSubscriberListener()->removeCallback(m_dataReader->getDataReader(), this); - delete m_dataReader; - } - if (m_dataReaderSd) - { - m_init->getSubscriberListener()->removeCallback(m_dataReaderSd->getDataReader(), this); - delete m_dataReaderSd; - } - m_init->cleanupSubscriberListener(); - delete m_dataWriter; - delete m_dataWriterSd; - delete m_init; - deleteLater(); + DEBUG_LOG(m_logger) << "GenericDataTests: cleanupTestCase"; + if (m_dataReader) + { + m_init->getSubscriberListener()->removeCallback(m_dataReader->getDataReader(), this); + delete m_dataReader; + } + if (m_dataReaderSd) + { + m_init->getSubscriberListener()->removeCallback(m_dataReaderSd->getDataReader(), this); + delete m_dataReaderSd; + } + m_init->cleanupSubscriberListener(); + delete m_dataWriter; + delete m_dataWriterSd; + delete m_init; + deleteLater(); } - -void GenericDataTests::processData(const DdsUnitTests::SpatialData &data, DataModification modType) +void GenericDataTests::processData(const DdsUnitTests::SpatialData& data, DataModification modType) { - DEBUG_LOG(m_logger) << "SpatialData: equipNo = " << data.equipNo() << " modType: " << modType; - m_spatialData = data; + DEBUG_LOG(m_logger) << "SpatialData: equipNo = " << data.equipNo() << " modType: " << modType; + m_spatialData = data; } -void GenericDataTests::processData(const DdsUnitTests::TestParticipant &data, const dds::sub::SampleInfo &si) +void GenericDataTests::processData(const DdsUnitTests::TestParticipant& data, const dds::sub::SampleInfo& si) { - Q_UNUSED(si); - DEBUG_LOG(m_logger) << "TestParticipant: equipNo = " << data.location().equipNo(); - m_testPart = data; + Q_UNUSED(si); + DEBUG_LOG(m_logger) << "TestParticipant: equipNo = " << data.location().equipNo(); + m_testPart = data; } -void GenericDataTests::droDataAvailable(const std::string &topicType, const std::string &topicName) +void GenericDataTests::droDataAvailable(const std::string& topicType, const std::string& topicName) { - Q_UNUSED(topicName) - DEBUG_LOG(m_logger) << "IN droDataAvailable: type = " << topicType; - if (topicType == "DdsUnitTests::TestParticipant") - { - m_init->getSubscriberListener()->enableCallback(m_dataReader->getDataReader(), this); - m_dataReader->read([this](const DdsUnitTests::TestParticipant &data, const dds::sub::SampleInfo &si) { processData(data, si); }); - } - else if(topicType == "DdsUnitTests::SpatialData") - { - m_init->getSubscriberListener()->enableCallback(m_dataReaderSd->getDataReader(), this); - m_dataReaderSd->read([this](const DdsUnitTests::SpatialData &data, DataModification modType) { processData(data, modType); } ); - } + Q_UNUSED(topicName) + DEBUG_LOG(m_logger) << "IN droDataAvailable: type = " << topicType; + if (topicType == "DdsUnitTests::TestParticipant") + { + m_init->getSubscriberListener()->enableCallback(m_dataReader->getDataReader(), this); + m_dataReader->read([this](const DdsUnitTests::TestParticipant& data, const dds::sub::SampleInfo& si) { + processData(data, si); + }); + } + else if (topicType == "DdsUnitTests::SpatialData") + { + m_init->getSubscriberListener()->enableCallback(m_dataReaderSd->getDataReader(), this); + m_dataReaderSd->read( + [this](const DdsUnitTests::SpatialData& data, DataModification modType) { processData(data, modType); }); + } } diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.h old mode 100755 new mode 100644 index f774e9312..91417fcae --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/generic_data_tests.h @@ -2,67 +2,63 @@ #pragma once -#include - #include "initialisation.h" +#include #include #include - -#include #include +#include namespace NGL { - class INGLLogger; +class INGLLogger; } class GenericDataTests : public DDSGeneric::SubscriberListenerCallback { - Q_OBJECT + Q_OBJECT -public: - GenericDataTests(); + public: + GenericDataTests(); -private Q_SLOTS: - void initTestCase(); - void initDRTestCase(); - void initDWTestCase(); - void dataWriterTestCase(); - void dataReaderTestCase(); - void deleteDataReaderTestCase(); - void cleanupTestCase(); + private Q_SLOTS: + void initTestCase(); + void initDRTestCase(); + void initDWTestCase(); + void dataWriterTestCase(); + void dataReaderTestCase(); + void deleteDataReaderTestCase(); + void cleanupTestCase(); -protected: - NGL::INGLLogger &m_logger; - void droDataAvailable(const std::string &topicType, const std::string &topicName) override; - void noWriterAnymore(const std::string &topicType, const std::string &topicName) override - { - Q_UNUSED(topicType); - Q_UNUSED(topicName); - } + protected: + NGL::INGLLogger& m_logger; + void droDataAvailable(const std::string& topicType, const std::string& topicName) override; - void writerAvailable(const std::string &topicType, const std::string &topicName) override - { - Q_UNUSED(topicType); - Q_UNUSED(topicName); - } + void noWriterAnymore(const std::string& topicType, const std::string& topicName) override + { + Q_UNUSED(topicType); + Q_UNUSED(topicName); + } - void processData(const DdsUnitTests::TestParticipant &data, const dds::sub::SampleInfo &si); - void processData(const DdsUnitTests::SpatialData &data, DataModification modType); + void writerAvailable(const std::string& topicType, const std::string& topicName) override + { + Q_UNUSED(topicType); + Q_UNUSED(topicName); + } -private: - Initialisation *m_init = nullptr; + void processData(const DdsUnitTests::TestParticipant& data, const dds::sub::SampleInfo& si); + void processData(const DdsUnitTests::SpatialData& data, DataModification modType); - DTS::DwoTestParticipant *m_dataWriter = nullptr; - DTC::DroTestParticipant *m_dataReader = nullptr; + private: + Initialisation* m_init = nullptr; - DTS::DwoSpatialData *m_dataWriterSd = nullptr; - DTC::DroSpatialData *m_dataReaderSd = nullptr; + DTS::DwoTestParticipant* m_dataWriter = nullptr; + DTC::DroTestParticipant* m_dataReader = nullptr; - DdsUnitTests::SpatialData m_spatialData; - DdsUnitTests::TestParticipant m_testPart; + DTS::DwoSpatialData* m_dataWriterSd = nullptr; + DTC::DroSpatialData* m_dataReaderSd = nullptr; + + DdsUnitTests::SpatialData m_spatialData; + DdsUnitTests::TestParticipant m_testPart; }; - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.cpp old mode 100755 new mode 100644 index 547b5c79c..35ad62b55 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.cpp @@ -2,11 +2,9 @@ #include "initialisation.h" -#include - #include #include - +#include Initialisation::Initialisation() : m_domainParticipant(nullptr) , m_domainParticipantSub(nullptr) @@ -16,81 +14,72 @@ Initialisation::Initialisation() : m_domainParticipant(nullptr) , m_ddsSubscriber(nullptr) , m_subListener(new DDSGeneric::SubscriberListener) .getNGLLogger("UnitTests.Initialisation")), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - if (!DDS::QosProfile::setDefault()) - ERROR_LOG(m_logger) << "Error setting default QoS from xml-file "; - + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + if (!DDS::QosProfile::setDefault()) + ERROR_LOG(m_logger) << "Error setting default QoS from xml-file "; } Initialisation::~Initialisation() { - cleanupSubscriberListener(); - m_ddsSubscriber = nullptr; - m_ddsPublisher = nullptr; + cleanupSubscriberListener(); + m_ddsSubscriber = nullptr; + m_ddsPublisher = nullptr; } void Initialisation::cleanupSubscriberListener() { - if (m_ddsSubscriber != nullptr && m_subListener != nullptr) - { - m_ddsSubscriber.listener(nullptr, dds::core::status::StatusMask::none()); - delete m_subListener; - m_subListener = nullptr; - } + if (m_ddsSubscriber != nullptr && m_subListener != nullptr) + { + m_ddsSubscriber.listener(nullptr, dds::core::status::StatusMask::none()); + delete m_subListener; + m_subListener = nullptr; + } } - bool Initialisation::initDDS(int domainId, int exerciseId, PubSub pubsub) { - if (m_domainParticipant == nullptr) - m_domainParticipant = dds::domain::DomainParticipant(domainId, DDS::QosProfile::domainParticipantShm()); + if (m_domainParticipant == nullptr) + m_domainParticipant = dds::domain::DomainParticipant(domainId, DDS::QosProfile::domainParticipantShm()); - - - if (pubsub == USE_PUBLISHER || pubsub == USE_PUB_SUB) - { - dds::pub::qos::PublisherQos publisherQos = m_domainParticipant.default_publisher_qos(); - - DEBUG_LOG(m_logger) << "Publish on partition " << IDL::exercisePartition(exerciseId); - - - dds::core::policy::Partition partitionQos; - partitionQos.name( { IDL::exercisePartition(exerciseId) } ); - publisherQos << partitionQos; - - m_ddsPublisher = dds::pub::Publisher(m_domainParticipant, - publisherQos); - } - - if (pubsub == USE_SUBSCRIBER || pubsub == USE_PUB_SUB) - { - dds::domain::DomainParticipant domainPart = m_domainParticipant; - if ( domainPart == nullptr || m_domainParticipantSub == nullptr) + if (pubsub == USE_PUBLISHER || pubsub == USE_PUB_SUB) { - m_domainParticipantSub = dds::domain::DomainParticipant(domainId, DDS::QosProfile::domainParticipantShm()); - domainPart = m_domainParticipantSub; + dds::pub::qos::PublisherQos publisherQos = m_domainParticipant.default_publisher_qos(); + + DEBUG_LOG(m_logger) << "Publish on partition " << IDL::exercisePartition(exerciseId); + + dds::core::policy::Partition partitionQos; + partitionQos.name({IDL::exercisePartition(exerciseId)}); + publisherQos << partitionQos; + + m_ddsPublisher = dds::pub::Publisher(m_domainParticipant, publisherQos); } - dds::sub::qos::SubscriberQos subscriberQos = domainPart.default_subscriber_qos(); + if (pubsub == USE_SUBSCRIBER || pubsub == USE_PUB_SUB) + { + dds::domain::DomainParticipant domainPart = m_domainParticipant; + if (domainPart == nullptr || m_domainParticipantSub == nullptr) + { + m_domainParticipantSub = dds::domain::DomainParticipant(domainId, DDS::QosProfile::domainParticipantShm()); + domainPart = m_domainParticipantSub; + } - DEBUG_LOG(m_logger) << "Subsribing on partition " << IDL::exercisePartition(exerciseId); + dds::sub::qos::SubscriberQos subscriberQos = domainPart.default_subscriber_qos(); - - dds::core::policy::Partition partitionQos; - partitionQos.name( { IDL::exercisePartition(exerciseId) } ); - subscriberQos << partitionQos; + DEBUG_LOG(m_logger) << "Subsribing on partition " << IDL::exercisePartition(exerciseId); - m_ddsSubscriber = dds::sub::Subscriber(domainPart, - subscriberQos, - m_subListener, - m_subListener->mask()); - } + dds::core::policy::Partition partitionQos; + partitionQos.name({IDL::exercisePartition(exerciseId)}); + subscriberQos << partitionQos; - if (m_domainId == 0) - m_domainId = domainId; + m_ddsSubscriber = dds::sub::Subscriber(domainPart, subscriberQos, m_subListener, m_subListener->mask()); + } - if (m_exerciseId < 0) - m_exerciseId = exerciseId; + if (m_domainId == 0) + m_domainId = domainId; - return true; + if (m_exerciseId < 0) + m_exerciseId = exerciseId; + + return true; } diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.h old mode 100755 new mode 100644 index 11c4d4220..e69d4cfa5 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/DdsUnitTests/initialisation.h @@ -5,43 +5,54 @@ #include #include -namespace NGL { - class INGLLogger; +namespace NGL +{ +class INGLLogger; } class Initialisation { -public: - Initialisation(); - virtual ~Initialisation(); + public: + Initialisation(); + virtual ~Initialisation(); - enum PubSub - { - USE_PUBLISHER = 1, - USE_SUBSCRIBER = 2, - USE_PUB_SUB = 4 - }; + enum PubSub { USE_PUBLISHER = 1, USE_SUBSCRIBER = 2, USE_PUB_SUB = 4 }; - - bool initDDS(int domainId, int exerciseId, PubSub pubsub = USE_PUBLISHER); - void cleanupSubscriberListener(); + bool initDDS(int domainId, int exerciseId, PubSub pubsub = USE_PUBLISHER); + void cleanupSubscriberListener(); - dds::domain::DomainParticipant getDomainParticipant() { return m_domainParticipant; } - dds::domain::DomainParticipant getDomainParticipantSub() { return m_domainParticipantSub != nullptr ? m_domainParticipantSub : m_domainParticipant; } - dds::pub::Publisher getDDSPublisher() { return m_ddsPublisher; } - dds::sub::Subscriber getDDSSubscriber() { return m_ddsSubscriber; } - DDSGeneric::SubscriberListener *getSubscriberListener() { return m_subListener; } + dds::domain::DomainParticipant getDomainParticipant() + { + return m_domainParticipant; + } -private: - NGL::INGLLogger &m_logger; - dds::domain::DomainParticipant m_domainParticipant; - dds::domain::DomainParticipant m_domainParticipantSub; - int m_domainId; - int m_exerciseId; - dds::pub::Publisher m_ddsPublisher; - dds::sub::Subscriber m_ddsSubscriber; - DDSGeneric::SubscriberListener *m_subListener; + dds::domain::DomainParticipant getDomainParticipantSub() + { + return m_domainParticipantSub != nullptr ? m_domainParticipantSub : m_domainParticipant; + } + + dds::pub::Publisher getDDSPublisher() + { + return m_ddsPublisher; + } + + dds::sub::Subscriber getDDSSubscriber() + { + return m_ddsSubscriber; + } + + DDSGeneric::SubscriberListener* getSubscriberListener() + { + return m_subListener; + } + + private: + NGL::INGLLogger& m_logger; + dds::domain::DomainParticipant m_domainParticipant; + dds::domain::DomainParticipant m_domainParticipantSub; + int m_domainId; + int m_exerciseId; + dds::pub::Publisher m_ddsPublisher; + dds::sub::Subscriber m_ddsSubscriber; + DDSGeneric::SubscriberListener* m_subListener; }; - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTC/generic_ftc_impl.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTC/generic_ftc_impl.h old mode 100755 new mode 100644 index bdaf164e1..57877c85d --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTC/generic_ftc_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTC/generic_ftc_impl.h @@ -1,566 +1,509 @@ #pragma once - - -#include "generic_ftc.h" #include "abstract_requester.h" +#include "generic_ftc.h" #include "generic_ftc_threading.h" #include #include -#include #include +#include #include - -#include #include +#include #include - -#include #include - +#include namespace FTC { -template -class HasStatusFunction +template class HasStatusFunction { - template - static std::true_type testSignature(void (T::*)(const Core::FtReplyState &)); + template static std::true_type testSignature(void (T::*)(const Core::FtReplyState&)); - template - static decltype(testSignature(&T::replyState)) test(std::nullptr_t); + template static decltype(testSignature(&T::replyState)) test(std::nullptr_t); - template - static std::false_type test(...); + template static std::false_type test(...); -public: - using type = decltype(test(nullptr)); - static const bool value = type::value; + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; }; -template -class HasRequestId +template class HasRequestId { - template - static std::true_type testSignature(const int32_t &(T::*)() const); - template - static std::true_type testSignature(int32_t (T::*)() const); + template static std::true_type testSignature(const int32_t& (T::*)() const); + template static std::true_type testSignature(int32_t (T::*)() const); - template - static decltype(testSignature(&T::requestId)) test(std::nullptr_t); + template static decltype(testSignature(&T::requestId)) test(std::nullptr_t); - template - static std::false_type test(...); + template static std::false_type test(...); -public: - using type = decltype(test(nullptr)); - static const bool value = type::value; + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; }; -template -struct TopicNames -{}; +template struct TopicNames +{ +}; -template +template class GenericFtcImpl final : public GenericFtc, public Threading { -public: - using RequestTopic = TOPICTYPE_REQUEST; - using ReplyTopic = TOPICTYPE_REPLY; - using TopicNameHelper = TopicNames>; + public: + using RequestTopic = TOPICTYPE_REQUEST; + using ReplyTopic = TOPICTYPE_REPLY; + using TopicNameHelper = TopicNames>; - GenericFtcImpl(const dds::domain::DomainParticipant &domainParticipant, - const dds::pub::Publisher &ddsPublisher, - const dds::sub::Subscriber &ddsSubscriber, - QObject *objToInform, - const std::string &partitionType, - int partitionId) - : GenericFtc() - , m_objToInform(objToInform) - , m_requesterParams(domainParticipant) - , m_partitionType(partitionType) - , m_partitionId(partitionId) - , m_logger(DDS::getLogger(TopicNameHelper::functionTopicName(), DDS::DataType::FUNCTION_TOPIC_CLIENT)) - { - - - Q_ASSERT(domainParticipant != nullptr); - Q_ASSERT(ddsPublisher != nullptr); - Q_ASSERT(ddsSubscriber != nullptr); - Q_ASSERT(objToInform != nullptr); - - - m_requesterParams.request_topic_name(TopicNameHelper::requestTopicName()); - m_requesterParams.reply_topic_name(TopicNameHelper::replyTopicName()); - m_requesterParams.publisher(ddsPublisher); - m_requesterParams.subscriber(ddsSubscriber); - m_requesterParams.datareader_qos(DDS::QosProfile::dataReaderDefault(DDS::QosProfile::TopicType::FunctionTopic)); - m_requesterParams.datawriter_qos(DDS::QosProfile::dataWriterDefault(DDS::QosProfile::TopicType::FunctionTopic)); - DDS::QosProfile::print(m_requesterParams.datareader_qos(), m_logger); - DDS::QosProfile::print(m_requesterParams.datawriter_qos(), m_logger); - - DEBUG_LOG(m_logger) << "=> Static request using request/reply topic names: " - << TopicNameHelper::requestTopicName() - << ", reply: " - << TopicNameHelper::replyTopicName(); - - qRegisterMetaType(TopicNameHelper::replyTopicTypeName()); - preInit(); - } - - - ~GenericFtcImpl() - { - Q_ASSERT(!m_dying); - m_dying = true; - - decltype(m_modernRequests) modernRequests; - decltype(m_classicRequests) classicRequests; + GenericFtcImpl(const dds::domain::DomainParticipant& domainParticipant, const dds::pub::Publisher& ddsPublisher, + const dds::sub::Subscriber& ddsSubscriber, QObject* objToInform, const std::string& partitionType, + int partitionId) + : GenericFtc(), m_objToInform(objToInform), m_requesterParams(domainParticipant), + m_partitionType(partitionType), m_partitionId(partitionId), + m_logger(DDS::getLogger(TopicNameHelper::functionTopicName(), DDS::DataType::FUNCTION_TOPIC_CLIENT)) { - { - std::lock_guard l(m_conditionMutex); - setWorkAvailable(false); - } - std::lock_guard l(m_requestMutex); - Q_ASSERT(m_classicRequests.empty()); - Q_ASSERT(m_modernRequests.empty()); + Q_ASSERT(domainParticipant != nullptr); + Q_ASSERT(ddsPublisher != nullptr); + Q_ASSERT(ddsSubscriber != nullptr); + Q_ASSERT(objToInform != nullptr); - classicRequests.swap(m_classicRequests); - modernRequests.swap(m_modernRequests); + m_requesterParams.request_topic_name(TopicNameHelper::requestTopicName()); + m_requesterParams.reply_topic_name(TopicNameHelper::replyTopicName()); + m_requesterParams.publisher(ddsPublisher); + m_requesterParams.subscriber(ddsSubscriber); + m_requesterParams.datareader_qos(DDS::QosProfile::dataReaderDefault(DDS::QosProfile::TopicType::FunctionTopic)); + m_requesterParams.datawriter_qos(DDS::QosProfile::dataWriterDefault(DDS::QosProfile::TopicType::FunctionTopic)); + DDS::QosProfile::print(m_requesterParams.datareader_qos(), m_logger); + DDS::QosProfile::print(m_requesterParams.datawriter_qos(), m_logger); + + DEBUG_LOG(m_logger) << "=> Static request using request/reply topic names: " + << TopicNameHelper::requestTopicName() << ", reply: " << TopicNameHelper::replyTopicName(); + + qRegisterMetaType(TopicNameHelper::replyTopicTypeName()); + preInit(); } - for (; !modernRequests.empty(); modernRequests.pop()) + ~GenericFtcImpl() { - ModernRequest &request = modernRequests.front(); - fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a modern request in the queue while the Ftc is being destroyed. Throwing!\n"); - Q_ASSERT(false); - request.promise.set_exception(std::make_exception_ptr(std::runtime_error("Session aborted."))); - emit request.requestWatcher->finished(); - } + Q_ASSERT(!m_dying); + m_dying = true; - for (; !classicRequests.empty(); classicRequests.pop()) - { - ClassicRequest &request = classicRequests.front(); - fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a classic request in the queue while the Ftc is being destroyed. Throwing!\n"); - Q_ASSERT(false); - sendError(request, 0, true ); - } - } - - - - struct ClassicRequest - { - connext::WriteSample sample; - QMetaMethod replySlot; - QMetaMethod errorSlot; - int uniqueId = 0; - }; - - - bool requestDataClassic(const RequestTopic &requestTopic, - const char *replySlot, - const char *errorSlot, - int &uniqueId) override - { - Q_ASSERT(!m_dying); - - ClassicRequest request; - if (!checkSlots(request, replySlot, errorSlot)) - return false; - request.sample.set_data(requestTopic); - request.uniqueId = ++m_uniqueId; - uniqueId = request.uniqueId; - - createThread(); - - { - std::lock_guard l(m_requestMutex); - m_classicRequests.push(request); - } - - runThread(); - - return true; - } - - - - template - struct ModernRequest - { - std::promise promise; - connext::WriteSample sample; - Request2 *requestWatcher; - }; - - - std::future requestDataModern(const RequestTopic &requestTopic, Request2 *requestWatcher) override - { - Q_ASSERT(!m_dying); - - std::promise promise; - std::future future = promise.get_future(); - - connext::WriteSample sample; - sample.set_data(requestTopic); - - createThread(); - - { - std::lock_guard l(m_requestMutex); - m_modernRequests.push({ std::move(promise), sample, requestWatcher }); - } - - runThread(); - - return future; - } - - -private: - QString functionTopicName() const override - { - return QString::fromUtf8(TopicNameHelper::functionTopicName()); - } - - - int partitionId() const override - { - return m_partitionId; - } - - - QString partitionType() const override - { - return QString::fromStdString(m_partitionType); - } - - - std::unique_ptr > requester; - - - void cleanupThread() override - { - - requester.reset(); - } - - - void threadDone() override - { - - - - - - for (; !m_modernRequests.empty(); m_modernRequests.pop()) - { - ModernRequest &request = m_modernRequests.front(); - fprintf(stderr, "[!] GenericFtcImpl::threadDone: there was a modern request in the queue while the thread already ended. Throwing!\n"); - Q_ASSERT(false); - request.promise.set_exception(std::make_exception_ptr(std::runtime_error("Worker thread timed out."))); - } - - for (; !m_classicRequests.empty(); m_classicRequests.pop()) - { - ClassicRequest &request = m_classicRequests.front(); - fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a classic request in the queue while the thread already ended. Throwing!\n"); - Q_ASSERT(false); - sendError(request, 0, true ); - } - } - - - void work() override - { - try - { - decltype(m_classicRequests) classicRequests; - decltype(m_modernRequests) modernRequests; - - Q_ASSERT(isWorkAvailable()); - if (!isWorkAvailable()) - { - fprintf(stderr, "[!] GenericFtc::work: called while marked as no work available! run? %d (%s)\n", isRun(), threadName().toStdString().c_str()); - } - setWorkAvailable(false); - - { - std::lock_guard l(m_requestMutex); - - if (!m_classicRequests.empty()) + decltype(m_modernRequests) modernRequests; + decltype(m_classicRequests) classicRequests; { - m_classicRequests.swap(classicRequests); + { + std::lock_guard l(m_conditionMutex); + setWorkAvailable(false); + } + + std::lock_guard l(m_requestMutex); + Q_ASSERT(m_classicRequests.empty()); + Q_ASSERT(m_modernRequests.empty()); + + classicRequests.swap(m_classicRequests); + modernRequests.swap(m_modernRequests); } - if (!m_modernRequests.empty()) + + for (; !modernRequests.empty(); modernRequests.pop()) { - m_modernRequests.swap(modernRequests); - } - } + ModernRequest& request = modernRequests.front(); + fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a modern request in the queue while the Ftc is being " + "destroyed. Throwing!\n"); + Q_ASSERT(false); + request.promise.set_exception(std::make_exception_ptr(std::runtime_error("Session aborted."))); + emit request.requestWatcher->finished(); + } - cancellationPoint(); + for (; !classicRequests.empty(); classicRequests.pop()) + { + ClassicRequest& request = classicRequests.front(); + fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a classic request in the queue while the Ftc is being " + "destroyed. Throwing!\n"); + Q_ASSERT(false); + sendError(request, 0, true); + } + } - if (classicRequests.empty() && modernRequests.empty()) - { - fprintf(stderr, "[!] GenericFtc::work: called without having any requests! (%s)\n", threadName().toStdString().c_str()); - Q_ASSERT(false); - return; - } + struct ClassicRequest + { + connext::WriteSample sample; + QMetaMethod replySlot; + QMetaMethod errorSlot; + int uniqueId = 0; + }; - if (!requester) - { - - - - - - - + bool requestDataClassic(const RequestTopic& requestTopic, const char* replySlot, const char* errorSlot, + int& uniqueId) override + { + Q_ASSERT(!m_dying); - requester.reset(new connext::Requester(m_requesterParams)); - } + ClassicRequest request; + if (!checkSlots(request, replySlot, errorSlot)) + return false; + request.sample.set_data(requestTopic); + request.uniqueId = ++m_uniqueId; + uniqueId = request.uniqueId; - for (; !classicRequests.empty(); classicRequests.pop()) - { - cancellationPoint(); - ClassicRequest &request = classicRequests.front(); - requester->send_request(request.sample); - cancellationPoint(); - getRequestedDataClassic(*requester.get(), request); - cancellationPoint(); - } + createThread(); - for (; !modernRequests.empty(); modernRequests.pop()) - { - cancellationPoint(); - ModernRequest &request = modernRequests.front(); - requester->send_request(request.sample); - cancellationPoint(); + { + std::lock_guard l(m_requestMutex); + m_classicRequests.push(request); + } + + runThread(); + + return true; + } + + template struct ModernRequest + { + std::promise promise; + connext::WriteSample sample; + Request2* requestWatcher; + }; + + std::future requestDataModern(const RequestTopic& requestTopic, Request2* requestWatcher) override + { + Q_ASSERT(!m_dying); + + std::promise promise; + std::future future = promise.get_future(); + + connext::WriteSample sample; + sample.set_data(requestTopic); + + createThread(); + + { + std::lock_guard l(m_requestMutex); + m_modernRequests.push({std::move(promise), sample, requestWatcher}); + } + + runThread(); + + return future; + } + + private: + QString functionTopicName() const override + { + return QString::fromUtf8(TopicNameHelper::functionTopicName()); + } + + int partitionId() const override + { + return m_partitionId; + } + + QString partitionType() const override + { + return QString::fromStdString(m_partitionType); + } + + std::unique_ptr> requester; + + void cleanupThread() override + { + + requester.reset(); + } + + void threadDone() override + { + + for (; !m_modernRequests.empty(); m_modernRequests.pop()) + { + ModernRequest& request = m_modernRequests.front(); + fprintf(stderr, "[!] GenericFtcImpl::threadDone: there was a modern request in the queue while the thread " + "already ended. Throwing!\n"); + Q_ASSERT(false); + request.promise.set_exception(std::make_exception_ptr(std::runtime_error("Worker thread timed out."))); + } + + for (; !m_classicRequests.empty(); m_classicRequests.pop()) + { + ClassicRequest& request = m_classicRequests.front(); + fprintf(stderr, "[!] GenericFtcImpl::dtor: there was a classic request in the queue while the thread " + "already ended. Throwing!\n"); + Q_ASSERT(false); + sendError(request, 0, true); + } + } + + void work() override + { try { - getModernRequestedData(*requester.get(), request); + decltype(m_classicRequests) classicRequests; + decltype(m_modernRequests) modernRequests; + + Q_ASSERT(isWorkAvailable()); + if (!isWorkAvailable()) + { + fprintf(stderr, "[!] GenericFtc::work: called while marked as no work available! run? %d (%s)\n", + isRun(), threadName().toStdString().c_str()); + } + setWorkAvailable(false); + + { + std::lock_guard l(m_requestMutex); + + if (!m_classicRequests.empty()) + { + m_classicRequests.swap(classicRequests); + } + if (!m_modernRequests.empty()) + { + m_modernRequests.swap(modernRequests); + } + } + + cancellationPoint(); + + if (classicRequests.empty() && modernRequests.empty()) + { + fprintf(stderr, "[!] GenericFtc::work: called without having any requests! (%s)\n", + threadName().toStdString().c_str()); + Q_ASSERT(false); + return; + } + + if (!requester) + { + + requester.reset(new connext::Requester(m_requesterParams)); + } + + for (; !classicRequests.empty(); classicRequests.pop()) + { + cancellationPoint(); + ClassicRequest& request = classicRequests.front(); + requester->send_request(request.sample); + cancellationPoint(); + getRequestedDataClassic(*requester.get(), request); + cancellationPoint(); + } + + for (; !modernRequests.empty(); modernRequests.pop()) + { + cancellationPoint(); + ModernRequest& request = modernRequests.front(); + requester->send_request(request.sample); + cancellationPoint(); + try + { + getModernRequestedData(*requester.get(), request); + } + catch (...) + { + request.promise.set_exception(std::current_exception()); + + QTimer::singleShot(0, request.requestWatcher, &Request2::finished); + } + cancellationPoint(); + } + } + catch (const dds::core::Exception& ex) + { + fprintf(stderr, "[!] GenericFtc::work: dds::core::exception: %s (%s)\n", ex.what(), + threadName().toStdString().c_str()); + } + catch (const std::exception& ex) + { + fprintf(stderr, "[!] GenericFtc::work: exception: %s (%s)\n", ex.what(), + threadName().toStdString().c_str()); } catch (...) { - request.promise.set_exception(std::current_exception()); - - QTimer::singleShot(0, request.requestWatcher, &Request2::finished); + fprintf(stderr, "[!] GenericFtc::work: unknown exception occured !!! (%s)\n", + threadName().toStdString().c_str()); } - cancellationPoint(); - } } - catch (const dds::core::Exception &ex) + + template ::value, int>::type = 0> + static inline bool isInProgress(const connext::Sample& reply) { - fprintf(stderr, "[!] GenericFtc::work: dds::core::exception: %s (%s)\n", ex.what(), threadName().toStdString().c_str()); + return (reply.data().replyState() == Core::FtReplyState::InProgress); } - catch (const std::exception &ex) + + template ::value, int>::type = 0> + static inline bool isInProgress(const connext::Sample&) { - fprintf(stderr, "[!] GenericFtc::work: exception: %s (%s)\n", ex.what(), threadName().toStdString().c_str()); - } - catch(...) - { - fprintf(stderr, "[!] GenericFtc::work: unknown exception occured !!! (%s)\n", threadName().toStdString().c_str()); - } - } - - template ::value, int>::type = 0> - static inline bool isInProgress(const connext::Sample &reply) - { - return (reply.data().replyState() == Core::FtReplyState::InProgress); - } - - - template ::value, int>::type = 0> - static inline bool isInProgress(const connext::Sample &) - { - - return false; - } - - - - void getRequestedDataClassic(connext::Requester &requester, ClassicRequest &request) - { - -#ifdef WIN32 - const dds::core::Duration MAX_WAIT(200); -#else - const dds::core::Duration MAX_WAIT(20); -#endif - - bool inProgress = true; - while (inProgress && isRun()) - { - DEBUG_LOG(m_logger) << "Waiting for reply "; - - connext::Sample reply; - - if (!requester.receive_reply(reply, MAX_WAIT)) - { - WARNING_LOG(m_logger) << "Timed out waiting for reply"; - sendError(request, 3); - return; - } - - - if (reply.info().valid()) - { - if (request.sample.info().identity() != reply.info()->related_original_publication_virtual_sample_identity()) - { - - INFO_LOG(m_logger) << "#receiveReply - outdated. sample id: " << connext::DebugInfo::toReadable(request.sample.info().identity()) - << ", virutal sample id: " << connext::DebugInfo::toReadable(reply.info()->related_original_publication_virtual_sample_identity()); - continue; - } - inProgress = isInProgress(reply); - if (request.replySlot.isValid()) - { - INFO_LOG(m_logger) << "#receiveReply for " << TopicNameHelper::replyTopicTypeName(); - - request.replySlot.invoke(m_objToInform, Qt::QueuedConnection, - QArgument(TopicNameHelper::replyTopicTypeName(), reply.data()), - Q_ARG(int, request.uniqueId), - Q_ARG(bool, !inProgress)); - } - else - { - WARNING_LOG(m_logger) << "reply slot doesn't exist for " << dds::topic::topic_type_name::value(); - } - if (!inProgress) - return; - } - else - WARNING_LOG(m_logger) << "No valid data available "; - - - - } - } - - - void getModernRequestedData(connext::Requester &requester, ModernRequest &request) noexcept(false) - { - -#ifdef WIN32 - const dds::core::Duration MAX_WAIT(200); -#else - const dds::core::Duration MAX_WAIT(20); -#endif - - while (isRun()) - { - connext::Sample reply; - - if (!requester.receive_reply(reply, MAX_WAIT)) - { - WARNING_LOG(m_logger) << "Timeout while waiting for reply!"; - throw std::runtime_error("Timeout while waiting for reply!"); - } - - - - if (!reply.info().valid()) - { - WARNING_LOG(m_logger) << "No valid data available!"; - - throw std::runtime_error("No valid data available!"); - } - - if (request.sample.info().identity() != reply.info()->related_original_publication_virtual_sample_identity()) - { - - INFO_LOG(m_logger) << "#receiveReply - outdated. sample id: " << connext::DebugInfo::toReadable(request.sample.info().identity()) - << ", virutal sample id: " << connext::DebugInfo::toReadable(reply.info()->related_original_publication_virtual_sample_identity()); - continue; - } - - Q_ASSERT(!isInProgress(reply)); - if (isInProgress(reply)) - { - ERROR_LOG(m_logger) << "Used ModernRequest for a request with FtReplyState! Your data will most likely be imcomplete!"; - } - - INFO_LOG(m_logger) << "#receiveReply for " << TopicNameHelper::replyTopicTypeName(); - - request.promise.set_value(reply.data()); - - QTimer::singleShot(0, request.requestWatcher, &Request2::finished); - - return; - - - - } - } - - - void sendErrorInternal(const QMetaMethod &errorSlot, int reason, int uniqueId, int requestId, bool directConnection = false) - { - if (errorSlot.isValid()) - { - errorSlot.invoke(m_objToInform, directConnection ? Qt::DirectConnection : Qt::QueuedConnection, - Q_ARG(int, reason), - Q_ARG(int, uniqueId), - Q_ARG(int, requestId)); - } - } - - - template < typename T = TOPICTYPE_REQUEST, typename std::enable_if < HasRequestId::value, int >::type = 0 > - void sendError(const ClassicRequest &request, int reason, bool directConnection = false) - { - sendErrorInternal(request.errorSlot, reason, request.uniqueId, request.sample.data().requestId(), directConnection); - } - - - template < typename T = TOPICTYPE_REQUEST, typename std::enable_if < !HasRequestId::value, int >::type = 0 > - void sendError(const ClassicRequest &request, int reason, bool directConnection = false) - { - sendErrorInternal(request.errorSlot, reason, request.uniqueId, -1, directConnection); - } - - - bool checkSlots(ClassicRequest &request, const char *replySlot, const char *errorSlot) - { - const QByteArray baReply = QByteArray::number(QSIGNAL_CODE) + - "signalSignature(" + - TopicNameHelper::replyTopicTypeName() + - ",int,bool)"; - request.replySlot = DDS::Helper::getMethod(m_logger, m_objToInform, replySlot, baReply.data()); - if (!request.replySlot.isValid()) - return false; - - if (errorSlot) - { - const QByteArray baError = QByteArray::number(QSIGNAL_CODE) + "signalSignature(int,int,int)"; - request.errorSlot = DDS::Helper::getMethod(m_logger, m_objToInform, errorSlot, baError.data()); - if (!request.errorSlot.isValid()) return false; } - else - request.errorSlot = QMetaMethod(); - return true; - } - + void getRequestedDataClassic(connext::Requester& requester, ClassicRequest& request) + { - - QObject *m_objToInform; - int m_uniqueId { 0 }; +#ifdef WIN32 + const dds::core::Duration MAX_WAIT(200); +#else + const dds::core::Duration MAX_WAIT(20); +#endif - - std::queue > m_modernRequests; - std::queue m_classicRequests; + bool inProgress = true; + while (inProgress && isRun()) + { + DEBUG_LOG(m_logger) << "Waiting for reply "; - connext::RequesterParams m_requesterParams; - bool m_dying { false }; - std::string m_partitionType; - int m_partitionId; - std::mutex m_requestMutex; + connext::Sample reply; + + if (!requester.receive_reply(reply, MAX_WAIT)) + { + WARNING_LOG(m_logger) << "Timed out waiting for reply"; + sendError(request, 3); + return; + } + + if (reply.info().valid()) + { + if (request.sample.info().identity() != + reply.info()->related_original_publication_virtual_sample_identity()) + { + + INFO_LOG(m_logger) << "#receiveReply - outdated. sample id: " + << connext::DebugInfo::toReadable(request.sample.info().identity()) + << ", virutal sample id: " + << connext::DebugInfo::toReadable( + reply.info()->related_original_publication_virtual_sample_identity()); + continue; + } + inProgress = isInProgress(reply); + if (request.replySlot.isValid()) + { + INFO_LOG(m_logger) << "#receiveReply for " << TopicNameHelper::replyTopicTypeName(); + + request.replySlot.invoke(m_objToInform, Qt::QueuedConnection, + QArgument(TopicNameHelper::replyTopicTypeName(), reply.data()), + Q_ARG(int, request.uniqueId), Q_ARG(bool, !inProgress)); + } + else + { + WARNING_LOG(m_logger) + << "reply slot doesn't exist for " << dds::topic::topic_type_name::value(); + } + if (!inProgress) + return; + } + else + WARNING_LOG(m_logger) << "No valid data available "; + } + } + + void getModernRequestedData(connext::Requester& requester, + ModernRequest& request) noexcept(false) + { + +#ifdef WIN32 + const dds::core::Duration MAX_WAIT(200); +#else + const dds::core::Duration MAX_WAIT(20); +#endif + + while (isRun()) + { + connext::Sample reply; + + if (!requester.receive_reply(reply, MAX_WAIT)) + { + WARNING_LOG(m_logger) << "Timeout while waiting for reply!"; + throw std::runtime_error("Timeout while waiting for reply!"); + } + + if (!reply.info().valid()) + { + WARNING_LOG(m_logger) << "No valid data available!"; + + throw std::runtime_error("No valid data available!"); + } + + if (request.sample.info().identity() != + reply.info()->related_original_publication_virtual_sample_identity()) + { + + INFO_LOG(m_logger) << "#receiveReply - outdated. sample id: " + << connext::DebugInfo::toReadable(request.sample.info().identity()) + << ", virutal sample id: " + << connext::DebugInfo::toReadable( + reply.info()->related_original_publication_virtual_sample_identity()); + continue; + } + + Q_ASSERT(!isInProgress(reply)); + if (isInProgress(reply)) + { + ERROR_LOG(m_logger) + << "Used ModernRequest for a request with FtReplyState! Your data will most likely be imcomplete!"; + } + + INFO_LOG(m_logger) << "#receiveReply for " << TopicNameHelper::replyTopicTypeName(); + + request.promise.set_value(reply.data()); + + QTimer::singleShot(0, request.requestWatcher, &Request2::finished); + + return; + } + } + + void sendErrorInternal(const QMetaMethod& errorSlot, int reason, int uniqueId, int requestId, + bool directConnection = false) + { + if (errorSlot.isValid()) + { + errorSlot.invoke(m_objToInform, directConnection ? Qt::DirectConnection : Qt::QueuedConnection, + Q_ARG(int, reason), Q_ARG(int, uniqueId), Q_ARG(int, requestId)); + } + } + + template ::value, int>::type = 0> + void sendError(const ClassicRequest& request, int reason, bool directConnection = false) + { + sendErrorInternal(request.errorSlot, reason, request.uniqueId, request.sample.data().requestId(), + directConnection); + } + + template ::value, int>::type = 0> + void sendError(const ClassicRequest& request, int reason, bool directConnection = false) + { + sendErrorInternal(request.errorSlot, reason, request.uniqueId, -1, directConnection); + } + + bool checkSlots(ClassicRequest& request, const char* replySlot, const char* errorSlot) + { + const QByteArray baReply = QByteArray::number(QSIGNAL_CODE) + "signalSignature(" + + TopicNameHelper::replyTopicTypeName() + ",int,bool)"; + request.replySlot = DDS::Helper::getMethod(m_logger, m_objToInform, replySlot, baReply.data()); + if (!request.replySlot.isValid()) + return false; + + if (errorSlot) + { + const QByteArray baError = QByteArray::number(QSIGNAL_CODE) + "signalSignature(int,int,int)"; + request.errorSlot = DDS::Helper::getMethod(m_logger, m_objToInform, errorSlot, baError.data()); + if (!request.errorSlot.isValid()) + return false; + } + else + request.errorSlot = QMetaMethod(); + return true; + } + + QObject* m_objToInform; + int m_uniqueId{0}; + + std::queue> m_modernRequests; + std::queue m_classicRequests; + + connext::RequesterParams m_requesterParams; + bool m_dying{false}; + std::string m_partitionType; + int m_partitionId; + std::mutex m_requestMutex; }; -} +} // namespace FTC diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/connext.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/connext.h old mode 100755 new mode 100644 index f2eec26a4..27ab6bce8 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/connext.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/connext.h @@ -1,8 +1,8 @@ - #pragma once +#include #include #include #include @@ -16,266 +16,263 @@ #include #include - -#include - namespace connext { namespace DebugInfo { -inline QByteArray toReadable(const rti::core::Guid &guid) +inline QByteArray toReadable(const rti::core::Guid& guid) { - const QByteArray str(reinterpret_cast(&guid[0]), 16); - return str.toHex(); -} -inline QByteArray toReadable(const rti::core::SequenceNumber &seqNo, - const rti::core::Guid &guid) -{ - return "SeqNo: " + QByteArray::number(seqNo.value()) + - ", Guid-DW: " + toReadable(guid); -} -inline QByteArray toReadable(const rti::core::SampleIdentity &identiy) -{ - return toReadable(identiy.sequence_number(), identiy.writer_guid()); -} + const QByteArray str(reinterpret_cast(&guid[0]), 16); + return str.toHex(); } - -template -dds::topic::Topic getTopic(const dds::domain::DomainParticipant &participant, - const std::string &topicName) +inline QByteArray toReadable(const rti::core::SequenceNumber& seqNo, const rti::core::Guid& guid) { - using DataTopic = dds::topic::Topic; - auto ret = dds::topic::find(participant, topicName); - if (ret != nullptr) - return ret; - return DataTopic(participant, topicName); + return "SeqNo: " + QByteArray::number(seqNo.value()) + ", Guid-DW: " + toReadable(guid); } - -template -class SampleBase +inline QByteArray toReadable(const rti::core::SampleIdentity& identiy) { -protected: - SampleBase() = default; - virtual ~SampleBase() = default; + return toReadable(identiy.sequence_number(), identiy.writer_guid()); +} +} // namespace DebugInfo -public: - void set_data(const T &data) - { - m_data = data; - } - T &data() - { - return m_data; - } - const T &data() const - { - return m_data; - } -protected: - T m_data; +template +dds::topic::Topic getTopic(const dds::domain::DomainParticipant& participant, const std::string& topicName) +{ + using DataTopic = dds::topic::Topic; + auto ret = dds::topic::find(participant, topicName); + if (ret != nullptr) + return ret; + return DataTopic(participant, topicName); +} + +template class SampleBase +{ + protected: + SampleBase() = default; + virtual ~SampleBase() = default; + + public: + void set_data(const T& data) + { + m_data = data; + } + + T& data() + { + return m_data; + } + + const T& data() const + { + return m_data; + } + + protected: + T m_data; }; -template -class WriteSample : public SampleBase +template class WriteSample : public SampleBase { -public: - WriteSample() = default; + public: + WriteSample() = default; - void set_info(const rti::pub::WriteParams &info) - { - m_info = info; - } - rti::pub::WriteParams &info() - { - return m_info; - } - const rti::pub::WriteParams &info() const - { - return m_info; - } + void set_info(const rti::pub::WriteParams& info) + { + m_info = info; + } -private: - rti::pub::WriteParams m_info; + rti::pub::WriteParams& info() + { + return m_info; + } + + const rti::pub::WriteParams& info() const + { + return m_info; + } + + private: + rti::pub::WriteParams m_info; }; -template -class WriteSampleRef +template class WriteSampleRef { -public: - WriteSampleRef() - : m_data_ptr(nullptr) - , m_info_ptr(nullptr) - {} + public: + WriteSampleRef() : m_data_ptr(nullptr), m_info_ptr(nullptr) {} - void set_data(T *data_ptr) - { - m_data_ptr = data_ptr; - } + void set_data(T* data_ptr) + { + m_data_ptr = data_ptr; + } - T &data() - { - return *m_data_ptr; - } + T& data() + { + return *m_data_ptr; + } - void set_info(rti::pub::WriteParams *info_ptr) - { - m_info_ptr = info_ptr; - } + void set_info(rti::pub::WriteParams* info_ptr) + { + m_info_ptr = info_ptr; + } - rti::pub::WriteParams &info() - { - return *m_info_ptr; - } + rti::pub::WriteParams& info() + { + return *m_info_ptr; + } -private: - T *m_data_ptr; - rti::pub::WriteParams *m_info_ptr; + private: + T* m_data_ptr; + rti::pub::WriteParams* m_info_ptr; }; -template -class Sample : public SampleBase +template class Sample : public SampleBase { -public: - Sample() = default; + public: + Sample() = default; - void set_info(const dds::sub::SampleInfo &info) - { - m_info = info; - } - dds::sub::SampleInfo &info() - { - return m_info; - } - const dds::sub::SampleInfo &info() const - { - return m_info; - } + void set_info(const dds::sub::SampleInfo& info) + { + m_info = info; + } - void set_identity(const rti::core::SampleIdentity &identity) - { - m_identity = identity; - } + dds::sub::SampleInfo& info() + { + return m_info; + } - const rti::core::SampleIdentity &identity() const - { - return m_identity; - } + const dds::sub::SampleInfo& info() const + { + return m_info; + } -private: - dds::sub::SampleInfo m_info; - rti::core::SampleIdentity m_identity; + void set_identity(const rti::core::SampleIdentity& identity) + { + m_identity = identity; + } + + const rti::core::SampleIdentity& identity() const + { + return m_identity; + } + + private: + dds::sub::SampleInfo m_info; + rti::core::SampleIdentity m_identity; }; class RequesterParams { -public: - explicit RequesterParams(const dds::domain::DomainParticipant &participant) - : m_participant(participant) - , m_publisher(nullptr) - , m_subscriber(nullptr) - {} - virtual ~RequesterParams() = default; + public: + explicit RequesterParams(const dds::domain::DomainParticipant& participant) + : m_participant(participant), m_publisher(nullptr), m_subscriber(nullptr) + { + } - const std::string &request_topic_name() const - { - return m_request_topic_name; - } - void request_topic_name(const std::string &request_topic_name) - { - m_request_topic_name = request_topic_name; - } + virtual ~RequesterParams() = default; - const std::string &reply_topic_name() const - { - return m_reply_topic_name; - } - void reply_topic_name(const std::string &reply_topic_name) - { - m_reply_topic_name = reply_topic_name; - } + const std::string& request_topic_name() const + { + return m_request_topic_name; + } - const dds::domain::DomainParticipant &domainParticipant() const - { - return m_participant; - } + void request_topic_name(const std::string& request_topic_name) + { + m_request_topic_name = request_topic_name; + } - const dds::pub::Publisher &publisher() const - { - return m_publisher; - } - void publisher(const dds::pub::Publisher &publisher) - { - m_publisher = publisher; - } + const std::string& reply_topic_name() const + { + return m_reply_topic_name; + } - const dds::sub::Subscriber &subscriber() const - { - return m_subscriber; - } - void subscriber(const dds::sub::Subscriber &subscriber) - { - m_subscriber = subscriber; - } + void reply_topic_name(const std::string& reply_topic_name) + { + m_reply_topic_name = reply_topic_name; + } - const dds::pub::qos::DataWriterQos &datawriter_qos() const - { - return m_datawriter_qos; - } - void datawriter_qos(const dds::pub::qos::DataWriterQos &datawriter_qos) - { - m_datawriter_qos = datawriter_qos; - } + const dds::domain::DomainParticipant& domainParticipant() const + { + return m_participant; + } - const dds::sub::qos::DataReaderQos &datareader_qos() const - { - return m_datareader_qos; - } - void datareader_qos(const dds::sub::qos::DataReaderQos &datareader_qos) - { - m_datareader_qos = datareader_qos; - } + const dds::pub::Publisher& publisher() const + { + return m_publisher; + } -protected: - dds::domain::DomainParticipant m_participant; - dds::pub::Publisher m_publisher; - dds::sub::Subscriber m_subscriber; - dds::pub::qos::DataWriterQos m_datawriter_qos; - dds::sub::qos::DataReaderQos m_datareader_qos; - std::string m_request_topic_name; - std::string m_reply_topic_name; + void publisher(const dds::pub::Publisher& publisher) + { + m_publisher = publisher; + } + + const dds::sub::Subscriber& subscriber() const + { + return m_subscriber; + } + + void subscriber(const dds::sub::Subscriber& subscriber) + { + m_subscriber = subscriber; + } + + const dds::pub::qos::DataWriterQos& datawriter_qos() const + { + return m_datawriter_qos; + } + + void datawriter_qos(const dds::pub::qos::DataWriterQos& datawriter_qos) + { + m_datawriter_qos = datawriter_qos; + } + + const dds::sub::qos::DataReaderQos& datareader_qos() const + { + return m_datareader_qos; + } + + void datareader_qos(const dds::sub::qos::DataReaderQos& datareader_qos) + { + m_datareader_qos = datareader_qos; + } + + protected: + dds::domain::DomainParticipant m_participant; + dds::pub::Publisher m_publisher; + dds::sub::Subscriber m_subscriber; + dds::pub::qos::DataWriterQos m_datawriter_qos; + dds::sub::qos::DataReaderQos m_datareader_qos; + std::string m_request_topic_name; + std::string m_reply_topic_name; }; -template -class ReplierParams : public RequesterParams +template class ReplierParams : public RequesterParams { -public: - using RequesterParams::RequesterParams; + public: + using RequesterParams::RequesterParams; }; -template -class ReplyRequestBase +template class ReplyRequestBase { -protected: - explicit ReplyRequestBase(const connext::RequesterParams &requesterParams) - : m_requestTopic(getTopic(requesterParams.domainParticipant(), - requesterParams.request_topic_name())) - , m_replyTopic(getTopic(requesterParams.domainParticipant(), - requesterParams.reply_topic_name())) - {} - virtual ~ReplyRequestBase() = default; + protected: + explicit ReplyRequestBase(const connext::RequesterParams& requesterParams) + : m_requestTopic(getTopic(requesterParams.domainParticipant(), requesterParams.request_topic_name())), + m_replyTopic(getTopic(requesterParams.domainParticipant(), requesterParams.reply_topic_name())) + { + } -protected: - dds::topic::Topic m_requestTopic; - dds::topic::Topic m_replyTopic; + virtual ~ReplyRequestBase() = default; + + protected: + dds::topic::Topic m_requestTopic; + dds::topic::Topic m_replyTopic; }; -template -class Requester final : public ReplyRequestBase +template class Requester final : public ReplyRequestBase { -public: + public: explicit Requester(const connext::RequesterParams &requesterParams) : ReplyRequestBase(requesterParams) , m_requesterParams(requesterParams) @@ -284,144 +281,145 @@ public: , m_contentFilteredTopic(nullptr) , m_curInstanceHandle(dds::core::InstanceHandle::nil()) .getNGLLogger("connext.requester")) - {} + { + } void create_contentfilter(bool bNewDataWriter) { - - if (!bNewDataWriter && m_contentFilteredTopic != nullptr) - return; - - rti::core::policy::DataWriterProtocol dwp; - m_dataWriter.qos() >> dwp; - const rti::core::Guid dwGuid = dwp.virtual_guid(); - const QByteArray writerGuid = DebugInfo::toReadable(dwGuid); - const QByteArray filterContent = "@related_sample_identity.writer_guid.value = &hex(" + writerGuid + ")"; - if (m_contentFilteredTopic == nullptr) - { - - const std::string rtName = ReplyRequestBase::m_replyTopic.name(); - const QByteArray filterName(QByteArray::fromRawData(rtName.c_str(), static_cast(rtName.size())) + - QByteArray(" ") + writerGuid); - m_contentFilteredTopic = dds::topic::ContentFilteredTopic(ReplyRequestBase::m_replyTopic, - filterName.data(), - dds::topic::Filter(filterContent.data())); - } - else - { - - m_contentFilteredTopic->filter(dds::topic::Filter(filterContent.data())); - } - DEBUG_LOG(m_logger) << "content filter for topic " - << ReplyRequestBase::m_requestTopic.name() - << " - related_sample_identity should be: " - << writerGuid; + + if (!bNewDataWriter && m_contentFilteredTopic != nullptr) + return; + + rti::core::policy::DataWriterProtocol dwp; + m_dataWriter.qos() >> dwp; + const rti::core::Guid dwGuid = dwp.virtual_guid(); + const QByteArray writerGuid = DebugInfo::toReadable(dwGuid); + const QByteArray filterContent = "@related_sample_identity.writer_guid.value = &hex(" + writerGuid + ")"; + if (m_contentFilteredTopic == nullptr) + { + + const std::string rtName = ReplyRequestBase::m_replyTopic.name(); + const QByteArray filterName(QByteArray::fromRawData(rtName.c_str(), static_cast(rtName.size())) + + QByteArray(" ") + writerGuid); + m_contentFilteredTopic = + dds::topic::ContentFilteredTopic(ReplyRequestBase::m_replyTopic, filterName.data(), + dds::topic::Filter(filterContent.data())); + } + else + { + + m_contentFilteredTopic->filter(dds::topic::Filter(filterContent.data())); + } + DEBUG_LOG(m_logger) << "content filter for topic " << ReplyRequestBase::m_requestTopic.name() + << " - related_sample_identity should be: " << writerGuid; } - void send_request(connext::WriteSample &request) + void send_request(connext::WriteSample& request) { - bool bNewDataWriter = false; - if (m_dataWriter == nullptr) - { - m_dataWriter = dds::pub::DataWriter(m_requesterParams.publisher(), - ReplyRequestBase::m_requestTopic, - m_requesterParams.datawriter_qos()); - bNewDataWriter = true; - } - else - { - - } + bool bNewDataWriter = false; + if (m_dataWriter == nullptr) + { + m_dataWriter = dds::pub::DataWriter(m_requesterParams.publisher(), + ReplyRequestBase::m_requestTopic, + m_requesterParams.datawriter_qos()); + bNewDataWriter = true; + } + else + { + } - create_contentfilter(bNewDataWriter); - - if (m_dataReader == nullptr) - { - - m_dataReader = dds::sub::DataReader(m_requesterParams.subscriber(), - m_contentFilteredTopic, - m_requesterParams.datareader_qos()); - } + create_contentfilter(bNewDataWriter); - m_curInstanceHandle = m_dataWriter.register_instance(request.data()); - request.info().replace_automatic_values(true); - request.info().identity(rti::core::SampleIdentity::automatic()); - m_dataWriter->write(request.data(), request.info()); + if (m_dataReader == nullptr) + { - const rti::core::SampleIdentity currentSampleIdentity = request.info().identity(); - DEBUG_LOG(m_logger) << "send_request for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", m_currentSampleIdentity: " - << DebugInfo::toReadable(currentSampleIdentity); + m_dataReader = dds::sub::DataReader(m_requesterParams.subscriber(), m_contentFilteredTopic, + m_requesterParams.datareader_qos()); + } + + m_curInstanceHandle = m_dataWriter.register_instance(request.data()); + request.info().replace_automatic_values(true); + request.info().identity(rti::core::SampleIdentity::automatic()); + m_dataWriter->write(request.data(), request.info()); + + const rti::core::SampleIdentity currentSampleIdentity = request.info().identity(); + DEBUG_LOG(m_logger) << "send_request for topic " << ReplyRequestBase::m_requestTopic.name() + << ", m_currentSampleIdentity: " << DebugInfo::toReadable(currentSampleIdentity); } - bool receive_reply(connext::Sample &reply, - const dds::core::Duration &duration) + bool receive_reply(connext::Sample& reply, const dds::core::Duration& duration) { - auto condition(dds::sub::cond::ReadCondition(m_dataReader, dds::sub::status::SampleState::not_read())); + auto condition(dds::sub::cond::ReadCondition(m_dataReader, dds::sub::status::SampleState::not_read())); - dds::core::cond::WaitSet waitset; - waitset.attach_condition(condition); + dds::core::cond::WaitSet waitset; + waitset.attach_condition(condition); - bool bRet = false; - while (true) - { - - if (m_dataReader->take(reply.data(), reply.info()) && reply.info().valid()) + bool bRet = false; + while (true) { - DEBUG_LOG(m_logger) << "receive_reply for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", SampleIdentity - original publication virtual: " - << DebugInfo::toReadable(reply.info()->original_publication_virtual_sample_identity()); - DEBUG_LOG(m_logger) << "receive_reply for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", SampleIdentity - related original: " - << DebugInfo::toReadable(reply.info()->related_original_publication_virtual_sample_identity()); + if (m_dataReader->take(reply.data(), reply.info()) && reply.info().valid()) + { + DEBUG_LOG(m_logger) << "receive_reply for topic " + << ReplyRequestBase::m_requestTopic.name() + << ", SampleIdentity - original publication virtual: " + << DebugInfo::toReadable( + reply.info()->original_publication_virtual_sample_identity()); - - bRet = true; - break; + DEBUG_LOG(m_logger) << "receive_reply for topic " + << ReplyRequestBase::m_requestTopic.name() + << ", SampleIdentity - related original: " + << DebugInfo::toReadable( + reply.info()->related_original_publication_virtual_sample_identity()); + + bRet = true; + break; + } + + dds::core::cond::WaitSet::ConditionSeq activeConditionsSeq = waitset.wait(duration); + if (activeConditionsSeq.empty()) + { + ERROR_LOG(m_logger) << "Bailing out!"; + break; + } } - dds::core::cond::WaitSet::ConditionSeq activeConditionsSeq = waitset.wait(duration); - if (activeConditionsSeq.empty()) + static const rti::core::SampleFlag irs(rti::core::SampleFlag::intermediate_reply_sequence()); + if ((reply.info()->flag() & irs) == 0) { - ERROR_LOG(m_logger) << "Bailing out!"; - break; - } - } - - static const rti::core::SampleFlag irs(rti::core::SampleFlag::intermediate_reply_sequence()); - if ((reply.info()->flag() & irs) == 0) - { - if (!m_curInstanceHandle.is_nil()) - { - - DEBUG_LOG(m_logger) << "Keyed topic - disposing instance: " - << ReplyRequestBase::m_requestTopic.name(); - m_dataWriter.dispose_instance(m_curInstanceHandle); - } - } + if (!m_curInstanceHandle.is_nil()) + { - return bRet; + DEBUG_LOG(m_logger) << "Keyed topic - disposing instance: " + << ReplyRequestBase::m_requestTopic.name(); + m_dataWriter.dispose_instance(m_curInstanceHandle); + } + } + + return bRet; } - dds::pub::DataWriter get_request_datawriter() const { return m_dataWriter; } - dds::sub::DataReader get_request_datareader() const { return m_dataReader; } + dds::pub::DataWriter get_request_datawriter() const + { + return m_dataWriter; + } + + dds::sub::DataReader get_request_datareader() const + { + return m_dataReader; + } private: - connext::RequesterParams m_requesterParams; + connext::RequesterParams m_requesterParams; dds::pub::DataWriter m_dataWriter; - dds::sub::DataReader m_dataReader; + dds::sub::DataReader m_dataReader; dds::topic::ContentFilteredTopic m_contentFilteredTopic; - dds::core::InstanceHandle m_curInstanceHandle; + dds::core::InstanceHandle m_curInstanceHandle; }; -template -class Replier final : public ReplyRequestBase +template class Replier final : public ReplyRequestBase { -public: + public: explicit Replier(const connext::ReplierParams &replierParams) : ReplyRequestBase(replierParams) , m_replierParams(replierParams) @@ -432,69 +430,74 @@ public: ReplyRequestBase::m_requestTopic, replierParams.datareader_qos())) .getNGLLogger("connext.replier")) - {} + { + } - void send_reply(connext::WriteSample &reply, - const rti::core::SampleIdentity &identity, + void send_reply(connext::WriteSample& reply, const rti::core::SampleIdentity& identity, bool bLastSample = true) { - connext::WriteSampleRef replyRef; - replyRef.set_data(&reply.data()); - replyRef.set_info(&reply.info()); - return send_reply(replyRef, identity, bLastSample); + connext::WriteSampleRef replyRef; + replyRef.set_data(&reply.data()); + replyRef.set_info(&reply.info()); + return send_reply(replyRef, identity, bLastSample); } - void send_reply(connext::WriteSampleRef &reply, - const rti::core::SampleIdentity &identity, + void send_reply(connext::WriteSampleRef& reply, const rti::core::SampleIdentity& identity, bool bLastSample = true) { - DEBUG_LOG(m_logger) << "send_reply for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", sampleIdentity: " << DebugInfo::toReadable(identity); + DEBUG_LOG(m_logger) << "send_reply for topic " << ReplyRequestBase::m_requestTopic.name() + << ", sampleIdentity: " << DebugInfo::toReadable(identity); - rti::core::SampleFlag sf = reply.info().flag(); - if (bLastSample) - sf &= ~rti::core::SampleFlag::intermediate_reply_sequence(); - else - sf |= rti::core::SampleFlag::intermediate_reply_sequence(); - reply.info().flag(sf); - reply.info().related_sample_identity(identity); - DEBUG_LOG(m_logger) << "send_reply for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", related sampleIdentity: " << DebugInfo::toReadable(reply.info().related_sample_identity()); + rti::core::SampleFlag sf = reply.info().flag(); + if (bLastSample) + sf &= ~rti::core::SampleFlag::intermediate_reply_sequence(); + else + sf |= rti::core::SampleFlag::intermediate_reply_sequence(); + reply.info().flag(sf); + reply.info().related_sample_identity(identity); + DEBUG_LOG(m_logger) << "send_reply for topic " << ReplyRequestBase::m_requestTopic.name() + << ", related sampleIdentity: " + << DebugInfo::toReadable(reply.info().related_sample_identity()); - m_dataWriter->write(reply.data(), reply.info()); + m_dataWriter->write(reply.data(), reply.info()); } - bool receive_request(connext::Sample &request) + bool receive_request(connext::Sample& request) { - if (!m_dataReader->take(request.data(), request.info())) - return false; + if (!m_dataReader->take(request.data(), request.info())) + return false; - if (request.info().valid()) - { - DEBUG_LOG(m_logger) << "receive_request for topic " - << ReplyRequestBase::m_requestTopic.name() - << ", sampleIdentity publication_virtual_sample_identity: " - << DebugInfo::toReadable(request.info()->publication_virtual_sample_identity()) - << ", original_publication_virtual_sample_identity: " - << DebugInfo::toReadable(request.info()->original_publication_virtual_sample_identity()) - << ", related_original_publication_virtual_sample_identity: " - << DebugInfo::toReadable(request.info()->related_original_publication_virtual_sample_identity()) - << " with timestamp_ " << request.info().source_timestamp().to_millisecs(); - request.set_identity(request.info()->original_publication_virtual_sample_identity()); - } + if (request.info().valid()) + { + DEBUG_LOG(m_logger) << "receive_request for topic " << ReplyRequestBase::m_requestTopic.name() + << ", sampleIdentity publication_virtual_sample_identity: " + << DebugInfo::toReadable(request.info()->publication_virtual_sample_identity()) + << ", original_publication_virtual_sample_identity: " + << DebugInfo::toReadable(request.info()->original_publication_virtual_sample_identity()) + << ", related_original_publication_virtual_sample_identity: " + << DebugInfo::toReadable( + request.info()->related_original_publication_virtual_sample_identity()) + << " with timestamp_ " << request.info().source_timestamp().to_millisecs(); + request.set_identity(request.info()->original_publication_virtual_sample_identity()); + } - return request.info().valid(); + return request.info().valid(); } - dds::pub::DataWriter get_request_datawriter() const { return m_dataWriter; } - dds::sub::DataReader get_request_datareader() const { return m_dataReader; } + dds::pub::DataWriter get_request_datawriter() const + { + return m_dataWriter; + } + + dds::sub::DataReader get_request_datareader() const + { + return m_dataReader; + } private: connext::ReplierParams m_replierParams; - dds::pub::DataWriter m_dataWriter; - dds::sub::DataReader m_dataReader; + dds::pub::DataWriter m_dataWriter; + dds::sub::DataReader m_dataReader; }; -} +} // namespace connext diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/generic_fts_impl.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/generic_fts_impl.h old mode 100755 new mode 100644 index 655d263ef..bfdda81ed --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/generic_fts_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/FTS/generic_fts_impl.h @@ -2,18 +2,17 @@ #pragma once -#include - -#include "generic_fts_internal.h" #include "connext.h" -#include +#include "generic_fts_internal.h" + +#include #include #include - +#include #include +#include #include #include -#include #ifndef tr_lts #define tr_lts(ctx, t) (t) @@ -21,265 +20,238 @@ namespace FTS { -template -class HasStatusFunction +template class HasStatusFunction { - template - static std::true_type testSignature(void (T::*)(const Core::FtReplyState&)); + template static std::true_type testSignature(void (T::*)(const Core::FtReplyState&)); - template - static decltype(testSignature(&T::replyState)) test(std::nullptr_t); + template static decltype(testSignature(&T::replyState)) test(std::nullptr_t); - template - static std::false_type test(...); + template static std::false_type test(...); -public: - using type = decltype(test(nullptr)); - static const bool value = type::value; + public: + using type = decltype(test(nullptr)); + static const bool value = type::value; }; -template -struct TopicNames; +template struct TopicNames; -template -class GenericFtsImpl final : public GenericFts - , public GenericFtsInternal +template +class GenericFtsImpl final : public GenericFts, public GenericFtsInternal { -public: - using RequestTopic = TOPICTYPE_REQUEST; - using ReplyTopic = TOPICTYPE_REPLY; - using TopicNameHelper = TopicNames>; -private: - using SubscriberCallback = std::function; + public: + using RequestTopic = TOPICTYPE_REQUEST; + using ReplyTopic = TOPICTYPE_REPLY; + using TopicNameHelper = TopicNames>; - template ::value, int>::type = 0> - void sendReplyState(Core::FtReplyState replyState, const rti::core::SampleIdentity &requestSampleIdentity) - { - connext::WriteSample reply; - reply.data().replyState(replyState); + private: + using SubscriberCallback = std::function; - bool bLastTelegram = ((replyState != Core::FtReplyState_def::InProgress) && - (replyState != Core::FtReplyState_def::NotStarted)); - m_replier->send_reply(reply, requestSampleIdentity, bLastTelegram); - } - - template ::value, int>::type = 0> - void sendReplyState(Core::FtReplyState, const rti::core::SampleIdentity &) - { - - } - - template ::value, int>::type = 0> - void setReply(T &data, Core::FtReplyState status) - { - data.replyState(status); - } - - template ::value, int>::type = 0> - void setReply(T &, Core::FtReplyState) - { - - } - -public: - GenericFtsImpl(const dds::domain::DomainParticipant &domainParticipant, - const dds::pub::Publisher &ddsPublisher, - const dds::sub::Subscriber &ddsSubscriber, - DDSGeneric::WaitSetHandler *wsHandler) - : GenericFts() - , GenericFtsInternal() - , m_wsHandler(wsHandler) - , m_subscriberCallback(nullptr) - , m_logger(DDS::getLogger(TopicNameHelper::functionTopicName(), DDS::DataType::FUNCTION_TOPIC_SERVER)) - { - Q_ASSERT(domainParticipant != nullptr); - Q_ASSERT(ddsPublisher != nullptr); - Q_ASSERT(ddsSubscriber != nullptr); - Q_ASSERT(wsHandler != nullptr); - - qRegisterMetaType (TopicNameHelper::requestTopicTypeName()); - - connext::ReplierParams replierParams(domainParticipant); - - - - - replierParams.request_topic_name(TopicNameHelper::requestTopicName()); - replierParams.reply_topic_name(TopicNameHelper::replyTopicName()); - replierParams.publisher(ddsPublisher); - replierParams.subscriber(ddsSubscriber); - replierParams.datareader_qos(readerQos(m_logger)); - replierParams.datawriter_qos(writerQos(m_logger)); - - - - - m_replier = new connext::Replier(replierParams); - m_readCondition = new dds::sub::cond::ReadCondition(m_replier->get_request_datareader(), dds::sub::status::SampleState::not_read()); - - m_wsHandler->attachWaitSet(*m_readCondition, this); - } - - ~GenericFtsImpl() - { - m_wsHandler->detachWaitSet(*m_readCondition, this); - delete m_readCondition; - delete m_replier; - } - - bool setSubscriberCallback(const SubscriberCallback &subscriberCallback) - { - if (m_subscriberCallback) + template ::value, int>::type = 0> + void sendReplyState(Core::FtReplyState replyState, const rti::core::SampleIdentity& requestSampleIdentity) { - WARNING_LOG(m_logger) << "Can not set subscriber callback - already set ..."; - return false; + connext::WriteSample reply; + reply.data().replyState(replyState); + + bool bLastTelegram = + ((replyState != Core::FtReplyState_def::InProgress) && (replyState != Core::FtReplyState_def::NotStarted)); + m_replier->send_reply(reply, requestSampleIdentity, bLastTelegram); } - m_subscriberCallback = subscriberCallback; - return true; - } - - - - bool sendReply(const rti::core::SampleIdentity &requestSampleIdentity, const ReplyTopic &replyData) override final - { - connext::WriteSampleRef reply; - rti::pub::WriteParams replyParams; - - reply.set_data(const_cast(&replyData)); - reply.set_info(&replyParams); - - m_replier->send_reply(reply, requestSampleIdentity); - return true; - } - - - - bool sendReply(const rti::core::SampleIdentity &requestIdentity, const QVector &replyData) override final - { - DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - IN sendReply"; - - for(int i = 0; i < replyData.size(); ++i) + template ::value, int>::type = 0> + void sendReplyState(Core::FtReplyState, const rti::core::SampleIdentity&) { - if (HasStatusFunction::value) - { - ReplyTopic rt = replyData.at(i); - setReply(rt, i == replyData.size() - 1 ? Core::FtReplyState::Completed : Core::FtReplyState::InProgress); - if (!sendReply(requestIdentity, rt)) - return false; - } else { - if (!sendReply(requestIdentity, replyData.at(i))) - return false; - } } - return true; - } - -protected: - - - - - - void processRequest(const connext::Sample &request) - { - DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - processRequest: " - << connext::DebugInfo::toReadable(request.identity()); - - qint64 age = qAbs(qint64(request.info().source_timestamp().to_secs()) - time(nullptr)); - - if (age > 10) + template ::value, int>::type = 0> + void setReply(T& data, Core::FtReplyState status) { - std::ostringstream ss; - ss << request.data(); - std::string s = ss.str(); - int slen = s.length(); - - static int max_slen = 1024; - if (slen > max_slen) - { - s.resize(max_slen); - s.append("..."); - } - - DEBUG_LOG(m_logger) << "received a request for topic " - << TopicNameHelper::requestTopicName() - << " but it was outdated - ignoring. " - << " local time: " << (time(nullptr) - 10) << "[s], source timestamp: " - << qint64(request.info().source_timestamp().to_secs()) - << "[s], -> age: " << age - << "[s], data: " << s; - ReplyTopic rt; - rt.errorString(tr_lts("dds", "Topic %1 was outdated and therefore ignored. Does the client time match the server time?")); - rt.errorParams({TopicNameHelper::requestTopicName()}); - sendReply(request.identity(), rt); - return; + data.replyState(status); } - sendReplyState(Core::FtReplyState::InProgress, request.identity()); - - m_subscriberCallback(request.identity(), request.data()); - } - - - - void processRequests() override - { - DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - processRequests"; - - while (true) + template ::value, int>::type = 0> + void setReply(T&, Core::FtReplyState) { - connext::Sample request; - { - std::lock_guard l(m_requestMutex); - if (m_requests.empty()) + } + + public: + GenericFtsImpl(const dds::domain::DomainParticipant& domainParticipant, const dds::pub::Publisher& ddsPublisher, + const dds::sub::Subscriber& ddsSubscriber, DDSGeneric::WaitSetHandler* wsHandler) + : GenericFts(), GenericFtsInternal(), m_wsHandler(wsHandler), + m_subscriberCallback(nullptr), + m_logger(DDS::getLogger(TopicNameHelper::functionTopicName(), DDS::DataType::FUNCTION_TOPIC_SERVER)) + { + Q_ASSERT(domainParticipant != nullptr); + Q_ASSERT(ddsPublisher != nullptr); + Q_ASSERT(ddsSubscriber != nullptr); + Q_ASSERT(wsHandler != nullptr); + + qRegisterMetaType(TopicNameHelper::requestTopicTypeName()); + + connext::ReplierParams replierParams(domainParticipant); + + replierParams.request_topic_name(TopicNameHelper::requestTopicName()); + replierParams.reply_topic_name(TopicNameHelper::replyTopicName()); + replierParams.publisher(ddsPublisher); + replierParams.subscriber(ddsSubscriber); + replierParams.datareader_qos(readerQos(m_logger)); + replierParams.datawriter_qos(writerQos(m_logger)); + + m_replier = new connext::Replier(replierParams); + m_readCondition = new dds::sub::cond::ReadCondition(m_replier->get_request_datareader(), + dds::sub::status::SampleState::not_read()); + + m_wsHandler->attachWaitSet(*m_readCondition, this); + } + + ~GenericFtsImpl() + { + m_wsHandler->detachWaitSet(*m_readCondition, this); + delete m_readCondition; + delete m_replier; + } + + bool setSubscriberCallback(const SubscriberCallback& subscriberCallback) + { + if (m_subscriberCallback) { - DEBUG_LOG(m_logger) << "No more requests"; - return; + WARNING_LOG(m_logger) << "Can not set subscriber callback - already set ..."; + return false; } - DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - read one request for "; - request = m_requests.front(); - m_requests.pop(); - } - if (!request.info().valid()) - { - WARNING_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - No valid data"; - continue; - } - processRequest(request); - } - DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - processRequests finished"; - } - bool enqueueRequests() override - { - bool bValidDataRead = false; - connext::Sample request; - while (m_replier->receive_request(request)) + m_subscriberCallback = subscriberCallback; + return true; + } + + bool sendReply(const rti::core::SampleIdentity& requestSampleIdentity, const ReplyTopic& replyData) override final { - if (!request.info().valid()) - continue; - bValidDataRead = true; - std::lock_guard l(m_requestMutex); - m_requests.push(request); + connext::WriteSampleRef reply; + rti::pub::WriteParams replyParams; + + reply.set_data(const_cast(&replyData)); + reply.set_info(&replyParams); + + m_replier->send_reply(reply, requestSampleIdentity); + return true; } - return bValidDataRead; - } -private: - - connext::Replier *m_replier; - dds::sub::cond::ReadCondition *m_readCondition; + bool sendReply(const rti::core::SampleIdentity& requestIdentity, + const QVector& replyData) override final + { + DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - IN sendReply"; - - DDSGeneric::WaitSetHandler *m_wsHandler; + for (int i = 0; i < replyData.size(); ++i) + { + if (HasStatusFunction::value) + { + ReplyTopic rt = replyData.at(i); + setReply(rt, + i == replyData.size() - 1 ? Core::FtReplyState::Completed : Core::FtReplyState::InProgress); + if (!sendReply(requestIdentity, rt)) + return false; + } + else + { + if (!sendReply(requestIdentity, replyData.at(i))) + return false; + } + } - std::queue> m_requests; - std::mutex m_requestMutex; + return true; + } - - SubscriberCallback m_subscriberCallback; + protected: + void processRequest(const connext::Sample& request) + { + DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() + << " - processRequest: " << connext::DebugInfo::toReadable(request.identity()); + + qint64 age = qAbs(qint64(request.info().source_timestamp().to_secs()) - time(nullptr)); + + if (age > 10) + { + std::ostringstream ss; + ss << request.data(); + std::string s = ss.str(); + int slen = s.length(); + + static int max_slen = 1024; + if (slen > max_slen) + { + s.resize(max_slen); + s.append("..."); + } + + DEBUG_LOG(m_logger) << "received a request for topic " << TopicNameHelper::requestTopicName() + << " but it was outdated - ignoring. " + << " local time: " << (time(nullptr) - 10) + << "[s], source timestamp: " << qint64(request.info().source_timestamp().to_secs()) + << "[s], -> age: " << age << "[s], data: " << s; + ReplyTopic rt; + rt.errorString(tr_lts( + "dds", "Topic %1 was outdated and therefore ignored. Does the client time match the server time?")); + rt.errorParams({TopicNameHelper::requestTopicName()}); + sendReply(request.identity(), rt); + return; + } + + sendReplyState(Core::FtReplyState::InProgress, request.identity()); + + m_subscriberCallback(request.identity(), request.data()); + } + + void processRequests() override + { + DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - processRequests"; + + while (true) + { + connext::Sample request; + { + std::lock_guard l(m_requestMutex); + if (m_requests.empty()) + { + DEBUG_LOG(m_logger) << "No more requests"; + return; + } + DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - read one request for "; + request = m_requests.front(); + m_requests.pop(); + } + if (!request.info().valid()) + { + WARNING_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - No valid data"; + continue; + } + processRequest(request); + } + DEBUG_LOG(m_logger) << TopicNameHelper::requestTopicName() << " - processRequests finished"; + } + + bool enqueueRequests() override + { + bool bValidDataRead = false; + connext::Sample request; + while (m_replier->receive_request(request)) + { + if (!request.info().valid()) + continue; + bValidDataRead = true; + std::lock_guard l(m_requestMutex); + m_requests.push(request); + } + return bValidDataRead; + } + + private: + connext::Replier* m_replier; + dds::sub::cond::ReadCondition* m_readCondition; + + DDSGeneric::WaitSetHandler* m_wsHandler; + + std::queue> m_requests; + std::mutex m_requestMutex; + + SubscriberCallback m_subscriberCallback; }; -} +} // namespace FTS diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/dynamic_data_reader.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/dynamic_data_reader.h old mode 100755 new mode 100644 index b4a08228d..2f06a6832 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/dynamic_data_reader.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/dynamic_data_reader.h @@ -1,353 +1,336 @@ - #pragma once +#include +#include +#include #include #include #include #include #include - -#include -#include -#include #include namespace DDSGeneric { -using StructType = dds::core::xtypes::StructType; +using StructType = dds::core::xtypes::StructType; using DynamicData = dds::core::xtypes::DynamicData; class DynamicDataReader final { -public: + public: + using TopicType = DynamicData; + using DataReader = dds::sub::DataReader; + using DataTopic = dds::topic::Topic; - using TopicType = DynamicData; - using DataReader = dds::sub::DataReader; - using DataTopic = dds::topic::Topic; + using SubscriberCallback = std::function; + using SubscriberCallbackWithSampleInfo = + std::function; - using SubscriberCallback = std::function; - using SubscriberCallbackWithSampleInfo = std::function; - - DynamicDataReader() - : m_dataReader(nullptr) - , m_structType(nullptr) - , m_ddsTopic(nullptr) - , m_bHaveSubscriberCallback(false) - , m_logger(DDS::getLogger("DynamicDataReader", DDS::DataType::DYNAMIC_DATA_READER)) - {} - - ~DynamicDataReader() - { - m_ddsTopic = nullptr; - m_dataReader = nullptr; - delete m_structType; - } - - const DataReader &getDataReader() const { return m_dataReader; } - const StructType &getStructType() const { return *m_structType; } - - bool create(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - const std::string &specialTopicName, - const StructType &structType) - { - DEBUG_LOG(m_logger) << "IN DynamicDataReader::create (" - << m_structType->name() - << ")"; - - if (domainParticipant == nullptr) + DynamicDataReader() + : m_dataReader(nullptr), m_structType(nullptr), m_ddsTopic(nullptr), m_bHaveSubscriberCallback(false), + m_logger(DDS::getLogger("DynamicDataReader", DDS::DataType::DYNAMIC_DATA_READER)) { - ERROR_LOG(m_logger) << "DomainParticipant does not exist "; - return false; } - if (m_ddsTopic != nullptr) + ~DynamicDataReader() { - ERROR_LOG(m_logger) << "Type '" - << m_structType->name() - << "' already created"; - return false; + m_ddsTopic = nullptr; + m_dataReader = nullptr; + delete m_structType; } - if (structType.has_parent()) - m_structType = new dds::core::xtypes::StructType(structType.name(), structType.parent(), structType.members()); - else - m_structType = new dds::core::xtypes::StructType(structType.name(), structType.members()); - - try + const DataReader& getDataReader() const { - - - const std::string topicName = specialTopicName.empty() ? - DDS::Helper::getShortTopicName(m_structType->name()) : - specialTopicName; - - DEBUG_LOG(m_logger) << "Creating topic " << topicName << " with type: " - << m_structType->name(); - - m_ddsTopic = dds::topic::find>(domainParticipant, topicName); - if (m_ddsTopic == nullptr) - { - rti::core::xtypes::DynamicDataTypeSerializationProperty serialization_property; - serialization_property.min_size_serialized(0); - dds::domain::DomainParticipant dp = domainParticipant; - rti::domain::register_type(dp, structType.name(), structType, serialization_property); - m_ddsTopic = dds::topic::Topic(domainParticipant, topicName, structType); - } - - DEBUG_LOG(m_logger) << "m_ddsTopic created: " << m_ddsTopic.name(); - - if (m_logger.isDebugEnabled()) - { - dds::sub::qos::SubscriberQos subscriberQoS = ddsSubscriber.qos(); - dds::core::policy::Partition partition = subscriberQoS.policy(); - dds::core::StringSeq parititionNames = partition.name(); - DEBUG_LOG(m_logger) << "Subscribing partitions: " << parititionNames.size(); - for (const std::string &name : parititionNames) - DEBUG_LOG(m_logger) << "SubscriberQoS: partition name = " << name; - } - - dds::sub::qos::DataReaderQos dataReaderQos = ddsSubscriber.default_datareader_qos(); - - QString typeName = QString::fromStdString(m_structType->name()); - if (typeName.endsWith(QLatin1String("Request")) || typeName.endsWith(QLatin1String("Reply"))) - { - - dds::core::policy::Durability readerDurability; - dataReaderQos >> readerDurability; - readerDurability.kind(dds::core::policy::DurabilityKind_def::VOLATILE); - dataReaderQos << readerDurability; - } - - m_dataReader = DataReader(ddsSubscriber, - m_ddsTopic, - dataReaderQos, - nullptr , - dds::core::status::StatusMask::all()); - - if (m_dataReader == nullptr) - { - ERROR_LOG(m_logger) << "Creating dataReader for '" << topicName << "' with type: '" - << m_structType->name() - << "' failed"; - return false; - } - - } - catch (const dds::core::Exception &ex) - { - ERROR_LOG(m_logger) << ex.what(); - return false; + return m_dataReader; } - DEBUG_LOG(m_logger) << "dataReader created (" - << m_structType->name() - << ")"; - - return true; - } - - - bool hasSamples() const - { - qint64 sampleSize = m_dataReader->datareader_cache_status().sample_count(); - DEBUG_LOG(m_logger) << "sampleSize = " << sampleSize; - return sampleSize > 0; - } - - - dds::sub::LoanedSamples readAlive(bool &bSeenNewSamples) - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::alive()).read(); - TRACE_LOG(m_logger) << "readAlive for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - bSeenNewSamples = checkNewSamples(samples); - return samples; - } - - - dds::sub::LoanedSamples takeAlive(bool &bSeenNewSamples) - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::alive()).take(); - TRACE_LOG(m_logger) << "takeAlive for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - bSeenNewSamples = checkNewSamples(samples); - return samples; - } - - dds::sub::LoanedSamples takeDisposed() - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::not_alive_disposed()).take(); - TRACE_LOG(m_logger) << "takeDisposed for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - return samples; - } - - template - bool read(C callbackFunc) - { - DEBUG_LOG(m_logger) << "IN read (" - << DDS::topic_type_name::value() - << "), this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - if (m_dataReader == nullptr || m_ddsTopic == nullptr) + const StructType& getStructType() const { - ERROR_LOG(m_logger) << "No dataReader initialised "; - return false; - } - if (!isValid(callbackFunc)) - { - ERROR_LOG(m_logger) << "No subscriber set for " - << DDS::topic_type_name::value(); - return false; + return *m_structType; } - - - dds::sub::LoanedSamples samples = m_dataReader.select().state(dds::sub::status::DataState::new_data()).read(); - - DEBUG_LOG(m_logger) << "got " << samples.length() + m_newSamplesDuringRead.size() << " samples from reader for " - << DDS::topic_type_name::value(); - - for (const auto &sample : samples) + bool create(const dds::domain::DomainParticipant& domainParticipant, const dds::sub::Subscriber& ddsSubscriber, + const std::string& specialTopicName, const StructType& structType) { - if (sample.info().valid()) - readData(sample, m_dataReader->topic_name(), callbackFunc); - } - - auto copy = m_newSamplesDuringRead; - - m_newSamplesDuringRead.clear(); - for (auto &sample : copy) - { - - readData(rti::sub::LoanedSample(sample.sample, &sample.info), m_dataReader->topic_name(), callbackFunc); - delete sample.sample; + DEBUG_LOG(m_logger) << "IN DynamicDataReader::create (" << m_structType->name() << ")"; + + if (domainParticipant == nullptr) + { + ERROR_LOG(m_logger) << "DomainParticipant does not exist "; + return false; + } + + if (m_ddsTopic != nullptr) + { + ERROR_LOG(m_logger) << "Type '" << m_structType->name() << "' already created"; + return false; + } + + if (structType.has_parent()) + m_structType = + new dds::core::xtypes::StructType(structType.name(), structType.parent(), structType.members()); + else + m_structType = new dds::core::xtypes::StructType(structType.name(), structType.members()); + + try + { + + const std::string topicName = + specialTopicName.empty() ? DDS::Helper::getShortTopicName(m_structType->name()) : specialTopicName; + + DEBUG_LOG(m_logger) << "Creating topic " << topicName << " with type: " << m_structType->name(); + + m_ddsTopic = dds::topic::find>(domainParticipant, topicName); + if (m_ddsTopic == nullptr) + { + rti::core::xtypes::DynamicDataTypeSerializationProperty serialization_property; + serialization_property.min_size_serialized(0); + dds::domain::DomainParticipant dp = domainParticipant; + rti::domain::register_type(dp, structType.name(), structType, serialization_property); + m_ddsTopic = dds::topic::Topic(domainParticipant, topicName, structType); + } + + DEBUG_LOG(m_logger) << "m_ddsTopic created: " << m_ddsTopic.name(); + + if (m_logger.isDebugEnabled()) + { + dds::sub::qos::SubscriberQos subscriberQoS = ddsSubscriber.qos(); + dds::core::policy::Partition partition = subscriberQoS.policy(); + dds::core::StringSeq parititionNames = partition.name(); + DEBUG_LOG(m_logger) << "Subscribing partitions: " << parititionNames.size(); + for (const std::string& name : parititionNames) + DEBUG_LOG(m_logger) << "SubscriberQoS: partition name = " << name; + } + + dds::sub::qos::DataReaderQos dataReaderQos = ddsSubscriber.default_datareader_qos(); + + QString typeName = QString::fromStdString(m_structType->name()); + if (typeName.endsWith(QLatin1String("Request")) || typeName.endsWith(QLatin1String("Reply"))) + { + + dds::core::policy::Durability readerDurability; + dataReaderQos >> readerDurability; + readerDurability.kind(dds::core::policy::DurabilityKind_def::VOLATILE); + dataReaderQos << readerDurability; + } + + m_dataReader = + DataReader(ddsSubscriber, m_ddsTopic, dataReaderQos, nullptr, dds::core::status::StatusMask::all()); + + if (m_dataReader == nullptr) + { + ERROR_LOG(m_logger) << "Creating dataReader for '" << topicName << "' with type: '" + << m_structType->name() << "' failed"; + return false; + } + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(m_logger) << ex.what(); + return false; + } + + DEBUG_LOG(m_logger) << "dataReader created (" << m_structType->name() << ")"; + + return true; } - return checkDisposedInstances(callbackFunc); - } + bool hasSamples() const + { + qint64 sampleSize = m_dataReader->datareader_cache_status().sample_count(); + DEBUG_LOG(m_logger) << "sampleSize = " << sampleSize; + return sampleSize > 0; + } - void setHaveSubscriberCallback(bool bHave) - { - m_bHaveSubscriberCallback = bHave; - } - std::string topicName() const - { - return m_ddsTopic.name(); - } + dds::sub::LoanedSamples readAlive(bool& bSeenNewSamples) + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::alive()).read(); + TRACE_LOG(m_logger) << "readAlive for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); - void recreateReader() - { - if (m_dataReader == nullptr) - return; - m_dataReader = DataReader(m_dataReader.subscriber(), m_ddsTopic); - } + bSeenNewSamples = checkNewSamples(samples); + return samples; + } -private: + dds::sub::LoanedSamples takeAlive(bool& bSeenNewSamples) + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::alive()).take(); + TRACE_LOG(m_logger) << "takeAlive for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); + + bSeenNewSamples = checkNewSamples(samples); + return samples; + } + + dds::sub::LoanedSamples takeDisposed() + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::not_alive_disposed()).take(); + TRACE_LOG(m_logger) << "takeDisposed for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); + return samples; + } + + template bool read(C callbackFunc) + { + DEBUG_LOG(m_logger) << "IN read (" << DDS::topic_type_name::value() << "), this: " << this + << ", instance handle " << m_dataReader.instance_handle(); + + if (m_dataReader == nullptr || m_ddsTopic == nullptr) + { + ERROR_LOG(m_logger) << "No dataReader initialised "; + return false; + } + if (!isValid(callbackFunc)) + { + ERROR_LOG(m_logger) << "No subscriber set for " << DDS::topic_type_name::value(); + return false; + } + + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::DataState::new_data()).read(); + + DEBUG_LOG(m_logger) << "got " << samples.length() + m_newSamplesDuringRead.size() << " samples from reader for " + << DDS::topic_type_name::value(); + + for (const auto& sample : samples) + { + if (sample.info().valid()) + readData(sample, m_dataReader->topic_name(), callbackFunc); + } + + auto copy = m_newSamplesDuringRead; + + m_newSamplesDuringRead.clear(); + for (auto& sample : copy) + { + + readData(rti::sub::LoanedSample(sample.sample, &sample.info), m_dataReader->topic_name(), + callbackFunc); + delete sample.sample; + } + + return checkDisposedInstances(callbackFunc); + } + + void setHaveSubscriberCallback(bool bHave) + { + m_bHaveSubscriberCallback = bHave; + } + + std::string topicName() const + { + return m_ddsTopic.name(); + } + + void recreateReader() + { + if (m_dataReader == nullptr) + return; + m_dataReader = DataReader(m_dataReader.subscriber(), m_ddsTopic); + } + + private: #if RTI_DDS_VERSION_MAJOR < 6 - inline bool checkNewSamples(dds::sub::LoanedSamples &samples) + inline bool checkNewSamples(dds::sub::LoanedSamples& samples) #else - inline bool checkNewSamples(const dds::sub::LoanedSamples &samples) + inline bool checkNewSamples(const dds::sub::LoanedSamples& samples) #endif - { - - if (!m_bHaveSubscriberCallback) - return false; - - bool bSeenNewSamples = false; - for (const auto &sample : samples) { - const dds::sub::status::DataState ds = sample.info()->state(); - if (ds.view_state() == dds::sub::status::ViewState::new_view() || - ds.sample_state() == dds::sub::status::SampleState::not_read()) - { - SampleStruct ss; - ss.sample = new DynamicData(sample.data()); - ss.info = sample.info(); - - m_newSamplesDuringRead.emplace_back(ss); - bSeenNewSamples = true; - } - } - return bSeenNewSamples; - } + if (!m_bHaveSubscriberCallback) + return false; - template - bool checkDisposedInstances(C callbackFunc) - { - const dds::sub::status::DataState ds(dds::sub::status::SampleState::any(), - dds::sub::status::ViewState::any(), - dds::sub::status::InstanceState::not_alive_mask()); + bool bSeenNewSamples = false; + for (const auto& sample : samples) + { + const dds::sub::status::DataState ds = sample.info()->state(); + if (ds.view_state() == dds::sub::status::ViewState::new_view() || + ds.sample_state() == dds::sub::status::SampleState::not_read()) + { + SampleStruct ss; + ss.sample = new DynamicData(sample.data()); + ss.info = sample.info(); - - dds::sub::LoanedSamples samples = m_dataReader.select().state(ds).take(); + m_newSamplesDuringRead.emplace_back(ss); - if (samples.length() == 0) - return false; - - DEBUG_LOG(m_logger) << "got " << samples.length() << " disposed instances from reader for " - << m_ddsTopic.name(); - - for (const auto &sample : samples) - { - if (sample.info().valid()) - readData(sample, m_dataReader->topic_name(), callbackFunc); + bSeenNewSamples = true; + } + } + return bSeenNewSamples; } - return true; - } + template bool checkDisposedInstances(C callbackFunc) + { + const dds::sub::status::DataState ds(dds::sub::status::SampleState::any(), dds::sub::status::ViewState::any(), + dds::sub::status::InstanceState::not_alive_mask()); - static void readData(const rti::sub::LoanedSample &sample, const std::string &topicName, const SubscriberCallback &callbackFunc) - { - DataModification modType = DataModification::eModified; - const dds::sub::status::DataState ds = sample.info()->state(); - if (ds.view_state() == dds::sub::status::ViewState::new_view()) - modType = DataModification::eAdded; - if (ds.instance_state() != dds::sub::status::InstanceState::alive()) - modType = DataModification::eRemoved; - + dds::sub::LoanedSamples samples = m_dataReader.select().state(ds).take(); - callbackFunc(sample.data(), topicName, modType); - } + if (samples.length() == 0) + return false; - static void readData(const rti::sub::LoanedSample &sample, const std::string &topicName, const SubscriberCallbackWithSampleInfo &callbackFunc) - { - callbackFunc(sample.data(), topicName, sample.info()); - } + DEBUG_LOG(m_logger) << "got " << samples.length() << " disposed instances from reader for " + << m_ddsTopic.name(); - static bool isValid(const SubscriberCallback &callbackFunc) - { - return callbackFunc != nullptr; - } - static bool isValid(const SubscriberCallbackWithSampleInfo &callbackFunc) - { - return callbackFunc != nullptr; - } + for (const auto& sample : samples) + { + if (sample.info().valid()) + readData(sample, m_dataReader->topic_name(), callbackFunc); + } -private: - DataReader m_dataReader; - StructType *m_structType; - DataTopic m_ddsTopic; + return true; + } - struct SampleStruct - { - DynamicData *sample = nullptr; - dds::sub::SampleInfo info; - }; - std::vector m_newSamplesDuringRead; - bool m_bHaveSubscriberCallback; + static void readData(const rti::sub::LoanedSample& sample, const std::string& topicName, + const SubscriberCallback& callbackFunc) + { + DataModification modType = DataModification::eModified; + const dds::sub::status::DataState ds = sample.info()->state(); + if (ds.view_state() == dds::sub::status::ViewState::new_view()) + modType = DataModification::eAdded; + if (ds.instance_state() != dds::sub::status::InstanceState::alive()) + modType = DataModification::eRemoved; + + callbackFunc(sample.data(), topicName, modType); + } + + static void readData(const rti::sub::LoanedSample& sample, const std::string& topicName, + const SubscriberCallbackWithSampleInfo& callbackFunc) + { + callbackFunc(sample.data(), topicName, sample.info()); + } + + static bool isValid(const SubscriberCallback& callbackFunc) + { + return callbackFunc != nullptr; + } + + static bool isValid(const SubscriberCallbackWithSampleInfo& callbackFunc) + { + return callbackFunc != nullptr; + } + + private: + DataReader m_dataReader; + StructType* m_structType; + DataTopic m_ddsTopic; + + struct SampleStruct + { + DynamicData* sample = nullptr; + dds::sub::SampleInfo info; + }; + + std::vector m_newSamplesDuringRead; + bool m_bHaveSubscriberCallback; }; -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_reader.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_reader.h old mode 100755 new mode 100644 index 36c643799..025ec8fd8 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_reader.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_reader.h @@ -1,381 +1,369 @@ - #pragma once -#include -#include -#include - #include #include #include +#include +#include +#include #include namespace DDSGeneric { -template -class GenericDataReader +template class GenericDataReader { -public: - using TopicType = TOPICTYPE; - using TopicTypeRead = TOPICTYPE; - using DataReader = dds::sub::DataReader; - using DataTopic = dds::topic::Topic; - using DataReaderQos = dds::sub::qos::DataReaderQos; - using SubscriberCallback = std::function; - using SubscriberCallbackWithSampleInfo = std::function; + public: + using TopicType = TOPICTYPE; + using TopicTypeRead = TOPICTYPE; + using DataReader = dds::sub::DataReader; + using DataTopic = dds::topic::Topic; + using DataReaderQos = dds::sub::qos::DataReaderQos; + using SubscriberCallback = std::function; + using SubscriberCallbackWithSampleInfo = std::function; - GenericDataReader() - : m_dataReader(nullptr) - , m_ddsTopic(nullptr) - , m_bHaveSubscriberCallback(false) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_READER)) - {} - - virtual ~GenericDataReader() - { - m_ddsTopic = nullptr; - m_dataReader = nullptr; - } - - DataReader getDataReader() const { return m_dataReader; } - - bool create(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value()), - bool bCreateDataReader = true) - { - DEBUG_LOG(m_logger) << "IN GenericDataReader::create (" - << DDS::topic_type_name::value() - << "), this: " << this; - - if (domainParticipant == nullptr) + GenericDataReader() + : m_dataReader(nullptr), m_ddsTopic(nullptr), m_bHaveSubscriberCallback(false), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_READER)) { - ERROR_LOG(m_logger) << "DomainParticipant does not exist "; - return false; } - if (m_ddsTopic != nullptr) + virtual ~GenericDataReader() { - ERROR_LOG(m_logger) << "Type '" - << DDS::topic_type_name::value() - << "' already created"; - return false; + m_ddsTopic = nullptr; + m_dataReader = nullptr; } - try + DataReader getDataReader() const { - DEBUG_LOG(m_logger) << "Creating read topic " << topicName << " with type: " - << DDS::topic_type_name::value(); + return m_dataReader; + } - m_ddsTopic = dds::topic::find(domainParticipant, topicName); - if (m_ddsTopic == nullptr) - m_ddsTopic = DataTopic(domainParticipant, topicName); + bool create(const dds::domain::DomainParticipant& domainParticipant, const dds::sub::Subscriber& ddsSubscriber, + const std::string& topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value()), + bool bCreateDataReader = true) + { + DEBUG_LOG(m_logger) << "IN GenericDataReader::create (" << DDS::topic_type_name::value() + << "), this: " << this; - if (m_logger.isDebugEnabled()) - { - dds::sub::qos::SubscriberQos subscriberQoS = ddsSubscriber.qos(); - dds::core::policy::Partition partition = subscriberQoS.policy(); - dds::core::StringSeq parititionNames = partition.name(); - DEBUG_LOG(m_logger) << "Subscribing partitions: " << parititionNames.size(); - for (const std::string &name : parititionNames) - DEBUG_LOG(m_logger) << " partition name = " << name; - } + if (domainParticipant == nullptr) + { + ERROR_LOG(m_logger) << "DomainParticipant does not exist "; + return false; + } + + if (m_ddsTopic != nullptr) + { + ERROR_LOG(m_logger) << "Type '" << DDS::topic_type_name::value() << "' already created"; + return false; + } + + try + { + DEBUG_LOG(m_logger) << "Creating read topic " << topicName + << " with type: " << DDS::topic_type_name::value(); + + m_ddsTopic = dds::topic::find(domainParticipant, topicName); + if (m_ddsTopic == nullptr) + m_ddsTopic = DataTopic(domainParticipant, topicName); + + if (m_logger.isDebugEnabled()) + { + dds::sub::qos::SubscriberQos subscriberQoS = ddsSubscriber.qos(); + dds::core::policy::Partition partition = subscriberQoS.policy(); + dds::core::StringSeq parititionNames = partition.name(); + DEBUG_LOG(m_logger) << "Subscribing partitions: " << parititionNames.size(); + for (const std::string& name : parititionNames) + DEBUG_LOG(m_logger) << " partition name = " << name; + } + + if (bCreateDataReader) + { + dds::sub::qos::DataReaderQos drQos = domainParticipant->default_datareader_qos(); + m_dataReader = DataReader(ddsSubscriber, m_ddsTopic, drQos); + if (m_dataReader == nullptr) + { + ERROR_LOG(m_logger) << "Creating dataReader for '" << topicName << "' with type: '" + << DDS::topic_type_name::value() << "' failed"; + return false; + } + } + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(m_logger) << ex.what(); + return false; + } + + DEBUG_LOG(m_logger) << "dataReader created (" << DDS::topic_type_name::value() << ")"; + + return true; + } + + bool hasSamples() const + { + qint64 sampleSize = m_dataReader->datareader_cache_status().sample_count(); + DEBUG_LOG(m_logger) << "sampleSize = " << sampleSize; + return sampleSize > 0; + } + + dds::sub::LoanedSamples readAlive(bool& bSeenNewSamples) + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::alive()).read(); + TRACE_LOG(m_logger) << "readAlive for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); + + bSeenNewSamples = checkNewSamples(samples); + return samples; + } + + dds::sub::LoanedSamples takeAlive(bool& bSeenNewSamples) + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::alive()).take(); + TRACE_LOG(m_logger) << "takeAlive for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); + + bSeenNewSamples = checkNewSamples(samples); + return samples; + } + + dds::sub::LoanedSamples takeDisposed() + { + dds::sub::LoanedSamples samples = + m_dataReader.select().state(dds::sub::status::InstanceState::not_alive_disposed()).take(); + TRACE_LOG(m_logger) << "takeDisposed for " << DDS::topic_type_name::value() + << ", count: " << samples.length() << ", this: " << this << ", instance handle " + << m_dataReader.instance_handle(); + return samples; + } + + template bool read(C callbackFunc) + { + DEBUG_LOG(m_logger) << "IN read (" << DDS::topic_type_name::value() << "), this: " << this + << ", instance handle " << m_dataReader.instance_handle(); - if (bCreateDataReader) - { - dds::sub::qos::DataReaderQos drQos = domainParticipant->default_datareader_qos(); - m_dataReader = DataReader(ddsSubscriber, m_ddsTopic, drQos); if (m_dataReader == nullptr) { - ERROR_LOG(m_logger) << "Creating dataReader for '" << topicName << "' with type: '" - << DDS::topic_type_name::value() - << "' failed"; - return false; + ERROR_LOG(m_logger) << "No dataReader initialised "; + return false; } - } + if (!isValid(callbackFunc)) + { + ERROR_LOG(m_logger) << "No subscriber set for " << DDS::topic_type_name::value(); + return false; + } + + std::vector samples; + { + dds::sub::LoanedSamples loanedSamples = + m_dataReader.select().state(dds::sub::status::DataState::new_data()).read(); + samples.reserve(loanedSamples.length()); + for (const auto& sample : loanedSamples) + { + if (!sample.info().valid()) + continue; + samples.emplace_back(sample.data(), sample.info()); + } + } + + DEBUG_LOG(m_logger) << "got " << samples.size() + m_newSamplesDuringRead.size() << " samples from reader for " + << DDS::topic_type_name::value(); + + for (const SampleStruct& ss : samples) + readData(ss.sample, ss.info, callbackFunc); + + if (!m_newSamplesDuringRead.empty()) + { + std::vector copy; + std::swap(copy, m_newSamplesDuringRead); + + for (const SampleStruct& ss : copy) + readData(ss.sample, ss.info, callbackFunc); + } + + return checkDisposedInstances(callbackFunc); } - catch (const dds::core::Exception &ex) + + void setHaveSubscriberCallback(bool bHave) { - ERROR_LOG(m_logger) << ex.what(); - return false; + m_bHaveSubscriberCallback = bHave; } - DEBUG_LOG(m_logger) << "dataReader created (" - << DDS::topic_type_name::value() - << ")"; - - return true; - } - - - bool hasSamples() const - { - qint64 sampleSize = m_dataReader->datareader_cache_status().sample_count(); - DEBUG_LOG(m_logger) << "sampleSize = " << sampleSize; - return sampleSize > 0; - } - - - - dds::sub::LoanedSamples readAlive(bool &bSeenNewSamples) - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::alive()).read(); - TRACE_LOG(m_logger) << "readAlive for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - bSeenNewSamples = checkNewSamples(samples); - return samples; - } - - - - dds::sub::LoanedSamples takeAlive(bool &bSeenNewSamples) - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::alive()).take(); - TRACE_LOG(m_logger) << "takeAlive for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - bSeenNewSamples = checkNewSamples(samples); - return samples; - } - - dds::sub::LoanedSamples takeDisposed() - { - dds::sub::LoanedSamples samples = - m_dataReader.select().state(dds::sub::status::InstanceState::not_alive_disposed()).take(); - TRACE_LOG(m_logger) << "takeDisposed for " << DDS::topic_type_name::value() - << ", count: " << samples.length() - << ", this: " << this << ", instance handle " << m_dataReader.instance_handle(); - return samples; - } - - template - bool read(C callbackFunc) - { - DEBUG_LOG(m_logger) << "IN read (" - << DDS::topic_type_name::value() - << "), this: " << this << ", instance handle " << m_dataReader.instance_handle(); - - if (m_dataReader == nullptr) + std::string topicName() const { - ERROR_LOG(m_logger) << "No dataReader initialised "; - return false; + return m_ddsTopic.name(); } - if (!isValid(callbackFunc)) + + DataReader dataReader() const { - ERROR_LOG(m_logger) << "No subscriber set for " - << DDS::topic_type_name::value(); - return false; + return m_dataReader; } - - - std::vector samples; + virtual void recreateReader() { - dds::sub::LoanedSamples loanedSamples = m_dataReader.select().state(dds::sub::status::DataState::new_data()).read(); - samples.reserve(loanedSamples.length()); - for (const auto &sample : loanedSamples) - { - if (!sample.info().valid()) - continue; - samples.emplace_back(sample.data(), sample.info()); - } + if (m_dataReader == nullptr) + return; + m_dataReader = DataReader(m_dataReader.subscriber(), m_ddsTopic); } - DEBUG_LOG(m_logger) << "got " << samples.size() + m_newSamplesDuringRead.size() << " samples from reader for " - << DDS::topic_type_name::value(); - - for (const SampleStruct &ss : samples) - readData(ss.sample, ss.info, callbackFunc); - - if (!m_newSamplesDuringRead.empty()) - { - std::vector copy; - std::swap(copy, m_newSamplesDuringRead); - - - for (const SampleStruct &ss : copy) - readData(ss.sample, ss.info, callbackFunc); - } - - return checkDisposedInstances(callbackFunc); - } - - void setHaveSubscriberCallback(bool bHave) - { - m_bHaveSubscriberCallback = bHave; - } - std::string topicName() const - { - return m_ddsTopic.name(); - } - - DataReader dataReader() const { return m_dataReader; } - - virtual void recreateReader() - { - if (m_dataReader == nullptr) - return; - m_dataReader = DataReader(m_dataReader.subscriber(), m_ddsTopic); - } -private: + private: #if RTI_DDS_VERSION_MAJOR < 6 - inline bool checkNewSamples(dds::sub::LoanedSamples &samples) + inline bool checkNewSamples(dds::sub::LoanedSamples& samples) #else - inline bool checkNewSamples(const dds::sub::LoanedSamples &samples) + inline bool checkNewSamples(const dds::sub::LoanedSamples& samples) #endif - { - - if (!m_bHaveSubscriberCallback) - return false; - - bool bSeenNewSamples = false; - for (const auto &sample : samples) { - const dds::sub::status::DataState ds = sample.info()->state(); - if (ds.view_state() == dds::sub::status::ViewState::new_view() || - ds.sample_state() == dds::sub::status::SampleState::not_read()) - { - - m_newSamplesDuringRead.emplace_back(sample.data(), sample.info()); - bSeenNewSamples = true; - } - } - return bSeenNewSamples; - } + if (!m_bHaveSubscriberCallback) + return false; - template - bool checkDisposedInstances(C callbackFunc) - { - const dds::sub::status::DataState ds(dds::sub::status::SampleState::any(), - dds::sub::status::ViewState::any(), - dds::sub::status::InstanceState::not_alive_mask()); + bool bSeenNewSamples = false; + for (const auto& sample : samples) + { + const dds::sub::status::DataState ds = sample.info()->state(); + if (ds.view_state() == dds::sub::status::ViewState::new_view() || + ds.sample_state() == dds::sub::status::SampleState::not_read()) + { - - dds::sub::LoanedSamples samples = m_dataReader.select().state(ds).take(); + m_newSamplesDuringRead.emplace_back(sample.data(), sample.info()); - if (samples.length() == 0) - return false; - - DEBUG_LOG(m_logger) << "got " << samples.length() << " disposed instances from reader for " - << DDS::topic_type_name::value(); - - for (const auto &sample : samples) - { - if (sample.info().valid()) - readData(sample.data(), sample.info(), callbackFunc); + bSeenNewSamples = true; + } + } + return bSeenNewSamples; } - return true; - } + template bool checkDisposedInstances(C callbackFunc) + { + const dds::sub::status::DataState ds(dds::sub::status::SampleState::any(), dds::sub::status::ViewState::any(), + dds::sub::status::InstanceState::not_alive_mask()); - static void readData(const TopicType &sample, const dds::sub::SampleInfo &info, const SubscriberCallback &callbackFunc) - { - DataModification modType = DataModification::eModified; - const dds::sub::status::DataState ds = info.state(); - if (ds.view_state() == dds::sub::status::ViewState::new_view()) - modType = DataModification::eAdded; - if (ds.instance_state() != dds::sub::status::InstanceState::alive()) - modType = DataModification::eRemoved; - + dds::sub::LoanedSamples samples = m_dataReader.select().state(ds).take(); - callbackFunc(sample, modType); - } + if (samples.length() == 0) + return false; - static void readData(const TopicType &sample, const dds::sub::SampleInfo &info, const SubscriberCallbackWithSampleInfo &callbackFunc) - { - callbackFunc(sample, info); - } + DEBUG_LOG(m_logger) << "got " << samples.length() << " disposed instances from reader for " + << DDS::topic_type_name::value(); - static bool isValid(const SubscriberCallback &callbackFunc) - { - return callbackFunc != nullptr; - } - static bool isValid(const SubscriberCallbackWithSampleInfo &callbackFunc) - { - return callbackFunc != nullptr; - } + for (const auto& sample : samples) + { + if (sample.info().valid()) + readData(sample.data(), sample.info(), callbackFunc); + } -protected: - DataReader m_dataReader; - DataReaderQos m_dataReaderQos; + return true; + } - DataTopic m_ddsTopic; - struct SampleStruct - { - TopicTypeRead sample; - dds::sub::SampleInfo info; + static void readData(const TopicType& sample, const dds::sub::SampleInfo& info, + const SubscriberCallback& callbackFunc) + { + DataModification modType = DataModification::eModified; + const dds::sub::status::DataState ds = info.state(); + if (ds.view_state() == dds::sub::status::ViewState::new_view()) + modType = DataModification::eAdded; + if (ds.instance_state() != dds::sub::status::InstanceState::alive()) + modType = DataModification::eRemoved; - SampleStruct() = default; - SampleStruct(const TopicTypeRead &s, const dds::sub::SampleInfo &i) - : sample(s) - , info(i) - {} - }; - std::vector m_newSamplesDuringRead; - bool m_bHaveSubscriberCallback; + callbackFunc(sample, modType); + } + + static void readData(const TopicType& sample, const dds::sub::SampleInfo& info, + const SubscriberCallbackWithSampleInfo& callbackFunc) + { + callbackFunc(sample, info); + } + + static bool isValid(const SubscriberCallback& callbackFunc) + { + return callbackFunc != nullptr; + } + + static bool isValid(const SubscriberCallbackWithSampleInfo& callbackFunc) + { + return callbackFunc != nullptr; + } + + protected: + DataReader m_dataReader; + DataReaderQos m_dataReaderQos; + + DataTopic m_ddsTopic; + + struct SampleStruct + { + TopicTypeRead sample; + dds::sub::SampleInfo info; + + SampleStruct() = default; + + SampleStruct(const TopicTypeRead& s, const dds::sub::SampleInfo& i) : sample(s), info(i) {} + }; + + std::vector m_newSamplesDuringRead; + bool m_bHaveSubscriberCallback; }; -template -class GenericDataReaderContentFilter final - : public GenericDataReader +template class GenericDataReaderContentFilter final : public GenericDataReader { - using BaseClass = GenericDataReader; -public: - using TopicType = TOPICTYPE; - using DataReader = dds::sub::DataReader; + using BaseClass = GenericDataReader; - using BaseClass::BaseClass; + public: + using TopicType = TOPICTYPE; + using DataReader = dds::sub::DataReader; - bool create(const dds::domain::DomainParticipant &domainParticipant, - const dds::sub::Subscriber &ddsSubscriber, - const std::string &specialTopicName, - const dds::topic::Filter &filter) - { - if (!BaseClass::create(domainParticipant, ddsSubscriber, specialTopicName, false)) - return false; - m_filter = filter; - try + using BaseClass::BaseClass; + + bool create(const dds::domain::DomainParticipant& domainParticipant, const dds::sub::Subscriber& ddsSubscriber, + const std::string& specialTopicName, const dds::topic::Filter& filter) { - qint64 ptr = reinterpret_cast(this); - const QByteArray name = QByteArray(DDS::topic_type_name::value().c_str()) - + "- content filter 0x" - + QByteArray::number(ptr, 16); - m_filteredTopic = dds::topic::ContentFilteredTopic(BaseClass::m_ddsTopic, name.data(), m_filter); - BaseClass::m_dataReader = DataReader(ddsSubscriber, m_filteredTopic); + if (!BaseClass::create(domainParticipant, ddsSubscriber, specialTopicName, false)) + return false; + m_filter = filter; + try + { + qint64 ptr = reinterpret_cast(this); + const QByteArray name = QByteArray(DDS::topic_type_name::value().c_str()) + + "- content filter 0x" + QByteArray::number(ptr, 16); + m_filteredTopic = dds::topic::ContentFilteredTopic(BaseClass::m_ddsTopic, name.data(), m_filter); + BaseClass::m_dataReader = DataReader(ddsSubscriber, m_filteredTopic); + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(BaseClass::m_logger) << ex.what(); + return false; + } + DEBUG_LOG(BaseClass::m_logger) << "dataReader with filter created (" << DDS::topic_type_name::value() + << ")"; + return true; } - catch (const dds::core::Exception &ex) + + dds::topic::Filter& filter() { - ERROR_LOG(BaseClass::m_logger) << ex.what(); - return false; + return m_filter; } - DEBUG_LOG(BaseClass::m_logger) << "dataReader with filter created (" - << DDS::topic_type_name::value() - << ")"; - return true; - } - dds::topic::Filter &filter() { return m_filter; } - const dds::topic::Filter &filter() const { return m_filter; } + const dds::topic::Filter& filter() const + { + return m_filter; + } - virtual void recreateReader() - { - if (BaseClass::m_dataReader == nullptr) - return; - BaseClass::m_dataReader = DataReader(BaseClass::m_dataReader.subscriber(), m_filteredTopic); - } + virtual void recreateReader() + { + if (BaseClass::m_dataReader == nullptr) + return; + BaseClass::m_dataReader = DataReader(BaseClass::m_dataReader.subscriber(), m_filteredTopic); + } -private: - dds::topic::ContentFilteredTopic m_filteredTopic = dds::topic::ContentFilteredTopic(nullptr); - dds::topic::Filter m_filter = dds::topic::Filter(std::string()); + private: + dds::topic::ContentFilteredTopic m_filteredTopic = dds::topic::ContentFilteredTopic(nullptr); + dds::topic::Filter m_filter = dds::topic::Filter(std::string()); }; -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_writer.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_writer.h old mode 100755 new mode 100644 index 73c48692f..4c036aab6 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_writer.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/generic_data_writer.h @@ -1,142 +1,131 @@ - #pragma once +#include +#include #include #include -#include #include - -#include -#include +#include namespace DDSGeneric { -template -class GenericDataWriter final +template class GenericDataWriter final { -public: - using TopicType = TOPICTYPE; - using DataWriter = dds::pub::DataWriter; - using DataTopic = dds::topic::Topic; + public: + using TopicType = TOPICTYPE; + using DataWriter = dds::pub::DataWriter; + using DataTopic = dds::topic::Topic; - GenericDataWriter() - : m_dataWriter(nullptr) - , m_ddsTopic(nullptr) - , m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_WRITER)) - {} - - bool create(const dds::domain::DomainParticipant &participant, - const dds::pub::Publisher &ddsPublisher, - const std::string &topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) - { - DEBUG_LOG(m_logger) << "IN GenericDataWriter::create (" - << DDS::topic_type_name::value() - << ")"; - - if (participant == nullptr) + GenericDataWriter() + : m_dataWriter(nullptr), m_ddsTopic(nullptr), + m_logger(DDS::getLogger(DDS::topic_type_name::value(), DDS::DataType::DATA_WRITER)) { - ERROR_LOG(m_logger) << "Participant not available, aborting. "; - return false; } - if (m_ddsTopic != nullptr) + bool create(const dds::domain::DomainParticipant& participant, const dds::pub::Publisher& ddsPublisher, + const std::string& topicName = DDS::Helper::getShortTopicName(DDS::topic_type_name::value())) { - ERROR_LOG(m_logger) << "Type '" - << DDS::topic_type_name::value() - << "' already created"; - return false; + DEBUG_LOG(m_logger) << "IN GenericDataWriter::create (" << DDS::topic_type_name::value() << ")"; + + if (participant == nullptr) + { + ERROR_LOG(m_logger) << "Participant not available, aborting. "; + return false; + } + + if (m_ddsTopic != nullptr) + { + ERROR_LOG(m_logger) << "Type '" << DDS::topic_type_name::value() << "' already created"; + return false; + } + + try + { + + DEBUG_LOG(m_logger) << "Creating write topic " << topicName + << " with type: " << DDS::topic_type_name::value(); + + m_ddsTopic = dds::topic::find(participant, topicName); + if (m_ddsTopic == nullptr) + m_ddsTopic = DataTopic(participant, topicName); + + m_dataWriter = DataWriter(ddsPublisher, m_ddsTopic, ddsPublisher.default_datawriter_qos()); + + if (m_dataWriter == nullptr) + { + ERROR_LOG(m_logger) << "Initialisation of " << DDS::topic_type_name::value() << " failed "; + return false; + } + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(m_logger) << ex.what(); + return false; + } + + DEBUG_LOG(m_logger) << "dataWriter created (" << DDS::topic_type_name::value() << ")"; + + return true; } - try { - - DEBUG_LOG(m_logger) << "Creating write topic " << topicName << " with type: " - << DDS::topic_type_name::value(); - - m_ddsTopic = dds::topic::find(participant, topicName); - if (m_ddsTopic == nullptr) - m_ddsTopic = DataTopic(participant, topicName); - - m_dataWriter = DataWriter(ddsPublisher, - m_ddsTopic, - ddsPublisher.default_datawriter_qos()); - - if (m_dataWriter == nullptr) - { - ERROR_LOG(m_logger) << "Initialisation of " - << DDS::topic_type_name::value() - << " failed "; - return false; - } - - } - catch ( const dds::core::Exception &ex ) + bool write(const TopicType& data, + const dds::core::optional& si = dds::core::optional()) { - ERROR_LOG(m_logger) << ex.what(); - return false; + DEBUG_LOG(m_logger) << "IN write (" << DDS::topic_type_name::value() << ") "; + + if (m_dataWriter == nullptr) + { + ERROR_LOG(m_logger) << "No dataWriter initialised "; + return false; + } + + if (si.is_set()) + { + rti::pub::WriteParams writeParams; + rti::core::SampleIdentity sampleIdentity(si.get()->source_guid(), si.get()->publication_sequence_number()); + writeParams.related_sample_identity(sampleIdentity); + + m_dataWriter->write(data, writeParams); + } + else + { + m_dataWriter.write(data); + } + return true; } - DEBUG_LOG(m_logger) << "dataWriter created (" - << DDS::topic_type_name::value() - << ")"; - - return true; - } - - bool write(const TopicType &data, - const dds::core::optional &si = dds::core::optional()) - { - DEBUG_LOG(m_logger) << "IN write (" - << DDS::topic_type_name::value() - << ") "; - - if (m_dataWriter == nullptr) { - ERROR_LOG(m_logger) << "No dataWriter initialised "; - return false; - } - - if (si.is_set()) + bool remove(const TopicType& data, bool errorMsgIfNotExists = true) { - rti::pub::WriteParams writeParams; - rti::core::SampleIdentity sampleIdentity(si.get()->source_guid(), si.get()->publication_sequence_number()); - writeParams.related_sample_identity(sampleIdentity); + DEBUG_LOG(m_logger) << "IN remove (" << DDS::topic_type_name::value() << ") "; - m_dataWriter->write(data, writeParams); - } else { - m_dataWriter.write(data); + if (m_dataWriter == nullptr) + { + ERROR_LOG(m_logger) << "No dataWriter initialised "; + return false; + } + const dds::core::InstanceHandle ih = m_dataWriter.lookup_instance(data); + if (ih.is_nil()) + { + if (errorMsgIfNotExists) + ERROR_LOG(m_logger) << "Could not find instance for topic " << DDS::topic_type_name::value() + << " for unregistering!"; + return false; + } + m_dataWriter.dispose_instance(ih); + return true; } - return true; - } - bool remove(const TopicType &data, bool errorMsgIfNotExists = true) - { - DEBUG_LOG(m_logger) << "IN remove (" - << DDS::topic_type_name::value() - << ") "; - - if (m_dataWriter == nullptr) { - ERROR_LOG(m_logger) << "No dataWriter initialised "; - return false; + DataWriter dataWriter() const + { + return m_dataWriter; } - const dds::core::InstanceHandle ih = m_dataWriter.lookup_instance(data); - if (ih.is_nil()) { - if (errorMsgIfNotExists) - ERROR_LOG(m_logger) << "Could not find instance for topic " - << DDS::topic_type_name::value() - << " for unregistering!"; - return false; - } - m_dataWriter.dispose_instance(ih); - return true; - } - DataWriter dataWriter() const { return m_dataWriter; } - -private: - DataWriter m_dataWriter; - DataTopic m_ddsTopic; + private: + DataWriter m_dataWriter; + DataTopic m_ddsTopic; }; -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.cpp old mode 100755 new mode 100644 index 6cc2140b8..94ef535bf --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.cpp @@ -1,7 +1,7 @@ - #include "subscriber_listener.h" + #include "generic_base.h" #include "generic_logger.h" @@ -9,183 +9,164 @@ namespace DDSGeneric { SubscriberListener::SubscriberListener() - : m_bPrepareForShutdown(false) - , m_logger(DDS::getLogger("SubscriberListener", DDS::DataType::DATA_TOPIC_CLIENT)) + : m_bPrepareForShutdown(false), m_logger(DDS::getLogger("SubscriberListener", DDS::DataType::DATA_TOPIC_CLIENT)) { - qRegisterMetaType("std::string"); - DEBUG_LOG(m_logger) << "SubscriberListener initialized, this " << this; + qRegisterMetaType("std::string"); + DEBUG_LOG(m_logger) << "SubscriberListener initialized, this " << this; } -void SubscriberListener::addCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb) +void SubscriberListener::addCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb) { - DEBUG_LOG(m_logger) << "addSubscriberCallback for " << topicName << ", type " << topicTypeName - << ", cb " << cb << ", this " << this; - QWriteLocker l(&m_accessLock); - if (m_bPrepareForShutdown) - return; - m_droCallbacks.insertMulti(std::make_pair(topicName, topicTypeName), fillData(dataReader, cb)); -} - -void SubscriberListener::removeCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb) -{ - DEBUG_LOG(m_logger) << "IN removeSubscriberCallback for " << topicName << ", type " << topicTypeName - << ", cb " << cb << ", this " << this; - QWriteLocker l(&m_accessLock); - m_droCallbacks.remove(std::make_pair(topicName, topicTypeName), fillData(dataReader, cb)); -} - -void SubscriberListener::enaDisaCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb, - bool bEnable) -{ - const std::pair key(std::make_pair(topicName, topicTypeName)); - const cbData cbDataSearch(fillData(dataReader, cb)); - bool bFound = false; - - { + DEBUG_LOG(m_logger) << "addSubscriberCallback for " << topicName << ", type " << topicTypeName << ", cb " << cb + << ", this " << this; QWriteLocker l(&m_accessLock); if (m_bPrepareForShutdown) - return; + return; + m_droCallbacks.insertMulti(std::make_pair(topicName, topicTypeName), fillData(dataReader, cb)); +} + +void SubscriberListener::removeCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb) +{ + DEBUG_LOG(m_logger) << "IN removeSubscriberCallback for " << topicName << ", type " << topicTypeName << ", cb " + << cb << ", this " << this; + QWriteLocker l(&m_accessLock); + m_droCallbacks.remove(std::make_pair(topicName, topicTypeName), fillData(dataReader, cb)); +} + +void SubscriberListener::enaDisaCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb, + bool bEnable) +{ + const std::pair key(std::make_pair(topicName, topicTypeName)); + const cbData cbDataSearch(fillData(dataReader, cb)); + bool bFound = false; - QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); - for( ; cbIt != m_droCallbacks.end() && cbIt.key() == key; ++cbIt) { - const cbData &data = cbIt.value(); - if (data != cbDataSearch) - continue; - bFound = true; - cbIt.value().enabled = bEnable; - break; - } - } + QWriteLocker l(&m_accessLock); + if (m_bPrepareForShutdown) + return; - if (!bFound) - WARNING_LOG(m_logger) << "Can not " << (bEnable ? "enable" : "disable") - << " callback for " << topicName << ", type " << topicTypeName - << ", cb " << cb << ", this " << this << " - not found!"; + QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); + for (; cbIt != m_droCallbacks.end() && cbIt.key() == key; ++cbIt) + { + const cbData& data = cbIt.value(); + if (data != cbDataSearch) + continue; + bFound = true; + cbIt.value().enabled = bEnable; + break; + } + } + + if (!bFound) + WARNING_LOG(m_logger) << "Can not " << (bEnable ? "enable" : "disable") << " callback for " << topicName + << ", type " << topicTypeName << ", cb " << cb << ", this " << this << " - not found!"; } void SubscriberListener::prepareShutdown() { - QWriteLocker l(&m_accessLock); - m_droCallbacks.clear(); - m_bPrepareForShutdown = true; + QWriteLocker l(&m_accessLock); + m_droCallbacks.clear(); + m_bPrepareForShutdown = true; } - -void SubscriberListener::on_data_available(dds::sub::AnyDataReader &reader) +void SubscriberListener::on_data_available(dds::sub::AnyDataReader& reader) { - - const std::string &topicName = reader.topic_name(); - const std::string &topicTypeName = reader.type_name(); - const std::pair key(std::make_pair(topicName, topicTypeName)); - QReadLocker l(&m_accessLock); - if (m_droCallbacks.isEmpty() || m_bPrepareForShutdown) - return; - DEBUG_LOG(m_logger) << "Data available for " << topicName << ", type " << topicTypeName << ", this " << this; - QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); - const QMultiMap, cbData>::iterator cbEnd = m_droCallbacks.end(); - for( ; cbIt != cbEnd && cbIt.key() == key; ++cbIt) - { - const cbData &data = cbIt.value(); - if (data.dataReader != reader) - continue; + const std::string& topicName = reader.topic_name(); + const std::string& topicTypeName = reader.type_name(); + const std::pair key(std::make_pair(topicName, topicTypeName)); - if (!data.enabled) - continue; - - if (data.methodToCall.isValid()) + QReadLocker l(&m_accessLock); + if (m_droCallbacks.isEmpty() || m_bPrepareForShutdown) + return; + DEBUG_LOG(m_logger) << "Data available for " << topicName << ", type " << topicTypeName << ", this " << this; + QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); + const QMultiMap, cbData>::iterator cbEnd = m_droCallbacks.end(); + for (; cbIt != cbEnd && cbIt.key() == key; ++cbIt) { - data.methodToCall.invoke(data.cb, Qt::QueuedConnection, - Q_ARG(std::string, topicTypeName), - Q_ARG(std::string, topicName)); - cbIt.value().enabled = false; + const cbData& data = cbIt.value(); + if (data.dataReader != reader) + continue; + + if (!data.enabled) + continue; + + if (data.methodToCall.isValid()) + { + data.methodToCall.invoke(data.cb, Qt::QueuedConnection, Q_ARG(std::string, topicTypeName), + Q_ARG(std::string, topicName)); + cbIt.value().enabled = false; + } + + break; } - - - break; - } } -void SubscriberListener::on_liveliness_changed(dds::sub::AnyDataReader &reader, - const dds::core::status::LivelinessChangedStatus &livelinessStatus) +void SubscriberListener::on_liveliness_changed(dds::sub::AnyDataReader& reader, + const dds::core::status::LivelinessChangedStatus& livelinessStatus) { - const std::string &topicName = reader.topic_name(); - const std::string &topicTypeName = reader.type_name(); - - DEBUG_LOG(m_logger) << "on_liveliness_changed: " << livelinessStatus.alive_count() - << ", " << livelinessStatus.not_alive_count() - << ", " << livelinessStatus.alive_count_change() - << ", " << livelinessStatus.not_alive_count_change() - << " for type " << topicTypeName; + const std::string& topicName = reader.topic_name(); + const std::string& topicTypeName = reader.type_name(); - bool bNewWriters = false; - bool bNoWritersAnymore = false; - if (livelinessStatus.alive_count() == 0 && - livelinessStatus.alive_count_change() < 0) - bNoWritersAnymore = true; - if (livelinessStatus.alive_count() != 0 && - livelinessStatus.alive_count_change() == livelinessStatus.alive_count()) - bNewWriters = true; - if (!bNewWriters && !bNoWritersAnymore) - return; + DEBUG_LOG(m_logger) << "on_liveliness_changed: " << livelinessStatus.alive_count() << ", " + << livelinessStatus.not_alive_count() << ", " << livelinessStatus.alive_count_change() << ", " + << livelinessStatus.not_alive_count_change() << " for type " << topicTypeName; - QReadLocker l(&m_accessLock); - if (m_droCallbacks.isEmpty()) - return; + bool bNewWriters = false; + bool bNoWritersAnymore = false; + if (livelinessStatus.alive_count() == 0 && livelinessStatus.alive_count_change() < 0) + bNoWritersAnymore = true; + if (livelinessStatus.alive_count() != 0 && livelinessStatus.alive_count_change() == livelinessStatus.alive_count()) + bNewWriters = true; + if (!bNewWriters && !bNoWritersAnymore) + return; - const std::pair key(std::make_pair(topicName, topicTypeName)); - QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); - const QMultiMap, cbData>::iterator cbEnd = m_droCallbacks.end(); - for( ; cbIt != cbEnd && cbIt.key() == key; ++cbIt) - { - const cbData &data = cbIt.value(); - if (data.dataReader != reader) - continue; + QReadLocker l(&m_accessLock); + if (m_droCallbacks.isEmpty()) + return; - if (bNoWritersAnymore) + const std::pair key(std::make_pair(topicName, topicTypeName)); + QMultiMap, cbData>::iterator cbIt = m_droCallbacks.find(key); + const QMultiMap, cbData>::iterator cbEnd = m_droCallbacks.end(); + for (; cbIt != cbEnd && cbIt.key() == key; ++cbIt) { - DEBUG_LOG(m_logger) << "bNoWritersAnymore for " << topicName << ", type " << topicTypeName; - data.cb->noWriterAnymore(topicTypeName, topicName); + const cbData& data = cbIt.value(); + if (data.dataReader != reader) + continue; + + if (bNoWritersAnymore) + { + DEBUG_LOG(m_logger) << "bNoWritersAnymore for " << topicName << ", type " << topicTypeName; + data.cb->noWriterAnymore(topicTypeName, topicName); + } + else if (bNewWriters) + { + data.cb->writerAvailable(topicTypeName, topicName); + if (!data.enabled) + continue; + if (data.methodToCall.isValid()) + { + DEBUG_LOG(m_logger) << "methodcall is valid for " << topicName << ", type " << topicTypeName; + data.methodToCall.invoke(data.cb, Qt::QueuedConnection, Q_ARG(std::string, topicTypeName), + Q_ARG(std::string, topicName)); + cbIt.value().enabled = false; + } + } } - else if (bNewWriters) - { - data.cb->writerAvailable(topicTypeName, topicName); - if (!data.enabled) - continue; - if (data.methodToCall.isValid()) - { - DEBUG_LOG(m_logger) << "methodcall is valid for " << topicName << ", type " << topicTypeName; - data.methodToCall.invoke(data.cb, Qt::QueuedConnection, - Q_ARG(std::string, topicTypeName), - Q_ARG(std::string, topicName)); - cbIt.value().enabled = false; - } - } - } } -SubscriberListener::cbData SubscriberListener::fillData(const dds::sub::AnyDataReader &dataReader, SubscriberListenerCallback *cb) const +SubscriberListener::cbData SubscriberListener::fillData(const dds::sub::AnyDataReader& dataReader, + SubscriberListenerCallback* cb) const { - - const char *signal = SIGNAL(droDataAvailable(std::string,std::string)); - const char *slot = SLOT(droDataAvailable(std::string,std::string)); - QMetaMethod method = DDS::Helper::getMethod(m_logger, - cb, - slot, - signal); - - - return cbData(cb, dataReader, method); + + const char* signal = SIGNAL(droDataAvailable(std::string, std::string)); + const char* slot = SLOT(droDataAvailable(std::string, std::string)); + QMetaMethod method = DDS::Helper::getMethod(m_logger, cb, slot, signal); + + return cbData(cb, dataReader, method); } -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.h old mode 100755 new mode 100644 index 770a9bba2..3613111a4 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/subscriber_listener.h @@ -1,140 +1,138 @@ - #pragma once -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include -namespace NGL { +namespace NGL +{ class INGLLogger; } - - namespace DDSGeneric { class DDSGEN_EXPORT SubscriberListenerCallback : public QObject { - Q_OBJECT -public: - virtual ~SubscriberListenerCallback() = default; -public Q_SLOTS: - - virtual void droDataAvailable(const std::string &topicType, const std::string &topicName) = 0; - - virtual void noWriterAnymore(const std::string &topicType, const std::string &topicName) = 0; - virtual void writerAvailable(const std::string &topicType, const std::string &topicName) = 0; + Q_OBJECT + public: + virtual ~SubscriberListenerCallback() = default; + public Q_SLOTS: + + virtual void droDataAvailable(const std::string& topicType, const std::string& topicName) = 0; + + virtual void noWriterAnymore(const std::string& topicType, const std::string& topicName) = 0; + virtual void writerAvailable(const std::string& topicType, const std::string& topicName) = 0; }; class DDSGEN_EXPORT SubscriberListener final : public dds::sub::SubscriberListener { -public: - SubscriberListener(); + public: + SubscriberListener(); - template - void addCallback(const dds::sub::DataReader &dataReader, - SubscriberListenerCallback *cb) - { - addCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb); - } - template - void removeCallback(const dds::sub::DataReader &dataReader, - SubscriberListenerCallback *cb) - { - removeCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb); - } - - template - void enableCallback(const dds::sub::DataReader &dataReader, - SubscriberListenerCallback *cb) - { - enaDisaCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb, true); - } - template - void disableCallback(const dds::sub::DataReader &dataReader, - SubscriberListenerCallback *cb) - { - enaDisaCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb, false); - } - - static dds::core::status::StatusMask mask() - { - return (dds::core::status::StatusMask::liveliness_changed() | dds::core::status::StatusMask::data_available()); - } - - void prepareShutdown(); - -protected: - NGL::INGLLogger &m_logger; - void addCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb); - void removeCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb); - void enaDisaCallback(const std::string &topicName, - const std::string &topicTypeName, - const dds::sub::AnyDataReader &dataReader, - SubscriberListenerCallback *cb, - bool bEnable); - - void on_data_on_readers(dds::sub::Subscriber &) override {} - - void on_liveliness_changed(dds::sub::AnyDataReader &reader, - const dds::core::status::LivelinessChangedStatus &livelinessStatus) override; - - void on_requested_deadline_missed(dds::sub::AnyDataReader&, - const dds::core::status::RequestedDeadlineMissedStatus&) override {} - void on_requested_incompatible_qos(dds::sub::AnyDataReader&, - const dds::core::status::RequestedIncompatibleQosStatus&) override {} - void on_sample_rejected(dds::sub::AnyDataReader&, - const dds::core::status::SampleRejectedStatus&) override {} - void on_data_available(dds::sub::AnyDataReader &reader) override; - void on_subscription_matched(dds::sub::AnyDataReader&, - const dds::core::status::SubscriptionMatchedStatus&) override {} - void on_sample_lost(dds::sub::AnyDataReader&, - const dds::core::status::SampleLostStatus&) override {} - -private: - struct cbData - { - SubscriberListenerCallback *cb = nullptr; - bool enabled = true; - dds::sub::AnyDataReader dataReader; - QMetaMethod methodToCall; - - bool operator ==(const cbData &o) const + template + void addCallback(const dds::sub::DataReader& dataReader, SubscriberListenerCallback* cb) { - - return cb == o.cb && methodToCall == o.methodToCall && dataReader == o.dataReader; - } - bool operator !=(const cbData &o) const - { - return !operator ==(o); + addCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb); } - cbData(SubscriberListenerCallback *cb_, - const dds::sub::AnyDataReader &dataReader_, - const QMetaMethod &methodToCall_) - : cb(cb_) - , enabled(true) - , dataReader(dataReader_) - , methodToCall(methodToCall_) - {} - }; - cbData fillData(const dds::sub::AnyDataReader &dataReader, SubscriberListenerCallback *cb) const; + template + void removeCallback(const dds::sub::DataReader& dataReader, SubscriberListenerCallback* cb) + { + removeCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb); + } - QMultiMap, cbData> m_droCallbacks; - QReadWriteLock m_accessLock; - bool m_bPrepareForShutdown; + template + void enableCallback(const dds::sub::DataReader& dataReader, SubscriberListenerCallback* cb) + { + enaDisaCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb, + true); + } + + template + void disableCallback(const dds::sub::DataReader& dataReader, SubscriberListenerCallback* cb) + { + enaDisaCallback(dataReader->topic_name(), dataReader->type_name(), dds::sub::AnyDataReader(dataReader), cb, + false); + } + + static dds::core::status::StatusMask mask() + { + return (dds::core::status::StatusMask::liveliness_changed() | dds::core::status::StatusMask::data_available()); + } + + void prepareShutdown(); + + protected: + NGL::INGLLogger& m_logger; + void addCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb); + void removeCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb); + void enaDisaCallback(const std::string& topicName, const std::string& topicTypeName, + const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb, bool bEnable); + + void on_data_on_readers(dds::sub::Subscriber&) override {} + + void on_liveliness_changed(dds::sub::AnyDataReader& reader, + const dds::core::status::LivelinessChangedStatus& livelinessStatus) override; + + void on_requested_deadline_missed(dds::sub::AnyDataReader&, + const dds::core::status::RequestedDeadlineMissedStatus&) override + { + } + + void on_requested_incompatible_qos(dds::sub::AnyDataReader&, + const dds::core::status::RequestedIncompatibleQosStatus&) override + { + } + + void on_sample_rejected(dds::sub::AnyDataReader&, const dds::core::status::SampleRejectedStatus&) override {} + + void on_data_available(dds::sub::AnyDataReader& reader) override; + + void on_subscription_matched(dds::sub::AnyDataReader&, const dds::core::status::SubscriptionMatchedStatus&) override + { + } + + void on_sample_lost(dds::sub::AnyDataReader&, const dds::core::status::SampleLostStatus&) override {} + + private: + struct cbData + { + SubscriberListenerCallback* cb = nullptr; + bool enabled = true; + dds::sub::AnyDataReader dataReader; + QMetaMethod methodToCall; + + bool operator==(const cbData& o) const + { + + return cb == o.cb && methodToCall == o.methodToCall && dataReader == o.dataReader; + } + + bool operator!=(const cbData& o) const + { + return !operator==(o); + } + + cbData(SubscriberListenerCallback* cb_, const dds::sub::AnyDataReader& dataReader_, + const QMetaMethod& methodToCall_) + : cb(cb_), enabled(true), dataReader(dataReader_), methodToCall(methodToCall_) + { + } + }; + + cbData fillData(const dds::sub::AnyDataReader& dataReader, SubscriberListenerCallback* cb) const; + + QMultiMap, cbData> m_droCallbacks; + QReadWriteLock m_accessLock; + bool m_bPrepareForShutdown; }; -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.cpp old mode 100755 new mode 100644 index 61811ae97..6b16aab85 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.cpp @@ -1,147 +1,144 @@ - - #include "wait_set_handler.h" -#include "generic_logger.h" + #include "generic_base.h" +#include "generic_logger.h" namespace DDSGeneric { -WaitSetHandler::WaitSetHandler() - : m_logger(DDS::getLogger("WaitSetHandler", DDS::DataType::FUNCTION_TOPIC_SERVER)) +WaitSetHandler::WaitSetHandler() : m_logger(DDS::getLogger("WaitSetHandler", DDS::DataType::FUNCTION_TOPIC_SERVER)) { - m_waitSet.attach_condition(m_abortCondition); - m_task = std::async(std::launch::async, [this]() { this->waitSetTask();}); + m_waitSet.attach_condition(m_abortCondition); + m_task = std::async(std::launch::async, [this]() { this->waitSetTask(); }); } WaitSetHandler::~WaitSetHandler() { - m_abortCondition.trigger_value(true); - m_task.wait(); + m_abortCondition.trigger_value(true); + m_task.wait(); } -bool WaitSetHandler::attachWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb) +bool WaitSetHandler::attachWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb) { - DEBUG_LOG(m_logger) << "AttachWaitSet with callback " << cb; + DEBUG_LOG(m_logger) << "AttachWaitSet with callback " << cb; - WaitSetData wsd(cond, cb); + WaitSetData wsd(cond, cb); - std::lock_guard l(m_accessMutex); - - auto it = m_waitSetData.find(wsd.condition->native_condition()); - if (it != m_waitSetData.end()) - { - WARNING_LOG(m_logger) << "Waitset " << cb << " already registered"; - return false; - } + std::lock_guard l(m_accessMutex); - m_waitSet.attach_condition(wsd.condition); - wsd.enabled = true; - wsd.needWaitSetAttach = false; + auto it = m_waitSetData.find(wsd.condition->native_condition()); + if (it != m_waitSetData.end()) + { + WARNING_LOG(m_logger) << "Waitset " << cb << " already registered"; + return false; + } - m_waitSetData.insert(std::make_pair(wsd.condition->native_condition(), wsd)); - return true; -} - -bool WaitSetHandler::detachWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb) -{ - DEBUG_LOG(m_logger) << "DetachWaitSet with callback " << cb; - - WaitSetData wsd(cond, cb); - - std::lock_guard l(m_accessMutex); - - auto it = m_waitSetData.find(wsd.condition->native_condition()); - if (it == m_waitSetData.end()) - { - WARNING_LOG(m_logger) << "Waitset for " << cb << " not registered"; - return false; - } - - m_waitSet.detach_condition(wsd.condition); - m_waitSetData.erase(it); - return true; -} - -bool WaitSetHandler::enableWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb) -{ - DEBUG_LOG(m_logger) << "EnableWaitSet with callback " << cb; - - WaitSetData wsd(cond, cb); - - std::lock_guard l(m_accessMutex); - auto it = m_waitSetData.find(wsd.condition->native_condition()); - if (it == m_waitSetData.end()) - { - ERROR_LOG(m_logger) << "Could not find WaitSetData - cannot enable waitSet for " << cb; - return false; - } - - if (it->second.needWaitSetAttach) m_waitSet.attach_condition(wsd.condition); - it->second.enabled = true; - it->second.needWaitSetAttach = false; - return true; + wsd.enabled = true; + wsd.needWaitSetAttach = false; + + m_waitSetData.insert(std::make_pair(wsd.condition->native_condition(), wsd)); + return true; } -bool WaitSetHandler::disableWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb) +bool WaitSetHandler::detachWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb) { - DEBUG_LOG(m_logger) << "DisableWaitSet with callback " << cb; + DEBUG_LOG(m_logger) << "DetachWaitSet with callback " << cb; - WaitSetData wsd(cond, cb); + WaitSetData wsd(cond, cb); - std::lock_guard l(m_accessMutex); - auto it = m_waitSetData.find(wsd.condition->native_condition()); - if (it == m_waitSetData.end()) - { - ERROR_LOG(m_logger) << "Could not find WaitSetData - cannot disable waitSet for " << cb; - return false; - } + std::lock_guard l(m_accessMutex); - m_waitSet.detach_condition(wsd.condition); - it->second.enabled = false; - it->second.needWaitSetAttach = true; - return true; + auto it = m_waitSetData.find(wsd.condition->native_condition()); + if (it == m_waitSetData.end()) + { + WARNING_LOG(m_logger) << "Waitset for " << cb << " not registered"; + return false; + } + + m_waitSet.detach_condition(wsd.condition); + m_waitSetData.erase(it); + return true; +} + +bool WaitSetHandler::enableWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb) +{ + DEBUG_LOG(m_logger) << "EnableWaitSet with callback " << cb; + + WaitSetData wsd(cond, cb); + + std::lock_guard l(m_accessMutex); + auto it = m_waitSetData.find(wsd.condition->native_condition()); + if (it == m_waitSetData.end()) + { + ERROR_LOG(m_logger) << "Could not find WaitSetData - cannot enable waitSet for " << cb; + return false; + } + + if (it->second.needWaitSetAttach) + m_waitSet.attach_condition(wsd.condition); + it->second.enabled = true; + it->second.needWaitSetAttach = false; + return true; +} + +bool WaitSetHandler::disableWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb) +{ + DEBUG_LOG(m_logger) << "DisableWaitSet with callback " << cb; + + WaitSetData wsd(cond, cb); + + std::lock_guard l(m_accessMutex); + auto it = m_waitSetData.find(wsd.condition->native_condition()); + if (it == m_waitSetData.end()) + { + ERROR_LOG(m_logger) << "Could not find WaitSetData - cannot disable waitSet for " << cb; + return false; + } + + m_waitSet.detach_condition(wsd.condition); + it->second.enabled = false; + it->second.needWaitSetAttach = true; + return true; } int WaitSetHandler::attachedConditionCount() const { - return m_waitSet.conditions().size(); + return m_waitSet.conditions().size(); } - void WaitSetHandler::waitSetTask() { - while (true) - { - dds::core::cond::WaitSet::ConditionSeq activeConditionsSeq = m_waitSet.wait(); - for (const dds::core::cond::Condition &cond : activeConditionsSeq) + while (true) { - if (cond == m_abortCondition) - { - m_waitSet->detach_all(); - return; - } - - std::lock_guard l(m_accessMutex); - const DDS_Condition *ddsCond = cond->native_condition(); - auto it = m_waitSetData.lower_bound(ddsCond); - while (it != m_waitSetData.end()) - { - WaitSetData &wsd = it->second; - if (wsd.enabled) + dds::core::cond::WaitSet::ConditionSeq activeConditionsSeq = m_waitSet.wait(); + for (const dds::core::cond::Condition& cond : activeConditionsSeq) { - DEBUG_LOG(m_logger) << "Condition triggered for " << wsd.callback; - wsd.callback->dataAvailable(); + if (cond == m_abortCondition) + { + m_waitSet->detach_all(); + return; + } + + std::lock_guard l(m_accessMutex); + const DDS_Condition* ddsCond = cond->native_condition(); + auto it = m_waitSetData.lower_bound(ddsCond); + while (it != m_waitSetData.end()) + { + WaitSetData& wsd = it->second; + if (wsd.enabled) + { + DEBUG_LOG(m_logger) << "Condition triggered for " << wsd.callback; + wsd.callback->dataAvailable(); + } + ++it; + if (it == m_waitSetData.end() || it->first != ddsCond) + break; + } } - ++it; - if (it == m_waitSetData.end() || it->first != ddsCond) - break; - } } - } } -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.h old mode 100755 new mode 100644 index 57fe05afb..37151c19f --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Generic/wait_set_handler.h @@ -1,15 +1,13 @@ - #pragma once #include #include #include - +#include #include #include -#include namespace NGL { @@ -20,48 +18,47 @@ namespace DDSGeneric { class DDSGEN_EXPORT WaitSetHandler final { -public: - class CallbackInterface - { public: - virtual ~CallbackInterface() = default; - virtual void dataAvailable() = 0; - }; + class CallbackInterface + { + public: + virtual ~CallbackInterface() = default; + virtual void dataAvailable() = 0; + }; - WaitSetHandler(); - ~WaitSetHandler(); + WaitSetHandler(); + ~WaitSetHandler(); - bool attachWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb); - bool detachWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb); - bool enableWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb); - bool disableWaitSet(const dds::core::cond::Condition &cond, CallbackInterface *cb); + bool attachWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb); + bool detachWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb); + bool enableWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb); + bool disableWaitSet(const dds::core::cond::Condition& cond, CallbackInterface* cb); - int attachedConditionCount() const; + int attachedConditionCount() const; -private: - NGL::INGLLogger &m_logger; - struct WaitSetData final - { - dds::core::cond::Condition condition; - CallbackInterface *callback = nullptr; - bool enabled = true; - bool needWaitSetAttach = false; + private: + NGL::INGLLogger& m_logger; - WaitSetData(const dds::core::cond::Condition &cond, CallbackInterface *cb) - : condition(cond) - , callback(cb) - {} - }; -private: - NGL::INGLLogger &m_logger; - void waitSetTask(); -private: + struct WaitSetData final + { + dds::core::cond::Condition condition; + CallbackInterface* callback = nullptr; + bool enabled = true; + bool needWaitSetAttach = false; - NGL::INGLLogger &m_logger; - dds::core::cond::WaitSet m_waitSet; - dds::core::cond::GuardCondition m_abortCondition; - std::future m_task; - std::mutex m_accessMutex; - std::map m_waitSetData; + WaitSetData(const dds::core::cond::Condition& cond, CallbackInterface* cb) : condition(cond), callback(cb) {} + }; + + private: + NGL::INGLLogger& m_logger; + void waitSetTask(); + + private: + NGL::INGLLogger& m_logger; + dds::core::cond::WaitSet m_waitSet; + dds::core::cond::GuardCondition m_abortCondition; + std::future m_task; + std::mutex m_accessMutex; + std::map m_waitSetData; }; -} +} // namespace DDSGeneric diff --git a/qt6-after/qt6-migrated-legatus/Lts/DDS/Routing/routing_plugin.h b/qt6-after/qt6-migrated-legatus/Lts/DDS/Routing/routing_plugin.h old mode 100755 new mode 100644 index e4dcc771a..0e5663490 --- a/qt6-after/qt6-migrated-legatus/Lts/DDS/Routing/routing_plugin.h +++ b/qt6-after/qt6-migrated-legatus/Lts/DDS/Routing/routing_plugin.h @@ -1,362 +1,335 @@ - -#include -#include -#include -#include -#include -#include - #include #include #include - - - - +#include +#include +#include +#include +#include +#include namespace DebugInfo { -static inline QByteArray toReadable(const rti::core::Guid &guid) +static inline QByteArray toReadable(const rti::core::Guid& guid) { - return QByteArray(reinterpret_cast(&guid[0]), 16).toHex(); + return QByteArray(reinterpret_cast(&guid[0]), 16).toHex(); } -static inline QByteArray toReadable(const rti::core::SequenceNumber &seqNo, - const rti::core::Guid &guid) + +static inline QByteArray toReadable(const rti::core::SequenceNumber& seqNo, const rti::core::Guid& guid) { - return "SeqNo: " + QByteArray::number(seqNo.value()) + ", Guid-DW: " + toReadable(guid); + return "SeqNo: " + QByteArray::number(seqNo.value()) + ", Guid-DW: " + toReadable(guid); } -static inline QByteArray toReadable(const rti::core::SampleIdentity &identiy) + +static inline QByteArray toReadable(const rti::core::SampleIdentity& identiy) { - return toReadable(identiy.sequence_number(), identiy.writer_guid()); -} + return toReadable(identiy.sequence_number(), identiy.writer_guid()); } +} // namespace DebugInfo namespace FTS { -template -struct TopicNames; +template struct TopicNames; } + namespace FTC { -template -struct TopicNames; +template struct TopicNames; } namespace RoutingService { - -template -static dds::topic::Topic getTopic(const dds::domain::DomainParticipant &participant, - const std::string &topicName) +template +static dds::topic::Topic getTopic(const dds::domain::DomainParticipant& participant, const std::string& topicName) { - using DataTopic = dds::topic::Topic; - auto ret = dds::topic::find(participant, topicName); - if (ret != nullptr) - return ret; - return DataTopic(participant, topicName); + using DataTopic = dds::topic::Topic; + auto ret = dds::topic::find(participant, topicName); + if (ret != nullptr) + return ret; + return DataTopic(participant, topicName); } - - - class SampleWriterInterface { -public: - SampleWriterInterface() = default; - virtual ~SampleWriterInterface() = default; + public: + SampleWriterInterface() = default; + virtual ~SampleWriterInterface() = default; - virtual void writeSamples() = 0; + virtual void writeSamples() = 0; - virtual NGL::INGLLogger &logger() = 0; + virtual NGL::INGLLogger& logger() = 0; }; class DataWriterTaskInterface { -public: - DataWriterTaskInterface() = default; - virtual ~DataWriterTaskInterface() = default; + public: + DataWriterTaskInterface() = default; + virtual ~DataWriterTaskInterface() = default; - virtual void enqueue(SampleWriterInterface *swi) = 0; + virtual void enqueue(SampleWriterInterface* swi) = 0; }; class TopicDispatcherInterface { -public: - TopicDispatcherInterface() = default; - virtual ~TopicDispatcherInterface() = default; + public: + TopicDispatcherInterface() = default; + virtual ~TopicDispatcherInterface() = default; - virtual bool init(DataWriterTaskInterface *dwt, - const dds::domain::DomainParticipant &dpIn, - const dds::sub::Subscriber &subIn, - const dds::domain::DomainParticipant &dpOut, - const dds::pub::Publisher &pubOut) = 0; - virtual void shutdown() = 0; + virtual bool init(DataWriterTaskInterface* dwt, const dds::domain::DomainParticipant& dpIn, + const dds::sub::Subscriber& subIn, const dds::domain::DomainParticipant& dpOut, + const dds::pub::Publisher& pubOut) = 0; + virtual void shutdown() = 0; }; - - - -template -class SampleWriter final : public SampleWriterInterface +template class SampleWriter final : public SampleWriterInterface { -public: - SampleWriter(dds::sub::LoanedSamples &&samples, - const dds::pub::DataWriter &dataWriter, - bool bWithOriginalIdentity, - NGL::INGLLogger &logger) - : m_loanedSamples(std::move(samples)) - , m_dataWriter(dataWriter) - , m_bWithOriginalIdentity(bWithOriginalIdentity) - , m_logger(logger) - {} - - rti::core::SampleIdentity getIdentity(const rti::core::SampleIdentity &identity) const - { - - static const auto s_unknownSequenceNumber(rti::core::SequenceNumber::unknown()); - static const auto s_unknownGui(rti::core::Guid::unknown()); - static const auto s_unknownSampleIdentity(rti::core::SampleIdentity::unknown()); - - if (!m_bWithOriginalIdentity) - return s_unknownSampleIdentity; - - if (identity.sequence_number() == s_unknownSequenceNumber) - return s_unknownSampleIdentity; - if (identity.writer_guid() == s_unknownGui) - return s_unknownSampleIdentity; - return identity; - } - - void writeSamples() override - { - TRACE_LOG(m_logger) << "Writing samples for " << DDS::topic_type_name::value() - << ", sample count: " << m_loanedSamples.length(); - rti::pub::WriteParams writeParams; - for (const auto &sample : m_loanedSamples) + public: + SampleWriter(dds::sub::LoanedSamples&& samples, const dds::pub::DataWriter& dataWriter, + bool bWithOriginalIdentity, NGL::INGLLogger& logger) + : m_loanedSamples(std::move(samples)), m_dataWriter(dataWriter), m_bWithOriginalIdentity(bWithOriginalIdentity), + m_logger(logger) { - try - { - writeParams.identity(getIdentity(sample.info()->original_publication_virtual_sample_identity())); - writeParams.related_sample_identity(getIdentity(sample.info()->related_original_publication_virtual_sample_identity())); - - - writeParams.handle(sample.info().instance_handle()); - writeParams.flag(sample.info()->flag()); - - - - TRACE_LOG(m_logger) << "identity: " << DebugInfo::toReadable(writeParams.identity()) - << ", related_sample_identity: " << DebugInfo::toReadable(writeParams.related_sample_identity()); - - const auto &state = sample.info().state(); - const dds::sub::status::InstanceState &instanceState = state.instance_state(); - if (instanceState == dds::sub::status::InstanceState::alive()) - { - m_dataWriter->write(sample.data(), writeParams); - } - else if (instanceState == dds::sub::status::InstanceState::not_alive_disposed()) - { - TRACE_LOG(m_logger) << " - is disposed"; - m_dataWriter->dispose_instance(writeParams); - } - else if (instanceState == dds::sub::status::InstanceState::not_alive_no_writers()) - { - TRACE_LOG(m_logger) << " - is unregistered"; - m_dataWriter->unregister_instance(writeParams); - } - else - WARNING_LOG(m_logger) << "Unknown instance state: " << instanceState; - } - catch (const dds::core::Exception &ex) - { - ERROR_LOG(m_logger) << "writeSamples exception: " << ex.what(); - } } - m_dataWriter->flush(); - } - NGL::INGLLogger &logger() override { return m_logger; } -private: - dds::sub::LoanedSamples m_loanedSamples; - dds::pub::DataWriter m_dataWriter; - bool m_bWithOriginalIdentity; - NGL::INGLLogger &m_logger; -}; -template -class DataTopicListener final : public dds::sub::DataReaderListener -{ -public: - using DataReader = dds::sub::DataReader; - - DataTopicListener(DataWriterTaskInterface *dwt, - const std::string &topicName, - DDS::QosProfile::TopicType topicType, - NGL::INGLLogger &logger) - : m_dwt(dwt) - , m_dataWriter(nullptr) - , m_topicName(topicName) - , m_topicType(topicType) - , m_logger(logger) - {} - - bool init(const dds::domain::DomainParticipant &dpOut, - const dds::pub::Publisher &pubOut) - { - if (!m_dwt) - return false; - DEBUG_LOG(m_logger) << "Creating DataWriter for domain " << dpOut.domain_id(); - m_dataWriter = dds::pub::DataWriter(pubOut, - getTopic(dpOut, m_topicName), - DDS::QosProfile::dataWriterDefault(m_topicType)); - - - dds::domain::DomainParticipant &dpOutNonConst = const_cast(dpOut); - dds::pub::ignore(dpOutNonConst, m_dataWriter.instance_handle()); - return true; - } - - void on_data_available(dds::sub::DataReader &reader) override - { - - - TRACE_LOG(m_logger) << "Data available for " << DDS::topic_type_name::value(); - auto ws = new SampleWriter(reader.take(), m_dataWriter, m_topicType == DDS::QosProfile::TopicType::FunctionTopic, m_logger); - m_dwt->enqueue(ws); - } - - void on_requested_deadline_missed(dds::sub::DataReader &, const dds::core::status::RequestedDeadlineMissedStatus &) override {} - void on_requested_incompatible_qos(dds::sub::DataReader &, - const dds::core::status::RequestedIncompatibleQosStatus &) override {} - void on_sample_rejected(dds::sub::DataReader &, - const dds::core::status::SampleRejectedStatus &) override {} - void on_liveliness_changed(dds::sub::DataReader &, - const dds::core::status::LivelinessChangedStatus &) override {} - void on_subscription_matched(dds::sub::DataReader &, - const dds::core::status::SubscriptionMatchedStatus &) override {} - void on_sample_lost(dds::sub::DataReader &, - const dds::core::status::SampleLostStatus &) override {} - - static dds::core::status::StatusMask mask() - { - return (dds::core::status::StatusMask::data_available()); - } - -protected: - DataWriterTaskInterface *m_dwt; - dds::pub::DataWriter m_dataWriter; - std::string m_topicName; - DDS::QosProfile::TopicType m_topicType; - NGL::INGLLogger &m_logger; -}; - -template -class TopicDispatcher : public TopicDispatcherInterface -{ -protected: - explicit TopicDispatcher(NGL::INGLLogger &logger, const std::string &topicName, DDS::QosProfile::TopicType topicType) - : m_dataReader(nullptr) - , m_topicName(topicName) - , m_topicType(topicType) - , m_logger(logger) - { - } - - ~TopicDispatcher() - { - shutdown(); - } - - bool init(DataWriterTaskInterface *dwt, - const dds::domain::DomainParticipant &dpIn, - const dds::sub::Subscriber &subIn, - const dds::domain::DomainParticipant &dpOut, - const dds::pub::Publisher &pubOut) override - { - DEBUG_LOG(m_logger) << "Initializing TopicDispatcher " << "(" << this << ")"; - if (m_dataReader != nullptr) - return false; - - m_dataReader = dds::sub::DataReader(subIn, - getTopic(dpIn, m_topicName), - DDS::QosProfile::dataReaderDefault(m_topicType)); - DEBUG_LOG(m_logger) << "Creating DataReader for domain " << dpIn.domain_id() << ", ptr: " << m_dataReader.delegate().get(); - - m_dtl.reset(new DataTopicListener(dwt, m_topicName, m_topicType, m_logger)); - - if (!m_dtl->init(dpOut, pubOut)) - return false; - m_dataReader.listener(m_dtl.get(), DataTopicListener::mask()); - return true; - } - - void shutdown() override - { - DEBUG_LOG(m_logger) << "Cleaning up TopicDispatcher " << "(" << this << ")"; - if (m_dataReader != nullptr) + rti::core::SampleIdentity getIdentity(const rti::core::SampleIdentity& identity) const { - DEBUG_LOG(m_logger) << "shutting down DataReader: " << m_dataReader.delegate().get(); - m_dataReader.listener(nullptr, dds::core::status::StatusMask::none()); - try - { - m_dataReader.close(); - } - catch (const dds::core::Exception &ex) - { - ERROR_LOG(m_logger) << "topic close ex: " << ex.what(); - } + + static const auto s_unknownSequenceNumber(rti::core::SequenceNumber::unknown()); + static const auto s_unknownGui(rti::core::Guid::unknown()); + static const auto s_unknownSampleIdentity(rti::core::SampleIdentity::unknown()); + + if (!m_bWithOriginalIdentity) + return s_unknownSampleIdentity; + + if (identity.sequence_number() == s_unknownSequenceNumber) + return s_unknownSampleIdentity; + if (identity.writer_guid() == s_unknownGui) + return s_unknownSampleIdentity; + return identity; } - - - m_dtl = nullptr; - - m_dataReader = nullptr; - } -private: - dds::sub::DataReader m_dataReader; - std::unique_ptr> m_dtl; - std::string m_topicName; - DDS::QosProfile::TopicType m_topicType; - NGL::INGLLogger &m_logger; + void writeSamples() override + { + TRACE_LOG(m_logger) << "Writing samples for " << DDS::topic_type_name::value() + << ", sample count: " << m_loanedSamples.length(); + rti::pub::WriteParams writeParams; + for (const auto& sample : m_loanedSamples) + { + try + { + writeParams.identity(getIdentity(sample.info()->original_publication_virtual_sample_identity())); + writeParams.related_sample_identity( + getIdentity(sample.info()->related_original_publication_virtual_sample_identity())); + + writeParams.handle(sample.info().instance_handle()); + writeParams.flag(sample.info()->flag()); + + TRACE_LOG(m_logger) << "identity: " << DebugInfo::toReadable(writeParams.identity()) + << ", related_sample_identity: " + << DebugInfo::toReadable(writeParams.related_sample_identity()); + + const auto& state = sample.info().state(); + const dds::sub::status::InstanceState& instanceState = state.instance_state(); + if (instanceState == dds::sub::status::InstanceState::alive()) + { + m_dataWriter->write(sample.data(), writeParams); + } + else if (instanceState == dds::sub::status::InstanceState::not_alive_disposed()) + { + TRACE_LOG(m_logger) << " - is disposed"; + m_dataWriter->dispose_instance(writeParams); + } + else if (instanceState == dds::sub::status::InstanceState::not_alive_no_writers()) + { + TRACE_LOG(m_logger) << " - is unregistered"; + m_dataWriter->unregister_instance(writeParams); + } + else + WARNING_LOG(m_logger) << "Unknown instance state: " << instanceState; + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(m_logger) << "writeSamples exception: " << ex.what(); + } + } + m_dataWriter->flush(); + } + + NGL::INGLLogger& logger() override + { + return m_logger; + } + + private: + dds::sub::LoanedSamples m_loanedSamples; + dds::pub::DataWriter m_dataWriter; + bool m_bWithOriginalIdentity; + NGL::INGLLogger& m_logger; }; - -template -class DataTopicDispatcher final : public TopicDispatcher +template class DataTopicListener final : public dds::sub::DataReaderListener { -public: - explicit DataTopicDispatcher(NGL::INGLLogger &logger) - : TopicDispatcher(logger, - DDS::Helper::getShortTopicName(dds::topic::topic_type_name::value()), - DDS::QosProfile::TopicType::DataTopic) - {} + public: + using DataReader = dds::sub::DataReader; + + DataTopicListener(DataWriterTaskInterface* dwt, const std::string& topicName, DDS::QosProfile::TopicType topicType, + NGL::INGLLogger& logger) + : m_dwt(dwt), m_dataWriter(nullptr), m_topicName(topicName), m_topicType(topicType), m_logger(logger) + { + } + + bool init(const dds::domain::DomainParticipant& dpOut, const dds::pub::Publisher& pubOut) + { + if (!m_dwt) + return false; + DEBUG_LOG(m_logger) << "Creating DataWriter for domain " << dpOut.domain_id(); + m_dataWriter = dds::pub::DataWriter(pubOut, getTopic(dpOut, m_topicName), + DDS::QosProfile::dataWriterDefault(m_topicType)); + + dds::domain::DomainParticipant& dpOutNonConst = const_cast(dpOut); + dds::pub::ignore(dpOutNonConst, m_dataWriter.instance_handle()); + return true; + } + + void on_data_available(dds::sub::DataReader& reader) override + { + + TRACE_LOG(m_logger) << "Data available for " << DDS::topic_type_name::value(); + auto ws = new SampleWriter(reader.take(), m_dataWriter, + m_topicType == DDS::QosProfile::TopicType::FunctionTopic, m_logger); + m_dwt->enqueue(ws); + } + + void on_requested_deadline_missed(dds::sub::DataReader&, + const dds::core::status::RequestedDeadlineMissedStatus&) override + { + } + + void on_requested_incompatible_qos(dds::sub::DataReader&, + const dds::core::status::RequestedIncompatibleQosStatus&) override + { + } + + void on_sample_rejected(dds::sub::DataReader&, const dds::core::status::SampleRejectedStatus&) override {} + + void on_liveliness_changed(dds::sub::DataReader&, const dds::core::status::LivelinessChangedStatus&) override {} + + void on_subscription_matched(dds::sub::DataReader&, const dds::core::status::SubscriptionMatchedStatus&) override + { + } + + void on_sample_lost(dds::sub::DataReader&, const dds::core::status::SampleLostStatus&) override {} + + static dds::core::status::StatusMask mask() + { + return (dds::core::status::StatusMask::data_available()); + } + + protected: + DataWriterTaskInterface* m_dwt; + dds::pub::DataWriter m_dataWriter; + std::string m_topicName; + DDS::QosProfile::TopicType m_topicType; + NGL::INGLLogger& m_logger; }; +template class TopicDispatcher : public TopicDispatcherInterface +{ + protected: + explicit TopicDispatcher(NGL::INGLLogger& logger, const std::string& topicName, + DDS::QosProfile::TopicType topicType) + : m_dataReader(nullptr), m_topicName(topicName), m_topicType(topicType), m_logger(logger) + { + } -template + ~TopicDispatcher() + { + shutdown(); + } + + bool init(DataWriterTaskInterface* dwt, const dds::domain::DomainParticipant& dpIn, + const dds::sub::Subscriber& subIn, const dds::domain::DomainParticipant& dpOut, + const dds::pub::Publisher& pubOut) override + { + DEBUG_LOG(m_logger) << "Initializing TopicDispatcher " << "(" << this << ")"; + if (m_dataReader != nullptr) + return false; + + m_dataReader = dds::sub::DataReader(subIn, getTopic(dpIn, m_topicName), + DDS::QosProfile::dataReaderDefault(m_topicType)); + DEBUG_LOG(m_logger) << "Creating DataReader for domain " << dpIn.domain_id() + << ", ptr: " << m_dataReader.delegate().get(); + + m_dtl.reset(new DataTopicListener(dwt, m_topicName, m_topicType, m_logger)); + + if (!m_dtl->init(dpOut, pubOut)) + return false; + m_dataReader.listener(m_dtl.get(), DataTopicListener::mask()); + return true; + } + + void shutdown() override + { + DEBUG_LOG(m_logger) << "Cleaning up TopicDispatcher " << "(" << this << ")"; + if (m_dataReader != nullptr) + { + DEBUG_LOG(m_logger) << "shutting down DataReader: " << m_dataReader.delegate().get(); + m_dataReader.listener(nullptr, dds::core::status::StatusMask::none()); + try + { + m_dataReader.close(); + } + catch (const dds::core::Exception& ex) + { + ERROR_LOG(m_logger) << "topic close ex: " << ex.what(); + } + } + + m_dtl = nullptr; + + m_dataReader = nullptr; + } + + private: + dds::sub::DataReader m_dataReader; + std::unique_ptr> m_dtl; + std::string m_topicName; + DDS::QosProfile::TopicType m_topicType; + NGL::INGLLogger& m_logger; +}; + +template class DataTopicDispatcher final : public TopicDispatcher +{ + public: + explicit DataTopicDispatcher(NGL::INGLLogger& logger) + : TopicDispatcher(logger, DDS::Helper::getShortTopicName(dds::topic::topic_type_name::value()), + DDS::QosProfile::TopicType::DataTopic) + { + } +}; + +template class FunctionTopicReplyDispatcher final : public TopicDispatcher { -public: - explicit FunctionTopicReplyDispatcher(NGL::INGLLogger &logger) - : TopicDispatcher(logger, - FTS::TopicNames::replyTopicName(), - DDS::QosProfile::TopicType::FunctionTopic) - {} + public: + explicit FunctionTopicReplyDispatcher(NGL::INGLLogger& logger) + : TopicDispatcher(logger, FTS::TopicNames::replyTopicName(), + DDS::QosProfile::TopicType::FunctionTopic) + { + } }; - -template +template class FunctionTopicRequestDispatcher final : public TopicDispatcher { -public: - explicit FunctionTopicRequestDispatcher(NGL::INGLLogger &logger) - : TopicDispatcher(logger, - FTC::TopicNames::requestTopicName(), - DDS::QosProfile::TopicType::FunctionTopic) - {} + public: + explicit FunctionTopicRequestDispatcher(NGL::INGLLogger& logger) + : TopicDispatcher(logger, FTC::TopicNames::requestTopicName(), + DDS::QosProfile::TopicType::FunctionTopic) + { + } }; -} +} // namespace RoutingService diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.cpp old mode 100755 new mode 100644 index 2b53c760d..b716073f4 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.cpp @@ -1,218 +1,211 @@ - #include "asb_foreign_interface_impl.h" + #include "logger.h" + #include #include -#include #include +#include namespace AdvancedSymbology { -ForeignInterfaceImpl::ForeignInterfaceImpl(const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc, - const std::shared_ptr &guezIedDtc) - : m_ppmDtc(ppmDtc) - , m_aesDtc(aesDtc) - , m_guezIedDtc(guezIedDtc) +ForeignInterfaceImpl::ForeignInterfaceImpl(const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc, + const std::shared_ptr& guezIedDtc) + : m_ppmDtc(ppmDtc), m_aesDtc(aesDtc), m_guezIedDtc(guezIedDtc) { - if (!m_ppmDtc) - { - WARNING_LOG(m_logger) << "m_ppmDtc not available, No color and injury information will be included in created symbols"; - Q_ASSERT(false); - } + if (!m_ppmDtc) + { + WARNING_LOG(m_logger) + << "m_ppmDtc not available, No color and injury information will be included in created symbols"; + Q_ASSERT(false); + } } - -AdvancedSymbology::SymbolDictionary &ForeignInterfaceImpl::getSymbolDictionary(AdvancedSymbology::SymbologyType type) const +AdvancedSymbology::SymbolDictionary& +ForeignInterfaceImpl::getSymbolDictionary(AdvancedSymbology::SymbologyType type) const { - - return AdvancedSymbology::SymbolDictionary::dictionary(type); -} + return AdvancedSymbology::SymbolDictionary::dictionary(type); +} AdvancedSymbology::SymbologyType ForeignInterfaceImpl::defaultSymbologyType() const { - return AdvancedSymbology::SymbolDictionary::defaultSymbologyType(); -} - - -QSharedPointer ForeignInterfaceImpl::findImage(const SymbolDictionary &dict, - const SymbolDataToRender &symDataToRender) const -{ - return dict.findImage(symDataToRender); + return AdvancedSymbology::SymbolDictionary::defaultSymbologyType(); } - -QSharedPointer ForeignInterfaceImpl::findImage(const SymbolDataToRender &symDataToRender) const +QSharedPointer ForeignInterfaceImpl::findImage(const SymbolDictionary& dict, + const SymbolDataToRender& symDataToRender) const { - return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findImage(symDataToRender); + return dict.findImage(symDataToRender); } - -QSharedPointer ForeignInterfaceImpl::findImage(const ParticipantManagement::Participant &participant, int sizeL, const QColor &desiredColor) const +QSharedPointer ForeignInterfaceImpl::findImage(const SymbolDataToRender& symDataToRender) const { - AdvancedSymbology::SymbolDataToRender symDataToRender(QString::fromStdString(participant.symbol()), sizeL); + return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findImage(symDataToRender); +} - if (!m_ppmDtc) - return findImage(symDataToRender); +QSharedPointer ForeignInterfaceImpl::findImage(const ParticipantManagement::Participant& participant, + int sizeL, const QColor& desiredColor) const +{ + AdvancedSymbology::SymbolDataToRender symDataToRender(QString::fromStdString(participant.symbol()), sizeL); - - const ParticipantManagement::Party &party = m_ppmDtc->party(participant.partyId()); - symDataToRender.role = AdvancedSymbology::roleToRole<>(party.role()); + if (!m_ppmDtc) + return findImage(symDataToRender); - - symDataToRender.fillColor = desiredColor.isValid() ? desiredColor : QColor::fromRgb(QRgb(party.color())); - symDataToRender.fillColorReplace = true; + const ParticipantManagement::Party& party = m_ppmDtc->party(participant.partyId()); + symDataToRender.role = AdvancedSymbology::roleToRole<>(party.role()); - - QColor injuryColor = QColor(100, 100, 0); - ProjectDataManagement::VulnerabilityState currentState = ProjectDataManagement::VulnerabilityState::CombatReady; + symDataToRender.fillColor = desiredColor.isValid() ? desiredColor : QColor::fromRgb(QRgb(party.color())); + symDataToRender.fillColorReplace = true; - const ParticipantManagement::DynamicParticipantData dData = m_ppmDtc->dynamicParticipantData(participant.id()); + QColor injuryColor = QColor(100, 100, 0); + ProjectDataManagement::VulnerabilityState currentState = ProjectDataManagement::VulnerabilityState::CombatReady; - if (dData.stateHistory().size()) - { - const ParticipantManagement::StateInformation &lastState = m_ppmDtc->youngestStateInformation(dData.stateHistory()); - currentState = lastState.vulnerabilityState(); + const ParticipantManagement::DynamicParticipantData dData = m_ppmDtc->dynamicParticipantData(participant.id()); - switch (lastState.originatorType().underlying()) + if (dData.stateHistory().size()) { - case ProjectDataManagement::StateChangeOriginator::ImprovisedExplosiveDevice: - { - if (m_guezIedDtc) - { - const GuezIedManagement::Ied &gIed = m_guezIedDtc->iedForEquipmentNumber(lastState.originatorId()); - if (gIed.id() > 0) + const ParticipantManagement::StateInformation& lastState = + m_ppmDtc->youngestStateInformation(dData.stateHistory()); + currentState = lastState.vulnerabilityState(); + + switch (lastState.originatorType().underlying()) { - int injuryPartyId = gIed.partyId(); - if (injuryPartyId >= 0) - injuryColor = m_ppmDtc->party(injuryPartyId).color(); + case ProjectDataManagement::StateChangeOriginator::ImprovisedExplosiveDevice: { + if (m_guezIedDtc) + { + const GuezIedManagement::Ied& gIed = m_guezIedDtc->iedForEquipmentNumber(lastState.originatorId()); + if (gIed.id() > 0) + { + int injuryPartyId = gIed.partyId(); + if (injuryPartyId >= 0) + injuryColor = m_ppmDtc->party(injuryPartyId).color(); + } + } + break; + } + case ProjectDataManagement::StateChangeOriginator::DusMine: { + if (!m_aesDtc) + { + WARNING_LOG(m_logger) << "Fetching 'm_aesDtc' failed, No color and injury information will be " + "included in symbol created for participant.id() " + << participant.id(); + return findImage(symDataToRender); + } + const int partyId = m_aesDtc->partyForDusMine(lastState.originatorId()); + if (partyId >= 0) + injuryColor = m_ppmDtc->party(partyId).color(); + break; + } + case ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation: + case ProjectDataManagement::StateChangeOriginator::FunctionalArea: { + if (!m_aesDtc) + { + WARNING_LOG(m_logger) << "Fetching 'm_aesDtc' failed, No color and injury information will be " + "included in symbol created for participant.id() " + << participant.id(); + return findImage(symDataToRender); + } + + AreaEffectSimulation::AesItem aesItem; + m_aesDtc->aesItemFromId(lastState.originatorId(), aesItem); + + if (aesItem.partyId().is_set()) + injuryColor = m_ppmDtc->party(aesItem.partyId().get()).color(); + + break; + } + + case ProjectDataManagement::StateChangeOriginator::Participant: { + const ParticipantManagement::Participant& participantOrigin = + m_ppmDtc->participant(lastState.originatorId()); + + if (participantOrigin.id()) + injuryColor = m_ppmDtc->party(participantOrigin.partyId()).color(); + break; + } + case ProjectDataManagement::StateChangeOriginator::Party: { + const ParticipantManagement::Party& partyOrigin = m_ppmDtc->party(lastState.originatorId()); + + if (partyOrigin.id()) + injuryColor = partyOrigin.color(); + break; + } + case ProjectDataManagement::StateChangeOriginator::ObserverController: + case ProjectDataManagement::StateChangeOriginator::ExerciseControl: + case ProjectDataManagement::StateChangeOriginator::Initialization: + injuryColor = m_ppmDtc->party(1).color(); + break; + case ProjectDataManagement::StateChangeOriginator::WoundTreatmentDevice: + case ProjectDataManagement::StateChangeOriginator::MedicalTimeout: + case ProjectDataManagement::StateChangeOriginator::Sanitation: + case ProjectDataManagement::StateChangeOriginator::MaintainanceDevice: + case ProjectDataManagement::StateChangeOriginator::Unknown: + break; } - } - break; - } - case ProjectDataManagement::StateChangeOriginator::DusMine: - { - if (!m_aesDtc) - { - WARNING_LOG(m_logger) << "Fetching 'm_aesDtc' failed, No color and injury information will be included in symbol created for participant.id() " << participant.id(); - return findImage(symDataToRender); - } - const int partyId = m_aesDtc->partyForDusMine(lastState.originatorId()); - if (partyId >= 0) - injuryColor = m_ppmDtc->party(partyId).color(); - break; - } - case ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation: - case ProjectDataManagement::StateChangeOriginator::FunctionalArea: - { - if (!m_aesDtc) - { - WARNING_LOG(m_logger) << "Fetching 'm_aesDtc' failed, No color and injury information will be included in symbol created for participant.id() " << participant.id(); - return findImage(symDataToRender); - } - - AreaEffectSimulation::AesItem aesItem; - m_aesDtc->aesItemFromId(lastState.originatorId(), aesItem); - - if (aesItem.partyId().is_set()) - injuryColor = m_ppmDtc->party(aesItem.partyId().get()).color(); - - break; } - case ProjectDataManagement::StateChangeOriginator::Participant: - { - const ParticipantManagement::Participant &participantOrigin = m_ppmDtc->participant(lastState.originatorId()); + symDataToRender.injury = stateToInjury(currentState); + symDataToRender.injuryColor = injuryColor; - - if (participantOrigin.id()) - injuryColor = m_ppmDtc->party(participantOrigin.partyId()).color(); - break; - } - case ProjectDataManagement::StateChangeOriginator::Party: - { - const ParticipantManagement::Party &partyOrigin = m_ppmDtc->party(lastState.originatorId()); - - if (partyOrigin.id()) - injuryColor = partyOrigin.color(); - break; - } - case ProjectDataManagement::StateChangeOriginator::ObserverController: - case ProjectDataManagement::StateChangeOriginator::ExerciseControl: - case ProjectDataManagement::StateChangeOriginator::Initialization: - injuryColor = m_ppmDtc->party(1).color(); - break; - case ProjectDataManagement::StateChangeOriginator::WoundTreatmentDevice: - case ProjectDataManagement::StateChangeOriginator::MedicalTimeout: - case ProjectDataManagement::StateChangeOriginator::Sanitation: - case ProjectDataManagement::StateChangeOriginator::MaintainanceDevice: - case ProjectDataManagement::StateChangeOriginator::Unknown: - break; - } - } - - symDataToRender.injury = stateToInjury(currentState); - symDataToRender.injuryColor = injuryColor; - - return findImage(symDataToRender); + return findImage(symDataToRender); } - -AdvancedSymbology::Injury ForeignInterfaceImpl::stateToInjury(const ProjectDataManagement::VulnerabilityState &state) +AdvancedSymbology::Injury ForeignInterfaceImpl::stateToInjury(const ProjectDataManagement::VulnerabilityState& state) { - switch (state.underlying()) - { - case ProjectDataManagement::VulnerabilityState::CombatReady: - case ProjectDataManagement::VulnerabilityState::TemporarySeverance: - case ProjectDataManagement::VulnerabilityState::NearMiss: - case ProjectDataManagement::VulnerabilityState::HitWithNoEffect: + switch (state.underlying()) + { + case ProjectDataManagement::VulnerabilityState::CombatReady: + case ProjectDataManagement::VulnerabilityState::TemporarySeverance: + case ProjectDataManagement::VulnerabilityState::NearMiss: + case ProjectDataManagement::VulnerabilityState::HitWithNoEffect: + return AdvancedSymbology::Injury::NoInjury; + case ProjectDataManagement::VulnerabilityState::LightDamage: + case ProjectDataManagement::VulnerabilityState::MediumDamage: + case ProjectDataManagement::VulnerabilityState::HeavyDamage: + case ProjectDataManagement::VulnerabilityState::NotReady: + return AdvancedSymbology::Injury::Hit; + case ProjectDataManagement::VulnerabilityState::MobilityKill: + case ProjectDataManagement::VulnerabilityState::VisibleMobilityKill: + return AdvancedSymbology::Injury::MobilityKill; + case ProjectDataManagement::VulnerabilityState::WeaponSystemDamage: + case ProjectDataManagement::VulnerabilityState::VisibleWeaponSystemDamage: + return AdvancedSymbology::Injury::WeaponKill; + case ProjectDataManagement::VulnerabilityState::CatastrophicKill: + return AdvancedSymbology::Injury::TotalKill; + case ProjectDataManagement::VulnerabilityState::NContamination: + case ProjectDataManagement::VulnerabilityState::BContamination: + case ProjectDataManagement::VulnerabilityState::CContamination: + case ProjectDataManagement::VulnerabilityState::VulnerabilityBitsChanged: + case ProjectDataManagement::VulnerabilityState::Reserved: + case ProjectDataManagement::VulnerabilityState::NoChange: + break; + } return AdvancedSymbology::Injury::NoInjury; - case ProjectDataManagement::VulnerabilityState::LightDamage: - case ProjectDataManagement::VulnerabilityState::MediumDamage: - case ProjectDataManagement::VulnerabilityState::HeavyDamage: - case ProjectDataManagement::VulnerabilityState::NotReady: - return AdvancedSymbology::Injury::Hit; - case ProjectDataManagement::VulnerabilityState::MobilityKill: - case ProjectDataManagement::VulnerabilityState::VisibleMobilityKill: - return AdvancedSymbology::Injury::MobilityKill; - case ProjectDataManagement::VulnerabilityState::WeaponSystemDamage: - case ProjectDataManagement::VulnerabilityState::VisibleWeaponSystemDamage: - return AdvancedSymbology::Injury::WeaponKill; - case ProjectDataManagement::VulnerabilityState::CatastrophicKill: - return AdvancedSymbology::Injury::TotalKill; - case ProjectDataManagement::VulnerabilityState::NContamination: - case ProjectDataManagement::VulnerabilityState::BContamination: - case ProjectDataManagement::VulnerabilityState::CContamination: - case ProjectDataManagement::VulnerabilityState::VulnerabilityBitsChanged: - case ProjectDataManagement::VulnerabilityState::Reserved: - case ProjectDataManagement::VulnerabilityState::NoChange: - break; - } - return AdvancedSymbology::Injury::NoInjury; } - -QSharedPointer ForeignInterfaceImpl::findPreview(const SymbolDictionary &dict, const QString &sidc) const +QSharedPointer ForeignInterfaceImpl::findPreview(const SymbolDictionary& dict, const QString& sidc) const { - return dict.findPreview(sidc); + return dict.findPreview(sidc); } -QSharedPointer ForeignInterfaceImpl::findPreview(const QString &sidc) const +QSharedPointer ForeignInterfaceImpl::findPreview(const QString& sidc) const { - return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findPreview(sidc); + return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findPreview(sidc); } -QSharedPointer ForeignInterfaceImpl::findBaseSymbol(const SymbolDictionary &dict, const QString &sidc) const +QSharedPointer ForeignInterfaceImpl::findBaseSymbol(const SymbolDictionary& dict, + const QString& sidc) const { - return dict.findBaseSymbol(sidc); + return dict.findBaseSymbol(sidc); } -QSharedPointer ForeignInterfaceImpl::findBaseSymbol(const QString &sidc) const +QSharedPointer ForeignInterfaceImpl::findBaseSymbol(const QString& sidc) const { - return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findBaseSymbol(sidc); + return AdvancedSymbology::SymbolDictionary::dictionary(defaultSymbologyType()).findBaseSymbol(sidc); } -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h old mode 100755 new mode 100644 index 4e07a85f8..a0d425ac5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Data/asb_foreign_interface_impl.h @@ -1,12 +1,11 @@ - #pragma once -#include #include -#include +#include #include +#include #include namespace AreaEffectSimulation @@ -15,50 +14,49 @@ namespace Interface { class Dtc; } -} +} // namespace AreaEffectSimulation + namespace ParticipantManagement { namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace AdvancedSymbology { class ForeignInterfaceImpl final : public QObject, public ForeignDataInterface { - Q_OBJECT -public: - explicit ForeignInterfaceImpl(const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc, - const std::shared_ptr &guezIedDtc); + Q_OBJECT + public: + explicit ForeignInterfaceImpl(const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc, + const std::shared_ptr& guezIedDtc); - - - - AdvancedSymbology::SymbolDictionary &getSymbolDictionary(AdvancedSymbology::SymbologyType type) const override; + AdvancedSymbology::SymbolDictionary& getSymbolDictionary(AdvancedSymbology::SymbologyType type) const override; - QSharedPointer findImage(const SymbolDictionary &dict, const SymbolDataToRender &symDataToRender) const override; - QSharedPointer findImage(const SymbolDataToRender &symDataToRender) const override; - QSharedPointer findImage(const ParticipantManagement::Participant &participant, int sizeL = 100, const QColor& desiredColor = QColor()) const override; + QSharedPointer findImage(const SymbolDictionary& dict, + const SymbolDataToRender& symDataToRender) const override; + QSharedPointer findImage(const SymbolDataToRender& symDataToRender) const override; + QSharedPointer findImage(const ParticipantManagement::Participant& participant, int sizeL = 100, + const QColor& desiredColor = QColor()) const override; - QSharedPointer findPreview(const SymbolDictionary &dict, const QString &sidc) const override; - QSharedPointer findPreview(const QString &sidc) const override; + QSharedPointer findPreview(const SymbolDictionary& dict, const QString& sidc) const override; + QSharedPointer findPreview(const QString& sidc) const override; - QSharedPointer findBaseSymbol(const SymbolDictionary &dict, const QString &sidc) const override; - QSharedPointer findBaseSymbol(const QString &sidc) const override; + QSharedPointer findBaseSymbol(const SymbolDictionary& dict, const QString& sidc) const override; + QSharedPointer findBaseSymbol(const QString& sidc) const override; - AdvancedSymbology::SymbologyType defaultSymbologyType() const override; + AdvancedSymbology::SymbologyType defaultSymbologyType() const override; -private: + private: + NGL::INGLLogger& m_logger; + static AdvancedSymbology::Injury stateToInjury(const ProjectDataManagement::VulnerabilityState& state); -NGL::INGLLogger &m_logger; - static AdvancedSymbology::Injury stateToInjury(const ProjectDataManagement::VulnerabilityState &state); - - std::shared_ptr m_ppmDtc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_guezIedDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_guezIedDtc; }; -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_select_text_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_select_text_dialog.h old mode 100755 new mode 100644 index 1cc6ad0dd..0395dce60 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_select_text_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_select_text_dialog.h @@ -1,10 +1,9 @@ - #pragma once -#include #include +#include class Ui_SelectTextDialog; @@ -13,24 +12,21 @@ namespace AdvancedSymbology class SelectTextDialog final : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - SelectTextDialog(QVariant &returnData, QWidget *parent); - ~SelectTextDialog(); + public: + SelectTextDialog(QVariant& returnData, QWidget* parent); + ~SelectTextDialog(); -protected: + protected: + NGL::INGLLogger& m_logger; + Ui_SelectTextDialog* ui; -NGL::INGLLogger &m_logger; - Ui_SelectTextDialog *ui; + private: + QVariant& m_returnData; -private: - - QVariant &m_returnData; - - -public slots: - void accept() override final; + public slots: + void accept() override final; }; -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.cpp old mode 100755 new mode 100644 index 81f2efd70..ab689b588 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.cpp @@ -1,149 +1,124 @@ - #include "asb_symbol_editor.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include +#include "asb_delete_elements_dialog.h" #include "asb_resize_dialog.h" #include "asb_rotate_dialog.h" -#include "asb_select_text_dialog.h" -#include "asb_delete_elements_dialog.h" #include "asb_save_as_symbol.h" +#include "asb_select_text_dialog.h" #include "asb_symbol_edit_scene.h" #include "flm_reply_handler.h" - #include "ui_asb_symbol_editor.h" - +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace AdvancedSymbology { -constexpr double VIEW_SCALE = 116.0; -constexpr double PREVIEW_SCALE = 10.0; -constexpr int SYMBOL_FOLDER_ID = 30; +constexpr double VIEW_SCALE = 116.0; +constexpr double PREVIEW_SCALE = 10.0; +constexpr int SYMBOL_FOLDER_ID = 30; class SymbolEditorPrivate { -public: - int m_lastFileId; - int m_lastValidFileId; - int m_lastFolderId; - double m_gridWidth; - double m_previewZoom; - double m_drawAreaZoom; - double m_transparency; - bool m_initFinished; - bool m_showDrawArea; - bool m_fillPrimitive; - bool m_updateInProgress; - bool m_displayPreviewBackground; - bool m_copyFromSelectedPrimitive; - bool m_saveSuccess; + public: + int m_lastFileId; + int m_lastValidFileId; + int m_lastFolderId; + double m_gridWidth; + double m_previewZoom; + double m_drawAreaZoom; + double m_transparency; + bool m_initFinished; + bool m_showDrawArea; + bool m_fillPrimitive; + bool m_updateInProgress; + bool m_displayPreviewBackground; + bool m_copyFromSelectedPrimitive; + bool m_saveSuccess; - SymbolEditor::t_editMode m_editMode; + SymbolEditor::t_editMode m_editMode; - SymbologyXML::SymbolTable m_symbolFrames; - SymbologyXML::SymbolTable m_app6cFrames; - SymbologyXML::SymbolTable m_mobilitySymbols; - SymbologyXML::SymbolTable m_vehicleSymbols; - SymbologyXML::SymbolTable m_intrinsicMobilitySymbols; - SymbologyXML::SymbolTable m_armingSymbols; - SymbologyXML::SymbolTable m_sectorSymbols; - SymbologyXML::SymbolTable m_miscSymbols; - SymbologyXML::SymbolTable m_bcdabSymbols; - SymbologyXML::SymbolTable m_commandLevelSymbols; - SymbologyXML::SymbolTable m_branchSymbols; + SymbologyXML::SymbolTable m_symbolFrames; + SymbologyXML::SymbolTable m_app6cFrames; + SymbologyXML::SymbolTable m_mobilitySymbols; + SymbologyXML::SymbolTable m_vehicleSymbols; + SymbologyXML::SymbolTable m_intrinsicMobilitySymbols; + SymbologyXML::SymbolTable m_armingSymbols; + SymbologyXML::SymbolTable m_sectorSymbols; + SymbologyXML::SymbolTable m_miscSymbols; + SymbologyXML::SymbolTable m_bcdabSymbols; + SymbologyXML::SymbolTable m_commandLevelSymbols; + SymbologyXML::SymbolTable m_branchSymbols; - QVector m_symbolUndoStack; + QVector m_symbolUndoStack; - std::shared_ptr m_flmFtc; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmGui; - std::shared_ptr m_ppmDtc; - QJsonDocument m_attributes; - FileManagementReplyHandler *m_replyHandler; + std::shared_ptr m_flmFtc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmGui; + std::shared_ptr m_ppmDtc; + QJsonDocument m_attributes; + FileManagementReplyHandler* m_replyHandler; - QPen m_pen; - QColor m_previewColor; - QColor m_fillColor; - QString m_symbolFileName; - QString m_lastFileName; - QPixmap m_previewBackground; - QPointF m_currentGraphicsItemPos; - QMap m_symbolColorsEditView; - QVector > m_symbolColorsPreview; - SymbologyXML::SymbolTypes::t_filltype m_frameEditFilltype; - SymbologyXML::SymbolTypes::AdditionalSymbolData m_additionalDataPreview; - QMap m_mapItemPrimitives; - QButtonGroup m_toolButtonGroup; - QGraphicsItem *m_currentGraphicsItem; - QGraphicsItem *m_currentGraphicsItemCopy; - QGraphicsPixmapItem *m_previewBackgroundItem; - SymbologyXML::Symbol m_symbol; - SymbologyXML::Symbol m_symbolDef; - SymbologyXML::Primitive *m_resizingPrimitive; - SymbologyXML::Primitive *m_currentPrimitiveCopy; - QGraphicsScene m_graphicsPreviewScene; - SymbolEditScene m_graphicsScene; + QPen m_pen; + QColor m_previewColor; + QColor m_fillColor; + QString m_symbolFileName; + QString m_lastFileName; + QPixmap m_previewBackground; + QPointF m_currentGraphicsItemPos; + QMap m_symbolColorsEditView; + QVector> m_symbolColorsPreview; + SymbologyXML::SymbolTypes::t_filltype m_frameEditFilltype; + SymbologyXML::SymbolTypes::AdditionalSymbolData m_additionalDataPreview; + QMap m_mapItemPrimitives; + QButtonGroup m_toolButtonGroup; + QGraphicsItem* m_currentGraphicsItem; + QGraphicsItem* m_currentGraphicsItemCopy; + QGraphicsPixmapItem* m_previewBackgroundItem; + SymbologyXML::Symbol m_symbol; + SymbologyXML::Symbol m_symbolDef; + SymbologyXML::Primitive* m_resizingPrimitive; + SymbologyXML::Primitive* m_currentPrimitiveCopy; + QGraphicsScene m_graphicsPreviewScene; + SymbolEditScene m_graphicsScene; - SymbolEditorPrivate( - const std::shared_ptr &flmFtc, - const std::shared_ptr &flmDtc, - const std::shared_ptr &flmGui, - const std::shared_ptr &ppmDtc, - SymbolEditor *q) - : m_lastFileId(-1) - , m_lastValidFileId(-1) - , m_lastFolderId(-1) - , m_gridWidth(0.1) - , m_previewZoom(1.0) - , m_drawAreaZoom(1.0) - , m_transparency(1.0) - , m_initFinished(false) - , m_showDrawArea(true) - , m_fillPrimitive(false) - , m_updateInProgress(false) - , m_displayPreviewBackground(false) - , m_copyFromSelectedPrimitive(true) - , m_saveSuccess(true) - , m_editMode(SymbolEditor::EDIT_NONE) - , m_flmFtc(flmFtc) - , m_flmDtc(flmDtc) - , m_flmGui(flmGui) - , m_ppmDtc(ppmDtc) - , m_replyHandler(new FileManagementReplyHandler(new LtsUtils::RequestHelper(q), q)) - , m_previewBackground(QPixmap(QLatin1String(":icons/previewBackground.xpm"))) - , m_frameEditFilltype(SymbologyXML::SymbolTypes::FILLTYPE_UNDEFINED) - , m_currentGraphicsItem(nullptr) - , m_currentGraphicsItemCopy(nullptr) - , m_previewBackgroundItem(nullptr) - , m_resizingPrimitive(nullptr) - , m_currentPrimitiveCopy(nullptr) - {} + SymbolEditorPrivate(const std::shared_ptr& flmFtc, + const std::shared_ptr& flmDtc, + const std::shared_ptr& flmGui, + const std::shared_ptr& ppmDtc, SymbolEditor* q) + : m_lastFileId(-1), m_lastValidFileId(-1), m_lastFolderId(-1), m_gridWidth(0.1), m_previewZoom(1.0), + m_drawAreaZoom(1.0), m_transparency(1.0), m_initFinished(false), m_showDrawArea(true), m_fillPrimitive(false), + m_updateInProgress(false), m_displayPreviewBackground(false), m_copyFromSelectedPrimitive(true), + m_saveSuccess(true), m_editMode(SymbolEditor::EDIT_NONE), m_flmFtc(flmFtc), m_flmDtc(flmDtc), + m_flmGui(flmGui), m_ppmDtc(ppmDtc), + m_replyHandler(new FileManagementReplyHandler(new LtsUtils::RequestHelper(q), q)), + m_previewBackground(QPixmap(QLatin1String(":icons/previewBackground.xpm"))), + m_frameEditFilltype(SymbologyXML::SymbolTypes::FILLTYPE_UNDEFINED), m_currentGraphicsItem(nullptr), + m_currentGraphicsItemCopy(nullptr), m_previewBackgroundItem(nullptr), m_resizingPrimitive(nullptr), + m_currentPrimitiveCopy(nullptr) + { + } }; SymbolEditor::SymbolEditor(LtsSession::LtsSession *session, QWidget *parent) @@ -152,3193 +127,2943 @@ SymbolEditor::SymbolEditor(LtsSession::LtsSession *session, QWidget *parent) , m_session(session) .getNGLLogger("SymbolEditor")) { - DEBUG_LOG(m_logger) << "SymbolEditor(" << "parent=" << parent << ")"; - m_ui->setupUi(this); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "SymbolEditor(" << "parent=" << parent << ")"; + m_ui->setupUi(this); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } -bool SymbolEditor::init(const std::shared_ptr &flmFtc, - const std::shared_ptr &flmDtc, - const std::shared_ptr &flmGui, - const std::shared_ptr &ppmDtc, - bool asApp) +bool SymbolEditor::init(const std::shared_ptr& flmFtc, + const std::shared_ptr& flmDtc, + const std::shared_ptr& flmGui, + const std::shared_ptr& ppmDtc, bool asApp) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - setOnlineHelpFilename(QStringLiteral("Symbol_Editor-Application")); - if (asApp) - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->hide(); - } - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); + setOnlineHelpFilename(QStringLiteral("Symbol_Editor-Application")); + if (asApp) + { + m_buttonBox->getButton(LtsWidgets::DialogButton::Close)->hide(); + } + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SymbolEditor::reset); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Reset")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SymbolEditor::reset); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Reset")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &SymbolEditor::slotImportTemplate); - m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Open")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &SymbolEditor::slotImportTemplate); + m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Open")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &SymbolEditor::slotSave); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Save")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &SymbolEditor::slotSave); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Save")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &SymbolEditor::slotSaveAs); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("Save As")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &SymbolEditor::slotSaveAs); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("Save As")); - connect(this, &SymbolEditor::signalChangesMade, this, - [this] () - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(m_internal->m_lastFileId > 0 && hasUnsavedChanges()); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(hasUnsavedChanges()); - }); + connect(this, &SymbolEditor::signalChangesMade, this, [this]() { + m_buttonBox->getButton(LtsWidgets::DialogButton::Save) + ->setEnabled(m_internal->m_lastFileId > 0 && hasUnsavedChanges()); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(hasUnsavedChanges()); + }); - connect(this, &SymbolEditor::signalChangesReset, this, - [this] () - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(m_internal->m_lastFileId > 0 && hasUnsavedChanges()); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(hasUnsavedChanges()); - }); + connect(this, &SymbolEditor::signalChangesReset, this, [this]() { + m_buttonBox->getButton(LtsWidgets::DialogButton::Save) + ->setEnabled(m_internal->m_lastFileId > 0 && hasUnsavedChanges()); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setEnabled(hasUnsavedChanges()); + }); - m_internal = new SymbolEditorPrivate(flmFtc, flmDtc, flmGui, ppmDtc, this); + m_internal = new SymbolEditorPrivate(flmFtc, flmDtc, flmGui, ppmDtc, this); - connect(this, &SymbolEditor::saveFinished, this, &SymbolEditor::slotSaveFinished); + connect(this, &SymbolEditor::saveFinished, this, &SymbolEditor::slotSaveFinished); - connect(m_internal->m_replyHandler, &FileManagementReplyHandler::signalFileContentModifyReplyReceived, - this, &SymbolEditor::apply); + connect(m_internal->m_replyHandler, &FileManagementReplyHandler::signalFileContentModifyReplyReceived, this, + &SymbolEditor::apply); - m_internal->m_frameEditFilltype = SymbologyXML::SymbolTypes::FILLTYPE_FILLED; - m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; - m_internal->m_additionalDataPreview.m_filltype = SymbologyXML::SymbolTypes::FILLTYPE_OUTLINED; + m_internal->m_frameEditFilltype = SymbologyXML::SymbolTypes::FILLTYPE_FILLED; + m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; + m_internal->m_additionalDataPreview.m_filltype = SymbologyXML::SymbolTypes::FILLTYPE_OUTLINED; - - if (!m_internal->m_symbolFrames.setDirectory(QLatin1String(":/Symbole/Attributes/symbolframes"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading SymbolFrame-XML-Files!"; - if (!m_internal->m_branchSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/branch"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading Branch/Truppengattung-XML-Files!"; - if (!m_internal->m_mobilitySymbols.setDirectory(QLatin1String(":/Symbole/Attributes/mobility"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading Mobility-XML-Files!"; - if (!m_internal->m_bcdabSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/bcdab"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading BCDAB-XML-Files!"; - if (!m_internal->m_commandLevelSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/commandlevel"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading CommandLevel-XML-Files!"; - if (!m_internal->m_vehicleSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/vehicle"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading vehicle-XML-Files!"; - if (!m_internal->m_intrinsicMobilitySymbols.setDirectory(QLatin1String(":/Symbole/Attributes/intrinsicmobility"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading Intrinsic-Mobility-XML-Files!"; - if (!m_internal->m_armingSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/arming"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading arming-XML-Files!"; - if (!m_internal->m_miscSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/misc"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading arming-XML-Files!"; - if (!m_internal->m_sectorSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/sectoricon"), QStringList(QLatin1String("*.xml")))) - ERROR_LOG(m_logger) << "Error while reading sectoricon-XML-Files!"; + if (!m_internal->m_symbolFrames.setDirectory(QLatin1String(":/Symbole/Attributes/symbolframes"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading SymbolFrame-XML-Files!"; + if (!m_internal->m_branchSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/branch"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading Branch/Truppengattung-XML-Files!"; + if (!m_internal->m_mobilitySymbols.setDirectory(QLatin1String(":/Symbole/Attributes/mobility"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading Mobility-XML-Files!"; + if (!m_internal->m_bcdabSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/bcdab"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading BCDAB-XML-Files!"; + if (!m_internal->m_commandLevelSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/commandlevel"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading CommandLevel-XML-Files!"; + if (!m_internal->m_vehicleSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/vehicle"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading vehicle-XML-Files!"; + if (!m_internal->m_intrinsicMobilitySymbols.setDirectory(QLatin1String(":/Symbole/Attributes/intrinsicmobility"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading Intrinsic-Mobility-XML-Files!"; + if (!m_internal->m_armingSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/arming"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading arming-XML-Files!"; + if (!m_internal->m_miscSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/misc"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading arming-XML-Files!"; + if (!m_internal->m_sectorSymbols.setDirectory(QLatin1String(":/Symbole/Attributes/sectoricon"), + QStringList(QLatin1String("*.xml")))) + ERROR_LOG(m_logger) << "Error while reading sectoricon-XML-Files!"; - m_internal->m_symbolColorsEditView.clear(); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::UNKNOWN, QColor(255, 255, 128)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::FRIEND, QColor(128, 224, 255)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::NEUTRAL, QColor(170, 255, 170)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::ENEMY, QColor(255, 128, 128)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::PENDING, QColor(255, 255, 128)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::ASSUMED_FRIEND, QColor(128, 224, 255)); - m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::SUSPECT, QColor(255, 128, 128)); + m_internal->m_symbolColorsEditView.clear(); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::UNKNOWN, QColor(255, 255, 128)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::FRIEND, QColor(128, 224, 255)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::NEUTRAL, QColor(170, 255, 170)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::ENEMY, QColor(255, 128, 128)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::PENDING, QColor(255, 255, 128)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::ASSUMED_FRIEND, QColor(128, 224, 255)); + m_internal->m_symbolColorsEditView.insert(SymbologyXML::SymbolTypes::SUSPECT, QColor(255, 128, 128)); - m_internal->m_symbolColorsPreview.clear(); - m_internal->m_ppmDtc->partys([this](const ParticipantManagement::Party & data) - { - m_internal->m_symbolColorsPreview.append({ParticipantManagement::trPartyName(data.name()), QColor::fromRgb(data.color())}); - m_internal->m_symbolColorsPreview.append({tr("%1 (faded)").arg(ParticipantManagement::trPartyName(data.name())), QColor::fromRgb(data.fadingColor())}); - }); + m_internal->m_symbolColorsPreview.clear(); + m_internal->m_ppmDtc->partys([this](const ParticipantManagement::Party& data) { + m_internal->m_symbolColorsPreview.append( + {ParticipantManagement::trPartyName(data.name()), QColor::fromRgb(data.color())}); + m_internal->m_symbolColorsPreview.append({tr("%1 (faded)").arg(ParticipantManagement::trPartyName(data.name())), + QColor::fromRgb(data.fadingColor())}); + }); - - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonRect); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonText); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonUndo); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonLine); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonCopy); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPaste); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonClear); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonScale); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonSelect); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonRotate); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonDelete); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPolygon); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonEllipse); - m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPolyline); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonRect); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonText); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonUndo); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonLine); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonCopy); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPaste); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonClear); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonScale); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonSelect); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonRotate); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonDelete); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPolygon); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonEllipse); + m_internal->m_toolButtonGroup.addButton(m_ui->ToolButtonPolyline); - - - m_ui->GraphicView->setRenderHint(QPainter::Antialiasing, true); - m_ui->GraphicView->setRenderHint(QPainter::TextAntialiasing, true); - m_ui->GraphicView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); - m_ui->GraphicView->scale(VIEW_SCALE, -VIEW_SCALE); + m_ui->GraphicView->setRenderHint(QPainter::Antialiasing, true); + m_ui->GraphicView->setRenderHint(QPainter::TextAntialiasing, true); + m_ui->GraphicView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); + m_ui->GraphicView->scale(VIEW_SCALE, -VIEW_SCALE); - - m_ui->GraphicPreview->setRenderHint(QPainter::Antialiasing, true); - m_ui->GraphicPreview->setRenderHint(QPainter::TextAntialiasing, true); - m_ui->GraphicPreview->scale(PREVIEW_SCALE, -PREVIEW_SCALE); + m_ui->GraphicPreview->setRenderHint(QPainter::Antialiasing, true); + m_ui->GraphicPreview->setRenderHint(QPainter::TextAntialiasing, true); + m_ui->GraphicPreview->scale(PREVIEW_SCALE, -PREVIEW_SCALE); - - connect(&m_internal->m_graphicsScene, &SymbolEditScene::zoomChanged, this, &SymbolEditor::setZoom); - connect(&m_internal->m_graphicsScene, &SymbolEditScene::addPrimitive, this, &SymbolEditor::addItem); - connect(&m_internal->m_graphicsScene, &SymbolEditScene::primitiveMoved, this, &SymbolEditor::movePrimitive); - connect(&m_internal->m_graphicsScene, &SymbolEditScene::primitiveChanged, this, &SymbolEditor::setChanged); - connect(&m_internal->m_graphicsScene, &SymbolEditScene::selectionChanged, this, &SymbolEditor::selectionChanged); - connect(&m_internal->m_graphicsScene, &SymbolEditScene::transformSelection, this, &SymbolEditor::transformSelection); - m_internal->m_graphicsScene.setCoordsLabels(m_ui->LabelCoordsX, m_ui->LabelCoordsY, m_ui->LabelZoomValue); - m_internal->m_graphicsScene.setSceneRect(-1.5, -1.5, 3.0, 3.0); - m_ui->GraphicView->setScene(&m_internal->m_graphicsScene); - m_ui->GraphicPreview->setScene(&m_internal->m_graphicsPreviewScene); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::zoomChanged, this, &SymbolEditor::setZoom); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::addPrimitive, this, &SymbolEditor::addItem); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::primitiveMoved, this, &SymbolEditor::movePrimitive); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::primitiveChanged, this, &SymbolEditor::setChanged); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::selectionChanged, this, &SymbolEditor::selectionChanged); + connect(&m_internal->m_graphicsScene, &SymbolEditScene::transformSelection, this, + &SymbolEditor::transformSelection); + m_internal->m_graphicsScene.setCoordsLabels(m_ui->LabelCoordsX, m_ui->LabelCoordsY, m_ui->LabelZoomValue); + m_internal->m_graphicsScene.setSceneRect(-1.5, -1.5, 3.0, 3.0); + m_ui->GraphicView->setScene(&m_internal->m_graphicsScene); + m_ui->GraphicPreview->setScene(&m_internal->m_graphicsPreviewScene); - - resetGUI(); - updateGUI(); - clearUndo(); + resetGUI(); + updateGUI(); + clearUndo(); - m_internal->m_additionalDataPreview.m_filltype = static_cast(SymbologyXML::SymbolTypes::FILLTYPE_FILLED); + m_internal->m_additionalDataPreview.m_filltype = + static_cast(SymbologyXML::SymbolTypes::FILLTYPE_FILLED); - m_ui->CheckBoxMain->setChecked(false); - m_ui->CheckBoxArming->setChecked(false); - m_ui->CheckBoxVehicle->setChecked(false); - m_ui->CheckBoxDrawArea->setChecked(true); + m_ui->CheckBoxMain->setChecked(false); + m_ui->CheckBoxArming->setChecked(false); + m_ui->CheckBoxVehicle->setChecked(false); + m_ui->CheckBoxDrawArea->setChecked(true); - m_ui->SpinBoxRaster->setValue(0.1); - m_ui->SpinBoxLineWidth->setValue(0.05); + m_ui->SpinBoxRaster->setValue(0.1); + m_ui->SpinBoxLineWidth->setValue(0.05); - onSliderTransparencyValueChanged(m_ui->SliderTransparency->value()); + onSliderTransparencyValueChanged(m_ui->SliderTransparency->value()); - m_internal->m_pen.setCapStyle(Qt::FlatCap); - m_internal->m_pen.setJoinStyle(Qt::BevelJoin); + m_internal->m_pen.setCapStyle(Qt::FlatCap); + m_internal->m_pen.setJoinStyle(Qt::BevelJoin); - - QJsonObject attributesObj; + QJsonObject attributesObj; - attributesObj.insert(QLatin1String("imageFormat"), QLatin1String("xml")); + attributesObj.insert(QLatin1String("imageFormat"), QLatin1String("xml")); - m_internal->m_attributes = QJsonDocument(attributesObj); + m_internal->m_attributes = QJsonDocument(attributesObj); - m_internal->m_initFinished = true; + m_internal->m_initFinished = true; - updateGraphicViews(); + updateGraphicViews(); - connect(m_ui->ToolButtonSelect, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonSelectClicked); - connect(m_ui->ToolButtonRotate, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonRotateClicked); - connect(m_ui->ToolButtonScale, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonScaleClicked); - connect(m_ui->ToolButtonDelete, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonDeleteClicked); - connect(m_ui->ToolButtonClear, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonClearClicked); - connect(m_ui->ToolButtonUndo, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonUndoClicked); - connect(m_ui->ToolButtonCopy, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonCopyClicked); - connect(m_ui->ToolButtonPaste, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonPasteClicked); - connect(m_ui->ToolButtonEllipse, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonEllipseClicked); - connect(m_ui->ToolButtonLine, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonLineClicked); - connect(m_ui->ToolButtonPolyline, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonPolylineClicked); - connect(m_ui->ToolButtonPolygon, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonPolygonClicked); - connect(m_ui->ToolButtonRect, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonRectClicked); - connect(m_ui->ToolButtonText, &QToolButton::clicked, - this, &SymbolEditor::onToolButtonTextClicked); + connect(m_ui->ToolButtonSelect, &QToolButton::clicked, this, &SymbolEditor::onToolButtonSelectClicked); + connect(m_ui->ToolButtonRotate, &QToolButton::clicked, this, &SymbolEditor::onToolButtonRotateClicked); + connect(m_ui->ToolButtonScale, &QToolButton::clicked, this, &SymbolEditor::onToolButtonScaleClicked); + connect(m_ui->ToolButtonDelete, &QToolButton::clicked, this, &SymbolEditor::onToolButtonDeleteClicked); + connect(m_ui->ToolButtonClear, &QToolButton::clicked, this, &SymbolEditor::onToolButtonClearClicked); + connect(m_ui->ToolButtonUndo, &QToolButton::clicked, this, &SymbolEditor::onToolButtonUndoClicked); + connect(m_ui->ToolButtonCopy, &QToolButton::clicked, this, &SymbolEditor::onToolButtonCopyClicked); + connect(m_ui->ToolButtonPaste, &QToolButton::clicked, this, &SymbolEditor::onToolButtonPasteClicked); + connect(m_ui->ToolButtonEllipse, &QToolButton::clicked, this, &SymbolEditor::onToolButtonEllipseClicked); + connect(m_ui->ToolButtonLine, &QToolButton::clicked, this, &SymbolEditor::onToolButtonLineClicked); + connect(m_ui->ToolButtonPolyline, &QToolButton::clicked, this, &SymbolEditor::onToolButtonPolylineClicked); + connect(m_ui->ToolButtonPolygon, &QToolButton::clicked, this, &SymbolEditor::onToolButtonPolygonClicked); + connect(m_ui->ToolButtonRect, &QToolButton::clicked, this, &SymbolEditor::onToolButtonRectClicked); + connect(m_ui->ToolButtonText, &QToolButton::clicked, this, &SymbolEditor::onToolButtonTextClicked); - connect(m_ui->PushButtonFillColor, &QPushButton::clicked, - this, &SymbolEditor::onPushButtonFillColorClicked); + connect(m_ui->PushButtonFillColor, &QPushButton::clicked, this, &SymbolEditor::onPushButtonFillColorClicked); - connect(m_ui->ComboBoxDimen, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxDimenCurrentIndexChanged); - connect(m_ui->ComboBoxAffil, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxAffilCurrentIndexChanged); - connect(m_ui->ComboBoxBCDAB, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxBCDABCurrentIndexChanged); - connect(m_ui->ComboBoxHeadquarter, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxHeadquarterCurrentIndexChanged); - connect(m_ui->ComboBoxCommandLevel, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxCommandLevelCurrentIndexChanged); - connect(m_ui->ComboBoxMob, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxMobCurrentIndexChanged); - connect(m_ui->ComboBoxVehicle, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxVehicleCurrentIndexChanged); - connect(m_ui->ComboBoxIntrinsicMob, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxIntrinsicMobCurrentIndexChanged); - connect(m_ui->ComboBoxIntrinsicMob_2, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxIntrinsicMob2CurrentIndexChanged); - connect(m_ui->ComboBoxArming, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxArmingCurrentIndexChanged); + connect(m_ui->ComboBoxDimen, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxDimenCurrentIndexChanged); + connect(m_ui->ComboBoxAffil, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxAffilCurrentIndexChanged); + connect(m_ui->ComboBoxBCDAB, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxBCDABCurrentIndexChanged); + connect(m_ui->ComboBoxHeadquarter, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxHeadquarterCurrentIndexChanged); + connect(m_ui->ComboBoxCommandLevel, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxCommandLevelCurrentIndexChanged); + connect(m_ui->ComboBoxMob, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxMobCurrentIndexChanged); + connect(m_ui->ComboBoxVehicle, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxVehicleCurrentIndexChanged); + connect(m_ui->ComboBoxIntrinsicMob, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxIntrinsicMobCurrentIndexChanged); + connect(m_ui->ComboBoxIntrinsicMob_2, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxIntrinsicMob2CurrentIndexChanged); + connect(m_ui->ComboBoxArming, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxArmingCurrentIndexChanged); - connect(m_ui->ListViewMisc, &QListWidget::itemSelectionChanged, - this, &SymbolEditor::onListViewMiscItemSelectionChanged); + connect(m_ui->ListViewMisc, &QListWidget::itemSelectionChanged, this, + &SymbolEditor::onListViewMiscItemSelectionChanged); - connect(m_ui->CheckBoxVehicle, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxVehicleStateChanged); - connect(m_ui->CheckBoxArming, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxArmingStateChanged); - connect(m_ui->CheckBoxMain, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxMainStateChanged); + connect(m_ui->CheckBoxVehicle, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxVehicleStateChanged); + connect(m_ui->CheckBoxArming, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxArmingStateChanged); + connect(m_ui->CheckBoxMain, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxMainStateChanged); - connect(m_ui->ComboBoxSector1, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxSector1CurrentIndexChanged); - connect(m_ui->ComboBoxSectorMain, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxSectorMainCurrentIndexChanged); + connect(m_ui->ComboBoxSector1, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxSector1CurrentIndexChanged); + connect(m_ui->ComboBoxSectorMain, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxSectorMainCurrentIndexChanged); - connect(m_ui->ListViewSectorMain, &QListWidget::itemSelectionChanged, - this, &SymbolEditor::onListViewSectorMainItemSelectionChanged); + connect(m_ui->ListViewSectorMain, &QListWidget::itemSelectionChanged, this, + &SymbolEditor::onListViewSectorMainItemSelectionChanged); - connect(m_ui->ComboBoxSector2, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxSector2CurrentIndexChanged); + connect(m_ui->ComboBoxSector2, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxSector2CurrentIndexChanged); - connect(m_ui->ComboBoxAlign1, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxAlign1CurrentIndexChanged); - connect(m_ui->ComboBoxAlign2, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxAlign2CurrentIndexChanged); - connect(m_ui->ComboBoxAlign3, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxAlign3CurrentIndexChanged); + connect(m_ui->ComboBoxAlign1, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxAlign1CurrentIndexChanged); + connect(m_ui->ComboBoxAlign2, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxAlign2CurrentIndexChanged); + connect(m_ui->ComboBoxAlign3, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxAlign3CurrentIndexChanged); - connect(m_ui->ComboBoxColor, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxColorCurrentIndexChanged); - connect(m_ui->ComboBoxLineStyle, QOverload::of(&QComboBox::currentIndexChanged), - this, &SymbolEditor::onComboBoxLineStyleCurrentIndexChanged); + connect(m_ui->ComboBoxColor, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxColorCurrentIndexChanged); + connect(m_ui->ComboBoxLineStyle, QOverload::of(&QComboBox::currentIndexChanged), this, + &SymbolEditor::onComboBoxLineStyleCurrentIndexChanged); - connect(m_ui->LineEdit1, &QLineEdit::textChanged, - this, &SymbolEditor::onLineEdit1TextChanged); - connect(m_ui->LineEdit2, &QLineEdit::textChanged, - this, &SymbolEditor::onLineEdit2TextChanged); - connect(m_ui->LineEdit3, &QLineEdit::textChanged, - this, &SymbolEditor::onLineEdit3TextChanged); + connect(m_ui->LineEdit1, &QLineEdit::textChanged, this, &SymbolEditor::onLineEdit1TextChanged); + connect(m_ui->LineEdit2, &QLineEdit::textChanged, this, &SymbolEditor::onLineEdit2TextChanged); + connect(m_ui->LineEdit3, &QLineEdit::textChanged, this, &SymbolEditor::onLineEdit3TextChanged); - connect(m_ui->ListViewTruppengattung, &QListWidget::itemSelectionChanged, - this, &SymbolEditor::onListViewTruppengattungItemSelectionChanged); + connect(m_ui->ListViewTruppengattung, &QListWidget::itemSelectionChanged, this, + &SymbolEditor::onListViewTruppengattungItemSelectionChanged); - connect(m_ui->CheckBoxBackground, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxBackgroundStateChanged); - connect(m_ui->CheckBoxCopyValues, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxCopyValuesStateChanged); - connect(m_ui->CheckBoxFill, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxFillStateChanged); - connect(m_ui->CheckBoxPlanned, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxPlannedStateChanged); - connect(m_ui->CheckBoxDrawArea, &QCheckBox::stateChanged, - this, &SymbolEditor::onCheckBoxDrawAreaStateChanged); + connect(m_ui->CheckBoxBackground, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxBackgroundStateChanged); + connect(m_ui->CheckBoxCopyValues, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxCopyValuesStateChanged); + connect(m_ui->CheckBoxFill, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxFillStateChanged); + connect(m_ui->CheckBoxPlanned, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxPlannedStateChanged); + connect(m_ui->CheckBoxDrawArea, &QCheckBox::stateChanged, this, &SymbolEditor::onCheckBoxDrawAreaStateChanged); - connect(m_ui->SpinBoxRaster, QOverload::of(&QDoubleSpinBox::valueChanged), - this, &SymbolEditor::onSpinBoxRasterValueChanged); - connect(m_ui->SpinBoxLineWidth, QOverload::of(&QDoubleSpinBox::valueChanged), - this, &SymbolEditor::onSpinBoxLineWidthValueChanged); - connect(m_ui->SpinBoxScale, QOverload::of(&QDoubleSpinBox::valueChanged), - this, &SymbolEditor::onSpinBoxScaleValueChanged); + connect(m_ui->SpinBoxRaster, QOverload::of(&QDoubleSpinBox::valueChanged), this, + &SymbolEditor::onSpinBoxRasterValueChanged); + connect(m_ui->SpinBoxLineWidth, QOverload::of(&QDoubleSpinBox::valueChanged), this, + &SymbolEditor::onSpinBoxLineWidthValueChanged); + connect(m_ui->SpinBoxScale, QOverload::of(&QDoubleSpinBox::valueChanged), this, + &SymbolEditor::onSpinBoxScaleValueChanged); - connect(m_ui->SliderTransparency, &QSlider::valueChanged, - this, &SymbolEditor::onSliderTransparencyValueChanged); + connect(m_ui->SliderTransparency, &QSlider::valueChanged, this, &SymbolEditor::onSliderTransparencyValueChanged); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return true; + return true; } SymbolEditor::~SymbolEditor() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - delete m_internal; - delete m_ui; - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + delete m_internal; + delete m_ui; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::movePrimitive(QPointF diff) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_currentGraphicsItem != nullptr) - { - QGraphicsItem *sepi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = sepi->data(SymbologyXML::primitiveKey).value(); - if (prim != nullptr) + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_currentGraphicsItem != nullptr) { - pushUndo(); - prim->move(diff); - updateGraphicViews(true, true); - restoreSelection(prim); - setChanged(true); + QGraphicsItem* sepi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = sepi->data(SymbologyXML::primitiveKey).value(); + if (prim != nullptr) + { + pushUndo(); + prim->move(diff); + updateGraphicViews(true, true); + restoreSelection(prim); + setChanged(true); + } } - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } -bool SymbolEditor::createNewSymbol(const QString &symbolname) +bool SymbolEditor::createNewSymbol(const QString& symbolname) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_symbol.reset(); - m_internal->m_symbol.setName(symbolname); + m_internal->m_symbol.reset(); + m_internal->m_symbol.setName(symbolname); - m_internal->m_symbolDef.reset(); - m_internal->m_symbolDef.setName(symbolname); + m_internal->m_symbolDef.reset(); + m_internal->m_symbolDef.setName(symbolname); - updateGUI(); + updateGUI(); - setChanged(false); - clearUndo(); + setChanged(false); + clearUndo(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return true; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return true; } void SymbolEditor::resetGUI() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - bool bOldUpdateInProgress = m_internal->m_updateInProgress; - m_internal->m_updateInProgress = true; + bool bOldUpdateInProgress = m_internal->m_updateInProgress; + m_internal->m_updateInProgress = true; - SymbologyXML::SymbolTypes::instance()->init(); + SymbologyXML::SymbolTypes::instance()->init(); - - - + m_internal->m_graphicsScene.reset(); - - m_internal->m_graphicsScene.reset(); + m_internal->m_graphicsPreviewScene.clear(); - - m_internal->m_graphicsPreviewScene.clear(); + m_ui->ComboBoxLineStyle->clear(); + m_ui->ComboBoxLineStyle->addItems({tr("Solid"), tr("Dashed"), tr("Dotted"), tr("Dashed Dotted")}); - - m_ui->ComboBoxLineStyle->clear(); - m_ui->ComboBoxLineStyle->addItems({tr("Solid"), tr("Dashed"), tr("Dotted"), tr("Dashed Dotted")}); + m_ui->ComboBoxHeadquarter->clear(); + m_ui->ComboBoxHeadquarter->addItems({tr("HeadquarterNo"), tr("HeadquarterYes")}); - - m_ui->ComboBoxHeadquarter->clear(); - m_ui->ComboBoxHeadquarter->addItems({tr("HeadquarterNo"), tr("HeadquarterYes")}); + SymbologyXML::SymbolTypes* SI = SymbologyXML::SymbolTypes::instance(); - - SymbologyXML::SymbolTypes *SI = SymbologyXML::SymbolTypes::instance(); + QMap contv = SI->getDimen()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxDimen, CATEGORY_DIMENSION, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, true, + false); - QMap contv = SI->getDimen()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxDimen, - CATEGORY_DIMENSION, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, - true , false ); + contv = SI->getAffil()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxAffil, CATEGORY_AFFILIATION, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, + true, false); - - contv = SI->getAffil()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxAffil, - CATEGORY_AFFILIATION, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, - true , false ); + contv = SI->getBcdab()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxBCDAB, CATEGORY_BCDAB, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, true, + false); - - contv = SI->getBcdab()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxBCDAB, - CATEGORY_BCDAB, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, - true , false ); + int indexSeparator = SymbologyXML::SymbolTypes::BCDAB_INSTALLATION; + m_ui->ComboBoxBCDAB->insertItem(indexSeparator, QLatin1String("-----------------------")); + QStandardItemModel* model = dynamic_cast(m_ui->ComboBoxBCDAB->model()); + QStandardItem* item = model->item(indexSeparator); + if (item) + item->setSelectable(false); - - int indexSeparator = SymbologyXML::SymbolTypes::BCDAB_INSTALLATION; - m_ui->ComboBoxBCDAB->insertItem(indexSeparator, QLatin1String("-----------------------")); - QStandardItemModel *model = dynamic_cast(m_ui->ComboBoxBCDAB->model()); - QStandardItem *item = model->item(indexSeparator); - if (item) - item->setSelectable(false); + contv = SI->getCommandLevel()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxCommandLevel, CATEGORY_COMMANDLEVEL, + SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, true, false); - - contv = SI->getCommandLevel()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxCommandLevel, - CATEGORY_COMMANDLEVEL, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, - true , false ); + contv = SI->getMob()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxMob, CATEGORY_MOBILITY, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, true, + false); - - contv = SI->getMob()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxMob, - CATEGORY_MOBILITY, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED, - true , false ); + contv = SI->getBranch()->getContainerAsInt(); + fillListWidget(contv, m_ui->ListViewTruppengattung, CATEGORY_BRANCH, + SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED); - - contv = SI->getBranch()->getContainerAsInt(); - fillListWidget(contv, m_ui->ListViewTruppengattung, - CATEGORY_BRANCH, SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED); + contv = SI->getIntrinsicMob()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxIntrinsicMob, CATEGORY_ICON_TYPE, + SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY); + fillListWidget(contv, m_ui->ComboBoxIntrinsicMob_2, CATEGORY_ICON_TYPE, + SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY); - contv = SI->getIntrinsicMob()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxIntrinsicMob, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY); - fillListWidget(contv, m_ui->ComboBoxIntrinsicMob_2, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY); + contv = SI->getVehicle()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxVehicle, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE); - contv = SI->getVehicle()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxVehicle, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE); + contv = SI->getArming()->getContainerAsInt(); + fillListWidget(contv, m_ui->ComboBoxArming, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_ARMING); - contv = SI->getArming()->getContainerAsInt(); - fillListWidget(contv, m_ui->ComboBoxArming, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_ARMING); + contv = SI->getMisc()->getContainerAsInt(); + fillListWidget(contv, m_ui->ListViewMisc, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_MISC); - contv = SI->getMisc()->getContainerAsInt(); - fillListWidget(contv, m_ui->ListViewMisc, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_MISC); + contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR1); + fillListWidget(contv, m_ui->ComboBoxSector1, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); - contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR1); - fillListWidget(contv, m_ui->ComboBoxSector1, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); + contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, + SymbologyXML::SymbolTypes::SELECT_WIDGET_CB); + fillListWidget(contv, m_ui->ComboBoxSectorMain, CATEGORY_ICON_TYPE, + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); - contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, SymbologyXML::SymbolTypes::SELECT_WIDGET_CB); - fillListWidget(contv, m_ui->ComboBoxSectorMain, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); + contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, + SymbologyXML::SymbolTypes::SELECT_WIDGET_LV); + fillListWidget(contv, m_ui->ListViewSectorMain, CATEGORY_ICON_TYPE, + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); - contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, SymbologyXML::SymbolTypes::SELECT_WIDGET_LV); - fillListWidget(contv, m_ui->ListViewSectorMain, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); + contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR2); + fillListWidget(contv, m_ui->ComboBoxSector2, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); - contv = SI->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR2); - fillListWidget(contv, m_ui->ComboBoxSector2, CATEGORY_ICON_TYPE, SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON); + m_ui->ComboBoxAlign1->clear(); + m_ui->ComboBoxAlign2->clear(); + m_ui->ComboBoxAlign3->clear(); - - m_ui->ComboBoxAlign1->clear(); - m_ui->ComboBoxAlign2->clear(); - m_ui->ComboBoxAlign3->clear(); + m_ui->ComboBoxAlign1->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); + m_ui->ComboBoxAlign2->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); + m_ui->ComboBoxAlign3->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); + m_ui->ComboBoxAlign1->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); + m_ui->ComboBoxAlign2->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); + m_ui->ComboBoxAlign3->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); + m_ui->ComboBoxAlign1->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); + m_ui->ComboBoxAlign2->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); + m_ui->ComboBoxAlign3->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); - m_ui->ComboBoxAlign1->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); - m_ui->ComboBoxAlign2->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); - m_ui->ComboBoxAlign3->addItem(tr("Left"), SymbologyXML::Symbol::LEFT); - m_ui->ComboBoxAlign1->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); - m_ui->ComboBoxAlign2->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); - m_ui->ComboBoxAlign3->addItem(tr("Center"), SymbologyXML::Symbol::CENTER); - m_ui->ComboBoxAlign1->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); - m_ui->ComboBoxAlign2->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); - m_ui->ComboBoxAlign3->addItem(tr("Right"), SymbologyXML::Symbol::RIGHT); + m_ui->ComboBoxColor->clear(); + for (const auto& scp : std::as_const(m_internal->m_symbolColorsPreview)) + { + QPixmap pixmap(20, 20); + pixmap.fill(scp.second); + QIcon colorIcon(pixmap); + QString name = scp.first.isEmpty() ? scp.second.name() : scp.first; + m_ui->ComboBoxColor->addItem(colorIcon, name); + } - - - m_ui->ComboBoxColor->clear(); - for (const auto &scp : std::as_const(m_internal->m_symbolColorsPreview)) - { - QPixmap pixmap(20, 20); - pixmap.fill(scp.second); - QIcon colorIcon(pixmap); - QString name = scp.first.isEmpty() ? scp.second.name() : scp.first; - m_ui->ComboBoxColor->addItem(colorIcon, name); - } + m_internal->m_updateInProgress = bOldUpdateInProgress; - m_internal->m_updateInProgress = bOldUpdateInProgress; - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } -void SymbolEditor::fillListWidget(const QMap &container, QWidget *widget, - e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, - bool withIcons, bool sort) +void SymbolEditor::fillListWidget(const QMap& container, QWidget* widget, e_category category, + SymbologyXML::SymbolTypes::t_icon_type iconType, bool withIcons, bool sort) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!widget) - return; - QListWidget *lwidget = qobject_cast(widget); - QComboBox *cwidget = qobject_cast(widget); + if (!widget) + return; + QListWidget* lwidget = qobject_cast(widget); + QComboBox* cwidget = qobject_cast(widget); - if (lwidget) - lwidget->clear(); - if (cwidget) - cwidget->clear(); - - int keyUndefined = 0; - QString textUndefined; - QMapIterator iter(container); - while (iter.hasNext()) - { - iter.next(); - if (iter.key() == keyUndefined) - { - if (lwidget) - continue; - textUndefined = iter.value(); - } - else - { - int index = 9999; - widgetInsertItem(widget, index, iter.value(), iter.key(), category, iconType, withIcons); - } - } - if (sort) - { if (lwidget) - lwidget->model()->sort(0, Qt::AscendingOrder); + lwidget->clear(); if (cwidget) - cwidget->model()->sort(0, Qt::AscendingOrder); - } - - if (!textUndefined.isNull()) - widgetInsertItem(widget, 0, textUndefined, keyUndefined, category, iconType, false); - if (cwidget) - { - cwidget->setCurrentIndex(cwidget->findData(keyUndefined)); - cwidget->setMaxVisibleItems(25); - } + cwidget->clear(); - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + int keyUndefined = 0; + QString textUndefined; + QMapIterator iter(container); + while (iter.hasNext()) + { + iter.next(); + if (iter.key() == keyUndefined) + { + if (lwidget) + continue; + textUndefined = iter.value(); + } + else + { + int index = 9999; + widgetInsertItem(widget, index, iter.value(), iter.key(), category, iconType, withIcons); + } + } + if (sort) + { + if (lwidget) + lwidget->model()->sort(0, Qt::AscendingOrder); + if (cwidget) + cwidget->model()->sort(0, Qt::AscendingOrder); + } + + if (!textUndefined.isNull()) + widgetInsertItem(widget, 0, textUndefined, keyUndefined, category, iconType, false); + if (cwidget) + { + cwidget->setCurrentIndex(cwidget->findData(keyUndefined)); + cwidget->setMaxVisibleItems(25); + } + + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } -void SymbolEditor::widgetInsertItem(QWidget *widget, int index, const QString &text, int key, - e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, - bool withIcons) +void SymbolEditor::widgetInsertItem(QWidget* widget, int index, const QString& text, int key, e_category category, + SymbologyXML::SymbolTypes::t_icon_type iconType, bool withIcons) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - QListWidget *lwidget = qobject_cast(widget); - QComboBox *cwidget = qobject_cast(widget); + QListWidget* lwidget = qobject_cast(widget); + QComboBox* cwidget = qobject_cast(widget); - if (lwidget) - { - - QListWidgetItem *item = new QListWidgetItem(text, lwidget); - item->setData(Qt::UserRole, key); - if (withIcons) + if (lwidget) { - const QIcon icon(getIcon(category, iconType, key, lwidget->iconSize())); - item->setIcon(icon); - } - lwidget->insertItem(index, item); - } - if (cwidget) - { - - if (withIcons) - { - const QIcon icon(getIcon(category, iconType, key, cwidget->iconSize())); - cwidget->insertItem(index, icon, text, key); - } - else - cwidget->insertItem(index, text, key); - } - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + QListWidgetItem* item = new QListWidgetItem(text, lwidget); + item->setData(Qt::UserRole, key); + if (withIcons) + { + const QIcon icon(getIcon(category, iconType, key, lwidget->iconSize())); + item->setIcon(icon); + } + lwidget->insertItem(index, item); + } + if (cwidget) + { + + if (withIcons) + { + const QIcon icon(getIcon(category, iconType, key, cwidget->iconSize())); + cwidget->insertItem(index, icon, text, key); + } + else + cwidget->insertItem(index, text, key); + } + + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } -QIcon SymbolEditor::getIcon(e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, int iconId, QSize iconSize) +QIcon SymbolEditor::getIcon(e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, int iconId, + QSize iconSize) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::Symbol *newSymbol = nullptr; - bool isAttrib = true; - switch (category) - { - case CATEGORY_HEADQUARTER: - break; - case CATEGORY_DIMENSION: - { - int tmpID = getFrameSymbolID((SymbologyXML::SymbolTypes::t_dimen)iconId, SymbologyXML::SymbolTypes::FRIEND); - if (m_internal->m_symbolFrames.contains(tmpID)) + SymbologyXML::Symbol* newSymbol = nullptr; + bool isAttrib = true; + switch (category) { - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_symbolFrames.value(tmpID))); - newSymbol->setDimen((SymbologyXML::SymbolTypes::t_dimen)iconId); - newSymbol->setAffil(SymbologyXML::SymbolTypes::FRIEND); + case CATEGORY_HEADQUARTER: + break; + case CATEGORY_DIMENSION: { + int tmpID = getFrameSymbolID((SymbologyXML::SymbolTypes::t_dimen)iconId, SymbologyXML::SymbolTypes::FRIEND); + if (m_internal->m_symbolFrames.contains(tmpID)) + { + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_symbolFrames.value(tmpID))); + newSymbol->setDimen((SymbologyXML::SymbolTypes::t_dimen)iconId); + newSymbol->setAffil(SymbologyXML::SymbolTypes::FRIEND); + } + break; + } + case CATEGORY_AFFILIATION: { + int tmpID = + getFrameSymbolID(SymbologyXML::SymbolTypes::LAND_UNITS, (SymbologyXML::SymbolTypes::t_affil)iconId); + if (m_internal->m_symbolFrames.contains(tmpID)) + { + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_symbolFrames.value(tmpID))); + newSymbol->setDimen(SymbologyXML::SymbolTypes::LAND_UNITS); + newSymbol->setAffil((SymbologyXML::SymbolTypes::t_affil)iconId); + } + break; + } + + case CATEGORY_BCDAB: { + int tmpID = SymbologyXML::SymbolTable::getBCDABSymbolID((SymbologyXML::SymbolTypes::t_bcdab)iconId); + if (m_internal->m_bcdabSymbols.contains(tmpID)) + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_bcdabSymbols.value(tmpID))); + break; + } + case CATEGORY_COMMANDLEVEL: { + int tmpID = + SymbologyXML::SymbolTable::getCommandLevelSymbolID((SymbologyXML::SymbolTypes::t_commandlevel)iconId); + if (m_internal->m_commandLevelSymbols.contains(tmpID)) + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_commandLevelSymbols.value(tmpID))); + break; + } + + case CATEGORY_MOBILITY: { + int tmpID = SymbologyXML::SymbolTable::getMobilitySymbolID((SymbologyXML::SymbolTypes::t_mob)iconId); + if (m_internal->m_mobilitySymbols.contains(tmpID)) + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_mobilitySymbols.value(tmpID))); + break; + } + case CATEGORY_BRANCH: { + SymbologyXML::SymbolTypes::t_branch val = (SymbologyXML::SymbolTypes::t_branch)iconId; + int tmpID = SymbologyXML::SymbolTable::getBranchSymbolID(val); + if (m_internal->m_branchSymbols.contains(tmpID)) + newSymbol = new SymbologyXML::Symbol(*(m_internal->m_branchSymbols.value(tmpID))); + break; + } + case CATEGORY_ICON_TYPE: { + SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; + symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = + &m_internal->m_intrinsicMobilitySymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; + + newSymbol = SymbologyXML::SymbolExporter::newSecIconSymbol(symTableCont, iconType, iconId); + isAttrib = false; + break; + } + default: + break; } - break; - } - case CATEGORY_AFFILIATION: - { - int tmpID = getFrameSymbolID(SymbologyXML::SymbolTypes::LAND_UNITS, (SymbologyXML::SymbolTypes::t_affil)iconId); - if (m_internal->m_symbolFrames.contains(tmpID)) - { - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_symbolFrames.value(tmpID))); - newSymbol->setDimen(SymbologyXML::SymbolTypes::LAND_UNITS); - newSymbol->setAffil((SymbologyXML::SymbolTypes::t_affil)iconId); - } - break; - } - case CATEGORY_BCDAB: - { - int tmpID = SymbologyXML::SymbolTable::getBCDABSymbolID((SymbologyXML::SymbolTypes::t_bcdab)iconId); - if (m_internal->m_bcdabSymbols.contains(tmpID)) - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_bcdabSymbols.value(tmpID))); - break; + if (!newSymbol) + return QIcon(); - } - case CATEGORY_COMMANDLEVEL: - { - int tmpID = SymbologyXML::SymbolTable::getCommandLevelSymbolID((SymbologyXML::SymbolTypes::t_commandlevel)iconId); - if (m_internal->m_commandLevelSymbols.contains(tmpID)) - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_commandLevelSymbols.value(tmpID))); - break; - } + QGraphicsScene scene; + drawSymbol(newSymbol, &scene, Qt::black, Qt::black, -0.3, isAttrib); + delete newSymbol; - case CATEGORY_MOBILITY: - { - int tmpID = SymbologyXML::SymbolTable::getMobilitySymbolID((SymbologyXML::SymbolTypes::t_mob)iconId); - if (m_internal->m_mobilitySymbols.contains(tmpID)) - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_mobilitySymbols.value(tmpID))); - break; - } - case CATEGORY_BRANCH: - { - SymbologyXML::SymbolTypes::t_branch val = (SymbologyXML::SymbolTypes::t_branch)iconId; - int tmpID = SymbologyXML::SymbolTable::getBranchSymbolID(val); - if (m_internal->m_branchSymbols.contains(tmpID)) - newSymbol = new SymbologyXML::Symbol(*(m_internal->m_branchSymbols.value(tmpID))); - break; - } - case CATEGORY_ICON_TYPE: - { - SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; - symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = &m_internal->m_intrinsicMobilitySymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; + QPixmap pm(iconSize); + pm.fill(Qt::white); + QPainter painter(&pm); - newSymbol = SymbologyXML::SymbolExporter::newSecIconSymbol(symTableCont, iconType, iconId); - isAttrib = false; - break; - } - default: - break; - } + painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - if (!newSymbol) - return QIcon(); + QRectF source = scene.itemsBoundingRect(); + qreal widthHeight = std::max(source.width(), source.height()); + QPointF center = QPointF(source.center()); + source.setWidth(widthHeight); + source.setHeight(widthHeight); + source.moveCenter(center); + QRectF target(0, 0, iconSize.width(), iconSize.height()); - QGraphicsScene scene; - drawSymbol(newSymbol, &scene, Qt::black, Qt::black, -0.3, isAttrib); - delete newSymbol; + scene.render(&painter, target, source); + painter.end(); - - QPixmap pm(iconSize); - pm.fill(Qt::white); - QPainter painter(&pm); + QTransform transformView; + transformView.scale(1.0, -1.0); - painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - - QRectF source = scene.itemsBoundingRect(); - qreal widthHeight = std::max(source.width(), source.height()); - QPointF center = QPointF(source.center()); - source.setWidth(widthHeight); - source.setHeight(widthHeight); - source.moveCenter(center); - QRectF target(0, 0, iconSize.width(), iconSize.height()); + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; - scene.render(&painter, target, source); - painter.end(); - - QTransform transformView; - transformView.scale(1.0, -1.0); - - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; - - return QIcon(pm.transformed(transformView)); + return QIcon(pm.transformed(transformView)); } int SymbolEditor::getFrameSymbolID(SymbologyXML::SymbolTypes::t_dimen dimen, SymbologyXML::SymbolTypes::t_affil affil) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_affil tmp_affil = affil; - if (tmp_affil == SymbologyXML::SymbolTypes::PENDING) - tmp_affil = SymbologyXML::SymbolTypes::UNKNOWN; - if (tmp_affil == SymbologyXML::SymbolTypes::SUSPECT) - tmp_affil = SymbologyXML::SymbolTypes::ENEMY; - if (tmp_affil == SymbologyXML::SymbolTypes::ASSUMED_FRIEND) - tmp_affil = SymbologyXML::SymbolTypes::FRIEND; + SymbologyXML::SymbolTypes::t_affil tmp_affil = affil; + if (tmp_affil == SymbologyXML::SymbolTypes::PENDING) + tmp_affil = SymbologyXML::SymbolTypes::UNKNOWN; + if (tmp_affil == SymbologyXML::SymbolTypes::SUSPECT) + tmp_affil = SymbologyXML::SymbolTypes::ENEMY; + if (tmp_affil == SymbologyXML::SymbolTypes::ASSUMED_FRIEND) + tmp_affil = SymbologyXML::SymbolTypes::FRIEND; - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; - return SymbologyXML::SymbolTable::getFrameSymbolID(dimen, tmp_affil); + return SymbologyXML::SymbolTable::getFrameSymbolID(dimen, tmp_affil); } void SymbolEditor::updateGUI() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_updateInProgress = true; + m_internal->m_updateInProgress = true; - resetGUI(); + resetGUI(); - updateSymbolAttributesWidgets(); + updateSymbolAttributesWidgets(); - - if (!m_internal->m_lastFileName.isEmpty()) - m_internal->m_symbol.setName(m_internal->m_lastFileName); - m_ui->leSymbolName->setText(m_internal->m_symbol.getName()); + if (!m_internal->m_lastFileName.isEmpty()) + m_internal->m_symbol.setName(m_internal->m_lastFileName); + m_ui->leSymbolName->setText(m_internal->m_symbol.getName()); - updateGraphicViews(true, true); - m_internal->m_updateInProgress = false; + updateGraphicViews(true, true); + m_internal->m_updateInProgress = false; - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::updateSymbolAttributesWidgets() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - bool bOldUpdateInProgress = m_internal->m_updateInProgress; - m_internal->m_updateInProgress = true; + bool bOldUpdateInProgress = m_internal->m_updateInProgress; + m_internal->m_updateInProgress = true; - - m_ui->ComboBoxDimen->setCurrentIndex(m_ui->ComboBoxDimen->findData(m_internal->m_symbol.getDimen())); - m_ui->ComboBoxAffil->setCurrentIndex(m_ui->ComboBoxAffil->findData(m_internal->m_symbol.getAffil())); - m_ui->ComboBoxBCDAB->setCurrentIndex(m_ui->ComboBoxBCDAB->findData(m_internal->m_symbol.getBcdab())); - m_ui->ComboBoxCommandLevel->setCurrentIndex(m_ui->ComboBoxCommandLevel->findData(m_internal->m_symbol.getCommandLevel())); - m_ui->ComboBoxMob->setCurrentIndex(m_ui->ComboBoxMob->findData(m_internal->m_symbol.getMob())); - m_ui->ComboBoxHeadquarter->setCurrentIndex((int)m_internal->m_symbol.getHeadquarter()); + m_ui->ComboBoxDimen->setCurrentIndex(m_ui->ComboBoxDimen->findData(m_internal->m_symbol.getDimen())); + m_ui->ComboBoxAffil->setCurrentIndex(m_ui->ComboBoxAffil->findData(m_internal->m_symbol.getAffil())); + m_ui->ComboBoxBCDAB->setCurrentIndex(m_ui->ComboBoxBCDAB->findData(m_internal->m_symbol.getBcdab())); + m_ui->ComboBoxCommandLevel->setCurrentIndex( + m_ui->ComboBoxCommandLevel->findData(m_internal->m_symbol.getCommandLevel())); + m_ui->ComboBoxMob->setCurrentIndex(m_ui->ComboBoxMob->findData(m_internal->m_symbol.getMob())); + m_ui->ComboBoxHeadquarter->setCurrentIndex((int)m_internal->m_symbol.getHeadquarter()); - - m_ui->ComboBoxVehicle->setCurrentIndex(0); - m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(0); - m_ui->ComboBoxArming->setCurrentIndex(0); - m_ui->ComboBoxSectorMain->setCurrentIndex(0); - m_ui->ComboBoxSector1->setCurrentIndex(0); - m_ui->ComboBoxSector2->setCurrentIndex(0); - m_ui->ComboBoxIntrinsicMob->setCurrentIndex(0); + m_ui->ComboBoxVehicle->setCurrentIndex(0); + m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(0); + m_ui->ComboBoxArming->setCurrentIndex(0); + m_ui->ComboBoxSectorMain->setCurrentIndex(0); + m_ui->ComboBoxSector1->setCurrentIndex(0); + m_ui->ComboBoxSector2->setCurrentIndex(0); + m_ui->ComboBoxIntrinsicMob->setCurrentIndex(0); - - m_ui->ListViewSectorMain->clearSelection(); - m_ui->ListViewMisc->clearSelection(); - m_ui->ListViewTruppengattung->clearSelection(); + m_ui->ListViewSectorMain->clearSelection(); + m_ui->ListViewMisc->clearSelection(); + m_ui->ListViewTruppengattung->clearSelection(); - QLinkedList primitives = m_internal->m_symbol.getPrimitives(); - QLinkedListIterator pi(primitives); - while (pi.hasNext()) - { - SymbologyXML::Primitive *prim = pi.next(); - int iconId = prim->icon(); - SymbologyXML::SymbolTypes::t_icon_type iconType = prim->iconType(); - SymbologyXML::SymbolTypes::t_sector_position sectorPosition = prim->position(); - - switch (iconType) - { - case SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON: + QLinkedList primitives = m_internal->m_symbol.getPrimitives(); + QLinkedListIterator pi(primitives); + while (pi.hasNext()) { + SymbologyXML::Primitive* prim = pi.next(); + int iconId = prim->icon(); + SymbologyXML::SymbolTypes::t_icon_type iconType = prim->iconType(); + SymbologyXML::SymbolTypes::t_sector_position sectorPosition = prim->position(); - switch (sectorPosition) - { - case SymbologyXML::SymbolTypes::SECTOR1: - m_ui->ComboBoxSector1->setCurrentIndex(m_ui->ComboBoxSector1->findData(iconId)); - break; - case SymbologyXML::SymbolTypes::SECTOR2: - m_ui->ComboBoxSector2->setCurrentIndex(m_ui->ComboBoxSector2->findData(iconId)); - break; - case SymbologyXML::SymbolTypes::SECTORMAIN: - { - bool foundinListView = false; - - for (int i = 0; i < m_ui->ListViewSectorMain->count(); i++) + switch (iconType) { - int curVal = (SymbologyXML::SymbolTypes::t_sectoricon)m_ui->ListViewSectorMain->item(i)->data(Qt::UserRole).toInt(); - if (curVal == iconId) - { - foundinListView = true; - m_ui->ListViewSectorMain->item(i)->setSelected(true); - } + case SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON: { + + switch (sectorPosition) + { + case SymbologyXML::SymbolTypes::SECTOR1: + m_ui->ComboBoxSector1->setCurrentIndex(m_ui->ComboBoxSector1->findData(iconId)); + break; + case SymbologyXML::SymbolTypes::SECTOR2: + m_ui->ComboBoxSector2->setCurrentIndex(m_ui->ComboBoxSector2->findData(iconId)); + break; + case SymbologyXML::SymbolTypes::SECTORMAIN: { + bool foundinListView = false; + + for (int i = 0; i < m_ui->ListViewSectorMain->count(); i++) + { + int curVal = (SymbologyXML::SymbolTypes::t_sectoricon)m_ui->ListViewSectorMain->item(i) + ->data(Qt::UserRole) + .toInt(); + if (curVal == iconId) + { + foundinListView = true; + m_ui->ListViewSectorMain->item(i)->setSelected(true); + } + } + + if (!foundinListView) + { + + int idx = m_ui->ComboBoxSectorMain->findData(iconId); + if (idx < 0) + ERROR_LOG(m_logger) << "SECTORMAIN: iconid (" << iconId << ") not found"; + else + m_ui->ComboBoxSectorMain->setCurrentIndex(m_ui->ComboBoxSectorMain->findData(iconId)); + } + } + break; + case SymbologyXML::SymbolTypes::SECTORFF: + break; + case SymbologyXML::SymbolTypes::SECTOR_POSITION_UNDEFINED: { + } + } + } + break; + case SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY: + m_ui->ComboBoxIntrinsicMob->setCurrentIndex(m_ui->ComboBoxIntrinsicMob->findData(iconId)); + m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(m_ui->ComboBoxIntrinsicMob_2->findData(iconId)); + break; + case SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE: + m_ui->ComboBoxVehicle->setCurrentIndex(m_ui->ComboBoxVehicle->findData(iconId)); + break; + case SymbologyXML::SymbolTypes::ICON_TYPE_ARMING: + m_ui->ComboBoxArming->setCurrentIndex(m_ui->ComboBoxArming->findData(iconId)); + break; + case SymbologyXML::SymbolTypes::ICON_TYPE_MISC: { + for (int i = 0; i < m_ui->ListViewMisc->count(); i++) + { + int curVal = + (SymbologyXML::SymbolTypes::t_misc)m_ui->ListViewMisc->item(i)->data(Qt::UserRole).toInt(); + if (curVal == iconId) + m_ui->ListViewMisc->item(i)->setSelected(true); + } + break; + } + case SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED: + case SymbologyXML::SymbolTypes::ICON_TYPE_END: { + } } - - if (!foundinListView) - { - - int idx = m_ui->ComboBoxSectorMain->findData(iconId); - if (idx < 0) - ERROR_LOG(m_logger) << "SECTORMAIN: iconid (" << iconId << ") not found"; - else - m_ui->ComboBoxSectorMain->setCurrentIndex(m_ui->ComboBoxSectorMain->findData(iconId)); - } - } - break; - case SymbologyXML::SymbolTypes::SECTORFF: - break; - case SymbologyXML::SymbolTypes::SECTOR_POSITION_UNDEFINED: - { - - } - } - } - break; - case SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY: - m_ui->ComboBoxIntrinsicMob->setCurrentIndex(m_ui->ComboBoxIntrinsicMob->findData(iconId)); - m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(m_ui->ComboBoxIntrinsicMob_2->findData(iconId)); - break; - case SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE: - m_ui->ComboBoxVehicle->setCurrentIndex(m_ui->ComboBoxVehicle->findData(iconId)); - break; - case SymbologyXML::SymbolTypes::ICON_TYPE_ARMING: - m_ui->ComboBoxArming->setCurrentIndex(m_ui->ComboBoxArming->findData(iconId)); - break; - case SymbologyXML::SymbolTypes::ICON_TYPE_MISC: + + m_internal->m_symbol.setTextType(SymbologyXML::Symbol::TEXT3); + + updateTextProperties(); + + m_ui->SpinBoxScale->setValue(m_internal->m_symbol.getScale()); + + NGL::BitSet branchTags = m_internal->m_symbol.getBranchTags(); + for (int i = 0; i < m_ui->ListViewTruppengattung->count(); i++) { - for (int i = 0; i < m_ui->ListViewMisc->count(); i++) - { - int curVal = (SymbologyXML::SymbolTypes::t_misc)m_ui->ListViewMisc->item(i)->data(Qt::UserRole).toInt(); - if (curVal == iconId) - m_ui->ListViewMisc->item(i)->setSelected(true); - } - break; - } - case SymbologyXML::SymbolTypes::ICON_TYPE_UNDEFINED: - case SymbologyXML::SymbolTypes::ICON_TYPE_END: - { - - } + SymbologyXML::SymbolTypes::t_branch val = + (SymbologyXML::SymbolTypes::t_branch)m_ui->ListViewTruppengattung->item(i)->data(Qt::UserRole).toInt(); + if (branchTags.at(val)) + m_ui->ListViewTruppengattung->item(i)->setSelected(true); + else + m_ui->ListViewTruppengattung->item(i)->setSelected(false); } - } + m_internal->m_updateInProgress = bOldUpdateInProgress; - m_internal->m_symbol.setTextType(SymbologyXML::Symbol::TEXT3); - - updateTextProperties(); - - m_ui->SpinBoxScale->setValue(m_internal->m_symbol.getScale()); - - - NGL::BitSet branchTags = m_internal->m_symbol.getBranchTags(); - for (int i = 0; i < m_ui->ListViewTruppengattung->count(); i++) - { - SymbologyXML::SymbolTypes::t_branch val = (SymbologyXML::SymbolTypes::t_branch)m_ui->ListViewTruppengattung->item(i)->data(Qt::UserRole).toInt(); - if (branchTags.at(val)) - m_ui->ListViewTruppengattung->item(i)->setSelected(true); - else - m_ui->ListViewTruppengattung->item(i)->setSelected(false); - } - - m_internal->m_updateInProgress = bOldUpdateInProgress; - - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } void SymbolEditor::updateTextProperties() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - - QLineEdit *arLE[3] = {m_ui->LineEdit1, m_ui->LineEdit2, m_ui->LineEdit3}; - QComboBox *arCB[3] = {m_ui->ComboBoxAlign1, m_ui->ComboBoxAlign2, m_ui->ComboBoxAlign3}; - for (int i = 0; i < 3; ++i) - { - - arLE[i]->setMaxLength(m_internal->m_symbol.maxStringLength()); - - arLE[i]->setText(m_internal->m_symbol.getText(i + 1)); - - - SymbologyXML::Symbol::t_alignment a = m_internal->m_symbol.getTextAlign(i + 1); - switch (a) + QLineEdit* arLE[3] = {m_ui->LineEdit1, m_ui->LineEdit2, m_ui->LineEdit3}; + QComboBox* arCB[3] = {m_ui->ComboBoxAlign1, m_ui->ComboBoxAlign2, m_ui->ComboBoxAlign3}; + for (int i = 0; i < 3; ++i) { - case SymbologyXML::Symbol::LEFT: - arLE[i]->setAlignment(Qt::AlignLeft); - break; - case SymbologyXML::Symbol::CENTER: - arLE[i]->setAlignment(Qt::AlignHCenter); - break; - case SymbologyXML::Symbol::RIGHT: - arLE[i]->setAlignment(Qt::AlignRight); - break; - default: - break; + + arLE[i]->setMaxLength(m_internal->m_symbol.maxStringLength()); + + arLE[i]->setText(m_internal->m_symbol.getText(i + 1)); + + SymbologyXML::Symbol::t_alignment a = m_internal->m_symbol.getTextAlign(i + 1); + switch (a) + { + case SymbologyXML::Symbol::LEFT: + arLE[i]->setAlignment(Qt::AlignLeft); + break; + case SymbologyXML::Symbol::CENTER: + arLE[i]->setAlignment(Qt::AlignHCenter); + break; + case SymbologyXML::Symbol::RIGHT: + arLE[i]->setAlignment(Qt::AlignRight); + break; + default: + break; + } + arCB[i]->setCurrentIndex(arCB[i]->findData(a)); + arCB[i]->setEnabled(false); + arLE[i]->setEnabled(false); } - arCB[i]->setCurrentIndex(arCB[i]->findData(a)); - arCB[i]->setEnabled(false); - arLE[i]->setEnabled(false); - } - - switch (m_internal->m_symbol.getTextType()) - { - case SymbologyXML::Symbol::TEXT3: - m_ui->LineEdit3->setEnabled(true); - m_ui->ComboBoxAlign3->setEnabled(true); - Q_FALLTHROUGH(); - case SymbologyXML::Symbol::TEXT2: - m_ui->LineEdit2->setEnabled(true); - m_ui->ComboBoxAlign2->setEnabled(true); - Q_FALLTHROUGH(); - case SymbologyXML::Symbol::TEXT1: - m_ui->LineEdit1->setEnabled(true); - m_ui->ComboBoxAlign1->setEnabled(true); - Q_FALLTHROUGH(); - case SymbologyXML::Symbol::TEXT_UNDEFINED: - break; - } + switch (m_internal->m_symbol.getTextType()) + { + case SymbologyXML::Symbol::TEXT3: + m_ui->LineEdit3->setEnabled(true); + m_ui->ComboBoxAlign3->setEnabled(true); + Q_FALLTHROUGH(); + case SymbologyXML::Symbol::TEXT2: + m_ui->LineEdit2->setEnabled(true); + m_ui->ComboBoxAlign2->setEnabled(true); + Q_FALLTHROUGH(); + case SymbologyXML::Symbol::TEXT1: + m_ui->LineEdit1->setEnabled(true); + m_ui->ComboBoxAlign1->setEnabled(true); + Q_FALLTHROUGH(); + case SymbologyXML::Symbol::TEXT_UNDEFINED: + break; + } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::updateGraphicViews(bool editview, bool preview) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!m_internal->m_initFinished) - return; + if (!m_internal->m_initFinished) + return; - - int cb_index = m_ui->ComboBoxAffil->currentIndex(); - int affil = m_ui->ComboBoxAffil->itemData(cb_index).toInt(); - QColor col = m_internal->m_symbolColorsEditView.value(affil); + int cb_index = m_ui->ComboBoxAffil->currentIndex(); + int affil = m_ui->ComboBoxAffil->itemData(cb_index).toInt(); + QColor col = m_internal->m_symbolColorsEditView.value(affil); - QColor editLineCol; - QColor editFrameFillCol; - QColor editAttFillCol; - if (m_internal->m_frameEditFilltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) - { - - editLineCol = Qt::black; - editFrameFillCol = col; - editAttFillCol = editLineCol; - - } - else - { - - editLineCol = col; - editFrameFillCol = Qt::white; - editAttFillCol = editLineCol; - } - - - SymbologyXML::Symbol *symbolFrameEditView = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getFrameSymbolID(m_internal->m_symbol); - if (m_internal->m_symbolFrames.contains(tmpID)) - symbolFrameEditView = m_internal->m_symbolFrames[tmpID]; - } - - SymbologyXML::Symbol *symbolFramePreview = nullptr; - if ((m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) || - (m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_OUTLINED)) - { - int tmpID = SymbologyXML::SymbolTable::getFrameSymbolID(m_internal->m_symbol); - if (m_internal->m_symbolFrames.contains(tmpID)) - symbolFramePreview = m_internal->m_symbolFrames[tmpID]; - } - - SymbologyXML::Symbol *mobilitySymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getMobilitySymbolID(m_internal->m_symbol); - if (m_internal->m_mobilitySymbols.contains(tmpID)) - mobilitySymbol = m_internal->m_mobilitySymbols[tmpID]; - } - - SymbologyXML::Symbol *vehicleSymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getVehicleSymbolID(m_internal->m_symbol); - if (m_internal->m_vehicleSymbols.contains(tmpID)) - vehicleSymbol = m_internal->m_vehicleSymbols[tmpID]; - } - - SymbologyXML::Symbol *intrinsicMobilitySymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getIntrinsicMobilitySymbolID(m_internal->m_symbol); - if (m_internal->m_intrinsicMobilitySymbols.contains(tmpID)) - intrinsicMobilitySymbol = m_internal->m_intrinsicMobilitySymbols[tmpID]; - } - - SymbologyXML::Symbol *armingSymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getArmingSymbolID(m_internal->m_symbol); - if (m_internal->m_armingSymbols.contains(tmpID)) - armingSymbol = m_internal->m_armingSymbols[tmpID]; - } - - QVector miscSymbols; - - NGL::BitSet misc = m_internal->m_symbol.getMiscTags(); - QVectorIterator it = SymbologyXML::SymbolTypes::instance()->getMisc()->getIterator(); - SymbologyXML::SymbolTypes::t_misc val; - while (it.hasNext()) - { - val = it.next(); - if (misc[val]) - { - int tmpID = SymbologyXML::SymbolTable::getMiscSymbolID(val); - if (m_internal->m_miscSymbols.contains(tmpID)) - { - SymbologyXML::Symbol *miscSymbol = new SymbologyXML::Symbol(*(m_internal->m_miscSymbols.value(tmpID))); - miscSymbol->setDimen(m_internal->m_symbol.getDimen()); - miscSymbol->setAffil(m_internal->m_symbol.getAffil()); - miscSymbols.append(miscSymbol); - } - } - } - - - SymbologyXML::Symbol *bcdabSymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getBCDABSymbolID(m_internal->m_symbol); - if (m_internal->m_bcdabSymbols.contains(tmpID)) - { - bcdabSymbol = new SymbologyXML::Symbol(*(m_internal->m_bcdabSymbols[tmpID])); - bcdabSymbol->setDimen(m_internal->m_symbol.getDimen()); - bcdabSymbol->setAffil(m_internal->m_symbol.getAffil()); - bcdabSymbol->transformSymbol(SymbologyXML::Symbol::TMG_BCDAB); - } - } - - SymbologyXML::Symbol *commandLevelSymbol = nullptr; - { - int tmpID = SymbologyXML::SymbolTable::getCommandLevelSymbolID(m_internal->m_symbol); - if (m_internal->m_commandLevelSymbols.contains(tmpID)) - { - commandLevelSymbol = new SymbologyXML::Symbol(*(m_internal->m_commandLevelSymbols[tmpID])); - commandLevelSymbol->setDimen(m_internal->m_symbol.getDimen()); - commandLevelSymbol->setAffil(m_internal->m_symbol.getAffil()); - - commandLevelSymbol->transformSymbol(SymbologyXML::Symbol::TMG_COMMAND_LEVEL); - } - } - - - QVector tgSymbols; - const QListitems = m_ui->ListViewTruppengattung->selectedItems(); - tgSymbols.reserve(items.size()); - for (const QListWidgetItem *item : items) - { - SymbologyXML::SymbolTypes::t_branch curBranch = (SymbologyXML::SymbolTypes::t_branch)item->data(Qt::UserRole).toInt(); - int tmpID = SymbologyXML::SymbolTable::getBranchSymbolID(curBranch); - if (m_internal->m_branchSymbols.contains(tmpID)) - { - SymbologyXML::Symbol *tgSymbol = new SymbologyXML::Symbol(*m_internal->m_branchSymbols.value(tmpID)); - tgSymbol->setDimen(m_internal->m_symbol.getDimen()); - tgSymbol->setAffil(m_internal->m_symbol.getAffil()); - - tgSymbol->transformSymbol(SymbologyXML::Symbol::TMG_BRANCHES, &m_internal->m_branchSymbols); - - tgSymbols.append(tgSymbol); - } - } - - - if (editview) - { - - - editLineCol.setAlphaF(1.0); - editFrameFillCol.setAlphaF(1.0); - editAttFillCol.setAlphaF(1.0); - - - - - - - m_internal->m_graphicsScene.cancelCurrentAction(); - - m_internal->m_currentGraphicsItemCopy = nullptr; - m_internal->m_currentGraphicsItem = nullptr; - m_internal->m_graphicsScene.clear(); - m_internal->m_mapItemPrimitives.clear(); - - if (symbolFrameEditView != nullptr) + QColor editLineCol; + QColor editFrameFillCol; + QColor editAttFillCol; + if (m_internal->m_frameEditFilltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) { - SymbologyXML::Symbol *l_symbolFrameEditView = new SymbologyXML::Symbol(*symbolFrameEditView); - - l_symbolFrameEditView->setDimen(m_internal->m_symbol.getDimen()); - l_symbolFrameEditView->setAffil(m_internal->m_symbol.getAffil()); - SymbologyXML::SymbolTypes::AdditionalSymbolData l_additionalData = m_internal->m_additionalDataPreview; - l_additionalData.m_filltype = m_internal->m_frameEditFilltype; - l_additionalData.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; - SymbologyXML::SymbolExporter::drawFrameSymbol(*l_symbolFrameEditView, l_additionalData, - &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, - -0.3); - delete l_symbolFrameEditView; - } - - SymbologyXML::SymbolExporter::drawHeadquarterPrims(&m_internal->m_graphicsScene, m_internal->m_symbol.getHeadquarter(), - m_internal->m_symbol.getDimen(), m_internal->m_symbol.getAffil(), - editLineCol); - - if (mobilitySymbol != nullptr) - { - drawSymbol(mobilitySymbol, &m_internal->m_graphicsScene, - editLineCol, - editFrameFillCol, - -0.29, true, false); - } - if (vehicleSymbol != nullptr) - { - drawSymbol(vehicleSymbol, &m_internal->m_graphicsScene, - editLineCol, - editFrameFillCol, - -0.29, true, false); - } - if (intrinsicMobilitySymbol != nullptr) - { - drawSymbol(intrinsicMobilitySymbol, &m_internal->m_graphicsScene, - editLineCol, - editFrameFillCol, - -0.29, true, false); - } - if (armingSymbol != nullptr) - { - drawSymbol(armingSymbol, &m_internal->m_graphicsScene, - editLineCol, - editFrameFillCol, - -0.29, true, false); - } - - if (bcdabSymbol != nullptr) - { - drawSymbol(bcdabSymbol, &m_internal->m_graphicsScene, - editLineCol, - editAttFillCol, - -0.29, true, false); - } - if (commandLevelSymbol != nullptr) - { - drawSymbol(commandLevelSymbol, &m_internal->m_graphicsScene, - editLineCol, - editAttFillCol, - -0.29, true, false); - } - for (const SymbologyXML::Symbol *tgtSym : tgSymbols) - { - if (tgtSym != nullptr) - { - drawSymbol(tgtSym, &m_internal->m_graphicsScene, - editLineCol, - editAttFillCol, - -0.29, true, false); - } - } - - - drawSymbol(&m_internal->m_symbol, &m_internal->m_graphicsScene, - editLineCol, - editLineCol, - 0.0, false, true, true); - - - onCheckBoxDrawAreaStateChanged(m_internal->m_showDrawArea); - onSpinBoxRasterValueChanged(m_internal->m_gridWidth); - } - - - if (preview) - { - - - QColor previewLineCol; - QColor previewFrameFillCol; - QColor previewAttFillCol; - if (m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) - { - - previewLineCol = Qt::black; - previewFrameFillCol = m_internal->m_previewColor; - previewAttFillCol = previewLineCol; + editLineCol = Qt::black; + editFrameFillCol = col; + editAttFillCol = editLineCol; } else { - - previewLineCol = m_internal->m_previewColor; - previewFrameFillCol = m_internal->m_previewColor; - previewAttFillCol = previewLineCol; + + editLineCol = col; + editFrameFillCol = Qt::white; + editAttFillCol = editLineCol; } - m_internal->m_graphicsPreviewScene.setSceneRect(-1.5, -1.5, 3.0, 3.0); + SymbologyXML::Symbol* symbolFrameEditView = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getFrameSymbolID(m_internal->m_symbol); + if (m_internal->m_symbolFrames.contains(tmpID)) + symbolFrameEditView = m_internal->m_symbolFrames[tmpID]; + } - - previewLineCol.setAlphaF(1.0); - previewFrameFillCol.setAlphaF(m_internal->m_transparency); - previewAttFillCol.setAlphaF(1.0); + SymbologyXML::Symbol* symbolFramePreview = nullptr; + if ((m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) || + (m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_OUTLINED)) + { + int tmpID = SymbologyXML::SymbolTable::getFrameSymbolID(m_internal->m_symbol); + if (m_internal->m_symbolFrames.contains(tmpID)) + symbolFramePreview = m_internal->m_symbolFrames[tmpID]; + } - m_internal->m_graphicsPreviewScene.clear(); - m_internal->m_previewBackgroundItem = nullptr; + SymbologyXML::Symbol* mobilitySymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getMobilitySymbolID(m_internal->m_symbol); + if (m_internal->m_mobilitySymbols.contains(tmpID)) + mobilitySymbol = m_internal->m_mobilitySymbols[tmpID]; + } - if ((symbolFramePreview != nullptr) -) + SymbologyXML::Symbol* vehicleSymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getVehicleSymbolID(m_internal->m_symbol); + if (m_internal->m_vehicleSymbols.contains(tmpID)) + vehicleSymbol = m_internal->m_vehicleSymbols[tmpID]; + } + + SymbologyXML::Symbol* intrinsicMobilitySymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getIntrinsicMobilitySymbolID(m_internal->m_symbol); + if (m_internal->m_intrinsicMobilitySymbols.contains(tmpID)) + intrinsicMobilitySymbol = m_internal->m_intrinsicMobilitySymbols[tmpID]; + } + + SymbologyXML::Symbol* armingSymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getArmingSymbolID(m_internal->m_symbol); + if (m_internal->m_armingSymbols.contains(tmpID)) + armingSymbol = m_internal->m_armingSymbols[tmpID]; + } + + QVector miscSymbols; + + NGL::BitSet misc = m_internal->m_symbol.getMiscTags(); + QVectorIterator it = + SymbologyXML::SymbolTypes::instance()->getMisc()->getIterator(); + SymbologyXML::SymbolTypes::t_misc val; + while (it.hasNext()) + { + val = it.next(); + if (misc[val]) + { + int tmpID = SymbologyXML::SymbolTable::getMiscSymbolID(val); + if (m_internal->m_miscSymbols.contains(tmpID)) + { + SymbologyXML::Symbol* miscSymbol = new SymbologyXML::Symbol(*(m_internal->m_miscSymbols.value(tmpID))); + miscSymbol->setDimen(m_internal->m_symbol.getDimen()); + miscSymbol->setAffil(m_internal->m_symbol.getAffil()); + miscSymbols.append(miscSymbol); + } + } + } + + SymbologyXML::Symbol* bcdabSymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getBCDABSymbolID(m_internal->m_symbol); + if (m_internal->m_bcdabSymbols.contains(tmpID)) + { + bcdabSymbol = new SymbologyXML::Symbol(*(m_internal->m_bcdabSymbols[tmpID])); + bcdabSymbol->setDimen(m_internal->m_symbol.getDimen()); + bcdabSymbol->setAffil(m_internal->m_symbol.getAffil()); + bcdabSymbol->transformSymbol(SymbologyXML::Symbol::TMG_BCDAB); + } + } + + SymbologyXML::Symbol* commandLevelSymbol = nullptr; + { + int tmpID = SymbologyXML::SymbolTable::getCommandLevelSymbolID(m_internal->m_symbol); + if (m_internal->m_commandLevelSymbols.contains(tmpID)) + { + commandLevelSymbol = new SymbologyXML::Symbol(*(m_internal->m_commandLevelSymbols[tmpID])); + commandLevelSymbol->setDimen(m_internal->m_symbol.getDimen()); + commandLevelSymbol->setAffil(m_internal->m_symbol.getAffil()); + + commandLevelSymbol->transformSymbol(SymbologyXML::Symbol::TMG_COMMAND_LEVEL); + } + } + + QVector tgSymbols; + const QList items = m_ui->ListViewTruppengattung->selectedItems(); + tgSymbols.reserve(items.size()); + for (const QListWidgetItem* item : items) + { + SymbologyXML::SymbolTypes::t_branch curBranch = + (SymbologyXML::SymbolTypes::t_branch)item->data(Qt::UserRole).toInt(); + int tmpID = SymbologyXML::SymbolTable::getBranchSymbolID(curBranch); + if (m_internal->m_branchSymbols.contains(tmpID)) + { + SymbologyXML::Symbol* tgSymbol = new SymbologyXML::Symbol(*m_internal->m_branchSymbols.value(tmpID)); + tgSymbol->setDimen(m_internal->m_symbol.getDimen()); + tgSymbol->setAffil(m_internal->m_symbol.getAffil()); + + tgSymbol->transformSymbol(SymbologyXML::Symbol::TMG_BRANCHES, &m_internal->m_branchSymbols); + + tgSymbols.append(tgSymbol); + } + } + + if (editview) { - SymbologyXML::Symbol *l_symbolFramePreview = new SymbologyXML::Symbol(*symbolFramePreview); + editLineCol.setAlphaF(1.0); + editFrameFillCol.setAlphaF(1.0); + editAttFillCol.setAlphaF(1.0); - l_symbolFramePreview->setDimen(m_internal->m_symbol.getDimen()); - l_symbolFramePreview->setAffil(m_internal->m_symbol.getAffil()); - SymbologyXML::SymbolTypes::AdditionalSymbolData l_additionalData = m_internal->m_additionalDataPreview; - SymbologyXML::SymbolExporter::drawFrameSymbol(*l_symbolFramePreview, l_additionalData, - &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, - -0.3); - delete l_symbolFramePreview; + m_internal->m_graphicsScene.cancelCurrentAction(); + + m_internal->m_currentGraphicsItemCopy = nullptr; + m_internal->m_currentGraphicsItem = nullptr; + m_internal->m_graphicsScene.clear(); + m_internal->m_mapItemPrimitives.clear(); + + if (symbolFrameEditView != nullptr) + { + + SymbologyXML::Symbol* l_symbolFrameEditView = new SymbologyXML::Symbol(*symbolFrameEditView); + + l_symbolFrameEditView->setDimen(m_internal->m_symbol.getDimen()); + l_symbolFrameEditView->setAffil(m_internal->m_symbol.getAffil()); + SymbologyXML::SymbolTypes::AdditionalSymbolData l_additionalData = m_internal->m_additionalDataPreview; + l_additionalData.m_filltype = m_internal->m_frameEditFilltype; + l_additionalData.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; + SymbologyXML::SymbolExporter::drawFrameSymbol(*l_symbolFrameEditView, l_additionalData, + &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, + -0.3); + delete l_symbolFrameEditView; + } + + SymbologyXML::SymbolExporter::drawHeadquarterPrims( + &m_internal->m_graphicsScene, m_internal->m_symbol.getHeadquarter(), m_internal->m_symbol.getDimen(), + m_internal->m_symbol.getAffil(), editLineCol); + + if (mobilitySymbol != nullptr) + { + drawSymbol(mobilitySymbol, &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, -0.29, true, false); + } + if (vehicleSymbol != nullptr) + { + drawSymbol(vehicleSymbol, &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, -0.29, true, false); + } + if (intrinsicMobilitySymbol != nullptr) + { + drawSymbol(intrinsicMobilitySymbol, &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, -0.29, + true, false); + } + if (armingSymbol != nullptr) + { + drawSymbol(armingSymbol, &m_internal->m_graphicsScene, editLineCol, editFrameFillCol, -0.29, true, false); + } + + if (bcdabSymbol != nullptr) + { + drawSymbol(bcdabSymbol, &m_internal->m_graphicsScene, editLineCol, editAttFillCol, -0.29, true, false); + } + if (commandLevelSymbol != nullptr) + { + drawSymbol(commandLevelSymbol, &m_internal->m_graphicsScene, editLineCol, editAttFillCol, -0.29, true, + false); + } + for (const SymbologyXML::Symbol* tgtSym : tgSymbols) + { + if (tgtSym != nullptr) + { + drawSymbol(tgtSym, &m_internal->m_graphicsScene, editLineCol, editAttFillCol, -0.29, true, false); + } + } + + drawSymbol(&m_internal->m_symbol, &m_internal->m_graphicsScene, editLineCol, editLineCol, 0.0, false, true, + true); + + onCheckBoxDrawAreaStateChanged(m_internal->m_showDrawArea); + onSpinBoxRasterValueChanged(m_internal->m_gridWidth); } - SymbologyXML::SymbolExporter::drawHeadquarterPrims(&m_internal->m_graphicsPreviewScene, m_internal->m_symbol.getHeadquarter(), - m_internal->m_symbol.getDimen(), m_internal->m_symbol.getAffil(), - previewLineCol); - if (mobilitySymbol != nullptr) + if (preview) { - drawSymbol(mobilitySymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } - if (vehicleSymbol != nullptr) - { - drawSymbol(vehicleSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } - if (intrinsicMobilitySymbol != nullptr) - { - drawSymbol(intrinsicMobilitySymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } - if (armingSymbol != nullptr) - { - drawSymbol(armingSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } - for (const SymbologyXML::Symbol *miscSymbol : std::as_const(miscSymbols)) - { - if (miscSymbol != nullptr) - { - drawSymbol(miscSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } - } - if (bcdabSymbol != nullptr) - { - drawSymbol(bcdabSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewAttFillCol, - -0.29, false, false); - } - if (commandLevelSymbol != nullptr) - { - drawSymbol(commandLevelSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewAttFillCol, - -0.29, false, false); - } - for (const SymbologyXML::Symbol *tgSymbol : std::as_const(tgSymbols)) - { - if (tgSymbol != nullptr) - { - drawSymbol(tgSymbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewFrameFillCol, - -0.29, false, false); - } + + QColor previewLineCol; + QColor previewFrameFillCol; + QColor previewAttFillCol; + if (m_internal->m_additionalDataPreview.m_filltype == SymbologyXML::SymbolTypes::FILLTYPE_FILLED) + { + + previewLineCol = Qt::black; + previewFrameFillCol = m_internal->m_previewColor; + previewAttFillCol = previewLineCol; + } + else + { + + previewLineCol = m_internal->m_previewColor; + previewFrameFillCol = m_internal->m_previewColor; + previewAttFillCol = previewLineCol; + } + + m_internal->m_graphicsPreviewScene.setSceneRect(-1.5, -1.5, 3.0, 3.0); + + previewLineCol.setAlphaF(1.0); + previewFrameFillCol.setAlphaF(m_internal->m_transparency); + previewAttFillCol.setAlphaF(1.0); + + m_internal->m_graphicsPreviewScene.clear(); + m_internal->m_previewBackgroundItem = nullptr; + + if ((symbolFramePreview != nullptr)) + { + + SymbologyXML::Symbol* l_symbolFramePreview = new SymbologyXML::Symbol(*symbolFramePreview); + + l_symbolFramePreview->setDimen(m_internal->m_symbol.getDimen()); + l_symbolFramePreview->setAffil(m_internal->m_symbol.getAffil()); + SymbologyXML::SymbolTypes::AdditionalSymbolData l_additionalData = m_internal->m_additionalDataPreview; + SymbologyXML::SymbolExporter::drawFrameSymbol(*l_symbolFramePreview, l_additionalData, + &m_internal->m_graphicsPreviewScene, previewLineCol, + previewFrameFillCol, -0.3); + delete l_symbolFramePreview; + } + + SymbologyXML::SymbolExporter::drawHeadquarterPrims( + &m_internal->m_graphicsPreviewScene, m_internal->m_symbol.getHeadquarter(), m_internal->m_symbol.getDimen(), + m_internal->m_symbol.getAffil(), previewLineCol); + if (mobilitySymbol != nullptr) + { + drawSymbol(mobilitySymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, -0.29, + false, false); + } + if (vehicleSymbol != nullptr) + { + drawSymbol(vehicleSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, -0.29, + false, false); + } + if (intrinsicMobilitySymbol != nullptr) + { + drawSymbol(intrinsicMobilitySymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, + previewFrameFillCol, -0.29, false, false); + } + if (armingSymbol != nullptr) + { + drawSymbol(armingSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, -0.29, + false, false); + } + for (const SymbologyXML::Symbol* miscSymbol : std::as_const(miscSymbols)) + { + if (miscSymbol != nullptr) + { + drawSymbol(miscSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, -0.29, + false, false); + } + } + if (bcdabSymbol != nullptr) + { + drawSymbol(bcdabSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewAttFillCol, -0.29, + false, false); + } + if (commandLevelSymbol != nullptr) + { + drawSymbol(commandLevelSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewAttFillCol, + -0.29, false, false); + } + for (const SymbologyXML::Symbol* tgSymbol : std::as_const(tgSymbols)) + { + if (tgSymbol != nullptr) + { + drawSymbol(tgSymbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewFrameFillCol, -0.29, + false, false); + } + } + + drawSymbol(&m_internal->m_symbol, &m_internal->m_graphicsPreviewScene, previewLineCol, previewLineCol, 0.0, + false, false, false); + + m_ui->GraphicPreview->resetTransform(); + QTransform transformPreview = m_ui->GraphicPreview->transform(); + transformPreview.scale(PREVIEW_SCALE * m_internal->m_previewZoom, -PREVIEW_SCALE * m_internal->m_previewZoom); + m_ui->GraphicPreview->setTransform(transformPreview); + + if (m_internal->m_displayPreviewBackground && (!m_internal->m_previewBackground.isNull())) + { + m_internal->m_previewBackgroundItem = + m_internal->m_graphicsPreviewScene.addPixmap(m_internal->m_previewBackground); + + QRectF r = m_internal->m_previewBackgroundItem->boundingRect(); + double factor = (1.0 / (PREVIEW_SCALE * m_internal->m_previewZoom)); + m_internal->m_previewBackgroundItem->setScale(factor); + m_internal->m_previewBackgroundItem->setPos(-(r.width() / 2.0) * factor, -(r.height() / 2.0) * factor); + m_internal->m_previewBackgroundItem->setZValue(-0.4); + } + m_ui->GraphicPreview->centerOn(0.0, 0.0); } - drawSymbol(&m_internal->m_symbol, &m_internal->m_graphicsPreviewScene, - previewLineCol, - previewLineCol, - 0.0, false, false, false); + qDeleteAll(miscSymbols); + qDeleteAll(tgSymbols); - - m_ui->GraphicPreview->resetTransform(); - QTransform transformPreview = m_ui->GraphicPreview->transform(); - transformPreview.scale(PREVIEW_SCALE * m_internal->m_previewZoom, - -PREVIEW_SCALE * m_internal->m_previewZoom); - m_ui->GraphicPreview->setTransform(transformPreview); + delete bcdabSymbol; + delete commandLevelSymbol; - - if (m_internal->m_displayPreviewBackground && (!m_internal->m_previewBackground.isNull())) - { - m_internal->m_previewBackgroundItem = - m_internal->m_graphicsPreviewScene.addPixmap(m_internal->m_previewBackground); - - - QRectF r = m_internal->m_previewBackgroundItem->boundingRect(); - double factor = (1.0 / (PREVIEW_SCALE * m_internal->m_previewZoom)); - m_internal->m_previewBackgroundItem->setScale(factor); - m_internal->m_previewBackgroundItem->setPos(-(r.width() / 2.0)*factor, - -(r.height() / 2.0)*factor); - m_internal->m_previewBackgroundItem->setZValue(-0.4); - } - m_ui->GraphicPreview->centerOn(0.0, 0.0); - } - - qDeleteAll(miscSymbols); - qDeleteAll(tgSymbols); - - delete bcdabSymbol; - delete commandLevelSymbol; - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::reset() { - - resetToolButtonGroupState(); - m_internal->m_symbol = SymbologyXML::Symbol(m_internal->m_symbolDef); + resetToolButtonGroupState(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(false); + m_internal->m_symbol = SymbologyXML::Symbol(m_internal->m_symbolDef); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setEnabled(false); - updateGUI(); - - __unchange__(); + updateGUI(); + + __unchange__(); } -void SymbolEditor::drawSymbol(const SymbologyXML::Symbol *symbol, QGraphicsScene *scene, - const QColor &color, const QColor &fillColor, - double z, bool isAttrib, bool updateMap, bool drawBoundRect) +void SymbolEditor::drawSymbol(const SymbologyXML::Symbol* symbol, QGraphicsScene* scene, const QColor& color, + const QColor& fillColor, double z, bool isAttrib, bool updateMap, bool drawBoundRect) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - QMap *mapItemPrimitives_p = nullptr; - if (updateMap) - mapItemPrimitives_p = &m_internal->m_mapItemPrimitives; + QMap* mapItemPrimitives_p = nullptr; + if (updateMap) + mapItemPrimitives_p = &m_internal->m_mapItemPrimitives; - bool antialias = true; + bool antialias = true; - SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; - symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = &m_internal->m_intrinsicMobilitySymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; + SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; + symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = &m_internal->m_intrinsicMobilitySymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; - SymbologyXML::SymbolExporter::drawSymbol(*symbol, - symTableCont, - scene, - color, - fillColor, - z, - isAttrib, - antialias, - nullptr, - mapItemPrimitives_p, drawBoundRect - ); + SymbologyXML::SymbolExporter::drawSymbol(*symbol, symTableCont, scene, color, fillColor, z, isAttrib, antialias, + nullptr, mapItemPrimitives_p, drawBoundRect); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } -void SymbolEditor::drawSymbolPrimitive(SymbologyXML::Primitive *primitive, QGraphicsScene *scene, - const QColor &color, const QColor &fillColor, - double z, bool isAttrib, bool drawBoundRect) +void SymbolEditor::drawSymbolPrimitive(SymbologyXML::Primitive* primitive, QGraphicsScene* scene, const QColor& color, + const QColor& fillColor, double z, bool isAttrib, bool drawBoundRect) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; - symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = &m_internal->m_intrinsicMobilitySymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; - symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; + SymbologyXML::SymbolTypes::t_symbolTableCont symTableCont; + symTableCont.resize(SymbologyXML::SymbolTypes::ICON_TYPE_END); + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON] = &m_internal->m_sectorSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY] = &m_internal->m_intrinsicMobilitySymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE] = &m_internal->m_vehicleSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_ARMING] = &m_internal->m_armingSymbols; + symTableCont[SymbologyXML::SymbolTypes::ICON_TYPE_MISC] = &m_internal->m_miscSymbols; - SymbologyXML::SymbolExporter::drawSymbolPrimitive(primitive, symTableCont, scene, color, fillColor, - z, isAttrib, &m_internal->m_mapItemPrimitives, drawBoundRect); + SymbologyXML::SymbolExporter::drawSymbolPrimitive(primitive, symTableCont, scene, color, fillColor, z, isAttrib, + &m_internal->m_mapItemPrimitives, drawBoundRect); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::enableSelectMove(bool enable) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) - { - it.next(); - QGraphicsItem *pi = it.key(); - pi->setFlag(QGraphicsItem::ItemIsSelectable, enable); - pi->setFlag(QGraphicsItem::ItemIsMovable, enable); - } + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) + { + it.next(); + QGraphicsItem* pi = it.key(); + pi->setFlag(QGraphicsItem::ItemIsSelectable, enable); + pi->setFlag(QGraphicsItem::ItemIsMovable, enable); + } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::setZoom(double zoom) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_ui->GraphicView->resetTransform(); - QTransform transformView = m_ui->GraphicView->transform(); - transformView.scale(VIEW_SCALE * zoom, -VIEW_SCALE * zoom); - m_ui->GraphicView->setTransform(transformView); + m_ui->GraphicView->resetTransform(); + QTransform transformView = m_ui->GraphicView->transform(); + transformView.scale(VIEW_SCALE * zoom, -VIEW_SCALE * zoom); + m_ui->GraphicView->setTransform(transformView); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } -void SymbolEditor::addItem(SymbologyXML::Primitive *prim) +void SymbolEditor::addItem(SymbologyXML::Primitive* prim) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - pushUndo(); - prim->setFill(m_internal->m_fillPrimitive); - prim->setColor(m_internal->m_fillColor); - m_internal->m_symbol.addPrimitive(prim); - setChanged(true); - updateGraphicViews(true, true); + pushUndo(); + prim->setFill(m_internal->m_fillPrimitive); + prim->setColor(m_internal->m_fillColor); + m_internal->m_symbol.addPrimitive(prim); + setChanged(true); + updateGraphicViews(true, true); - - m_internal->m_graphicsScene.clearSelection(); - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) - { - it.next(); - QGraphicsItem *pi = it.key(); - if (pi->data(SymbologyXML::primitiveKey).value() == prim) + m_internal->m_graphicsScene.clearSelection(); + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) { - pi->setSelected(true); - break; + it.next(); + QGraphicsItem* pi = it.key(); + if (pi->data(SymbologyXML::primitiveKey).value() == prim) + { + pi->setSelected(true); + break; + } } - } - enableSelectMove(false); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::slotImportTemplate() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!m_internal->m_flmGui) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error FileManagementGuiPlugin isn't loaded."; - return; - } - - QByteArray content; - int fileId = m_internal->m_flmGui->loadFileContent(this, content, {FileManagement::FileType::OperatorDefinedSymbol}, 0, QString(), SYMBOL_FOLDER_ID); - if (fileId > 0) - { - if (content.size() == 0) + if (!m_internal->m_flmGui) { - ERROR_LOG(m_logger) << Q_FUNC_INFO << "Empty SymbolContent read from library"; + ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error FileManagementGuiPlugin isn't loaded."; + return; } - else + + QByteArray content; + int fileId = m_internal->m_flmGui->loadFileContent(this, content, {FileManagement::FileType::OperatorDefinedSymbol}, + 0, QString(), SYMBOL_FOLDER_ID); + if (fileId > 0) { - FileManagement::FileContent fc = m_internal->m_flmDtc->fileContent(fileId); - QString symbolName = QString::fromStdString(fc.name()); - SymbologyXML::SymbolReader sr; - pushUndo(); - sr.read(content, m_internal->m_symbol); - m_internal->m_symbolDef = SymbologyXML::Symbol(m_internal->m_symbol); + if (content.size() == 0) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << "Empty SymbolContent read from library"; + } + else + { + FileManagement::FileContent fc = m_internal->m_flmDtc->fileContent(fileId); + QString symbolName = QString::fromStdString(fc.name()); + SymbologyXML::SymbolReader sr; + pushUndo(); + sr.read(content, m_internal->m_symbol); + m_internal->m_symbolDef = SymbologyXML::Symbol(m_internal->m_symbol); - m_internal->m_lastFileId = fileId; - m_internal->m_lastFileName = symbolName; - m_internal->m_lastFolderId = fc.folderId(); + m_internal->m_lastFileId = fileId; + m_internal->m_lastFileName = symbolName; + m_internal->m_lastFolderId = fc.folderId(); - updateGUI(); - __unchange__(); + updateGUI(); + __unchange__(); + } } - } - resetToolButtonGroupState(); + resetToolButtonGroupState(); - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonSelectClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_MOVE); - m_internal->m_editMode = EDIT_MOVE; - enableSelectMove(true); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_MOVE); + m_internal->m_editMode = EDIT_MOVE; + enableSelectMove(true); - if (m_internal->m_currentGraphicsItem != nullptr) - { - m_internal->m_currentGraphicsItemPos = m_internal->m_currentGraphicsItem->scenePos(); - m_internal->m_currentGraphicsItem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); - } + if (m_internal->m_currentGraphicsItem != nullptr) + { + m_internal->m_currentGraphicsItemPos = m_internal->m_currentGraphicsItem->scenePos(); + m_internal->m_currentGraphicsItem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); + } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::onToolButtonRotateClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_ROTATE); - m_internal->m_editMode = EDIT_ROTATE; + SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_ROTATE); + m_internal->m_editMode = EDIT_ROTATE; - SymbologyXML::Primitive *currPrimitive = nullptr; - if (m_internal->m_currentGraphicsItem != nullptr) - currPrimitive = m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); + SymbologyXML::Primitive* currPrimitive = nullptr; + if (m_internal->m_currentGraphicsItem != nullptr) + currPrimitive = + m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); - if (!currPrimitive) - return; + if (!currPrimitive) + return; - pushUndo(); + pushUndo(); - RotateDialog *rotateDialog = new RotateDialog(); - rotateDialog->setAttribute(Qt::WA_DeleteOnClose); + RotateDialog* rotateDialog = new RotateDialog(); + rotateDialog->setAttribute(Qt::WA_DeleteOnClose); - double oldValue = currPrimitive->getRotation(); + double oldValue = currPrimitive->getRotation(); - connect(rotateDialog, &RotateDialog::rotationValueChanged, this, - [this, currPrimitive](double value) - { - currPrimitive->setRotation(value); - SymbologyXML::SymbolExporter::redraw(m_internal->m_currentGraphicsItem, true); - }); - connect(rotateDialog, &RotateDialog::rejected, this, - [this, currPrimitive, oldValue]() - { - currPrimitive->setRotation(oldValue); - SymbologyXML::SymbolExporter::redraw(m_internal->m_currentGraphicsItem, true); - }); + connect(rotateDialog, &RotateDialog::rotationValueChanged, this, [this, currPrimitive](double value) { + currPrimitive->setRotation(value); + SymbologyXML::SymbolExporter::redraw(m_internal->m_currentGraphicsItem, true); + }); + connect(rotateDialog, &RotateDialog::rejected, this, [this, currPrimitive, oldValue]() { + currPrimitive->setRotation(oldValue); + SymbologyXML::SymbolExporter::redraw(m_internal->m_currentGraphicsItem, true); + }); - rotateDialog->show(); - + rotateDialog->show(); - updateGraphicViews(true, true); - restoreSelection(currPrimitive); - m_internal->m_graphicsScene.setDrawMode(dm); + updateGraphicViews(true, true); + restoreSelection(currPrimitive); + m_internal->m_graphicsScene.setDrawMode(dm); - resetToolButtonGroupState(); + resetToolButtonGroupState(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::onToolButtonScaleClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_currentGraphicsItem == nullptr) - { - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } + if (m_internal->m_currentGraphicsItem == nullptr) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } - SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_SCALE); - m_internal->m_editMode = EDIT_SCALE; + SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELEMENT_SCALE); + m_internal->m_editMode = EDIT_SCALE; - SymbologyXML::Primitive *currPrimitive = nullptr; - if (m_internal->m_currentGraphicsItem != nullptr) - currPrimitive = m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); - if (!currPrimitive) - return; + SymbologyXML::Primitive* currPrimitive = nullptr; + if (m_internal->m_currentGraphicsItem != nullptr) + currPrimitive = + m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); + if (!currPrimitive) + return; - SymbologyXML::Primitive pCopy(*currPrimitive); + SymbologyXML::Primitive pCopy(*currPrimitive); - bool enabled = !(currPrimitive->type() == SymbologyXML::Primitive::TEXT); - bool checked = ((currPrimitive->type() == SymbologyXML::Primitive::TEXT) || - (currPrimitive->type() == SymbologyXML::Primitive::ICON && - currPrimitive->scalemode() != SymbologyXML::Primitive::Scalemode_Unproport)); + bool enabled = !(currPrimitive->type() == SymbologyXML::Primitive::TEXT); + bool checked = ((currPrimitive->type() == SymbologyXML::Primitive::TEXT) || + (currPrimitive->type() == SymbologyXML::Primitive::ICON && + currPrimitive->scalemode() != SymbologyXML::Primitive::Scalemode_Unproport)); - ResizeDialog *resizeDialog = new ResizeDialog(checked, enabled); - resizeDialog->setAttribute(Qt::WA_DeleteOnClose); + ResizeDialog* resizeDialog = new ResizeDialog(checked, enabled); + resizeDialog->setAttribute(Qt::WA_DeleteOnClose); - connect(resizeDialog, &ResizeDialog::primitiveScaled, this, - [this, currPrimitive, pCopy](double xScale, double yScale) - { - *currPrimitive = pCopy; - currPrimitive->scale(xScale, yScale); - m_internal->m_graphicsScene.removeItem(m_internal->m_currentGraphicsItem); - delete m_internal->m_currentGraphicsItem; - drawSymbolPrimitive(currPrimitive, &m_internal->m_graphicsScene, - currPrimitive->getColor(), - currPrimitive->getColor(), 0.0, - (currPrimitive->type() == SymbologyXML::Primitive::ICON), - true); + connect(resizeDialog, &ResizeDialog::primitiveScaled, this, + [this, currPrimitive, pCopy](double xScale, double yScale) { + *currPrimitive = pCopy; + currPrimitive->scale(xScale, yScale); + m_internal->m_graphicsScene.removeItem(m_internal->m_currentGraphicsItem); + delete m_internal->m_currentGraphicsItem; + drawSymbolPrimitive(currPrimitive, &m_internal->m_graphicsScene, currPrimitive->getColor(), + currPrimitive->getColor(), 0.0, + (currPrimitive->type() == SymbologyXML::Primitive::ICON), true); + restoreSelection(currPrimitive); + }); + + connect(resizeDialog, &ResizeDialog::rejected, this, [currPrimitive, pCopy]() { *currPrimitive = pCopy; }); + + pushUndo(); + + resizeDialog->show(); + + setChanged(true); + updateGraphicViews(true, true); restoreSelection(currPrimitive); - }); + m_internal->m_graphicsScene.setDrawMode(dm); - connect(resizeDialog, &ResizeDialog::rejected, this, - [currPrimitive, pCopy]() - { - *currPrimitive = pCopy; - }); + resetToolButtonGroupState(); - pushUndo(); - - resizeDialog->show(); - - setChanged(true); - updateGraphicViews(true, true); - restoreSelection(currPrimitive); - m_internal->m_graphicsScene.setDrawMode(dm); - - resetToolButtonGroupState(); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::onToolButtonClearClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - DeleteElementsDialog *selElemsDial = new DeleteElementsDialog(this); - if (selElemsDial->exec() != QDialog::Accepted) - return; + DeleteElementsDialog* selElemsDial = new DeleteElementsDialog(this); + if (selElemsDial->exec() != QDialog::Accepted) + return; - bool changed = false; + bool changed = false; - bool checkedPrims; - bool checkedPrimsSectorText; - bool checkedAttributes; + bool checkedPrims; + bool checkedPrimsSectorText; + bool checkedAttributes; - selElemsDial->getCheckedElements(checkedPrims, checkedPrimsSectorText, checkedAttributes); - - if (checkedPrims || checkedPrimsSectorText) - { - - - QMutableMapIterator it(m_internal->m_mapItemPrimitives); - QVariant nullData; - nullData.setValue(nullptr); + selElemsDial->getCheckedElements(checkedPrims, checkedPrimsSectorText, checkedAttributes); - while (it.hasNext()) + if (checkedPrims || checkedPrimsSectorText) { - it.next(); - QGraphicsItem *pi = it.key(); - SymbologyXML::Primitive *prim = it.value(); - if ((prim->type() == SymbologyXML::Primitive::ICON) || (prim->type() == SymbologyXML::Primitive::TEXT)) - { - - if (checkedPrimsSectorText) + + QMutableMapIterator it(m_internal->m_mapItemPrimitives); + QVariant nullData; + nullData.setValue(nullptr); + + while (it.hasNext()) { - pi->setData(SymbologyXML::primitiveKey, nullData); - it.remove(); + it.next(); + QGraphicsItem* pi = it.key(); + SymbologyXML::Primitive* prim = it.value(); + if ((prim->type() == SymbologyXML::Primitive::ICON) || (prim->type() == SymbologyXML::Primitive::TEXT)) + { + + if (checkedPrimsSectorText) + { + pi->setData(SymbologyXML::primitiveKey, nullData); + it.remove(); + } + } + else + { + + if (checkedPrims) + { + pi->setData(SymbologyXML::primitiveKey, nullData); + it.remove(); + } + } } - } - else - { - if (checkedPrims) { - pi->setData(SymbologyXML::primitiveKey, nullData); - it.remove(); + m_internal->m_symbol.clearPrimitives(true); + changed = true; } - } + if (checkedPrimsSectorText) + { + + m_internal->m_symbol.setText(QString(), m_internal->m_symbol.getTextAlign(1), QString(), + m_internal->m_symbol.getTextAlign(2), QString(), + m_internal->m_symbol.getTextAlign(3)); + + m_internal->m_symbol.clearPrimitivesICON_TEXT(); + + QVectorIterator it2 = + SymbologyXML::SymbolTypes::instance()->getBranch()->getIterator(); + while (it2.hasNext()) + { + SymbologyXML::SymbolTypes::t_branch val = it2.next(); + m_internal->m_symbol.removeBranch(val); + } + changed = true; + } + m_internal->m_currentGraphicsItemCopy = nullptr; + m_internal->m_currentPrimitiveCopy = nullptr; + m_ui->ToolButtonPaste->setEnabled(false); } - if (checkedPrims) + + if (checkedAttributes) { - m_internal->m_symbol.clearPrimitives(true); - changed = true; + m_internal->m_symbol.setDimen(SymbologyXML::SymbolTypes::DIMEN_UNDEFINED); + m_internal->m_symbol.setAffil(SymbologyXML::SymbolTypes::AFFIL_UNDEFINED); + m_internal->m_symbol.setBcdab(SymbologyXML::SymbolTypes::BCDAB_UNDEFINED); + m_internal->m_symbol.setHeadquarter(false); + m_internal->m_symbol.setCommandLevel(SymbologyXML::SymbolTypes::CL_UNDEFINED); + m_internal->m_symbol.setMob(SymbologyXML::SymbolTypes::MOB_UNDEFINED); + changed = true; } - if (checkedPrimsSectorText) - { - - m_internal->m_symbol.setText(QString(), m_internal->m_symbol.getTextAlign(1), - QString(), m_internal->m_symbol.getTextAlign(2), - QString(), m_internal->m_symbol.getTextAlign(3)); - - m_internal->m_symbol.clearPrimitivesICON_TEXT(); - - QVectorIterator it2 = SymbologyXML::SymbolTypes::instance()->getBranch()->getIterator(); - while (it2.hasNext()) - { - SymbologyXML::SymbolTypes::t_branch val = it2.next(); - m_internal->m_symbol.removeBranch(val); - } - changed = true; - } - m_internal->m_currentGraphicsItemCopy = nullptr; - m_internal->m_currentPrimitiveCopy = nullptr; - m_ui->ToolButtonPaste->setEnabled(false); - } - - if (checkedAttributes) - { - m_internal->m_symbol.setDimen(SymbologyXML::SymbolTypes::DIMEN_UNDEFINED); - m_internal->m_symbol.setAffil(SymbologyXML::SymbolTypes::AFFIL_UNDEFINED); - m_internal->m_symbol.setBcdab(SymbologyXML::SymbolTypes::BCDAB_UNDEFINED); - m_internal->m_symbol.setHeadquarter(false); - m_internal->m_symbol.setCommandLevel(SymbologyXML::SymbolTypes::CL_UNDEFINED); - m_internal->m_symbol.setMob(SymbologyXML::SymbolTypes::MOB_UNDEFINED); - changed = true; - } + updateSymbolAttributesWidgets(); + updateGraphicViews(true, true); + setChanged(changed); - updateSymbolAttributesWidgets(); - updateGraphicViews(true, true); - setChanged(changed); + resetToolButtonGroupState(); - resetToolButtonGroupState(); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonUndoClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - int scrollx = m_ui->GraphicView->horizontalScrollBar()->sliderPosition(); - int scrolly = m_ui->GraphicView->verticalScrollBar()->sliderPosition(); + int scrollx = m_ui->GraphicView->horizontalScrollBar()->sliderPosition(); + int scrolly = m_ui->GraphicView->verticalScrollBar()->sliderPosition(); - updateGraphicViews(true, true); - popUndo(); + updateGraphicViews(true, true); + popUndo(); - - m_ui->GraphicView->horizontalScrollBar()->setSliderPosition(scrollx); - m_ui->GraphicView->verticalScrollBar()->setSliderPosition(scrolly); + m_ui->GraphicView->horizontalScrollBar()->setSliderPosition(scrollx); + m_ui->GraphicView->verticalScrollBar()->setSliderPosition(scrolly); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonDeleteClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_mapItemPrimitives.find(m_internal->m_currentGraphicsItem) != m_internal->m_mapItemPrimitives.end()) - { - pushUndo(); - SymbologyXML::Primitive *prim = m_internal->m_mapItemPrimitives.take(m_internal->m_currentGraphicsItem); - m_internal->m_symbol.removePrimitive(prim->id()); - m_internal->m_graphicsScene.removeItem(m_internal->m_currentGraphicsItem); - updateSymbolAttributesWidgets(); - updateGraphicViews(false, true); - if (m_internal->m_currentGraphicsItemCopy != m_internal->m_currentGraphicsItem) + if (m_internal->m_mapItemPrimitives.find(m_internal->m_currentGraphicsItem) != + m_internal->m_mapItemPrimitives.end()) { - - delete m_internal->m_currentPrimitiveCopy; - delete m_internal->m_currentGraphicsItemCopy; - m_internal->m_currentPrimitiveCopy = nullptr; - m_internal->m_currentGraphicsItemCopy = nullptr; + pushUndo(); + SymbologyXML::Primitive* prim = m_internal->m_mapItemPrimitives.take(m_internal->m_currentGraphicsItem); + m_internal->m_symbol.removePrimitive(prim->id()); + m_internal->m_graphicsScene.removeItem(m_internal->m_currentGraphicsItem); + updateSymbolAttributesWidgets(); + updateGraphicViews(false, true); + if (m_internal->m_currentGraphicsItemCopy != m_internal->m_currentGraphicsItem) + { + + delete m_internal->m_currentPrimitiveCopy; + delete m_internal->m_currentGraphicsItemCopy; + m_internal->m_currentPrimitiveCopy = nullptr; + m_internal->m_currentGraphicsItemCopy = nullptr; + } + delete m_internal->m_currentGraphicsItem; + m_internal->m_currentGraphicsItem = nullptr; + setChanged(true); } - delete m_internal->m_currentGraphicsItem; - m_internal->m_currentGraphicsItem = nullptr; - setChanged(true); - } - resetToolButtonGroupState(); + resetToolButtonGroupState(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonCopyClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_editMode = EDIT_COPY; + m_internal->m_editMode = EDIT_COPY; - if (m_internal->m_currentGraphicsItem != nullptr) - { - m_internal->m_currentPrimitiveCopy = m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); - m_ui->ToolButtonPaste->setEnabled(true); - } + if (m_internal->m_currentGraphicsItem != nullptr) + { + m_internal->m_currentPrimitiveCopy = + m_internal->m_currentGraphicsItem->data(SymbologyXML::primitiveKey).value(); + m_ui->ToolButtonPaste->setEnabled(true); + } - resetToolButtonGroupState(); + resetToolButtonGroupState(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonPasteClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_editMode = EDIT_PASTE; + m_internal->m_editMode = EDIT_PASTE; - if (m_internal->m_currentPrimitiveCopy != nullptr) - { - SymbologyXML::Primitive *prim = new SymbologyXML::Primitive(*m_internal->m_currentPrimitiveCopy); - - QPolygonF pointList = prim->getPoints(); - pointList.translate(-0.1, -0.1); - prim->setPoints(pointList); - addItem(prim); - m_internal->m_currentPrimitiveCopy = nullptr; - m_internal->m_currentGraphicsItemCopy = nullptr; - m_ui->ToolButtonPaste->setEnabled(false); - m_ui->ToolButtonSelect->animateClick(); - } + if (m_internal->m_currentPrimitiveCopy != nullptr) + { + SymbologyXML::Primitive* prim = new SymbologyXML::Primitive(*m_internal->m_currentPrimitiveCopy); - resetToolButtonGroupState(); + QPolygonF pointList = prim->getPoints(); + pointList.translate(-0.1, -0.1); + prim->setPoints(pointList); + addItem(prim); + m_internal->m_currentPrimitiveCopy = nullptr; + m_internal->m_currentGraphicsItemCopy = nullptr; + m_ui->ToolButtonPaste->setEnabled(false); + m_ui->ToolButtonSelect->animateClick(); + } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + resetToolButtonGroupState(); + + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonEllipseClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELLIPSE_START); - enableSelectMove(false); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::ELLIPSE_START); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonLineClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::LINE_START); - enableSelectMove(false); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::LINE_START); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonPolylineClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::POLYLINE_START); - enableSelectMove(false); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::POLYLINE_START); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonPolygonClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::POLYGON_START); - enableSelectMove(false); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::POLYGON_START); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonTextClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - resetToolButtonGroupState(); + resetToolButtonGroupState(); - QVariant dialogData; + QVariant dialogData; - SelectTextDialog *dialog = new SelectTextDialog(dialogData, this); + SelectTextDialog* dialog = new SelectTextDialog(dialogData, this); - if (dialog->exec() == QDialog::Accepted && - dialogData.canConvert(QMetaType::QVariantMap)) - { - QVariantMap vmap = dialogData.toMap(); + if (dialog->exec() == QDialog::Accepted && dialogData.canConvert(QMetaType::QVariantMap)) + { + QVariantMap vmap = dialogData.toMap(); - QString line1 = vmap[QStringLiteral("line_one")].toString(), - line2 = vmap[QStringLiteral("line_two")].toString(); + QString line1 = vmap[QStringLiteral("line_one")].toString(), + line2 = vmap[QStringLiteral("line_two")].toString(); - - - if (line2.isEmpty()) - line2 = QStringLiteral(" "); + if (line2.isEmpty()) + line2 = QStringLiteral(" "); - SymbologyXML::Primitive *prim = new SymbologyXML::Primitive(SymbologyXML::Primitive::TEXT); - prim->setText(QStringLiteral("%1\n%2").arg(line1, line2)); + SymbologyXML::Primitive* prim = new SymbologyXML::Primitive(SymbologyXML::Primitive::TEXT); + prim->setText(QStringLiteral("%1\n%2").arg(line1, line2)); - QRectF rect = SymbologyXML::SymbolTypes::getDefaultPrimTEXTRect(); - QPolygonF poly; - poly.append(rect.topLeft()); - poly.append(rect.bottomRight()); - prim->setPoints(poly); - prim->setPosition(SymbologyXML::SymbolTypes::SECTORFF); + QRectF rect = SymbologyXML::SymbolTypes::getDefaultPrimTEXTRect(); + QPolygonF poly; + poly.append(rect.topLeft()); + poly.append(rect.bottomRight()); + prim->setPoints(poly); + prim->setPosition(SymbologyXML::SymbolTypes::SECTORFF); - m_internal->m_symbol.addPrimitive(prim); + m_internal->m_symbol.addPrimitive(prim); - setChanged(true); - updateGraphicViews(); - } + setChanged(true); + updateGraphicViews(); + } - - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::resetToolButtonGroupState() { - m_ui->ToolButtonSelect->animateClick(1); + m_ui->ToolButtonSelect->animateClick(1); } - void SymbolEditor::onPushButtonFillColorClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_fillColor = QColorDialog::getColor(Qt::white, this, tr("Select fill color"), QColorDialog::DontUseNativeDialog); - setPushButtonFillColorBackground(m_internal->m_fillColor); + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + m_internal->m_fillColor = + QColorDialog::getColor(Qt::white, this, tr("Select fill color"), QColorDialog::DontUseNativeDialog); + setPushButtonFillColorBackground(m_internal->m_fillColor); - if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) - { - if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) { - - QGraphicsItem *pi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = pi->data(SymbologyXML::primitiveKey).value(); - if ((prim->type() != SymbologyXML::Primitive::TEXT)) - { - prim->setColor(m_internal->m_fillColor); - SymbologyXML::SymbolExporter::redraw(pi); - updateGraphicViews(true, true); - - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) + if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) { - it.next(); - QGraphicsItem *pi2 = it.key(); - if (pi2->data(SymbologyXML::primitiveKey).value() == prim) - { - - pi2->setSelected(true); - } - } - setChanged(true); - } - } - } - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; -} + QGraphicsItem* pi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = pi->data(SymbologyXML::primitiveKey).value(); + if ((prim->type() != SymbologyXML::Primitive::TEXT)) + { + prim->setColor(m_internal->m_fillColor); + SymbologyXML::SymbolExporter::redraw(pi); + updateGraphicViews(true, true); + + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) + { + it.next(); + QGraphicsItem* pi2 = it.key(); + if (pi2->data(SymbologyXML::primitiveKey).value() == prim) + { + + pi2->setSelected(true); + } + } + setChanged(true); + } + } + } + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; +} void SymbolEditor::setPushButtonFillColorBackground(QColor color) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_fillColor = color; - m_ui->PushButtonFillColor->setStyleSheet(QStringLiteral("background-color:rgb(%1,%2,%3)").arg(color.red()).arg(color.green()).arg(color.blue())); - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + m_internal->m_fillColor = color; + m_ui->PushButtonFillColor->setStyleSheet( + QStringLiteral("background-color:rgb(%1,%2,%3)").arg(color.red()).arg(color.green()).arg(color.blue())); + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } - void SymbolEditor::onToolButtonRectClicked() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::RECT_START); - enableSelectMove(false); + m_internal->m_graphicsScene.setDrawMode(SymbolEditScene::RECT_START); + enableSelectMove(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::copyElementsFromSymbol(const SymbologyXML::Symbol &tmpSymbol) const +void SymbolEditor::copyElementsFromSymbol(const SymbologyXML::Symbol& tmpSymbol) const { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - - if (m_internal->m_symbol.getDimen() == SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) - m_internal->m_symbol.setDimen(tmpSymbol.getDimen()); - if (m_internal->m_symbol.getAffil() == SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) - m_internal->m_symbol.setAffil(tmpSymbol.getAffil()); - if (m_internal->m_symbol.getBcdab() == SymbologyXML::SymbolTypes::BCDAB_UNDEFINED) - m_internal->m_symbol.setBcdab(tmpSymbol.getBcdab()); - m_internal->m_symbol.setHeadquarter(tmpSymbol.getHeadquarter()); - if (m_internal->m_symbol.getCommandLevel() == SymbologyXML::SymbolTypes::CL_UNDEFINED) - m_internal->m_symbol.setCommandLevel(tmpSymbol.getCommandLevel()); - if (m_internal->m_symbol.getMob() == SymbologyXML::SymbolTypes::MOB_UNDEFINED) - m_internal->m_symbol.setMob(tmpSymbol.getMob()); + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - - NGL::BitSet tmpBranchTags = tmpSymbol.getBranchTags(); + if (m_internal->m_symbol.getDimen() == SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) + m_internal->m_symbol.setDimen(tmpSymbol.getDimen()); + if (m_internal->m_symbol.getAffil() == SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) + m_internal->m_symbol.setAffil(tmpSymbol.getAffil()); + if (m_internal->m_symbol.getBcdab() == SymbologyXML::SymbolTypes::BCDAB_UNDEFINED) + m_internal->m_symbol.setBcdab(tmpSymbol.getBcdab()); + m_internal->m_symbol.setHeadquarter(tmpSymbol.getHeadquarter()); + if (m_internal->m_symbol.getCommandLevel() == SymbologyXML::SymbolTypes::CL_UNDEFINED) + m_internal->m_symbol.setCommandLevel(tmpSymbol.getCommandLevel()); + if (m_internal->m_symbol.getMob() == SymbologyXML::SymbolTypes::MOB_UNDEFINED) + m_internal->m_symbol.setMob(tmpSymbol.getMob()); - for (size_t idx = 0; idx < tmpBranchTags.size(); ++idx) - { - if (tmpBranchTags.at(idx)) - m_internal->m_symbol.addBranch((SymbologyXML::SymbolTypes::t_branch)idx); - } + NGL::BitSet tmpBranchTags = tmpSymbol.getBranchTags(); - - QLinkedList prims = tmpSymbol.getPrimitives(); - QLinkedListIterator pi(prims); - while (pi.hasNext()) - { - SymbologyXML::Primitive *prim = pi.next(); - if ((prim->type() == SymbologyXML::Primitive::ICON) && - m_internal->m_symbol.containsPrimitive(prim->iconType(), prim->position(), prim->icon())) - continue; - m_internal->m_symbol.addPrimitive(new SymbologyXML::Primitive(*prim)); - } + for (size_t idx = 0; idx < tmpBranchTags.size(); ++idx) + { + if (tmpBranchTags.at(idx)) + m_internal->m_symbol.addBranch((SymbologyXML::SymbolTypes::t_branch)idx); + } - - QString text1 = m_internal->m_symbol.getText(1); - QString text2 = m_internal->m_symbol.getText(2); - QString text3 = m_internal->m_symbol.getText(3); - SymbologyXML::Symbol::t_alignment align1 = m_internal->m_symbol.getTextAlign(1); - SymbologyXML::Symbol::t_alignment align2 = m_internal->m_symbol.getTextAlign(2); - SymbologyXML::Symbol::t_alignment align3 = m_internal->m_symbol.getTextAlign(3); + QLinkedList prims = tmpSymbol.getPrimitives(); + QLinkedListIterator pi(prims); + while (pi.hasNext()) + { + SymbologyXML::Primitive* prim = pi.next(); + if ((prim->type() == SymbologyXML::Primitive::ICON) && + m_internal->m_symbol.containsPrimitive(prim->iconType(), prim->position(), prim->icon())) + continue; + m_internal->m_symbol.addPrimitive(new SymbologyXML::Primitive(*prim)); + } - if (tmpSymbol.getText(1).size() > 0) - { - text1 = tmpSymbol.getText(1); - align1 = tmpSymbol.getTextAlign(1); - } - if (tmpSymbol.getText(2).size() > 0) - { - text2 = tmpSymbol.getText(2); - align2 = tmpSymbol.getTextAlign(2); - } - if (tmpSymbol.getText(3).size() > 0) - { - text3 = tmpSymbol.getText(3); - align3 = tmpSymbol.getTextAlign(3); - } - m_internal->m_symbol.setText(text1, align1, text2, align2, text3, align3); + QString text1 = m_internal->m_symbol.getText(1); + QString text2 = m_internal->m_symbol.getText(2); + QString text3 = m_internal->m_symbol.getText(3); + SymbologyXML::Symbol::t_alignment align1 = m_internal->m_symbol.getTextAlign(1); + SymbologyXML::Symbol::t_alignment align2 = m_internal->m_symbol.getTextAlign(2); + SymbologyXML::Symbol::t_alignment align3 = m_internal->m_symbol.getTextAlign(3); - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + if (tmpSymbol.getText(1).size() > 0) + { + text1 = tmpSymbol.getText(1); + align1 = tmpSymbol.getTextAlign(1); + } + if (tmpSymbol.getText(2).size() > 0) + { + text2 = tmpSymbol.getText(2); + align2 = tmpSymbol.getTextAlign(2); + } + if (tmpSymbol.getText(3).size() > 0) + { + text3 = tmpSymbol.getText(3); + align3 = tmpSymbol.getTextAlign(3); + } + m_internal->m_symbol.setText(text1, align1, text2, align2, text3, align3); + + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxDimenCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_dimen dimen = + (SymbologyXML::SymbolTypes::t_dimen)m_ui->ComboBoxDimen->itemData(index).toInt(); + m_internal->m_symbol.setDimen(dimen); + setChanged(true); + + if (((SymbologyXML::SymbolTypes::t_dimen)dimen != SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) && + m_internal->m_symbol.getAffil() == SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) + m_ui->ComboBoxAffil->setCurrentIndex(m_ui->ComboBoxAffil->findData(SymbologyXML::SymbolTypes::NEUTRAL)); + if ((SymbologyXML::SymbolTypes::t_dimen)dimen != SymbologyXML::SymbolTypes::LAND_UNITS) + { + m_ui->ComboBoxHeadquarter->setCurrentIndex(0); + m_internal->m_symbol.setHeadquarter(false); + } + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - - SymbologyXML::SymbolTypes::t_dimen dimen = (SymbologyXML::SymbolTypes::t_dimen)m_ui->ComboBoxDimen->itemData(index).toInt(); - m_internal->m_symbol.setDimen(dimen); - setChanged(true); - - if (((SymbologyXML::SymbolTypes::t_dimen)dimen != SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) && - m_internal->m_symbol.getAffil() == SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) - m_ui->ComboBoxAffil->setCurrentIndex(m_ui->ComboBoxAffil->findData(SymbologyXML::SymbolTypes::NEUTRAL)); - if ((SymbologyXML::SymbolTypes::t_dimen)dimen != SymbologyXML::SymbolTypes::LAND_UNITS) - { - m_ui->ComboBoxHeadquarter->setCurrentIndex(0); - m_internal->m_symbol.setHeadquarter(false); - } - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxAffilCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_affil affil = + (SymbologyXML::SymbolTypes::t_affil)m_ui->ComboBoxAffil->itemData(index).toInt(); + m_internal->m_symbol.setAffil(affil); + setChanged(true); + + if ((affil != SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) && + m_internal->m_symbol.getDimen() == SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) + m_ui->ComboBoxDimen->setCurrentIndex(m_ui->ComboBoxDimen->findData(SymbologyXML::SymbolTypes::LAND_UNITS)); + + bool enable = true; + if ((affil == SymbologyXML::SymbolTypes::ASSUMED_FRIEND) || (affil == SymbologyXML::SymbolTypes::SUSPECT) || + (affil == SymbologyXML::SymbolTypes::PENDING)) + enable = false; + m_ui->CheckBoxPlanned->setEnabled(enable); + + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - - SymbologyXML::SymbolTypes::t_affil affil = (SymbologyXML::SymbolTypes::t_affil)m_ui->ComboBoxAffil->itemData(index).toInt(); - m_internal->m_symbol.setAffil(affil); - setChanged(true); - - if ((affil != SymbologyXML::SymbolTypes::AFFIL_UNDEFINED) && - m_internal->m_symbol.getDimen() == SymbologyXML::SymbolTypes::DIMEN_UNDEFINED) - m_ui->ComboBoxDimen->setCurrentIndex(m_ui->ComboBoxDimen->findData(SymbologyXML::SymbolTypes::LAND_UNITS)); - - bool enable = true; - if ((affil == SymbologyXML::SymbolTypes::ASSUMED_FRIEND) || - (affil == SymbologyXML::SymbolTypes::SUSPECT) || - (affil == SymbologyXML::SymbolTypes::PENDING)) - enable = false; - m_ui->CheckBoxPlanned->setEnabled(enable); - - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxBCDABCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_bcdab bcdab = + (SymbologyXML::SymbolTypes::t_bcdab)m_ui->ComboBoxBCDAB->itemData(index).toInt(); + m_internal->m_symbol.setBcdab(bcdab); + + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - SymbologyXML::SymbolTypes::t_bcdab bcdab = (SymbologyXML::SymbolTypes::t_bcdab)m_ui->ComboBoxBCDAB->itemData(index).toInt(); - m_internal->m_symbol.setBcdab(bcdab); - - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxHeadquarterCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setHeadquarter((bool)index); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - m_internal->m_symbol.setHeadquarter((bool)index); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxCommandLevelCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_commandlevel cl = + (SymbologyXML::SymbolTypes::t_commandlevel)m_ui->ComboBoxCommandLevel->itemData(index).toInt(); + m_internal->m_symbol.setCommandLevel(cl); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - SymbologyXML::SymbolTypes::t_commandlevel cl = (SymbologyXML::SymbolTypes::t_commandlevel)m_ui->ComboBoxCommandLevel->itemData(index).toInt(); - m_internal->m_symbol.setCommandLevel(cl); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxMobCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_mob mob = (SymbologyXML::SymbolTypes::t_mob)m_ui->ComboBoxMob->itemData(index).toInt(); + m_internal->m_symbol.setMob(mob); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - SymbologyXML::SymbolTypes::t_mob mob = (SymbologyXML::SymbolTypes::t_mob)m_ui->ComboBoxMob->itemData(index).toInt(); - m_internal->m_symbol.setMob(mob); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxVehicleCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (m_ui->CheckBoxVehicle->isChecked()) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxVehicle, - index, SymbologyXML::SymbolTypes::instance()->getVehicle()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (m_ui->CheckBoxVehicle->isChecked()) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxVehicle, index, SymbologyXML::SymbolTypes::instance()->getVehicle()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE, SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxVehicleStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (state) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxVehicle, - m_ui->ComboBoxVehicle->currentIndex(), - SymbologyXML::SymbolTypes::instance()->getVehicle()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); - DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (state) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged(m_ui->ComboBoxVehicle, m_ui->ComboBoxVehicle->currentIndex(), + SymbologyXML::SymbolTypes::instance()->getVehicle()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_VEHICLE, SymbologyXML::SymbolTypes::SECTORMAIN, + rectpos); + DEBUG_LOG(m_logger) << "END" << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxIntrinsicMobCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + help_on_ComboBoxIndexChanged(m_ui->ComboBoxIntrinsicMob, index, + SymbologyXML::SymbolTypes::instance()->getIntrinsicMob()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY, + SymbologyXML::SymbolTypes::SECTOR2); + m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(index); - help_on_ComboBoxIndexChanged(m_ui->ComboBoxIntrinsicMob, - index, SymbologyXML::SymbolTypes::instance()->getIntrinsicMob()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY, - SymbologyXML::SymbolTypes::SECTOR2); - m_ui->ComboBoxIntrinsicMob_2->setCurrentIndex(index); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxIntrinsicMob2CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + help_on_ComboBoxIndexChanged(m_ui->ComboBoxIntrinsicMob_2, index, + SymbologyXML::SymbolTypes::instance()->getIntrinsicMob()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY, + SymbologyXML::SymbolTypes::SECTOR2); + m_ui->ComboBoxIntrinsicMob->setCurrentIndex(index); - help_on_ComboBoxIndexChanged(m_ui->ComboBoxIntrinsicMob_2, - index, SymbologyXML::SymbolTypes::instance()->getIntrinsicMob()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_INTRINSIC_MOBILITY, - SymbologyXML::SymbolTypes::SECTOR2); - m_ui->ComboBoxIntrinsicMob->setCurrentIndex(index); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxArmingCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (m_ui->CheckBoxArming->isChecked()) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxArming, - index, SymbologyXML::SymbolTypes::instance()->getArming()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_ARMING, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (m_ui->CheckBoxArming->isChecked()) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxArming, index, SymbologyXML::SymbolTypes::instance()->getArming()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_ARMING, SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxArmingStateChanged(int state) { - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (state) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxArming, - m_ui->ComboBoxArming->currentIndex(), - SymbologyXML::SymbolTypes::instance()->getArming()->getContainerAsInt(), - SymbologyXML::SymbolTypes::ICON_TYPE_ARMING, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (state) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged(m_ui->ComboBoxArming, m_ui->ComboBoxArming->currentIndex(), + SymbologyXML::SymbolTypes::instance()->getArming()->getContainerAsInt(), + SymbologyXML::SymbolTypes::ICON_TYPE_ARMING, SymbologyXML::SymbolTypes::SECTORMAIN, + rectpos); } - void SymbolEditor::onListViewMiscItemSelectionChanged() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress) - { + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_sector_position pos = SymbologyXML::SymbolTypes::SECTORMAIN; + + for (int row = 0; row < m_ui->ListViewMisc->count(); ++row) + { + QListWidgetItem* item = m_ui->ListViewMisc->item(row); + SymbologyXML::SymbolTypes::t_misc misc = (SymbologyXML::SymbolTypes::t_misc)item->data(Qt::UserRole).toInt(); + if (m_ui->ListViewMisc->selectedItems().contains(item)) + { + + if (!m_internal->m_symbol.containsPrimitive(misc)) + { + + SymbologyXML::Primitive* prim = SymbologyXML::SymbolExporter::newPrimitiveICON( + SymbologyXML::SymbolTypes::ICON_TYPE_MISC, pos, SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT, + (int)misc); + m_internal->m_symbol.addPrimitive(prim); + } + } + else + { + + m_internal->m_symbol.removePrimitive(misc); + } + } + + setChanged(true); + updateGraphicViews(true, true); DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - - SymbologyXML::SymbolTypes::t_sector_position pos = SymbologyXML::SymbolTypes::SECTORMAIN; - - for (int row = 0; row < m_ui->ListViewMisc->count(); ++row) - { - QListWidgetItem *item = m_ui->ListViewMisc->item(row); - SymbologyXML::SymbolTypes::t_misc misc = (SymbologyXML::SymbolTypes::t_misc)item->data(Qt::UserRole).toInt(); - if (m_ui->ListViewMisc->selectedItems().contains(item)) - { - - if (!m_internal->m_symbol.containsPrimitive(misc)) - { - - SymbologyXML::Primitive *prim = SymbologyXML::SymbolExporter::newPrimitiveICON(SymbologyXML::SymbolTypes::ICON_TYPE_MISC, - pos, SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT, - (int)misc); - m_internal->m_symbol.addPrimitive(prim); - } - } - else - { - - m_internal->m_symbol.removePrimitive(misc); - } - } - - setChanged(true); - updateGraphicViews(true, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxSector1CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxSector1, - index, - SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR1), - SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, - SymbologyXML::SymbolTypes::SECTOR1); + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxSector1, index, + SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR1), + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, SymbologyXML::SymbolTypes::SECTOR1); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxSectorMainCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (m_ui->CheckBoxMain && m_ui->CheckBoxMain->isChecked()) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxSectorMain, - index, - SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, - SymbologyXML::SymbolTypes::SELECT_WIDGET_CB), - SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (m_ui->CheckBoxMain && m_ui->CheckBoxMain->isChecked()) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxSectorMain, index, + SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt( + SymbologyXML::SymbolTypes::SECTORMAIN, SymbologyXML::SymbolTypes::SELECT_WIDGET_CB), + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxMainStateChanged(int state) { - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; - if (state) - rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxSectorMain, - m_ui->ComboBoxSectorMain->currentIndex(), - SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTORMAIN, - SymbologyXML::SymbolTypes::SELECT_WIDGET_CB), + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT; + if (state) + rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_LARGE; + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxSectorMain, m_ui->ComboBoxSectorMain->currentIndex(), + SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt( + SymbologyXML::SymbolTypes::SECTORMAIN, SymbologyXML::SymbolTypes::SELECT_WIDGET_CB), - SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, - SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, SymbologyXML::SymbolTypes::SECTORMAIN, rectpos); } - void SymbolEditor::onListViewSectorMainItemSelectionChanged() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + SymbologyXML::SymbolTypes::t_sector_position pos = SymbologyXML::SymbolTypes::SECTORMAIN; + + for (int row = 0; row < m_ui->ListViewSectorMain->count(); ++row) + { + QListWidgetItem* item = m_ui->ListViewSectorMain->item(row); + SymbologyXML::SymbolTypes::t_sectoricon secicon = + (SymbologyXML::SymbolTypes::t_sectoricon)item->data(Qt::UserRole).toInt(); + if (m_ui->ListViewSectorMain->selectedItems().contains(item)) + { + + if (!m_internal->m_symbol.containsPrimitive(secicon)) + { + + SymbologyXML::Primitive* prim = SymbologyXML::SymbolExporter::newPrimitiveICON( + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, pos, + SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT, (int)secicon); + m_internal->m_symbol.addPrimitive(prim); + } + } + else + { + + m_internal->m_symbol.removePrimitive(secicon); + } + } + setChanged(true); + updateGraphicViews(true, true); - if (m_internal->m_updateInProgress) - { DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - - SymbologyXML::SymbolTypes::t_sector_position pos = SymbologyXML::SymbolTypes::SECTORMAIN; - - for (int row = 0; row < m_ui->ListViewSectorMain->count(); ++row) - { - QListWidgetItem *item = m_ui->ListViewSectorMain->item(row); - SymbologyXML::SymbolTypes::t_sectoricon secicon = (SymbologyXML::SymbolTypes::t_sectoricon)item->data(Qt::UserRole).toInt(); - if (m_ui->ListViewSectorMain->selectedItems().contains(item)) - { - - if (!m_internal->m_symbol.containsPrimitive(secicon)) - { - - SymbologyXML::Primitive *prim = SymbologyXML::SymbolExporter::newPrimitiveICON(SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, - pos, SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT, - (int)secicon); - m_internal->m_symbol.addPrimitive(prim); - } - } - else - { - - m_internal->m_symbol.removePrimitive(secicon); - } - } - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxSector2CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - help_on_ComboBoxIndexChanged(m_ui->ComboBoxSector2, - index, - SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR2), - SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, - SymbologyXML::SymbolTypes::SECTOR2); + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + help_on_ComboBoxIndexChanged( + m_ui->ComboBoxSector2, index, + SymbologyXML::SymbolTypes::instance()->getSectorIcon()->getContainerAsInt(SymbologyXML::SymbolTypes::SECTOR2), + SymbologyXML::SymbolTypes::ICON_TYPE_SECTOR_ICON, SymbologyXML::SymbolTypes::SECTOR2); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::help_on_ComboBoxIndexChanged(QComboBox *comboBox, - int index, const QMap &contv, +void SymbolEditor::help_on_ComboBoxIndexChanged(QComboBox* comboBox, int index, const QMap& contv, SymbologyXML::SymbolTypes::t_icon_type iconType, SymbologyXML::SymbolTypes::t_sector_position pos, SymbologyXML::SymbolTypes::t_sector_rectpos rectpos) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + + if (m_internal->m_updateInProgress || index < 0) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + int keyUndefined = 0; + QMapIterator iter(contv); + while (iter.hasNext()) + { + iter.next(); + if (iter.key() != keyUndefined) + m_internal->m_symbol.clearPrimitives(iconType, pos, iter.key()); + } + int id = comboBox->itemData(index).toInt(); + if (id != 0) + { + SymbologyXML::Primitive* prim = SymbologyXML::SymbolExporter::newPrimitiveICON(iconType, pos, rectpos, id); + m_internal->m_symbol.addPrimitive(prim); + } + setChanged(true); + updateGraphicViews(true, true); - if (m_internal->m_updateInProgress || index < 0) - { DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - int keyUndefined = 0; - QMapIterator iter(contv); - while (iter.hasNext()) - { - iter.next(); - if (iter.key() != keyUndefined) - m_internal->m_symbol.clearPrimitives(iconType, pos, iter.key()); - } - int id = comboBox->itemData(index).toInt(); - if (id != 0) - { - SymbologyXML::Primitive *prim = SymbologyXML::SymbolExporter::newPrimitiveICON(iconType, pos, rectpos, id); - m_internal->m_symbol.addPrimitive(prim); - } - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxAlign1CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), + (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign1->itemData(index).toInt(), + m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), + m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); + updateTextProperties(); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign1->itemData(index).toInt(), - m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), - m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); - updateTextProperties(); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxAlign2CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), + m_internal->m_symbol.getText(2), + (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign2->itemData(index).toInt(), + m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); + updateTextProperties(); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), - m_internal->m_symbol.getText(2), (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign2->itemData(index).toInt(), - m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); - updateTextProperties(); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxAlign3CurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress || (index < 0)) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress || (index < 0)) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), + m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), + m_internal->m_symbol.getText(3), + (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign3->itemData(index).toInt()); + updateTextProperties(); + setChanged(true); + updateGraphicViews(true, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), - m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), - m_internal->m_symbol.getText(3), (SymbologyXML::Symbol::t_alignment)m_ui->ComboBoxAlign3->itemData(index).toInt()); - updateTextProperties(); - setChanged(true); - updateGraphicViews(true, true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::onComboBoxColorCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (index != -1) - { - m_internal->m_previewColor = m_internal->m_symbolColorsPreview.at(index).second; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (index != -1) + { + m_internal->m_previewColor = m_internal->m_symbolColorsPreview.at(index).second; - updateGraphicViews(true, true); - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + updateGraphicViews(true, true); + } + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onComboBoxLineStyleCurrentIndexChanged(int index) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - switch (index) - { - case 3: - m_internal->m_pen.setStyle(Qt::DashDotLine); - break; - case 2: - m_internal->m_pen.setStyle(Qt::DotLine); - break; - case 1: - m_internal->m_pen.setStyle(Qt::DashLine); - break; - case 0: - default: - m_internal->m_pen.setStyle(Qt::SolidLine); - break; - } - m_internal->m_graphicsScene.setPen(m_internal->m_pen); - - if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) - { - if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + switch (index) { - - SymbologyXML::Primitive *prim = m_internal->m_mapItemPrimitives[m_internal->m_currentGraphicsItem]; - if ((prim->type() != SymbologyXML::Primitive::ICON) && (prim->type() != SymbologyXML::Primitive::TEXT)) - { - prim->setLineStyle((SymbologyXML::Primitive::t_linestyle)index); - QGraphicsItem *pi = m_internal->m_currentGraphicsItem; - SymbologyXML::SymbolExporter::redraw(pi); - updateGraphicViews(true, true); - - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) - { - it.next(); - QGraphicsItem *pi2 = it.key(); - if (pi2->data(SymbologyXML::primitiveKey).value() == prim) - { - - pi2->setSelected(true); - } - } - setChanged(true); - } + case 3: + m_internal->m_pen.setStyle(Qt::DashDotLine); + break; + case 2: + m_internal->m_pen.setStyle(Qt::DotLine); + break; + case 1: + m_internal->m_pen.setStyle(Qt::DashLine); + break; + case 0: + default: + m_internal->m_pen.setStyle(Qt::SolidLine); + break; } - } + m_internal->m_graphicsScene.setPen(m_internal->m_pen); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; -} + if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) + { + if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + { + SymbologyXML::Primitive* prim = m_internal->m_mapItemPrimitives[m_internal->m_currentGraphicsItem]; + if ((prim->type() != SymbologyXML::Primitive::ICON) && (prim->type() != SymbologyXML::Primitive::TEXT)) + { + prim->setLineStyle((SymbologyXML::Primitive::t_linestyle)index); + QGraphicsItem* pi = m_internal->m_currentGraphicsItem; + SymbologyXML::SymbolExporter::redraw(pi); + updateGraphicViews(true, true); + + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) + { + it.next(); + QGraphicsItem* pi2 = it.key(); + if (pi2->data(SymbologyXML::primitiveKey).value() == prim) + { + + pi2->setSelected(true); + } + } + setChanged(true); + } + } + } -void SymbolEditor::onLineEdit1TextChanged(const QString &text) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress) - { DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - m_internal->m_symbol.setText( - text, m_internal->m_symbol.getTextAlign(1), - m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), - m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); - updateGraphicViews(true, true); - setChanged(true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::onLineEdit2TextChanged(const QString &text) +void SymbolEditor::onLineEdit1TextChanged(const QString& text) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(text, m_internal->m_symbol.getTextAlign(1), m_internal->m_symbol.getText(2), + m_internal->m_symbol.getTextAlign(2), m_internal->m_symbol.getText(3), + m_internal->m_symbol.getTextAlign(3)); + updateGraphicViews(true, true); + setChanged(true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - m_internal->m_symbol.setText( - m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), - text, m_internal->m_symbol.getTextAlign(2), - m_internal->m_symbol.getText(3), m_internal->m_symbol.getTextAlign(3)); - updateGraphicViews(true, true); - setChanged(true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::onLineEdit3TextChanged(const QString &text) +void SymbolEditor::onLineEdit2TextChanged(const QString& text) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress) - { + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), text, + m_internal->m_symbol.getTextAlign(2), m_internal->m_symbol.getText(3), + m_internal->m_symbol.getTextAlign(3)); + updateGraphicViews(true, true); + setChanged(true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), - m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), - text, m_internal->m_symbol.getTextAlign(3)); - updateGraphicViews(true, true); - setChanged(true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } +void SymbolEditor::onLineEdit3TextChanged(const QString& text) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbol.setText(m_internal->m_symbol.getText(1), m_internal->m_symbol.getTextAlign(1), + m_internal->m_symbol.getText(2), m_internal->m_symbol.getTextAlign(2), text, + m_internal->m_symbol.getTextAlign(3)); + updateGraphicViews(true, true); + setChanged(true); + + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; +} void SymbolEditor::onListViewTruppengattungItemSelectionChanged() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_internal->m_updateInProgress) - { + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + QVectorIterator it = + SymbologyXML::SymbolTypes::instance()->getBranch()->getIterator(); + while (it.hasNext()) + { + SymbologyXML::SymbolTypes::t_branch val = it.next(); + m_internal->m_symbol.removeBranch(val); + } + + const QList items = m_ui->ListViewTruppengattung->selectedItems(); + for (const QListWidgetItem* item : items) + { + SymbologyXML::SymbolTypes::t_branch curBranch = + (SymbologyXML::SymbolTypes::t_branch)item->data(Qt::UserRole).toInt(); + m_internal->m_symbol.addBranch(curBranch); + } + setChanged(true); + updateGraphicViews(true, true); DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - - QVectorIterator it = SymbologyXML::SymbolTypes::instance()->getBranch()->getIterator(); - while (it.hasNext()) - { - SymbologyXML::SymbolTypes::t_branch val = it.next(); - m_internal->m_symbol.removeBranch(val); - } - - const QList items = m_ui->ListViewTruppengattung->selectedItems(); - for (const QListWidgetItem *item : items) - { - SymbologyXML::SymbolTypes::t_branch curBranch = (SymbologyXML::SymbolTypes::t_branch)item->data(Qt::UserRole).toInt(); - m_internal->m_symbol.addBranch(curBranch); - } - setChanged(true); - updateGraphicViews(true, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxBackgroundStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_displayPreviewBackground = (bool)state; - updateGraphicViews(false, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + m_internal->m_displayPreviewBackground = (bool)state; + updateGraphicViews(false, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxPlannedStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if ((bool)state) - m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_ANTICIPATED; - else - m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; - updateGraphicViews(false, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if ((bool)state) + m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_ANTICIPATED; + else + m_internal->m_additionalDataPreview.m_state = SymbologyXML::SymbolTypes::STATE_PRESENT; + updateGraphicViews(false, true); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxCopyValuesStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_copyFromSelectedPrimitive = (bool)state; - copyFromSelectedPrimitive(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + m_internal->m_copyFromSelectedPrimitive = (bool)state; + copyFromSelectedPrimitive(); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxFillStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_fillPrimitive = state; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + m_internal->m_fillPrimitive = state; - if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) - { - if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) { - - QGraphicsItem *pi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = pi->data(SymbologyXML::primitiveKey).value(); - if ((prim->type() != SymbologyXML::Primitive::TEXT)) - { - prim->setFill(m_internal->m_fillPrimitive); - SymbologyXML::SymbolExporter::redraw(pi); - updateGraphicViews(true, true); - - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) + if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) { - it.next(); - QGraphicsItem *pi2 = it.key(); - if (pi2->data(SymbologyXML::primitiveKey).value() == prim) - { - - pi2->setSelected(true); - } + + QGraphicsItem* pi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = pi->data(SymbologyXML::primitiveKey).value(); + if ((prim->type() != SymbologyXML::Primitive::TEXT)) + { + prim->setFill(m_internal->m_fillPrimitive); + SymbologyXML::SymbolExporter::redraw(pi); + updateGraphicViews(true, true); + + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) + { + it.next(); + QGraphicsItem* pi2 = it.key(); + if (pi2->data(SymbologyXML::primitiveKey).value() == prim) + { + + pi2->setSelected(true); + } + } + setChanged(true); + } } - setChanged(true); - } } - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onCheckBoxDrawAreaStateChanged(int state) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_showDrawArea = (bool)state; - m_internal->m_graphicsScene.setShowDrawingArea(m_internal->m_showDrawArea); - m_internal->m_graphicsScene.invalidate(m_internal->m_graphicsScene.sceneRect(), QGraphicsScene::ForegroundLayer); + m_internal->m_showDrawArea = (bool)state; + m_internal->m_graphicsScene.setShowDrawingArea(m_internal->m_showDrawArea); + m_internal->m_graphicsScene.invalidate(m_internal->m_graphicsScene.sceneRect(), QGraphicsScene::ForegroundLayer); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onSpinBoxRasterValueChanged(double d) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_gridWidth = d; - m_internal->m_graphicsScene.setGridWidth(d); - m_internal->m_graphicsScene.invalidate(m_internal->m_graphicsScene.sceneRect(), QGraphicsScene::BackgroundLayer); + m_internal->m_gridWidth = d; + m_internal->m_graphicsScene.setGridWidth(d); + m_internal->m_graphicsScene.invalidate(m_internal->m_graphicsScene.sceneRect(), QGraphicsScene::BackgroundLayer); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onSpinBoxScaleValueChanged(double d) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_symbol.setScale(d); - setChanged(true); + m_internal->m_symbol.setScale(d); + setChanged(true); - m_internal->m_previewZoom = d; - updateGraphicViews(false, true); + m_internal->m_previewZoom = d; + updateGraphicViews(false, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onSpinBoxLineWidthValueChanged(double d) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_pen.setWidthF(d); - m_internal->m_graphicsScene.setPen(m_internal->m_pen); + m_internal->m_pen.setWidthF(d); + m_internal->m_graphicsScene.setPen(m_internal->m_pen); - if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) - { - if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + if (m_internal->m_copyFromSelectedPrimitive && (m_internal->m_currentGraphicsItem != nullptr)) { - - QGraphicsItem *pi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = pi->data(SymbologyXML::primitiveKey).value(); - if ((prim->type() != SymbologyXML::Primitive::TEXT)) - { - prim->setLineWidth(d); - SymbologyXML::SymbolExporter::redraw(pi); - updateGraphicViews(true, true); - - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) + if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) { - it.next(); - QGraphicsItem *pi2 = it.key(); - if (pi2->data(SymbologyXML::primitiveKey).value() == prim) - { - - pi2->setSelected(true); - } + + QGraphicsItem* pi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = pi->data(SymbologyXML::primitiveKey).value(); + if ((prim->type() != SymbologyXML::Primitive::TEXT)) + { + prim->setLineWidth(d); + SymbologyXML::SymbolExporter::redraw(pi); + updateGraphicViews(true, true); + + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) + { + it.next(); + QGraphicsItem* pi2 = it.key(); + if (pi2->data(SymbologyXML::primitiveKey).value() == prim) + { + + pi2->setSelected(true); + } + } + setChanged(true); + } } - setChanged(true); - } } - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::onSliderTransparencyValueChanged(int value) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_transparency = 1.0 - (double)value / 100.0; - m_ui->LabelTransparency->setText(QLocale().toString((double)value / 100.0, 'f', 2)); - updateGraphicViews(false, true); + m_internal->m_transparency = 1.0 - (double)value / 100.0; + m_ui->LabelTransparency->setText(QLocale().toString((double)value / 100.0, 'f', 2)); + updateGraphicViews(false, true); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::setChanged(bool changed) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (changed) - slotChangesMade(); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + if (changed) + slotChangesMade(); + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::selectionChanged() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - bool enableEdit = false; - bool selPrimIsICON = false; - bool selPrimIsTEXT = false; - bool isFilled = m_internal->m_fillPrimitive; - QList items = m_internal->m_graphicsScene.selectedItems(); - if (!items.isEmpty()) - { - QGraphicsItem *item = dynamic_cast(items.at(0)); - QMap::const_iterator it = m_internal->m_mapItemPrimitives.constFind(item); - if (it != m_internal->m_mapItemPrimitives.constEnd()) + bool enableEdit = false; + bool selPrimIsICON = false; + bool selPrimIsTEXT = false; + bool isFilled = m_internal->m_fillPrimitive; + QList items = m_internal->m_graphicsScene.selectedItems(); + if (!items.isEmpty()) { - - m_internal->m_currentGraphicsItem = item; - m_internal->m_currentGraphicsItemPos = m_internal->m_currentGraphicsItem->scenePos(); - m_internal->m_currentGraphicsItem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); - enableEdit = true; - SymbologyXML::Primitive *prim = it.value(); - isFilled = prim->fill(); - if (prim->type() == SymbologyXML::Primitive::ICON) - selPrimIsICON = true; - if (prim->type() == SymbologyXML::Primitive::TEXT) - selPrimIsTEXT = true; + QGraphicsItem* item = dynamic_cast(items.at(0)); + QMap::const_iterator it = + m_internal->m_mapItemPrimitives.constFind(item); + if (it != m_internal->m_mapItemPrimitives.constEnd()) + { + + m_internal->m_currentGraphicsItem = item; + m_internal->m_currentGraphicsItemPos = m_internal->m_currentGraphicsItem->scenePos(); + m_internal->m_currentGraphicsItem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); + enableEdit = true; + SymbologyXML::Primitive* prim = it.value(); + isFilled = prim->fill(); + if (prim->type() == SymbologyXML::Primitive::ICON) + selPrimIsICON = true; + if (prim->type() == SymbologyXML::Primitive::TEXT) + selPrimIsTEXT = true; + } } - } - else - { - - m_internal->m_currentGraphicsItem = nullptr; - } + else + { - m_ui->ToolButtonRotate->setEnabled(enableEdit && !selPrimIsTEXT); - m_ui->ToolButtonScale->setEnabled(enableEdit); - m_ui->ToolButtonCopy->setEnabled(enableEdit && - !selPrimIsICON && !selPrimIsTEXT); - m_ui->ToolButtonPaste->setEnabled(enableEdit && (m_internal->m_currentGraphicsItemCopy != nullptr) && - !selPrimIsICON && !selPrimIsTEXT); - m_ui->ToolButtonDelete->setEnabled(enableEdit); - m_ui->CheckBoxFill->blockSignals(true); - m_ui->CheckBoxFill->setChecked(isFilled); - m_internal->m_fillPrimitive = isFilled; - m_ui->CheckBoxFill->blockSignals(false); - copyFromSelectedPrimitive(); + m_internal->m_currentGraphicsItem = nullptr; + } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + m_ui->ToolButtonRotate->setEnabled(enableEdit && !selPrimIsTEXT); + m_ui->ToolButtonScale->setEnabled(enableEdit); + m_ui->ToolButtonCopy->setEnabled(enableEdit && !selPrimIsICON && !selPrimIsTEXT); + m_ui->ToolButtonPaste->setEnabled(enableEdit && (m_internal->m_currentGraphicsItemCopy != nullptr) && + !selPrimIsICON && !selPrimIsTEXT); + m_ui->ToolButtonDelete->setEnabled(enableEdit); + m_ui->CheckBoxFill->blockSignals(true); + m_ui->CheckBoxFill->setChecked(isFilled); + m_internal->m_fillPrimitive = isFilled; + m_ui->CheckBoxFill->blockSignals(false); + copyFromSelectedPrimitive(); + + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::copyFromSelectedPrimitive() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!m_internal->m_copyFromSelectedPrimitive || (m_internal->m_currentGraphicsItem == nullptr)) - { - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) - { - - SymbologyXML::Primitive *prim = m_internal->m_mapItemPrimitives[m_internal->m_currentGraphicsItem]; - if (prim->type() != SymbologyXML::Primitive::TEXT) + if (!m_internal->m_copyFromSelectedPrimitive || (m_internal->m_currentGraphicsItem == nullptr)) { - - - m_internal->m_copyFromSelectedPrimitive = false; - double lineWidth = prim->getLineWidth(); - m_ui->SpinBoxLineWidth->setValue(lineWidth); - onSpinBoxLineWidthValueChanged(lineWidth); - - SymbologyXML::Primitive::t_linestyle ls = prim->getLineStyle(); - m_ui->ComboBoxLineStyle->setCurrentIndex((int)ls); - onComboBoxLineStyleCurrentIndexChanged((int)ls); - - QColor fillColor = prim->getColor(); - setPushButtonFillColorBackground(fillColor); - - - m_internal->m_copyFromSelectedPrimitive = true; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; } - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + if (m_internal->m_mapItemPrimitives.contains(m_internal->m_currentGraphicsItem)) + { + + SymbologyXML::Primitive* prim = m_internal->m_mapItemPrimitives[m_internal->m_currentGraphicsItem]; + if (prim->type() != SymbologyXML::Primitive::TEXT) + { + + m_internal->m_copyFromSelectedPrimitive = false; + + double lineWidth = prim->getLineWidth(); + m_ui->SpinBoxLineWidth->setValue(lineWidth); + onSpinBoxLineWidthValueChanged(lineWidth); + + SymbologyXML::Primitive::t_linestyle ls = prim->getLineStyle(); + m_ui->ComboBoxLineStyle->setCurrentIndex((int)ls); + onComboBoxLineStyleCurrentIndexChanged((int)ls); + + QColor fillColor = prim->getColor(); + setPushButtonFillColorBackground(fillColor); + + m_internal->m_copyFromSelectedPrimitive = true; + } + } + + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::pushUndo() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + + if (m_internal->m_updateInProgress) + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } + + m_internal->m_symbolUndoStack.append(SymbologyXML::Symbol(m_internal->m_symbol)); + + m_ui->ToolButtonUndo->setEnabled(true); - if (m_internal->m_updateInProgress) - { DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - m_internal->m_symbolUndoStack.append(SymbologyXML::Symbol(m_internal->m_symbol)); - - m_ui->ToolButtonUndo->setEnabled(true); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::popUndo() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); + SymbolEditScene::DrawMode dm = m_internal->m_graphicsScene.getDrawMode(); - m_internal->m_mapItemPrimitives.clear(); - m_internal->m_symbol.reset(); + m_internal->m_mapItemPrimitives.clear(); + m_internal->m_symbol.reset(); - if (!m_internal->m_symbolUndoStack.isEmpty()) - { - m_internal->m_symbol = m_internal->m_symbolUndoStack.last(); - m_internal->m_symbolUndoStack.removeLast(); - updateGUI(); - } + if (!m_internal->m_symbolUndoStack.isEmpty()) + { + m_internal->m_symbol = m_internal->m_symbolUndoStack.last(); + m_internal->m_symbolUndoStack.removeLast(); + updateGUI(); + } - + if (m_internal->m_symbolUndoStack.isEmpty()) + m_ui->ToolButtonUndo->setEnabled(false); - if (m_internal->m_symbolUndoStack.isEmpty()) - m_ui->ToolButtonUndo->setEnabled(false); + m_internal->m_graphicsScene.setDrawMode(dm); - - m_internal->m_graphicsScene.setDrawMode(dm); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::clearUndo() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_internal->m_symbolUndoStack.clear(); + m_internal->m_symbolUndoStack.clear(); - m_ui->ToolButtonUndo->setEnabled(false); + m_ui->ToolButtonUndo->setEnabled(false); - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::keyPressEvent(QKeyEvent *keyEvent) +void SymbolEditor::keyPressEvent(QKeyEvent* keyEvent) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - + u_int modCtrl = Qt::ControlModifier; + Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); + int keyCode = keyEvent->key(); + if ((keyCode == Qt::Key_Space) && (modifiers == modCtrl)) + m_ui->ToolButtonSelect->animateClick(); + else if ((keyCode == Qt::Key_C) && (modifiers == modCtrl)) + m_ui->ToolButtonCopy->animateClick(); + else if (((keyCode == Qt::Key_D) && (modifiers == modCtrl)) || (keyCode == Qt::Key_Delete)) + m_ui->ToolButtonDelete->animateClick(); + else if ((keyCode == Qt::Key_V) && (modifiers == modCtrl)) + m_ui->ToolButtonPaste->animateClick(); + else if ((keyCode == Qt::Key_Z) && (modifiers == modCtrl)) + m_ui->ToolButtonUndo->animateClick(); + else if ((keyCode == Qt::Key_R) && (modifiers == modCtrl)) + m_ui->ToolButtonRotate->animateClick(); + else if ((keyCode == Qt::Key_S) && (modifiers == modCtrl)) + m_ui->ToolButtonScale->animateClick(); + else if ((keyCode == Qt::Key_T) && (modifiers == modCtrl)) + m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->animateClick(); + else if ((keyCode == Qt::Key_W) && (modifiers == modCtrl)) + m_ui->ToolButtonClear->animateClick(); + else if ((keyCode == Qt::Key_1) && (modifiers == modCtrl)) + m_ui->ToolButtonEllipse->animateClick(); + else if ((keyCode == Qt::Key_2) && (modifiers == modCtrl)) + m_ui->ToolButtonLine->animateClick(); + else if ((keyCode == Qt::Key_3) && (modifiers == modCtrl)) + m_ui->ToolButtonPolyline->animateClick(); + else if ((keyCode == Qt::Key_4) && (modifiers == modCtrl)) + m_ui->ToolButtonPolygon->animateClick(); + else if ((keyCode == Qt::Key_5) && (modifiers == modCtrl)) + m_ui->ToolButtonRect->animateClick(); + else if ((keyCode == Qt::Key_6) && (modifiers == modCtrl)) + m_ui->ToolButtonText->animateClick(); + else + LtsWidgets::LtsDialog::keyPressEvent(keyEvent); - - u_int modCtrl = Qt::ControlModifier; - - Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); - int keyCode = keyEvent->key(); - if ((keyCode == Qt::Key_Space) && (modifiers == modCtrl)) - m_ui->ToolButtonSelect->animateClick(); - else if ((keyCode == Qt::Key_C) && (modifiers == modCtrl)) - m_ui->ToolButtonCopy->animateClick(); - else if (((keyCode == Qt::Key_D) && (modifiers == modCtrl)) || - (keyCode == Qt::Key_Delete)) - m_ui->ToolButtonDelete->animateClick(); - else if ((keyCode == Qt::Key_V) && (modifiers == modCtrl)) - m_ui->ToolButtonPaste->animateClick(); - else if ((keyCode == Qt::Key_Z) && (modifiers == modCtrl)) - m_ui->ToolButtonUndo->animateClick(); - else if ((keyCode == Qt::Key_R) && (modifiers == modCtrl)) - m_ui->ToolButtonRotate->animateClick(); - else if ((keyCode == Qt::Key_S) && (modifiers == modCtrl)) - m_ui->ToolButtonScale->animateClick(); - else if ((keyCode == Qt::Key_T) && (modifiers == modCtrl)) - m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->animateClick(); - else if ((keyCode == Qt::Key_W) && (modifiers == modCtrl)) - m_ui->ToolButtonClear->animateClick(); - else if ((keyCode == Qt::Key_1) && (modifiers == modCtrl)) - m_ui->ToolButtonEllipse->animateClick(); - else if ((keyCode == Qt::Key_2) && (modifiers == modCtrl)) - m_ui->ToolButtonLine->animateClick(); - else if ((keyCode == Qt::Key_3) && (modifiers == modCtrl)) - m_ui->ToolButtonPolyline->animateClick(); - else if ((keyCode == Qt::Key_4) && (modifiers == modCtrl)) - m_ui->ToolButtonPolygon->animateClick(); - else if ((keyCode == Qt::Key_5) && (modifiers == modCtrl)) - m_ui->ToolButtonRect->animateClick(); - else if ((keyCode == Qt::Key_6) && (modifiers == modCtrl)) - m_ui->ToolButtonText->animateClick(); - else - LtsWidgets::LtsDialog::keyPressEvent(keyEvent); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - void SymbolEditor::transformSelection(int key, Qt::KeyboardModifiers modifiers) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - - u_int modAlt = Qt::AltModifier; - u_int modAltShift = Qt::AltModifier | Qt::ShiftModifier; - u_int modCtrl = Qt::ControlModifier; - u_int modCtrlShift = Qt::ControlModifier | Qt::ShiftModifier; - u_int modShift = Qt::ShiftModifier; + u_int modAlt = Qt::AltModifier; + u_int modAltShift = Qt::AltModifier | Qt::ShiftModifier; + u_int modCtrl = Qt::ControlModifier; + u_int modCtrlShift = Qt::ControlModifier | Qt::ShiftModifier; + u_int modShift = Qt::ShiftModifier; - + QPolygonF pol = m_ui->GraphicView->mapToScene(QRect(QPoint(0, 0), QSize(2, 2))); + QRectF rect = pol.boundingRect(); + double stepWidth = rect.width(); + double factor = ((modifiers & modShift) == modShift) ? 10.0 : 1.0; + double dx = 0.0; + double dy = 0.0; + if (key == Qt::Key_Left) + { + dx = -1.0; + dy = 0.0; + } + else if (key == Qt::Key_Up) + { + dx = 0.0; + dy = 1.0; + } + else if (key == Qt::Key_Right) + { + dx = 1.0; + dy = 0.0; + } + else if (key == Qt::Key_Down) + { + dx = 0.0; + dy = -1.0; + } + else + { + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + return; + } - QPolygonF pol = m_ui->GraphicView->mapToScene(QRect(QPoint(0, 0), QSize(2, 2))); - QRectF rect = pol.boundingRect(); - double stepWidth = rect.width(); - double factor = ((modifiers & modShift) == modShift) ? 10.0 : 1.0; + if ((modifiers == modAlt) || (modifiers == modAltShift)) + { + if (m_internal->m_currentGraphicsItem != nullptr) + { + QGraphicsItem* sepi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = sepi->data(SymbologyXML::primitiveKey).value(); + double r = prim->getRotation(); + prim->setRotation(r + (dx * factor)); + updateGraphicViews(true, true); + restoreSelection(prim); + setChanged(true); + } + } + else if ((modifiers == modCtrl) || (modifiers == modCtrlShift)) + { + if (m_internal->m_currentGraphicsItem != nullptr) + { + QGraphicsItem* sepi = m_internal->m_currentGraphicsItem; + SymbologyXML::Primitive* prim = sepi->data(SymbologyXML::primitiveKey).value(); + if (factor != 1.0) + factor = 2.0; + double scaleX = (dx / 10.0 * factor) + 1.0; + double scaleY = (dy / 10.0 * factor) + 1.0; + prim->scale(scaleX, scaleY); + updateGraphicViews(true, true); + restoreSelection(prim); + setChanged(true); + } + } + else + movePrimitive(QPointF(stepWidth * factor * dx, stepWidth * factor * dy)); - double dx = 0.0; - double dy = 0.0; - if (key == Qt::Key_Left) - { - dx = -1.0; - dy = 0.0; - } - else if (key == Qt::Key_Up) - { - dx = 0.0; - dy = 1.0; - } - else if (key == Qt::Key_Right) - { - dx = 1.0; - dy = 0.0; - } - else if (key == Qt::Key_Down) - { - dx = 0.0; - dy = -1.0; - } - else - { DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; - return; - } - - if ((modifiers == modAlt) || (modifiers == modAltShift)) - { - if (m_internal->m_currentGraphicsItem != nullptr) - { - QGraphicsItem *sepi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = sepi->data(SymbologyXML::primitiveKey).value(); - double r = prim->getRotation(); - prim->setRotation(r + (dx * factor)); - updateGraphicViews(true, true); - restoreSelection(prim); - setChanged(true); - } - } - else if ((modifiers == modCtrl) || (modifiers == modCtrlShift)) - { - if (m_internal->m_currentGraphicsItem != nullptr) - { - QGraphicsItem *sepi = m_internal->m_currentGraphicsItem; - SymbologyXML::Primitive *prim = sepi->data(SymbologyXML::primitiveKey).value(); - if (factor != 1.0) - factor = 2.0; - double scaleX = (dx / 10.0 * factor) + 1.0; - double scaleY = (dy / 10.0 * factor) + 1.0; - prim->scale(scaleX, scaleY); - updateGraphicViews(true, true); - restoreSelection(prim); - setChanged(true); - } - } - else - movePrimitive(QPointF(stepWidth * factor * dx, stepWidth * factor * dy)); - - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } - -void SymbolEditor::restoreSelection(SymbologyXML::Primitive *prim) +void SymbolEditor::restoreSelection(SymbologyXML::Primitive* prim) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - QMapIterator it(m_internal->m_mapItemPrimitives); - while (it.hasNext()) - { - it.next(); - QGraphicsItem *pi = it.key(); - if (pi->data(SymbologyXML::primitiveKey).value() == prim) + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + QMapIterator it(m_internal->m_mapItemPrimitives); + while (it.hasNext()) { - - pi->setSelected(true); + it.next(); + QGraphicsItem* pi = it.key(); + if (pi->data(SymbologyXML::primitiveKey).value() == prim) + { + + pi->setSelected(true); + } } - } - DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << "END " << Q_FUNC_INFO; } void SymbolEditor::retranslate() { - translate(m_ui, tr("Symbol Editor")); + translate(m_ui, tr("Symbol Editor")); } bool SymbolEditor::writeFile(bool saveAsNew) { - bool bRet = false; - if (!m_internal->m_flmGui) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error FileManagementGuiPlugin isn't loaded."; - return false; - } + bool bRet = false; + if (!m_internal->m_flmGui) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error FileManagementGuiPlugin isn't loaded."; + return false; + } - if (saveAsNew) - m_internal->m_symbol.setID(-1); - SymbologyXML::SymbolWriter writer; - const QByteArray byteArray = writer.toString(m_internal->m_symbol); - const QString properties = QString::fromUtf8(m_internal->m_attributes.toJson(QJsonDocument::Compact)); - - int fileId = m_internal->m_flmGui->saveFileContent(this, FileManagement::FileType::OperatorDefinedSymbol, m_session->exerciseId(), byteArray, SYMBOL_FOLDER_ID, properties); - if (fileId > 0) - { - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - m_internal->m_lastFileId = fileId; - FileManagement::FileContent fc = m_internal->m_flmDtc->fileContent(fileId); - m_internal->m_lastFolderId = fc.folderId(); - const QString fileName = QString::fromStdString(fc.name()); - m_internal->m_lastFileName = fileName; - m_internal->m_symbol.setName(fileName); - bRet = true; - } - else - ERROR_LOG(m_logger) << "Could not save file in library "; - - return bRet; -} - -bool SymbolEditor::apply() -{ - return m_internal->m_saveSuccess; -} - - -void SymbolEditor::slotSaveAs() -{ - - m_internal->m_saveSuccess = writeFile(true); - emit saveFinished(); - - - - - - - -} - - -void SymbolEditor::slotSave() -{ - if (m_internal->m_lastFileId > 0) - { + if (saveAsNew) + m_internal->m_symbol.setID(-1); SymbologyXML::SymbolWriter writer; const QByteArray byteArray = writer.toString(m_internal->m_symbol); const QString properties = QString::fromUtf8(m_internal->m_attributes.toJson(QJsonDocument::Compact)); - if (m_internal->m_flmGui->saveContent(m_internal->m_lastFileId, byteArray, properties)) - DEBUG_LOG(m_logger) << "Saved file with id = " << m_internal->m_lastFileId; + int fileId = + m_internal->m_flmGui->saveFileContent(this, FileManagement::FileType::OperatorDefinedSymbol, + m_session->exerciseId(), byteArray, SYMBOL_FOLDER_ID, properties); + if (fileId > 0) + { + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + m_internal->m_lastFileId = fileId; + FileManagement::FileContent fc = m_internal->m_flmDtc->fileContent(fileId); + m_internal->m_lastFolderId = fc.folderId(); + const QString fileName = QString::fromStdString(fc.name()); + m_internal->m_lastFileName = fileName; + m_internal->m_symbol.setName(fileName); + bRet = true; + } else - ERROR_LOG(m_logger) << "Could not save file in library "; - } - emit saveFinished(); + ERROR_LOG(m_logger) << "Could not save file in library "; + + return bRet; } +bool SymbolEditor::apply() +{ + return m_internal->m_saveSuccess; +} + +void SymbolEditor::slotSaveAs() +{ + + m_internal->m_saveSuccess = writeFile(true); + emit saveFinished(); +} + +void SymbolEditor::slotSave() +{ + if (m_internal->m_lastFileId > 0) + { + SymbologyXML::SymbolWriter writer; + const QByteArray byteArray = writer.toString(m_internal->m_symbol); + const QString properties = QString::fromUtf8(m_internal->m_attributes.toJson(QJsonDocument::Compact)); + + if (m_internal->m_flmGui->saveContent(m_internal->m_lastFileId, byteArray, properties)) + DEBUG_LOG(m_logger) << "Saved file with id = " << m_internal->m_lastFileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; + } + emit saveFinished(); +} void SymbolEditor::slotSaveFinished() { - if (m_internal->m_saveSuccess) - { - m_internal->m_symbolDef = m_internal->m_symbol; - m_ui->leSymbolName->setText(m_internal->m_symbol.getName()); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->click(); - } + if (m_internal->m_saveSuccess) + { + m_internal->m_symbolDef = m_internal->m_symbol; + m_ui->leSymbolName->setText(m_internal->m_symbol.getName()); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->click(); + } } - -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.h old mode 100755 new mode 100644 index 60cb937bf..5cd872bb1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolEditor/asb_symbol_editor.h @@ -1,25 +1,33 @@ - #pragma once +#include #include #include - +#include #include #include -#include -#include - #include -#include class QGraphicsScene; class QComboBox; -namespace Ui { class SymbolEditor; } -namespace FileManagement { class ForeignGuiInterface; } -namespace SymbologyXML { class Symbol; class Primitive;} +namespace Ui +{ +class SymbolEditor; +} + +namespace FileManagement +{ +class ForeignGuiInterface; +} + +namespace SymbologyXML +{ +class Symbol; +class Primitive; +} // namespace SymbologyXML namespace AdvancedSymbology { @@ -28,203 +36,190 @@ class SymbolEditorPrivate; class SymbolEditor final : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: + public: + explicit SymbolEditor(LtsSession::LtsSession* session, QWidget* parent = nullptr); - explicit SymbolEditor(LtsSession::LtsSession *session, QWidget *parent = nullptr); + ~SymbolEditor(); - ~SymbolEditor(); + bool init(const std::shared_ptr& flmFtc, + const std::shared_ptr& flmDtc, + const std::shared_ptr& flmGui, + const std::shared_ptr& ppmDtc, bool asApp = false); - bool init(const std::shared_ptr &flmFtc, - const std::shared_ptr &flmDtc, - const std::shared_ptr &flmGui, - const std::shared_ptr &ppmDtc, - bool asApp = false); + void keyPressEvent(QKeyEvent* keyEvent) override final; + void retranslate() override final; + bool apply() override final; - void keyPressEvent(QKeyEvent *keyEvent) override final; - void retranslate() override final; - bool apply() override final; + bool writeFile(bool saveAsNew); - bool writeFile(bool saveAsNew); + enum e_category { + CATEGORY_UNDEFINED = 0, + CATEGORY_HEADQUARTER, + CATEGORY_DIMENSION, + CATEGORY_AFFILIATION, + CATEGORY_BCDAB, + CATEGORY_COMMANDLEVEL, + CATEGORY_MOBILITY, + CATEGORY_BRANCH, + CATEGORY_ICON_TYPE + }; - enum e_category - { - CATEGORY_UNDEFINED = 0, - CATEGORY_HEADQUARTER, - CATEGORY_DIMENSION, - CATEGORY_AFFILIATION, - CATEGORY_BCDAB, - CATEGORY_COMMANDLEVEL, - CATEGORY_MOBILITY, - CATEGORY_BRANCH, - CATEGORY_ICON_TYPE - }; + enum t_editMode { + EDIT_NONE, + EDIT_PICK, + EDIT_MOVE, + EDIT_ROTATE, + EDIT_SCALE, + EDIT_COPY, + EDIT_PASTE, + EDIT_DELETE, + EDIT_EDIT + }; - enum t_editMode - { - EDIT_NONE, - EDIT_PICK, - EDIT_MOVE, - EDIT_ROTATE, - EDIT_SCALE, - EDIT_COPY, - EDIT_PASTE, - EDIT_DELETE, - EDIT_EDIT - }; + public slots: -public slots: + void movePrimitive(QPointF diff); + bool createNewSymbol(const QString& symbolname); + void setChanged(bool changed); + void updateGraphicViews(bool editview = true, bool preview = true); + void reset(); + void slotSaveAs(); + void slotSave(); + void slotSaveFinished(); + void slotImportTemplate(); - void movePrimitive(QPointF diff); - bool createNewSymbol(const QString &symbolname); - void setChanged(bool changed); - void updateGraphicViews(bool editview = true, bool preview = true); - void reset(); - void slotSaveAs(); - void slotSave(); - void slotSaveFinished(); - void slotImportTemplate(); + signals: -signals: + void documentChanged(bool changed); + void symbolSaved(bool saveToLib, bool saveToCurrent, bool saveToAll); + void canceled(); + void helpRequested(); + void invokeHelp(const QString& context); + void saveFinished(); - void documentChanged(bool changed); - void symbolSaved(bool saveToLib, bool saveToCurrent, bool saveToAll); - void canceled(); - void helpRequested(); - void invokeHelp(const QString &context); - void saveFinished(); + private slots: -private slots: + void transformSelection(int key, Qt::KeyboardModifiers modifiers); - void transformSelection(int key, Qt::KeyboardModifiers modifiers); + void onToolButtonSelectClicked(); + void onToolButtonRotateClicked(); + void onToolButtonScaleClicked(); + void onToolButtonDeleteClicked(); + void onToolButtonClearClicked(); + void onToolButtonUndoClicked(); + void onToolButtonCopyClicked(); + void onToolButtonPasteClicked(); + void onToolButtonEllipseClicked(); + void onToolButtonLineClicked(); + void onToolButtonPolylineClicked(); + void onToolButtonPolygonClicked(); + void onToolButtonRectClicked(); + void onToolButtonTextClicked(); - void onToolButtonSelectClicked(); - void onToolButtonRotateClicked(); - void onToolButtonScaleClicked(); - void onToolButtonDeleteClicked(); - void onToolButtonClearClicked(); - void onToolButtonUndoClicked(); - void onToolButtonCopyClicked(); - void onToolButtonPasteClicked(); - void onToolButtonEllipseClicked(); - void onToolButtonLineClicked(); - void onToolButtonPolylineClicked(); - void onToolButtonPolygonClicked(); - void onToolButtonRectClicked(); - void onToolButtonTextClicked(); + void onPushButtonFillColorClicked(); - void onPushButtonFillColorClicked(); + void onComboBoxDimenCurrentIndexChanged(int index); + void onComboBoxAffilCurrentIndexChanged(int index); + void onComboBoxBCDABCurrentIndexChanged(int index); + void onComboBoxHeadquarterCurrentIndexChanged(int index); + void onComboBoxCommandLevelCurrentIndexChanged(int index); + void onComboBoxMobCurrentIndexChanged(int index); + void onComboBoxVehicleCurrentIndexChanged(int index); + void onComboBoxIntrinsicMobCurrentIndexChanged(int index); + void onComboBoxIntrinsicMob2CurrentIndexChanged(int index); + void onComboBoxArmingCurrentIndexChanged(int index); - void onComboBoxDimenCurrentIndexChanged(int index); - void onComboBoxAffilCurrentIndexChanged(int index); - void onComboBoxBCDABCurrentIndexChanged(int index); - void onComboBoxHeadquarterCurrentIndexChanged(int index); - void onComboBoxCommandLevelCurrentIndexChanged(int index); - void onComboBoxMobCurrentIndexChanged(int index); - void onComboBoxVehicleCurrentIndexChanged(int index); - void onComboBoxIntrinsicMobCurrentIndexChanged(int index); - void onComboBoxIntrinsicMob2CurrentIndexChanged(int index); - void onComboBoxArmingCurrentIndexChanged(int index); + void onListViewMiscItemSelectionChanged(); - void onListViewMiscItemSelectionChanged(); + void onCheckBoxVehicleStateChanged(int state); + void onCheckBoxArmingStateChanged(int state); + void onCheckBoxMainStateChanged(int state); - void onCheckBoxVehicleStateChanged(int state); - void onCheckBoxArmingStateChanged(int state); - void onCheckBoxMainStateChanged(int state); + void onComboBoxSector1CurrentIndexChanged(int index); + void onComboBoxSectorMainCurrentIndexChanged(int index); - void onComboBoxSector1CurrentIndexChanged(int index); - void onComboBoxSectorMainCurrentIndexChanged(int index); + void onListViewSectorMainItemSelectionChanged(); - void onListViewSectorMainItemSelectionChanged(); + void onComboBoxSector2CurrentIndexChanged(int index); - void onComboBoxSector2CurrentIndexChanged(int index); + void help_on_ComboBoxIndexChanged( + QComboBox* comboBox, int index, const QMap& contv, + SymbologyXML::SymbolTypes::t_icon_type iconType, SymbologyXML::SymbolTypes::t_sector_position pos, + SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT); - void help_on_ComboBoxIndexChanged(QComboBox *comboBox, - int index, const QMap &contv, - SymbologyXML::SymbolTypes::t_icon_type iconType, - SymbologyXML::SymbolTypes::t_sector_position pos, - SymbologyXML::SymbolTypes::t_sector_rectpos rectpos = SymbologyXML::SymbolTypes::SECTOR_RECTPOS_DEFAULT); + void onComboBoxAlign1CurrentIndexChanged(int index); + void onComboBoxAlign2CurrentIndexChanged(int index); + void onComboBoxAlign3CurrentIndexChanged(int index); + void onComboBoxColorCurrentIndexChanged(int index); + void onComboBoxLineStyleCurrentIndexChanged(int index); - void onComboBoxAlign1CurrentIndexChanged(int index); - void onComboBoxAlign2CurrentIndexChanged(int index); - void onComboBoxAlign3CurrentIndexChanged(int index); + void onLineEdit1TextChanged(const QString& text); + void onLineEdit2TextChanged(const QString& text); + void onLineEdit3TextChanged(const QString& text); - void onComboBoxColorCurrentIndexChanged(int index); - void onComboBoxLineStyleCurrentIndexChanged(int index); + void onListViewTruppengattungItemSelectionChanged(); - void onLineEdit1TextChanged(const QString &text); - void onLineEdit2TextChanged(const QString &text); - void onLineEdit3TextChanged(const QString &text); + void onCheckBoxBackgroundStateChanged(int state); + void onCheckBoxCopyValuesStateChanged(int state); + void onCheckBoxFillStateChanged(int state); + void onCheckBoxPlannedStateChanged(int state); + void onCheckBoxDrawAreaStateChanged(int state); - void onListViewTruppengattungItemSelectionChanged(); + void onSpinBoxRasterValueChanged(double d); + void onSpinBoxLineWidthValueChanged(double d); + void onSpinBoxScaleValueChanged(double d); - void onCheckBoxBackgroundStateChanged(int state); - void onCheckBoxCopyValuesStateChanged(int state); - void onCheckBoxFillStateChanged(int state); - void onCheckBoxPlannedStateChanged(int state); - void onCheckBoxDrawAreaStateChanged(int state); + void onSliderTransparencyValueChanged(int value); - void onSpinBoxRasterValueChanged(double d); - void onSpinBoxLineWidthValueChanged(double d); - void onSpinBoxScaleValueChanged(double d); + void setZoom(double zoom); - void onSliderTransparencyValueChanged(int value); + void addItem(SymbologyXML::Primitive* prim); - void setZoom(double zoom); + void selectionChanged(); - void addItem(SymbologyXML::Primitive *prim); + private: + NGL::INGLLogger& m_logger; + void resetGUI(); + void updateGUI(); + void updateSymbolAttributesWidgets(); + void updateTextProperties(); + void resetToolButtonGroupState(); - void selectionChanged(); + void pushUndo(); + void popUndo(); + void clearUndo(); -private: + void restoreSelection(SymbologyXML::Primitive* prim); + void copyFromSelectedPrimitive(); + void enableSelectMove(bool enable); + void setPushButtonFillColorBackground(QColor color); -NGL::INGLLogger &m_logger; - void resetGUI(); - void updateGUI(); - void updateSymbolAttributesWidgets(); - void updateTextProperties(); - void resetToolButtonGroupState(); + QIcon getIcon(e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, int iconId, QSize iconSize); - void pushUndo(); - void popUndo(); - void clearUndo(); + int getFrameSymbolID(SymbologyXML::SymbolTypes::t_dimen dimen, SymbologyXML::SymbolTypes::t_affil affil); - void restoreSelection(SymbologyXML::Primitive *prim); - void copyFromSelectedPrimitive(); - void enableSelectMove(bool enable); + void fillListWidget(const QMap& container, QWidget* widget, e_category category, + SymbologyXML::SymbolTypes::t_icon_type iconType, bool withIcons = true, bool sort = true); - void setPushButtonFillColorBackground(QColor color); + void widgetInsertItem(QWidget* widget, int index, const QString& text, int key, e_category category, + SymbologyXML::SymbolTypes::t_icon_type iconType, bool withIcons); - QIcon getIcon(e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, - int iconId, QSize iconSize); + void drawSymbol(const SymbologyXML::Symbol* symbol, QGraphicsScene* scene, const QColor& color, + const QColor& fillColor, double z, bool isAttrib = false, bool updateMap = false, + bool drawBoundRect = false); - int getFrameSymbolID(SymbologyXML::SymbolTypes::t_dimen dimen, - SymbologyXML::SymbolTypes::t_affil affil); + void drawSymbolPrimitive(SymbologyXML::Primitive* primitive, QGraphicsScene* scene, const QColor& color, + const QColor& fillColor, double z, bool isAttrib = false, bool drawBoundRect = false); - void fillListWidget(const QMap &container, QWidget *widget, - e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, - bool withIcons = true, bool sort = true); + void copyElementsFromSymbol(const SymbologyXML::Symbol& tmpSymbol) const; - void widgetInsertItem(QWidget *widget, int index, const QString &text, int key, - e_category category, SymbologyXML::SymbolTypes::t_icon_type iconType, - bool withIcons); - - void drawSymbol(const SymbologyXML::Symbol *symbol, QGraphicsScene *scene, - const QColor &color, const QColor &fillColor, - double z, bool isAttrib = false, bool updateMap = false, bool drawBoundRect = false); - - void drawSymbolPrimitive(SymbologyXML::Primitive *primitive, QGraphicsScene *scene, - const QColor &color, const QColor &fillColor, - double z, bool isAttrib = false, bool drawBoundRect = false); - - void copyElementsFromSymbol(const SymbologyXML::Symbol &tmpSymbol) const; - - Ui::SymbolEditor *m_ui; - SymbolEditorPrivate *m_internal; - LtsSession::LtsSession *m_session; + Ui::SymbolEditor* m_ui; + SymbolEditorPrivate* m_internal; + LtsSession::LtsSession* m_session; }; -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.cpp old mode 100755 new mode 100644 index 5a17727f2..7acc37dbf --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.cpp @@ -1,740 +1,632 @@ - #include "asb_flm_subscriber.h" -#include + +#include "flm_symbol_proxy.h" #include #include -#include -#include -#include "flm_symbol_proxy.h" - #include #include - - +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include #include +#include +#include +#include namespace AdvancedSymbology { uint qHash(SymbologyType type) { - return static_cast(type); + return static_cast(type); } struct FileContentStruct { - enum SymbolType { UnsupportedSymbol, EtsSymbol, XmlSymbol }; - enum ReplyState { Undefined, Requested, RequestFailure, ReplyReceived, ReplySuccess, ReplyFailure }; + enum SymbolType { UnsupportedSymbol, EtsSymbol, XmlSymbol }; - QString name; - SymbolType type{UnsupportedSymbol}; - QString operatorName; - int64_t lastModified{0}; - QStringList usrTags; - QColor colorTobeReplaced; + enum ReplyState { Undefined, Requested, RequestFailure, ReplyReceived, ReplySuccess, ReplyFailure }; - struct Monitoring - { - qint64 requestTime{-1}; - int retryCnt{0}; - ReplyState replyState{Undefined}; - int replyContentSize{-1}; - }; - mutable Monitoring monitoring; + QString name; + SymbolType type{UnsupportedSymbol}; + QString operatorName; + int64_t lastModified{0}; + QStringList usrTags; + QColor colorTobeReplaced; + + struct Monitoring + { + qint64 requestTime{-1}; + int retryCnt{0}; + ReplyState replyState{Undefined}; + int replyContentSize{-1}; + }; + + mutable Monitoring monitoring; }; qint64 getRequestTime() { - return time(nullptr); + return time(nullptr); } QString toString(FileContentStruct::ReplyState rs) { - switch (rs) - { - case FileContentStruct::Undefined: - return QStringLiteral("Undefined"); - case FileContentStruct::Requested: - return QStringLiteral("Requested"); - case FileContentStruct::RequestFailure: - return QStringLiteral("RequestFailure"); - case FileContentStruct::ReplyReceived: - return QStringLiteral("ReplyReceived"); - case FileContentStruct::ReplySuccess: - return QStringLiteral("ReplySuccess"); - case FileContentStruct::ReplyFailure: - return QStringLiteral("ReplyFailure"); - } - return QStringLiteral("UnknownReplyState"); + switch (rs) + { + case FileContentStruct::Undefined: + return QStringLiteral("Undefined"); + case FileContentStruct::Requested: + return QStringLiteral("Requested"); + case FileContentStruct::RequestFailure: + return QStringLiteral("RequestFailure"); + case FileContentStruct::ReplyReceived: + return QStringLiteral("ReplyReceived"); + case FileContentStruct::ReplySuccess: + return QStringLiteral("ReplySuccess"); + case FileContentStruct::ReplyFailure: + return QStringLiteral("ReplyFailure"); + } + return QStringLiteral("UnknownReplyState"); } - - struct FlmSubscriber::Private { - QHash m_fileContentMap; - QTimer *m_reFetchTimer{nullptr}; - FlmSymbolProxy m_symbolProxy; + QHash m_fileContentMap; + QTimer* m_reFetchTimer{nullptr}; + FlmSymbolProxy m_symbolProxy; - QSet m_symbolDictionaryToUpdate; + QSet m_symbolDictionaryToUpdate; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; - std::shared_ptr m_opmDtc; + std::shared_ptr m_opmDtc; - static long m_counter; + static long m_counter; }; + long FlmSubscriber::Private::m_counter = 0; - -FlmSubscriber::FlmSubscriber(const std::shared_ptr &flmDtc, - const std::shared_ptr &flmFtc, - const std::shared_ptr &opmDtc) - : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("AdvSymbology.FlmSubscriber")) - , d(new Private()) +FlmSubscriber::FlmSubscriber(const std::shared_ptr& flmDtc, + const std::shared_ptr& flmFtc, + const std::shared_ptr& opmDtc) + : m_logger(NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("AdvSymbology.FlmSubscriber")), d(new Private()) { - INFO_LOG(m_logger) << Q_FUNC_INFO << " m_counter =" << ++d->m_counter; - d->m_flmDtc = flmDtc; - d->m_flmFtc = flmFtc; - d->m_opmDtc = opmDtc; + INFO_LOG(m_logger) << Q_FUNC_INFO << " m_counter =" << ++d->m_counter; + d->m_flmDtc = flmDtc; + d->m_flmFtc = flmFtc; + d->m_opmDtc = opmDtc; - d->m_reFetchTimer = new QTimer(this); - d->m_reFetchTimer->setInterval(10000); - connect(d->m_reFetchTimer, &QTimer::timeout, - this, &FlmSubscriber::checkForReFetching); + d->m_reFetchTimer = new QTimer(this); + d->m_reFetchTimer->setInterval(10000); + connect(d->m_reFetchTimer, &QTimer::timeout, this, &FlmSubscriber::checkForReFetching); - - qRegisterMetaType("FileManagement::FileContent"); - qRegisterMetaType("DataModification"); + qRegisterMetaType("FileManagement::FileContent"); + qRegisterMetaType("DataModification"); } FlmSubscriber::~FlmSubscriber() { - INFO_LOG(m_logger) << Q_FUNC_INFO << " m_counter =" << d->m_counter--; + INFO_LOG(m_logger) << Q_FUNC_INFO << " m_counter =" << d->m_counter--; - if (d->m_reFetchTimer) - d->m_reFetchTimer->stop(); + if (d->m_reFetchTimer) + d->m_reFetchTimer->stop(); - delete d; + delete d; } bool FlmSubscriber::createFlmSymbolProxy(int type_placeholder) { - Q_UNUSED(type_placeholder); - if (!d->m_flmDtc || !d->m_flmFtc) - return false; + Q_UNUSED(type_placeholder); + if (!d->m_flmDtc || !d->m_flmFtc) + return false; - d->m_flmDtc->enableFileContent(); - d->m_flmFtc->enableGetFileContentData(); + d->m_flmDtc->enableFileContent(); + d->m_flmFtc->enableGetFileContentData(); - - - - - connect(d->m_flmDtc.get(), &FileManagement::Interface::Dtc::fileContentChanged, - this, &FlmSubscriber::onFileContentChanged, Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection)); + connect(d->m_flmDtc.get(), &FileManagement::Interface::Dtc::fileContentChanged, this, + &FlmSubscriber::onFileContentChanged, Qt::ConnectionType(Qt::QueuedConnection | Qt::UniqueConnection)); - - - - const auto cb = [this](const FileManagement::FileContent & data) -> void - { - updateFileContentMap(data); - }; - if (!d->m_flmDtc->fileContents(cb)) - ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error performing fileContents"; + const auto cb = [this](const FileManagement::FileContent& data) -> void { updateFileContentMap(data); }; + if (!d->m_flmDtc->fileContents(cb)) + ERROR_LOG(m_logger) << Q_FUNC_INFO << " Error performing fileContents"; - INFO_LOG(m_logger) << Q_FUNC_INFO << " m_fileContentMap.size()=" << d->m_fileContentMap.size() ; + INFO_LOG(m_logger) << Q_FUNC_INFO << " m_fileContentMap.size()=" << d->m_fileContentMap.size(); - - - - for (auto it = d->m_fileContentMap.cbegin(); it != d->m_fileContentMap.cend(); ++it) - { - const int fileContentId = it.key(); - FileManagement::GetFileContentDataRequest request(fileContentId); - const FileContentStruct &fcsRef = it.value(); + for (auto it = d->m_fileContentMap.cbegin(); it != d->m_fileContentMap.cend(); ++it) + { + const int fileContentId = it.key(); + FileManagement::GetFileContentDataRequest request(fileContentId); + const FileContentStruct& fcsRef = it.value(); #ifdef LTS_DEBUG #ifdef SKIP_SOME_TO_TEST_REFETCHING - if (fileContentId>=98) - request.fileContentId(-1); -#endif -#endif + if (fileContentId >= 98) + request.fileContentId(-1); +#endif +#endif - if (d->m_flmFtc->getFileContentDataRequest(request, this)) - { - fcsRef.monitoring.requestTime = getRequestTime(); - fcsRef.monitoring.replyState = FileContentStruct::Requested; - } else { - fcsRef.monitoring.replyState = FileContentStruct::RequestFailure; - ERROR_LOG(m_logger) << "Error requesting FileContentData, fileContentId=" << fileContentId; + if (d->m_flmFtc->getFileContentDataRequest(request, this)) + { + fcsRef.monitoring.requestTime = getRequestTime(); + fcsRef.monitoring.replyState = FileContentStruct::Requested; + } + else + { + fcsRef.monitoring.replyState = FileContentStruct::RequestFailure; + ERROR_LOG(m_logger) << "Error requesting FileContentData, fileContentId=" << fileContentId; + } } - } + const int randomOffset = rand() % 10 + 5; + QTimer::singleShot(randomOffset, this, [this]() { + DEBUG_LOG(m_logger) << "start ReFetchingTimer"; + d->m_reFetchTimer->start(); + }); - - - - const int randomOffset = rand() % 10 + 5; - QTimer::singleShot(randomOffset, this , [this]() - { - DEBUG_LOG(m_logger) << "start ReFetchingTimer"; - d->m_reFetchTimer->start(); - }); - - return true; + return true; } - -void FlmSubscriber::onGetFileContentDataReply(const FileManagement::GetFileContentDataReply &reply) +void FlmSubscriber::onGetFileContentDataReply(const FileManagement::GetFileContentDataReply& reply) { - const int32_t fileContentId = reply.id(); + const int32_t fileContentId = reply.id(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, " << fileContentId; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START, " << fileContentId; - if (!d->m_fileContentMap.contains(fileContentId)) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " fileContentId unknown, fileContentId=" << fileContentId; - return; - } - - const FileContentStruct &fcData = d->m_fileContentMap[fileContentId]; - fcData.monitoring.replyState = FileContentStruct::ReplyReceived; - const QString &name = fcData.name; - const QString &operatorName = fcData.operatorName; - const qint64 lastModified = fcData.lastModified; - - DEBUG_LOG(m_logger) << Q_FUNC_INFO - << " fileContentId=" << fileContentId - << " name=" << name - << " operatorName=" << operatorName - << " lastModified=" << lastModified - << " #bytes =" << reply.content().size(); - - fcData.monitoring.replyContentSize = reply.content().size(); - - switch (fcData.type) - { - case FileContentStruct::SymbolType::EtsSymbol: - { - QImage image; - if (!svgToImage(QByteArray::fromRawData(reinterpret_cast(&reply.content().at(0)), reply.content().size()), image)) + if (!d->m_fileContentMap.contains(fileContentId)) { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " svgToImage failed, fileContentId=" << fileContentId; - fcData.monitoring.replyState = FileContentStruct::ReplyFailure; - return; + ERROR_LOG(m_logger) << Q_FUNC_INFO << " fileContentId unknown, fileContentId=" << fileContentId; + return; } - + const FileContentStruct& fcData = d->m_fileContentMap[fileContentId]; + fcData.monitoring.replyState = FileContentStruct::ReplyReceived; + const QString& name = fcData.name; + const QString& operatorName = fcData.operatorName; + const qint64 lastModified = fcData.lastModified; - - FlmSymbolProxy::SymbolData symbolData(name, image, fcData.colorTobeReplaced); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " fileContentId=" << fileContentId << " name=" << name + << " operatorName=" << operatorName << " lastModified=" << lastModified + << " #bytes =" << reply.content().size(); - symbolData.setUsrTags(fcData.usrTags); + fcData.monitoring.replyContentSize = reply.content().size(); - - d->m_symbolProxy.setSymbol(fileContentId, symbolData); - fcData.monitoring.replyState = FileContentStruct::ReplySuccess; - break; - } - - case FileContentStruct::SymbolType::XmlSymbol: - { - FlmSymbolProxy::SymbolData symbolData(name, operatorName, lastModified, LtsUtils::toQByteArray(reply.content())); - - if (symbolData.isXmlSymbol()) + switch (fcData.type) { - symbolData.setUsrTags(fcData.usrTags); - - d->m_symbolProxy.setSymbol(fileContentId, symbolData); - fcData.monitoring.replyState = FileContentStruct::ReplySuccess; - } - else - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " xmlSymbolContent is empty, fileContentId=" << fileContentId; - fcData.monitoring.replyState = FileContentStruct::ReplyFailure; - } - break; - } + case FileContentStruct::SymbolType::EtsSymbol: { + QImage image; + if (!svgToImage(QByteArray::fromRawData(reinterpret_cast(&reply.content().at(0)), + reply.content().size()), + image)) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " svgToImage failed, fileContentId=" << fileContentId; + fcData.monitoring.replyState = FileContentStruct::ReplyFailure; + return; + } - case FileContentStruct::SymbolType::UnsupportedSymbol: - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " unsupported symbol found, fileContentId=" << fileContentId; - fcData.monitoring.replyState = FileContentStruct::ReplyFailure; - break; - } + FlmSymbolProxy::SymbolData symbolData(name, image, fcData.colorTobeReplaced); - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + symbolData.setUsrTags(fcData.usrTags); + + d->m_symbolProxy.setSymbol(fileContentId, symbolData); + fcData.monitoring.replyState = FileContentStruct::ReplySuccess; + break; + } + + case FileContentStruct::SymbolType::XmlSymbol: { + FlmSymbolProxy::SymbolData symbolData(name, operatorName, lastModified, + LtsUtils::toQByteArray(reply.content())); + + if (symbolData.isXmlSymbol()) + { + symbolData.setUsrTags(fcData.usrTags); + + d->m_symbolProxy.setSymbol(fileContentId, symbolData); + fcData.monitoring.replyState = FileContentStruct::ReplySuccess; + } + else + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " xmlSymbolContent is empty, fileContentId=" << fileContentId; + fcData.monitoring.replyState = FileContentStruct::ReplyFailure; + } + break; + } + + case FileContentStruct::SymbolType::UnsupportedSymbol: { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " unsupported symbol found, fileContentId=" << fileContentId; + fcData.monitoring.replyState = FileContentStruct::ReplyFailure; + break; + } + } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } -bool FlmSubscriber::svgToImage(const QByteArray &svgByteArray, QImage &imageOut) +bool FlmSubscriber::svgToImage(const QByteArray& svgByteArray, QImage& imageOut) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - - QSvgRenderer svgRenderer; - if (!svgRenderer.load(svgByteArray)) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " svgRenderer.load failed"; - return false; - } + QSvgRenderer svgRenderer; + if (!svgRenderer.load(svgByteArray)) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " svgRenderer.load failed"; + return false; + } - - int size = 200; - imageOut = QImage(size, size, QImage::Format_ARGB32); - imageOut.fill(Qt::transparent); + int size = 200; + imageOut = QImage(size, size, QImage::Format_ARGB32); + imageOut.fill(Qt::transparent); - - QPainter painter(&imageOut); - svgRenderer.render(&painter); - painter.end(); + QPainter painter(&imageOut); + svgRenderer.render(&painter); + painter.end(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; - return true; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + return true; } QString FlmSubscriber::operatorName(int operatorId) { - if (d->m_opmDtc) - return QString::fromStdString(d->m_opmDtc->user(operatorId).name()); - return QStringLiteral("unknown user<%1>").arg(operatorId); + if (d->m_opmDtc) + return QString::fromStdString(d->m_opmDtc->user(operatorId).name()); + return QStringLiteral("unknown user<%1>").arg(operatorId); } - void FlmSubscriber::checkForReFetching() { - - LOGGER_T logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("AdvSymbology.FlmSubscriber.ReFetch"); + LOGGER_T logger = NGL::NGLLoggerBootstrap::getNGLRootLogger().getNGLLogger("AdvSymbology.FlmSubscriber.ReFetch"); - DEBUG_LOG(logger) << "********** checkForReFetching START, size=" << d->m_fileContentMap.size(); + DEBUG_LOG(logger) << "********** checkForReFetching START, size=" << d->m_fileContentMap.size(); - int i{0}; - int unfinished{0}; - int reFetchCounter{0}; - static int s_reFetchCounter = 0; + int i{0}; + int unfinished{0}; + int reFetchCounter{0}; + static int s_reFetchCounter = 0; - const qint64 curTime = time(nullptr); + const qint64 curTime = time(nullptr); - for (auto it = d->m_fileContentMap.cbegin(); it != d->m_fileContentMap.cend(); ++it) - { - const FileContentStruct &fcs = it.value(); - qint64 ageSec = curTime - fcs.monitoring.requestTime; - - DEBUG_LOG(logger) << "***** dump i=" << ++i - << ", fileContentId=" << it.key() - << ", retryCnt=" << fcs.monitoring.retryCnt - << ", ageSec = " << ageSec - << ", replyState=" << toString(fcs.monitoring.replyState) - << ", replyContentSize=" << fcs.monitoring.replyContentSize - << ", name='" << fcs.name << "'" - ; - - if (fcs.monitoring.replyState != FileContentStruct::ReplySuccess) + for (auto it = d->m_fileContentMap.cbegin(); it != d->m_fileContentMap.cend(); ++it) { - ++unfinished; - if ((ageSec > 30) && (fcs.monitoring.retryCnt < 3)) - { - - const int32_t fileContentId = it.key(); - INFO_LOG(logger) << "***** reFetch *** :" - << " ageSec = " << ageSec - << ", fileContentId=" << fileContentId - << ", replyState=" << toString(fcs.monitoring.replyState) - << ", replyContentSize=" << fcs.monitoring.replyContentSize - << ", name='" << fcs.name << "'" - ; - FileManagement::GetFileContentDataRequest request(fileContentId); - if (!d->m_flmFtc->getFileContentDataRequest(request, this)) - ERROR_LOG(logger) << Q_FUNC_INFO << "Error reading FileContentData, fileContentId=" << fileContentId; + const FileContentStruct& fcs = it.value(); + qint64 ageSec = curTime - fcs.monitoring.requestTime; - fcs.monitoring.replyState = FileContentStruct::Requested; - fcs.monitoring.requestTime = getRequestTime(); - ++fcs.monitoring.retryCnt; - + DEBUG_LOG(logger) << "***** dump i=" << ++i << ", fileContentId=" << it.key() + << ", retryCnt=" << fcs.monitoring.retryCnt << ", ageSec = " << ageSec + << ", replyState=" << toString(fcs.monitoring.replyState) + << ", replyContentSize=" << fcs.monitoring.replyContentSize << ", name='" << fcs.name << "'"; - ++reFetchCounter; - ++s_reFetchCounter; - } + if (fcs.monitoring.replyState != FileContentStruct::ReplySuccess) + { + ++unfinished; + if ((ageSec > 30) && (fcs.monitoring.retryCnt < 3)) + { + + const int32_t fileContentId = it.key(); + INFO_LOG(logger) << "***** reFetch *** :" + << " ageSec = " << ageSec << ", fileContentId=" << fileContentId + << ", replyState=" << toString(fcs.monitoring.replyState) + << ", replyContentSize=" << fcs.monitoring.replyContentSize << ", name='" << fcs.name + << "'"; + FileManagement::GetFileContentDataRequest request(fileContentId); + if (!d->m_flmFtc->getFileContentDataRequest(request, this)) + ERROR_LOG(logger) << Q_FUNC_INFO + << "Error reading FileContentData, fileContentId=" << fileContentId; + + fcs.monitoring.replyState = FileContentStruct::Requested; + fcs.monitoring.requestTime = getRequestTime(); + ++fcs.monitoring.retryCnt; + + ++reFetchCounter; + ++s_reFetchCounter; + } + } } - } - INFO_LOG(logger) << "***** checkForReFetching END" - << ", size=" << d->m_fileContentMap.size() - << ", unfinished=" << unfinished - << ", reFetchCounter=" << reFetchCounter - << ", s_reFetchCounter=" << s_reFetchCounter; + INFO_LOG(logger) << "***** checkForReFetching END" + << ", size=" << d->m_fileContentMap.size() << ", unfinished=" << unfinished + << ", reFetchCounter=" << reFetchCounter << ", s_reFetchCounter=" << s_reFetchCounter; } -void FlmSubscriber::onFileContentChanged(const FileManagement::FileContent &data, DataModification modType) +void FlmSubscriber::onFileContentChanged(const FileManagement::FileContent& data, DataModification modType) { - TRACE_LOG(m_logger) << Q_FUNC_INFO - << " data.id=" << data.id() - << " data.fileStatus=" << data.fileStatus().underlying() - << " modType=" << modType - << " data.name='" << data.name().c_str() << "'"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " data.id=" << data.id() + << " data.fileStatus=" << data.fileStatus().underlying() << " modType=" << modType + << " data.name='" << data.name().c_str() << "'"; - if (!d->m_flmFtc) - return; + if (!d->m_flmFtc) + return; - if (data.isDeleted()) - return; + if (data.isDeleted()) + return; - - if (data.fileType().underlying() != FileManagement::FileType::OperatorDefinedSymbol) - return; + if (data.fileType().underlying() != FileManagement::FileType::OperatorDefinedSymbol) + return; - - - if (data.fileStatus().underlying() == FileManagement::FileStatus::Deleted) - { + if (data.fileStatus().underlying() == FileManagement::FileStatus::Deleted) + { + switch (modType) + { + case DataModification::eAdded: + return; + case DataModification::eModified: + modType = DataModification::eRemoved; + break; + case DataModification::eRemoved: + + break; + } + } + + const int32_t fileContentId = data.id(); switch (modType) { - case DataModification::eAdded: - return; - case DataModification::eModified: - modType = DataModification::eRemoved; - break; - case DataModification::eRemoved: - - break; - } - } + case DataModification::eAdded: + case DataModification::eModified: { - - - + updateFileContentMap(data); - const int32_t fileContentId = data.id(); - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - - - updateFileContentMap(data); + FileManagement::GetFileContentDataRequest request(fileContentId); + if (!d->m_flmFtc->getFileContentDataRequest(request, this)) + ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error reading FileContentData, fileContentId=" << fileContentId; + break; + } - FileManagement::GetFileContentDataRequest request(fileContentId); - if (!d->m_flmFtc->getFileContentDataRequest(request, this)) - ERROR_LOG(m_logger) << Q_FUNC_INFO << "Error reading FileContentData, fileContentId=" << fileContentId; - break; - } + case DataModification::eRemoved: { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " modType=" << modType << " fileContentId=" << fileContentId + << " fileContentName=" << data.name(); - case DataModification::eRemoved: - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO - << " modType=" << modType - << " fileContentId=" << fileContentId - << " fileContentName=" << data.name(); + d->m_fileContentMap.remove(fileContentId); - - d->m_fileContentMap.remove(fileContentId); - - - if (!d->m_symbolProxy.removeSymbol(fileContentId)) - ERROR_LOG(m_logger) << Q_FUNC_INFO << " removeSymbol failed" - << " fileContentId=" << fileContentId - << " fileContentName='" << data.name() << "'" - << " contains=" << d->m_fileContentMap.contains(fileContentId); - break; - } - } -} - - -void FlmSubscriber::updateFileContentMap(const FileManagement::FileContent &data) -{ - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << " d->m_fileContentMap.size()=" << d->m_fileContentMap.size() - << " fileContentId=" << data.id() - << " data.isDeleted()=" <errorString: '" << parseError.errorString() << "'" - << ", offset: " << parseError.offset; - } - } - - d->m_fileContentMap[fileContentId] = fcData; - - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" - << " d->m_fileContentMap.size()=" << d->m_fileContentMap.size() - << " fileContentId=" << data.id() - << " data.isDeleted()=" <m_symbolDictionaryToUpdate)) - { - AdvancedSymbology::SymbolDictionary &dict = - AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); - this->setEtsSymbolToDict(dict, fileContentId, name, image, colorToBeReplaced, usrTags); - } -} - -void FlmSubscriber::onLocalSymbolProxyEtsSymbolRemoved(qint32 fileContentId, const QString &name) -{ - for (const SymbologyType &symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) - { - AdvancedSymbology::SymbolDictionary &dict = - AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); - INFO_LOG(m_logger) << Q_FUNC_INFO << " dict.removeEtsSymbol:" - << " symbologyType='" << (int)symbologyType << "'" - << ", name='" << name << "'" - << ", fileContentId=" << fileContentId; - dict.removeEtsSymbol(fileContentId); - dict.removeEtsSymbol(name); - } -} - -void FlmSubscriber::onLocalSymbolProxyXmlSymbolAdded(qint32 fileContentId, - const QString &operatorName, - qint64 lastModified, - const QString &name, - const QString &xmlContent, - const QStringList &usrTags) -{ - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" - << " fileContentId=" << fileContentId - << " name='" << name << "'"; - - if (!xmlContent.isEmpty()) - { - for (const SymbologyType &symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) - { - AdvancedSymbology::SymbolDictionary &dict = - AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); - if (!this->setXmlSymbolToDict(dict, fileContentId, operatorName, lastModified, name, xmlContent, usrTags)) - ERROR_LOG(m_logger) << Q_FUNC_INFO << " dict.setXmlSymbolToDict failed" - << ", symbologyType='" << (int)symbologyType << "'" - << ", name='" << name << "'"; + if (!d->m_symbolProxy.removeSymbol(fileContentId)) + ERROR_LOG(m_logger) << Q_FUNC_INFO << " removeSymbol failed" + << " fileContentId=" << fileContentId << " fileContentName='" << data.name() << "'" + << " contains=" << d->m_fileContentMap.contains(fileContentId); + break; + } } - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" - << " fileContentId=" << fileContentId - << " name='" << name << "'"; +} + +void FlmSubscriber::updateFileContentMap(const FileManagement::FileContent& data) +{ + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" + << " d->m_fileContentMap.size()=" << d->m_fileContentMap.size() + << " fileContentId=" << data.id() << " data.isDeleted()=" << data.isDeleted() + << " data.fileStatus().underlying()=" << data.fileStatus().underlying() << " data.name='" + << QString::fromStdString(data.name()) << "'"; + + if (data.isDeleted()) + return; + + if (data.fileStatus().underlying() == FileManagement::FileStatus::Deleted) + return; + + if (data.fileType() != FileManagement::FileType::OperatorDefinedSymbol) + return; + + const int32_t fileContentId = data.id(); + + FileContentStruct fcData; + + fcData.name = QString::fromStdString(data.name()); + fcData.type = FileContentStruct::SymbolType::UnsupportedSymbol; + fcData.operatorName = operatorName(data.operatorId()); + fcData.lastModified = data.lastModified(); + + fcData.usrTags << QStringLiteral("file-id=%1").arg(fileContentId); + fcData.usrTags << QStringLiteral("exercise-id=%1").arg(data.exerciseId().is_set() ? data.exerciseId().get() : -1); + fcData.usrTags << fcData.operatorName; + + if (data.properties().size() != 0) + { + const QByteArray attributesJson(QByteArray::fromRawData(data.properties().c_str(), data.properties().size())); + QJsonParseError parseError; + QJsonDocument jDoc(QJsonDocument::fromJson(attributesJson, &parseError)); + + if (parseError.error == QJsonParseError::NoError) + { + const QJsonObject& obj = jDoc.object(); + const QLatin1String imageFormatKey("imageFormat"); + if (obj.contains(imageFormatKey)) + { + const QString& imageFormatValue = obj[imageFormatKey].toString(); + if (QLatin1String("xml") == imageFormatValue) + fcData.type = FileContentStruct::SymbolType::XmlSymbol; + + if (QLatin1String("ets") == imageFormatValue) + fcData.type = FileContentStruct::SymbolType::EtsSymbol; + } + else + fcData.type = FileContentStruct::SymbolType::EtsSymbol; + + if (FileContentStruct::SymbolType::EtsSymbol == fcData.type) + { + + const QLatin1String partyColorStr("partyColor"); + if (obj.contains(partyColorStr)) + { + QJsonObject partyColor = obj[partyColorStr].toObject(); + if (partyColor.size() == 3) + { + + fcData.colorTobeReplaced.setRgb(partyColor[QLatin1String("r")].toInt(), + partyColor[QLatin1String("g")].toInt(), + partyColor[QLatin1String("b")].toInt()); + } + } + } + } + else + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " QJsonParseError->errorString: '" << parseError.errorString() << "'" + << ", offset: " << parseError.offset; + } + } + + d->m_fileContentMap[fileContentId] = fcData; + + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" + << " d->m_fileContentMap.size()=" << d->m_fileContentMap.size() + << " fileContentId=" << data.id() << " data.isDeleted()=" << data.isDeleted() + << " data.fileStatus().underlying()=" << data.fileStatus().underlying() << " data.name='" + << QString::fromStdString(data.name()) << "'"; +} + +void FlmSubscriber::onLocalSymbolProxyEtsSymbolAdded(qint32 fileContentId, const QString& name, const QImage& image, + const QColor& colorToBeReplaced, const QStringList& usrTags) +{ + Q_UNUSED(fileContentId); + for (const SymbologyType symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) + { + AdvancedSymbology::SymbolDictionary& dict = AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); + this->setEtsSymbolToDict(dict, fileContentId, name, image, colorToBeReplaced, usrTags); + } +} + +void FlmSubscriber::onLocalSymbolProxyEtsSymbolRemoved(qint32 fileContentId, const QString& name) +{ + for (const SymbologyType& symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) + { + AdvancedSymbology::SymbolDictionary& dict = AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); + INFO_LOG(m_logger) << Q_FUNC_INFO << " dict.removeEtsSymbol:" + << " symbologyType='" << (int)symbologyType << "'" + << ", name='" << name << "'" + << ", fileContentId=" << fileContentId; + dict.removeEtsSymbol(fileContentId); + dict.removeEtsSymbol(name); + } +} + +void FlmSubscriber::onLocalSymbolProxyXmlSymbolAdded(qint32 fileContentId, const QString& operatorName, + qint64 lastModified, const QString& name, + const QString& xmlContent, const QStringList& usrTags) +{ + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" + << " fileContentId=" << fileContentId << " name='" << name << "'"; + + if (!xmlContent.isEmpty()) + { + for (const SymbologyType& symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) + { + AdvancedSymbology::SymbolDictionary& dict = AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); + if (!this->setXmlSymbolToDict(dict, fileContentId, operatorName, lastModified, name, xmlContent, usrTags)) + ERROR_LOG(m_logger) << Q_FUNC_INFO << " dict.setXmlSymbolToDict failed" + << ", symbologyType='" << (int)symbologyType << "'" + << ", name='" << name << "'"; + } + } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" + << " fileContentId=" << fileContentId << " name='" << name << "'"; } void FlmSubscriber::onLocalSymbolProxyXmlSymbolRemoved(qint32 fileContentId) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << " fileContentId=" << fileContentId; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" << " fileContentId=" << fileContentId; - for (const SymbologyType &symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) - { - AdvancedSymbology::SymbolDictionary &dict = - AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dict.removeXmlSymbol:" - << " symbologyType='" << symbologyType << "'" - << ", fileContentId=" << fileContentId; + for (const SymbologyType& symbologyType : std::as_const(d->m_symbolDictionaryToUpdate)) + { + AdvancedSymbology::SymbolDictionary& dict = AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dict.removeXmlSymbol:" + << " symbologyType='" << symbologyType << "'" + << ", fileContentId=" << fileContentId; - const QString &skey = QString::number(fileContentId); - const QString &sidc = SidcCodec::encodeCivilXml(skey); - dict.removeXmlSymbol(sidc); - dict.removeXmlSymbol(fileContentId); - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" << " fileContentId=" << fileContentId; + const QString& skey = QString::number(fileContentId); + const QString& sidc = SidcCodec::encodeCivilXml(skey); + dict.removeXmlSymbol(sidc); + dict.removeXmlSymbol(fileContentId); + } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END" << " fileContentId=" << fileContentId; } - - - - - bool FlmSubscriber::connectFlmSymbolProxy(int type_placeholder, SymbologyType symbologyType) { - Q_UNUSED(type_placeholder); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " m_fileContentMap.size()=" << d->m_fileContentMap.size() ; + Q_UNUSED(type_placeholder); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " m_fileContentMap.size()=" << d->m_fileContentMap.size(); - d->m_symbolDictionaryToUpdate.insert(symbologyType); + d->m_symbolDictionaryToUpdate.insert(symbologyType); - - - connect(&d->m_symbolProxy, &FlmSymbolProxy::etsSymbolAdded, - this, &FlmSubscriber::onLocalSymbolProxyEtsSymbolAdded, Qt::QueuedConnection); - connect(&d->m_symbolProxy, &FlmSymbolProxy::etsSymbolRemoved, - this, &FlmSubscriber::onLocalSymbolProxyEtsSymbolRemoved, Qt::QueuedConnection); + connect(&d->m_symbolProxy, &FlmSymbolProxy::etsSymbolAdded, this, &FlmSubscriber::onLocalSymbolProxyEtsSymbolAdded, + Qt::QueuedConnection); + connect(&d->m_symbolProxy, &FlmSymbolProxy::etsSymbolRemoved, this, + &FlmSubscriber::onLocalSymbolProxyEtsSymbolRemoved, Qt::QueuedConnection); - - - connect(&d->m_symbolProxy, &FlmSymbolProxy::xmlSymbolAdded, - this, &FlmSubscriber::onLocalSymbolProxyXmlSymbolAdded, Qt::QueuedConnection); - connect(&d->m_symbolProxy, &FlmSymbolProxy::xmlSymbolRemoved, - this, &FlmSubscriber::onLocalSymbolProxyXmlSymbolRemoved, Qt::QueuedConnection); + connect(&d->m_symbolProxy, &FlmSymbolProxy::xmlSymbolAdded, this, &FlmSubscriber::onLocalSymbolProxyXmlSymbolAdded, + Qt::QueuedConnection); + connect(&d->m_symbolProxy, &FlmSymbolProxy::xmlSymbolRemoved, this, + &FlmSubscriber::onLocalSymbolProxyXmlSymbolRemoved, Qt::QueuedConnection); + if (d->m_symbolProxy.isEmpty()) + return true; + + AdvancedSymbology::SymbolDictionary& dict = AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); + + dict.blockSignals(true); + for (auto mapIt = d->m_symbolProxy.getMap().begin(); mapIt != d->m_symbolProxy.getMap().end(); ++mapIt) + { + const int fileContentId = mapIt.key(); + const FlmSymbolProxy::SymbolData& symData = mapIt.value(); + if (symData.isXmlSymbol()) + setXmlSymbolToDict(dict, fileContentId, symData.operatorName(), symData.lastModified(), symData.name(), + symData.xmlContent(), symData.usrTags()); + else + setEtsSymbolToDict(dict, fileContentId, symData.name(), symData.image(), symData.colorToBeReplaced(), + symData.usrTags()); + } + dict.blockSignals(false); - - if (d->m_symbolProxy.isEmpty()) return true; +} - AdvancedSymbology::SymbolDictionary &dict = - AdvancedSymbology::SymbolDictionary::dictionary(symbologyType); +bool FlmSubscriber::setEtsSymbolToDict(SymbolDictionary& dict, qint32 fileContentId, const QString& name, + const QImage& image, const QColor& colorToBeReplaced, const QStringList& usrTags) +{ - - dict.blockSignals(true); - for (auto mapIt = d->m_symbolProxy.getMap().begin(); mapIt != d->m_symbolProxy.getMap().end(); ++mapIt) - { - const int fileContentId = mapIt.key(); - const FlmSymbolProxy::SymbolData &symData = mapIt.value(); - if (symData.isXmlSymbol()) - setXmlSymbolToDict(dict, fileContentId, symData.operatorName(), symData.lastModified(), symData.name(), symData.xmlContent(), symData.usrTags()); + SymbolProperties symProps; + symProps.setKey(name); + symProps.setSidc(SidcCodec::encodeCivilEts(name)); + symProps.setName(name); + + symProps.setSymbolClass(QLatin1String("3")); + symProps.setGeometryType(GeometryType::Point); + symProps.setTags(QStringList() << name << usrTags); + symProps.setColorToBeReplaced(colorToBeReplaced); + + if (!dict.setEtsSymbol(fileContentId, symProps.sidc(), symProps, image)) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " dict.insertExtraSymbol failed" + << ", fileContentId=" << fileContentId << ", name='" << name << "'"; + return false; + } else - setEtsSymbolToDict(dict, fileContentId, symData.name(), symData.image(), symData.colorToBeReplaced(), symData.usrTags()); - } - dict.blockSignals(false); + INFO_LOG(m_logger) << Q_FUNC_INFO << " dict.insertExtraSymbol done" + << ", fileContentId=" << fileContentId << ", name='" << name << "'"; - return true; + return true; } - -bool FlmSubscriber::setEtsSymbolToDict(SymbolDictionary &dict, - qint32 fileContentId, - const QString &name, - const QImage &image, - const QColor &colorToBeReplaced, - const QStringList &usrTags) +bool FlmSubscriber::setXmlSymbolToDict(SymbolDictionary& dict, qint32 fileContentId, const QString& operatorName, + qint64 lastModified, const QString& name, const QString& xmlContent, + const QStringList& usrTags) { - - SymbolProperties symProps; - symProps.setKey(name); - symProps.setSidc(SidcCodec::encodeCivilEts(name)); - symProps.setName(name); + SymbolProperties symProps; - symProps.setSymbolClass(QLatin1String("3")); - symProps.setGeometryType(GeometryType::Point); - symProps.setTags(QStringList() << name << usrTags); - symProps.setColorToBeReplaced(colorToBeReplaced); + symProps.setTags(QStringList() << name << usrTags); - if (!dict.setEtsSymbol(fileContentId, symProps.sidc(), symProps, image)) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " dict.insertExtraSymbol failed" - << ", fileContentId=" << fileContentId << ", name='" << name << "'"; - return false; - } - else - INFO_LOG(m_logger) << Q_FUNC_INFO << " dict.insertExtraSymbol done" - << ", fileContentId=" << fileContentId << ", name='" << name << "'"; + bool success = dict.setXmlSymbol(fileContentId, name, operatorName, lastModified, xmlContent, symProps); - return true; + if (!success) + ERROR_LOG(m_logger) << Q_FUNC_INFO << " setXmlSymbol failed:" + << ", file-id=" << fileContentId << ", filenameid='" << name << "'"; + return success; } -bool FlmSubscriber::setXmlSymbolToDict(SymbolDictionary &dict, - qint32 fileContentId, - const QString &operatorName, - qint64 lastModified, - const QString &name, - const QString &xmlContent, - const QStringList &usrTags) -{ - SymbolProperties symProps; - - - - symProps.setTags(QStringList() << name << usrTags); - - - - bool success = dict.setXmlSymbol(fileContentId, name, operatorName, lastModified, xmlContent, symProps); - - if (!success) - ERROR_LOG(m_logger) << Q_FUNC_INFO << " setXmlSymbol failed:" - << ", file-id=" << fileContentId - << ", filenameid='" << name << "'"; - return success; -} - -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.h old mode 100755 new mode 100644 index 58feaaee5..7289215b7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AdvancedSymbology/Gui/SymbolProxy/asb_flm_subscriber.h @@ -1,20 +1,15 @@ - #pragma once -#include #include - -#include -#include - #include #include - +#include +#include +#include #include - namespace LtsUtils { class RequestHelper; @@ -23,75 +18,53 @@ class RequestHelper; namespace AdvancedSymbology { -class FlmSubscriber final - : public QObject - , public ForeignGuiFlmSymbolsProxyInterface - , public FileManagement::Interface::Ftc::GetFileContentDataReplyHandler +class FlmSubscriber final : public QObject, + public ForeignGuiFlmSymbolsProxyInterface, + public FileManagement::Interface::Ftc::GetFileContentDataReplyHandler { - Q_OBJECT -public: - explicit FlmSubscriber(const std::shared_ptr &flmDtc, - const std::shared_ptr &flmFtc, - const std::shared_ptr &opmDtc); - ~FlmSubscriber(); + Q_OBJECT + public: + explicit FlmSubscriber(const std::shared_ptr& flmDtc, + const std::shared_ptr& flmFtc, + const std::shared_ptr& opmDtc); + ~FlmSubscriber(); + bool createFlmSymbolProxy(int type_placeholder) override; + bool connectFlmSymbolProxy(int type_placeholder, SymbologyType symbologyType) override; - bool createFlmSymbolProxy(int type_placeholder) override; - bool connectFlmSymbolProxy(int type_placeholder, SymbologyType symbologyType) override; + private: + NGL::INGLLogger& m_logger; + bool setEtsSymbolToDict(SymbolDictionary& dict, qint32 fileContentId, const QString& name, const QImage& image, + const QColor& colorToBeReplaced, const QStringList& usrTags); -private: + bool setXmlSymbolToDict(SymbolDictionary& dict, qint32 fileContentId, const QString& operatorName, + qint64 lastModified, const QString& name, const QString& xmlContent, + const QStringList& usrTags); -NGL::INGLLogger &m_logger; - bool setEtsSymbolToDict(SymbolDictionary &dict, - qint32 fileContentId, - const QString &name, - const QImage &image, - const QColor &colorToBeReplaced, - const QStringList &usrTags); + protected slots: + void onFileContentChanged(const FileManagement::FileContent& data, DataModification modType); + void updateFileContentMap(const FileManagement::FileContent& data); - bool setXmlSymbolToDict(SymbolDictionary &dict, - qint32 fileContentId, - const QString &operatorName, - qint64 lastModified, - const QString &name, - const QString &xmlContent, - const QStringList &usrTags); + void onLocalSymbolProxyEtsSymbolAdded(qint32 fileContentId, const QString& name, const QImage& image, + const QColor& colorToBeReplaced, const QStringList& usrTags); + void onLocalSymbolProxyEtsSymbolRemoved(qint32 fileContentId, const QString& name); -protected slots: - void onFileContentChanged(const FileManagement::FileContent &data, DataModification modType); - void updateFileContentMap(const FileManagement::FileContent &data); + void onLocalSymbolProxyXmlSymbolAdded(qint32 fileContentId, const QString& operatorName, qint64 lastModified, + const QString& name, const QString& xmlContent, const QStringList& usrTags); + void onLocalSymbolProxyXmlSymbolRemoved(qint32 fileContentId); - void onLocalSymbolProxyEtsSymbolAdded(qint32 fileContentId, - const QString &name, - const QImage &image, - const QColor &colorToBeReplaced, - const QStringList &usrTags); - void onLocalSymbolProxyEtsSymbolRemoved(qint32 fileContentId, const QString &name); + protected: + void onGetFileContentDataReply(const FileManagement::GetFileContentDataReply& reply) override; - void onLocalSymbolProxyXmlSymbolAdded(qint32 fileContentId, - const QString &operatorName, - qint64 lastModified, - const QString &name, - const QString &xmlContent, - const QStringList &usrTags); - void onLocalSymbolProxyXmlSymbolRemoved(qint32 fileContentId); + bool svgToImage(const QByteArray& svgByteArray, QImage& imageOut); -protected: - + QString operatorName(int operatorId); - void onGetFileContentDataReply(const FileManagement::GetFileContentDataReply &reply) override; + void checkForReFetching(); - bool svgToImage(const QByteArray &svgByteArray, QImage &imageOut); - - QString operatorName(int operatorId); - - void checkForReFetching(); - -private: - struct Private; - - - Private *d = nullptr; + private: + struct Private; + Private* d = nullptr; }; -} +} // namespace AdvancedSymbology diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.cpp old mode 100755 new mode 100644 index d9716d709..a9d88c334 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.cpp @@ -1,7 +1,7 @@ - #include "alm_config_alarm_model.h" + #include #include #include @@ -9,156 +9,132 @@ namespace AlarmManagement { - - -ConfigAlarmModel::ConfigAlarmModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +ConfigAlarmModel::ConfigAlarmModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Equip. No."), tr("Designator"), tr("Tact. Identifier"), tr("Vulnerability State"), + tr("Event Type"), tr("Message Window"), tr("Set Marker")}, + parent), + m_dtc(nullptr), m_ppmDtc(nullptr), m_alarmHistoryModel(nullptr), m_global(false) { - tr("Id"), - tr("Equip. No."), - tr("Designator"), - tr("Tact. Identifier"), - tr("Vulnerability State"), - tr("Event Type"), - tr("Message Window"), - tr("Set Marker") -}, -parent) - , m_dtc(nullptr) - , m_ppmDtc(nullptr) - , m_alarmHistoryModel(nullptr) - , m_global(false) -{} - - -bool ConfigAlarmModel::initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ppmDtc, - AlarmHistoryModel *alarmHistoryModel, - bool global) -{ - m_dtc = dtc; - m_ppmDtc = ppmDtc; - m_alarmHistoryModel = alarmHistoryModel; - m_global = global; - - - const QMap alarmConfigs = m_dtc->alarmConfigs(); - INFO_LOG(m_logger) << "initModel - #AlarmConfig: " << alarmConfigs.size(); - - connect(m_dtc.get(), &Interface::Dtc::alarmConfigChanged, - this, &ConfigAlarmModel::onAlarmConfigChanged); - - m_dtc->enableAlarmConfig(); - auto cb = [this] (const AlarmManagement::AlarmConfig &d) - { - onAlarmConfigChanged(d, DataModification::eAdded); - }; - m_dtc->alarmConfigs(cb); - return true; } -QVariant ConfigAlarmModel::data(const QModelIndex &index, int role) const +bool ConfigAlarmModel::initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ppmDtc, + AlarmHistoryModel* alarmHistoryModel, bool global) { - DEBUG_LOG(m_logger) << "AlarmManagementModel::data"; + m_dtc = dtc; + m_ppmDtc = ppmDtc; + m_alarmHistoryModel = alarmHistoryModel; + m_global = global; - if (role != Qt::DisplayRole || !indexIsValid(index)) - return QVariant(); + const QMap alarmConfigs = m_dtc->alarmConfigs(); + INFO_LOG(m_logger) << "initModel - #AlarmConfig: " << alarmConfigs.size(); - const AlarmManagement::AlarmConfig &alarmConfig = m_vecData.at(index.row()); - if (alarmConfig.global() != m_global) - return QVariant(); + connect(m_dtc.get(), &Interface::Dtc::alarmConfigChanged, this, &ConfigAlarmModel::onAlarmConfigChanged); - switch (index.column()) - { - case Id: - return alarmConfig.id(); - case EquipmentNumber: - { - const int equipmentNumber = m_alarmHistoryModel->participantId2EquipNo(alarmConfig.participantId()); - if (equipmentNumber == 0) - return tr("All"); - return equipmentNumber; - } - case Designator: - return m_alarmHistoryModel->getDesignator(alarmConfig.participantId()); - case TactIdentifier: - return m_alarmHistoryModel->getTactIdentifier(alarmConfig.participantId()); - case VulnerabilityState: - { - QString vulnerabilityState = tr("All Types"); - if (alarmConfig.vulnerabilityState()>=0){ - ParticipantManagement::TypeClass typeClass = - m_ppmDtc->type(m_ppmDtc->participant(alarmConfig.participantId()).typeId()).typeClass(); - - const ProjectDataManagement::VulnerabilityClass vc = typeClass == ParticipantManagement::TypeClass::Human ? - ProjectDataManagement::VulnerabilityClass_def::SoldierInjuries : - ProjectDataManagement::VulnerabilityClass_def::VehicleDamages; - ProjectDataManagement::VulnerabilityState vs = static_cast(alarmConfig.vulnerabilityState()); - vulnerabilityState = ProjectDataManagement::toString(vs, vc); - } - return vulnerabilityState; - } - - case EventType: - return ProjectDataManagement::toString(alarmConfig.eventTypeId()); - case MessageWindow: - return alarmConfig.messageWindow() ? tr("Yes") : tr("No"); - case SetMarker: - return alarmConfig.setMarker() ? tr("Yes") : tr("No"); - } - - return QVariant(); + m_dtc->enableAlarmConfig(); + auto cb = [this](const AlarmManagement::AlarmConfig& d) { onAlarmConfigChanged(d, DataModification::eAdded); }; + m_dtc->alarmConfigs(cb); + return true; } - -void ConfigAlarmModel::onAlarmConfigChanged(const AlarmManagement::AlarmConfig &data, - const DataModification modType) +QVariant ConfigAlarmModel::data(const QModelIndex& index, int role) const { - const int id = data.id(); - if (data.global() != m_global) - return; + DEBUG_LOG(m_logger) << "AlarmManagementModel::data"; - int row = findRowForId(id); + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); - const int eventTypeId = data.eventTypeId().underlying(); - const bool messageWindow = data.messageWindow(); - const bool setMarker = data.setMarker(); - DEBUG_LOG(m_logger) << "onAlarmConfigChanged: " << eventTypeId << " messageWindow=" << messageWindow - << "setMarker"<participantId2EquipNo(data.participantId()) > 0) - setRowData(row, data); - break; - } - case DataModification::eAdded: - { - DEBUG_LOG(m_logger) << "DataModification::eAdded"; - insertRow(data); - } - break; - } + case Id: + return alarmConfig.id(); + case EquipmentNumber: { + const int equipmentNumber = m_alarmHistoryModel->participantId2EquipNo(alarmConfig.participantId()); + if (equipmentNumber == 0) + return tr("All"); + return equipmentNumber; + } + case Designator: + return m_alarmHistoryModel->getDesignator(alarmConfig.participantId()); + case TactIdentifier: + return m_alarmHistoryModel->getTactIdentifier(alarmConfig.participantId()); + case VulnerabilityState: { + QString vulnerabilityState = tr("All Types"); + if (alarmConfig.vulnerabilityState() >= 0) + { + ParticipantManagement::TypeClass typeClass = + m_ppmDtc->type(m_ppmDtc->participant(alarmConfig.participantId()).typeId()).typeClass(); + const ProjectDataManagement::VulnerabilityClass vc = + typeClass == ParticipantManagement::TypeClass::Human + ? ProjectDataManagement::VulnerabilityClass_def::SoldierInjuries + : ProjectDataManagement::VulnerabilityClass_def::VehicleDamages; + ProjectDataManagement::VulnerabilityState vs = + static_cast(alarmConfig.vulnerabilityState()); + vulnerabilityState = ProjectDataManagement::toString(vs, vc); + } + return vulnerabilityState; + } + + case EventType: + return ProjectDataManagement::toString(alarmConfig.eventTypeId()); + case MessageWindow: + return alarmConfig.messageWindow() ? tr("Yes") : tr("No"); + case SetMarker: + return alarmConfig.setMarker() ? tr("Yes") : tr("No"); + } + + return QVariant(); } -} +void ConfigAlarmModel::onAlarmConfigChanged(const AlarmManagement::AlarmConfig& data, const DataModification modType) +{ + const int id = data.id(); + if (data.global() != m_global) + return; + + int row = findRowForId(id); + + const int eventTypeId = data.eventTypeId().underlying(); + const bool messageWindow = data.messageWindow(); + const bool setMarker = data.setMarker(); + DEBUG_LOG(m_logger) << "onAlarmConfigChanged: " << eventTypeId << " messageWindow=" << messageWindow << "setMarker" + << setMarker; + + switch (modType) + { + case DataModification::eRemoved: { + + DEBUG_LOG(m_logger) << "AlarmConfig was removed: " << id; + AlarmManagement::AlarmConfig data1 = data; + data1.messageWindow(false); + data1.setMarker(false); + setRowData(row, data1); + removeRow(row); + return; + } + case DataModification::eModified: { + DEBUG_LOG(m_logger) << "DataModification::eModified: "; + if (row < 0) + { + + return; + } + if (m_alarmHistoryModel->participantId2EquipNo(data.participantId()) > 0) + setRowData(row, data); + break; + } + case DataModification::eAdded: { + DEBUG_LOG(m_logger) << "DataModification::eAdded"; + insertRow(data); + } + break; + } +} + +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.h old mode 100755 new mode 100644 index 38fc83f29..9422adc0b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_config_alarm_model.h @@ -1,54 +1,49 @@ - #pragma once +#include "alm_history_alarm_model.h" #include "almcommon_export.h" + #include #include - -#include #include -#include "alm_history_alarm_model.h" +#include namespace AlarmManagement { - - class ALMCOMMON_EXPORT ConfigAlarmModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Id, - EquipmentNumber, - Designator, - TactIdentifier, - VulnerabilityState, - EventType, - MessageWindow, - SetMarker - }; + Q_OBJECT + public: + enum Columns { + Id, + EquipmentNumber, + Designator, + TactIdentifier, + VulnerabilityState, + EventType, + MessageWindow, + SetMarker + }; - explicit ConfigAlarmModel(QObject *parent = nullptr); + explicit ConfigAlarmModel(QObject* parent = nullptr); - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ppmDtc, - AlarmHistoryModel *alarmHistoryModel, - bool global); + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ppmDtc, + AlarmHistoryModel* alarmHistoryModel, bool global); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -private slots: - void onAlarmConfigChanged(const AlarmManagement::AlarmConfig &data, - const DataModification modType); -private: -NGL::INGLLogger &m_logger; - std::shared_ptr m_dtc; - std::shared_ptr m_ppmDtc; - AlarmHistoryModel *m_alarmHistoryModel; - bool m_global; + private slots: + void onAlarmConfigChanged(const AlarmManagement::AlarmConfig& data, const DataModification modType); + + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_dtc; + std::shared_ptr m_ppmDtc; + AlarmHistoryModel* m_alarmHistoryModel; + bool m_global; }; -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.cpp old mode 100755 new mode 100644 index a2f9d4b78..021d506d8 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.cpp @@ -1,318 +1,282 @@ - #include "alm_history_alarm_model.h" -#include + +#include #include #include -#include #include #include #include #include #include +#include namespace AlarmManagement { - - -AlarmHistoryModel::AlarmHistoryModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +AlarmHistoryModel::AlarmHistoryModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + { + tr("Id"), + tr("Date"), + tr("Incident"), + tr("Equip. No."), + tr("Hierarchie"), + tr("Participant Id"), + tr("Position"), + tr("Aes Id"), + tr("Aes Name"), + }, + parent), + m_dtc(nullptr), m_ppmDtc(nullptr) { - tr("Id"), - tr("Date"), - tr("Incident"), - tr("Equip. No."), - tr("Hierarchie"), - tr("Participant Id"), - tr("Position"), - tr("Aes Id"), - tr("Aes Name"), -}, -parent) -, m_dtc(nullptr) -, m_ppmDtc(nullptr) -{} - - -bool AlarmHistoryModel::initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc) -{ - m_dtc = dtc; - m_ppmDtc = ppmDtc; - m_aesDtc = aesDtc; - - - - connect(m_dtc.get(), &Interface::Dtc::notificationChanged, - this, &AlarmHistoryModel::onNotificationChanged); - - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, - this, &AlarmHistoryModel::onParticipantChanged); - - m_ppmDtc->enableParticipant(); - m_dtc->enableNotification(); - - - const auto cbParticipants = [this](const ParticipantManagement::Participant & participant) - { - onParticipantChanged(participant, DataModification::eAdded); - }; - m_ppmDtc->participants(cbParticipants); - - - - - - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::borderlineChanged, - this, &AlarmHistoryModel::onAesItemChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::dangerAreaChanged, - this, &AlarmHistoryModel::onAesItemChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::nContaminationChanged, - this, &AlarmHistoryModel::onAesItemChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::bCContaminationChanged, - this, &AlarmHistoryModel::onBCContaminationChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::mineAreaChanged, - this, &AlarmHistoryModel::onAesItemChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::functionalAreaChanged, - this, &AlarmHistoryModel::onAesItemChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, - this, &AlarmHistoryModel::onBoobyTrapChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::offRouteMineChanged, - this, &AlarmHistoryModel::onOffRouteMineChanged); - - - auto cbAesItem = [this](const AreaEffectSimulation::AesItem & item) - { - onAesItemChanged(item, DataModification::eAdded); - }; - m_aesDtc->borderlines(cbAesItem); - m_aesDtc->dangerAreas(cbAesItem); - m_aesDtc->nContaminations(cbAesItem); - m_aesDtc->mineAreas(cbAesItem); - m_aesDtc->functionalAreas(cbAesItem); - m_aesDtc->boobyTraps(cbAesItem); - m_aesDtc->offRouteMines(cbAesItem); - - return true; -} - - -QVariant AlarmHistoryModel::data(const QModelIndex &index, int role) const -{ - if (!indexIsValid(index)) - return QVariant(); - if ((role != Qt::DisplayRole) && (role != Qt::UserRole) && (role != Qt::BackgroundRole)) - return QVariant(); - - const NotificationEx ¬ificationEx = m_vecData.at(index.row()); - - if (role == Qt::BackgroundRole) - { - if (notificationEx.eventType() == ProjectDataManagement::EventType_def::EmergencyCall) - return QColor(Qt::red); - return QVariant(); - } - - switch (index.column()) - { - case Id: - return notificationEx.id(); - case Date: - return QDateTime::fromMSecsSinceEpoch(notificationEx.time()); - case EquipmentNumber: - if (notificationEx.equipmentNumber) - return notificationEx.equipmentNumber; - break; - case Incident: - return ProjectDataManagement::toString(notificationEx.eventTypeId); - case Hierarchie: - return m_ppmDtc->hierarchyFromParticipant(notificationEx.participantId); - case ParticipantId: - return notificationEx.participantId; - case Position: - if (role == Qt::DisplayRole) - return LtsCoordTrans::mgrsFromGeographic(notificationEx.position().lon(), notificationEx.position().lat()); - else if (role == Qt::UserRole) - return QPointF(notificationEx.position().lon(), notificationEx.position().lat()); - break; - case AesId: - return notificationEx.aesId; - case AesName: - - return m_aesNameMap.value(notificationEx.aesId, tr("-")); - } - return QVariant(); -} - - -bool AlarmHistoryModel::isFiltered(const NotificationEx &data, DataModification modType) const -{ - Q_UNUSED(modType); - if (data.operatorId() == 0) - return false; - return data.operatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); } -void AlarmHistoryModel::onNotificationChanged(const AlarmManagement::Notification &data, - const DataModification modType) +bool AlarmHistoryModel::initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc) { - if (modType == DataModification::eRemoved) - return; + m_dtc = dtc; + m_ppmDtc = ppmDtc; + m_aesDtc = aesDtc; - NotificationEx notification(data); - const QByteArray properties = QByteArray::fromRawData(data.properties().c_str(), data.properties().size()); - const QJsonDocument propertieJsonDoc = QJsonDocument::fromJson(properties); - const QJsonObject propertieJsonObj = propertieJsonDoc.object(); + connect(m_dtc.get(), &Interface::Dtc::notificationChanged, this, &AlarmHistoryModel::onNotificationChanged); - notification.equipmentNumber = data.equipmentNumber(); - if (data.participantId().is_set()) - notification.participantId = data.participantId().get(); - notification.eventTypeId = data.eventType(); - if (data.aesId().is_set()) - notification.aesId = data.aesId().get(); - const int global = propertieJsonObj[QStringLiteral("Global")].toInt(); - const int friendlyFire = propertieJsonObj[QStringLiteral("FriendlyFire")].toInt(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, this, + &AlarmHistoryModel::onParticipantChanged); - DEBUG_LOG(m_logger) << Q_FUNC_INFO - << " notification:" << data - << ", Global: " << global - << ", FriendlyFire: " << friendlyFire; + m_ppmDtc->enableParticipant(); + m_dtc->enableNotification(); - onDataChanged(notification, modType); -} + const auto cbParticipants = [this](const ParticipantManagement::Participant& participant) { + onParticipantChanged(participant, DataModification::eAdded); + }; + m_ppmDtc->participants(cbParticipants); -void AlarmHistoryModel::onParticipantChanged(const ParticipantManagement::Participant &participant, + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::borderlineChanged, this, + &AlarmHistoryModel::onAesItemChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::dangerAreaChanged, this, + &AlarmHistoryModel::onAesItemChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::nContaminationChanged, this, + &AlarmHistoryModel::onAesItemChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::bCContaminationChanged, this, + &AlarmHistoryModel::onBCContaminationChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::mineAreaChanged, this, + &AlarmHistoryModel::onAesItemChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::functionalAreaChanged, this, + &AlarmHistoryModel::onAesItemChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, this, + &AlarmHistoryModel::onBoobyTrapChanged); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::offRouteMineChanged, this, + &AlarmHistoryModel::onOffRouteMineChanged); + + auto cbAesItem = [this](const AreaEffectSimulation::AesItem& item) { + onAesItemChanged(item, DataModification::eAdded); + }; + m_aesDtc->borderlines(cbAesItem); + m_aesDtc->dangerAreas(cbAesItem); + m_aesDtc->nContaminations(cbAesItem); + m_aesDtc->mineAreas(cbAesItem); + m_aesDtc->functionalAreas(cbAesItem); + m_aesDtc->boobyTraps(cbAesItem); + m_aesDtc->offRouteMines(cbAesItem); + + return true; +} + +QVariant AlarmHistoryModel::data(const QModelIndex& index, int role) const +{ + if (!indexIsValid(index)) + return QVariant(); + if ((role != Qt::DisplayRole) && (role != Qt::UserRole) && (role != Qt::BackgroundRole)) + return QVariant(); + + const NotificationEx& notificationEx = m_vecData.at(index.row()); + + if (role == Qt::BackgroundRole) + { + if (notificationEx.eventType() == ProjectDataManagement::EventType_def::EmergencyCall) + return QColor(Qt::red); + return QVariant(); + } + + switch (index.column()) + { + case Id: + return notificationEx.id(); + case Date: + return QDateTime::fromMSecsSinceEpoch(notificationEx.time()); + case EquipmentNumber: + if (notificationEx.equipmentNumber) + return notificationEx.equipmentNumber; + break; + case Incident: + return ProjectDataManagement::toString(notificationEx.eventTypeId); + case Hierarchie: + return m_ppmDtc->hierarchyFromParticipant(notificationEx.participantId); + case ParticipantId: + return notificationEx.participantId; + case Position: + if (role == Qt::DisplayRole) + return LtsCoordTrans::mgrsFromGeographic(notificationEx.position().lon(), + notificationEx.position().lat()); + else if (role == Qt::UserRole) + return QPointF(notificationEx.position().lon(), notificationEx.position().lat()); + break; + case AesId: + return notificationEx.aesId; + case AesName: + + return m_aesNameMap.value(notificationEx.aesId, tr("-")); + } + return QVariant(); +} + +bool AlarmHistoryModel::isFiltered(const NotificationEx& data, DataModification modType) const +{ + Q_UNUSED(modType); + if (data.operatorId() == 0) + return false; + return data.operatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); +} + +void AlarmHistoryModel::onNotificationChanged(const AlarmManagement::Notification& data, const DataModification modType) +{ + if (modType == DataModification::eRemoved) + return; + + NotificationEx notification(data); + const QByteArray properties = QByteArray::fromRawData(data.properties().c_str(), data.properties().size()); + const QJsonDocument propertieJsonDoc = QJsonDocument::fromJson(properties); + const QJsonObject propertieJsonObj = propertieJsonDoc.object(); + + notification.equipmentNumber = data.equipmentNumber(); + if (data.participantId().is_set()) + notification.participantId = data.participantId().get(); + notification.eventTypeId = data.eventType(); + if (data.aesId().is_set()) + notification.aesId = data.aesId().get(); + const int global = propertieJsonObj[QStringLiteral("Global")].toInt(); + const int friendlyFire = propertieJsonObj[QStringLiteral("FriendlyFire")].toInt(); + + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " notification:" << data << ", Global: " << global + << ", FriendlyFire: " << friendlyFire; + + onDataChanged(notification, modType); +} + +void AlarmHistoryModel::onParticipantChanged(const ParticipantManagement::Participant& participant, const DataModification modType) { - if (modType == DataModification::eRemoved) - return; - QString designator = QString::fromStdString(participant.designator()); - m_idDesignatorMap.insert(participant.id(), designator); + if (modType == DataModification::eRemoved) + return; + QString designator = QString::fromStdString(participant.designator()); + m_idDesignatorMap.insert(participant.id(), designator); - const int equipNo = participant.equipmentNumber().is_set() ? participant.equipmentNumber().get() : 0; - m_partId2EquipNoMap.insert(participant.id(), equipNo); + const int equipNo = participant.equipmentNumber().is_set() ? participant.equipmentNumber().get() : 0; + m_partId2EquipNoMap.insert(participant.id(), equipNo); - QString tacticalIdentifier = QString::fromStdString(participant.tacticalIdentifier()); - m_idTactIdentifierMap.insert(participant.id(), tacticalIdentifier); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id=" << participant.id() - << " designator=" << designator - << " tacticalIdentifier=" << tacticalIdentifier; -} + QString tacticalIdentifier = QString::fromStdString(participant.tacticalIdentifier()); + m_idTactIdentifierMap.insert(participant.id(), tacticalIdentifier); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id=" << participant.id() << " designator=" << designator + << " tacticalIdentifier=" << tacticalIdentifier; +} int AlarmHistoryModel::participantId2EquipNo(const int participantId) const { - int ret = m_partId2EquipNoMap.value(participantId, 0); - INFO_LOG(m_logger) << "participantId2EquipNo participantId=" << participantId - << " EquipmentNumber=" << ret; - return ret; -} + int ret = m_partId2EquipNoMap.value(participantId, 0); + INFO_LOG(m_logger) << "participantId2EquipNo participantId=" << participantId << " EquipmentNumber=" << ret; + return ret; +} QString AlarmHistoryModel::getDesignator(const int participantId) const { - QString designator = m_idDesignatorMap.value(participantId); - DEBUG_LOG(m_logger) << "m_idDesignatorMap.value(participantId)=" << designator; + QString designator = m_idDesignatorMap.value(participantId); + DEBUG_LOG(m_logger) << "m_idDesignatorMap.value(participantId)=" << designator; - return designator; + return designator; } QString AlarmHistoryModel::getTactIdentifier(const int participantId) const { - QString tactIdentifier = m_idTactIdentifierMap.value(participantId); - DEBUG_LOG(m_logger) << "m_idTactIdentifierMap.value(participantId)=" << tactIdentifier; + QString tactIdentifier = m_idTactIdentifierMap.value(participantId); + DEBUG_LOG(m_logger) << "m_idTactIdentifierMap.value(participantId)=" << tactIdentifier; - return tactIdentifier; + return tactIdentifier; } -void AlarmHistoryModel::onBCContaminationChanged(const AreaEffectSimulation::BCContamination &data, - const DataModification modType) +void AlarmHistoryModel::onBCContaminationChanged(const AreaEffectSimulation::BCContamination& data, + const DataModification modType) { - if (modType == DataModification::eRemoved) - return; - int id = data.id(); - QString name = QString::fromStdString(data.name()); - m_aesNameMap[id] = name; - DEBUG_LOG(m_logger) << "onBCContaminationChanged: " << data - << " Name=" << name - << " id=" << id; + if (modType == DataModification::eRemoved) + return; + int id = data.id(); + QString name = QString::fromStdString(data.name()); + m_aesNameMap[id] = name; + DEBUG_LOG(m_logger) << "onBCContaminationChanged: " << data << " Name=" << name << " id=" << id; } -void AlarmHistoryModel::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &data, - const DataModification modType) +void AlarmHistoryModel::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& data, const DataModification modType) { - if (modType == DataModification::eRemoved) - return; - int id = data.id(); - QString name = QString::fromStdString(data.name()); - m_aesNameMap[id] = name; - DEBUG_LOG(m_logger) << "BoobyTrap: " << data - << " Name=" << name - << " id=" << id; + if (modType == DataModification::eRemoved) + return; + int id = data.id(); + QString name = QString::fromStdString(data.name()); + m_aesNameMap[id] = name; + DEBUG_LOG(m_logger) << "BoobyTrap: " << data << " Name=" << name << " id=" << id; } -void AlarmHistoryModel::onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine &data, - const DataModification modType) +void AlarmHistoryModel::onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine& data, + const DataModification modType) { - if (modType == DataModification::eRemoved) - return; - int id = data.id(); - QString name = QString::fromStdString(data.name()); - m_aesNameMap[id] = name; - DEBUG_LOG(m_logger) << "OffRouteMine: " << data - << " Name=" << name - << " id=" << id; + if (modType == DataModification::eRemoved) + return; + int id = data.id(); + QString name = QString::fromStdString(data.name()); + m_aesNameMap[id] = name; + DEBUG_LOG(m_logger) << "OffRouteMine: " << data << " Name=" << name << " id=" << id; } -void AlarmHistoryModel::onAesItemChanged(const AreaEffectSimulation::AesItem &item, - const DataModification modType) +void AlarmHistoryModel::onAesItemChanged(const AreaEffectSimulation::AesItem& item, const DataModification modType) { - if (modType == DataModification::eRemoved) - return; - QString name = QString::fromStdString(item.name()); - int id = item.id(); - m_aesNameMap[id] = name; - DEBUG_LOG(m_logger) << "AreaEffectSimulation::AesItem onAesItemChanged: " << item - << " Name=" << name - << " id=" << item.id(); -} - - - - -void AlarmHistoryProxyModel::setSourceModel(QAbstractItemModel *sourceModel) -{ - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + if (modType == DataModification::eRemoved) + return; + QString name = QString::fromStdString(item.name()); + int id = item.id(); + m_aesNameMap[id] = name; + DEBUG_LOG(m_logger) << "AreaEffectSimulation::AesItem onAesItemChanged: " << item << " Name=" << name + << " id=" << item.id(); } -bool AlarmHistoryProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +void AlarmHistoryProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); +} + +bool AlarmHistoryProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const +{ + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case AlarmHistoryModel::Date: + return dataLeft.time() < dataRight.time(); + + case AlarmHistoryModel::Id: + case AlarmHistoryModel::Incident: + case AlarmHistoryModel::EquipmentNumber: + case AlarmHistoryModel::Hierarchie: + case AlarmHistoryModel::ParticipantId: + case AlarmHistoryModel::Position: + case AlarmHistoryModel::AesId: + case AlarmHistoryModel::AesName: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case AlarmHistoryModel::Date: - return dataLeft.time() < dataRight.time(); - - case AlarmHistoryModel::Id: - case AlarmHistoryModel::Incident: - case AlarmHistoryModel::EquipmentNumber: - case AlarmHistoryModel::Hierarchie: - case AlarmHistoryModel::ParticipantId: - case AlarmHistoryModel::Position: - case AlarmHistoryModel::AesId: - case AlarmHistoryModel::AesName: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } -} - - +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.h old mode 100755 new mode 100644 index 22948d44a..23184ef51 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/Common/alm_history_alarm_model.h @@ -1,107 +1,84 @@ - #pragma once #include "almcommon_export.h" -#include -#include -#include -#include +#include +#include +#include #include #include +#include namespace AlarmManagement { - - struct NotificationEx : public AlarmManagement::Notification { - int equipmentNumber = 0; - int participantId = 0; - int aesId = 0; - ProjectDataManagement::EventType eventTypeId = ProjectDataManagement::EventType::Unknown; + int equipmentNumber = 0; + int participantId = 0; + int aesId = 0; + ProjectDataManagement::EventType eventTypeId = ProjectDataManagement::EventType::Unknown; - NotificationEx() = default; - explicit NotificationEx(const AlarmManagement::Notification &n) - : AlarmManagement::Notification(n) - {} + NotificationEx() = default; + + explicit NotificationEx(const AlarmManagement::Notification& n) : AlarmManagement::Notification(n) {} }; class ALMCOMMON_EXPORT AlarmHistoryModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: + Q_OBJECT + public: + enum Columns { Id, Date, Incident, EquipmentNumber, Hierarchie, ParticipantId, Position, AesId, AesName }; - enum Columns - { - Id, - Date, - Incident, - EquipmentNumber, - Hierarchie, - ParticipantId, - Position, - AesId, - AesName - }; + explicit AlarmHistoryModel(QObject* parent = nullptr); - explicit AlarmHistoryModel(QObject *parent = nullptr); + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc); - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc); + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int participantId2EquipNo(const int participantId) const; + QString getDesignator(const int participantId) const; + QString getTactIdentifier(const int participantId) const; - + protected: + NGL::INGLLogger& m_logger; + bool isFiltered(const NotificationEx& data, DataModification modType) const override; + private slots: + void onNotificationChanged(const AlarmManagement::Notification& data, const DataModification modType); + void onParticipantChanged(const ParticipantManagement::Participant& participant, const DataModification modType); + void onAesItemChanged(const AreaEffectSimulation::AesItem& item, const DataModification modType); + void onBCContaminationChanged(const AreaEffectSimulation::BCContamination& data, const DataModification modType); + void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& data, const DataModification modType); + void onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine& data, const DataModification modType); - int participantId2EquipNo(const int participantId) const; - QString getDesignator(const int participantId) const; - QString getTactIdentifier(const int participantId) const; + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_aesDtc; -protected: + QMap m_partId2EquipNoMap; + QHash m_idDesignatorMap; + QHash m_idTactIdentifierMap; + QHash m_aesNameMap; -NGL::INGLLogger &m_logger; - bool isFiltered(const NotificationEx &data, DataModification modType) const override; -private slots: - void onNotificationChanged(const AlarmManagement::Notification &data, - const DataModification modType); - void onParticipantChanged(const ParticipantManagement::Participant &participant, - const DataModification modType); - void onAesItemChanged(const AreaEffectSimulation::AesItem &item, - const DataModification modType); - void onBCContaminationChanged(const AreaEffectSimulation::BCContamination &data, - const DataModification modType); - void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &data, - const DataModification modType); - void onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine &data, - const DataModification modType); - -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_aesDtc; - - QMap m_partId2EquipNoMap; - QHash m_idDesignatorMap; - QHash m_idTactIdentifierMap; - QHash m_aesNameMap; - - friend class AlarmHistoryProxyModel; + friend class AlarmHistoryProxyModel; }; class ALMCOMMON_EXPORT AlarmHistoryProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - AlarmHistoryModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + AlarmHistoryModel* m_sourceModel = nullptr; }; -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_dialog.cpp old mode 100755 new mode 100644 index 10dc5e716..6f9a156fb --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_dialog.cpp @@ -1,311 +1,287 @@ - #include "alm_dialog.h" -#include -#include "ui_alm_dialog.h" + #include "alm_history.h" -#include -#include +#include "ui_alm_dialog.h" #include -#include -#include #include +#include +#include +#include +#include +#include namespace AlarmManagement { -AlarmDialog::AlarmDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_configAlarmModel(nullptr) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_ui(new Ui::AlarmDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_operatorId(-1) +AlarmDialog::AlarmDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_configAlarmModel(nullptr), + m_dtc(nullptr), m_ftc(nullptr), m_ui(new Ui::AlarmDialog), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_operatorId(-1) { - AlarmCheckBox alarmCheckBox; - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); + AlarmCheckBox alarmCheckBox; + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableNuclearContaminations = ps->value(QLatin1String("aes"), - QLatin1String("enableNuclearContaminations")).toBool(); - const bool enableDangerAreas = ps->value(QLatin1String("aes"), - QLatin1String("enableDangerAreas")).toBool(); - const bool enableMineAreas = ps->value(QLatin1String("aes"), - QLatin1String("enableMineAreas")).toBool(); + const bool enableNuclearContaminations = + ps->value(QLatin1String("aes"), QLatin1String("enableNuclearContaminations")).toBool(); + const bool enableDangerAreas = ps->value(QLatin1String("aes"), QLatin1String("enableDangerAreas")).toBool(); + const bool enableMineAreas = ps->value(QLatin1String("aes"), QLatin1String("enableMineAreas")).toBool(); - m_ui->setupUi(this); + m_ui->setupUi(this); - if (!enableNuclearContaminations) - { - m_ui->lblNAgentEntry->hide(); - m_ui->cbxNMarker->hide(); - m_ui->cbxNMessage->hide(); - } + if (!enableNuclearContaminations) + { + m_ui->lblNAgentEntry->hide(); + m_ui->cbxNMarker->hide(); + m_ui->cbxNMessage->hide(); + } - if (!enableDangerAreas) - { - m_ui->lblDangerAreaEntry->hide(); - m_ui->cbxDanerAreaMarker->hide(); - m_ui->cbxDangerAreaMessage->hide(); - } - if (!enableMineAreas) - { - m_ui->lblMineAreaEntry->hide(); - m_ui->cbxMineAreaEntryMarker->hide(); - m_ui->cbxMineAreaEntryMessage->hide(); - m_ui->lblMineAreaHit->hide(); - m_ui->cbxMineAreaHitMarker->hide(); - m_ui->cbxMineAreaHitMessage->hide(); - } + if (!enableDangerAreas) + { + m_ui->lblDangerAreaEntry->hide(); + m_ui->cbxDanerAreaMarker->hide(); + m_ui->cbxDangerAreaMessage->hide(); + } + if (!enableMineAreas) + { + m_ui->lblMineAreaEntry->hide(); + m_ui->cbxMineAreaEntryMarker->hide(); + m_ui->cbxMineAreaEntryMessage->hide(); + m_ui->lblMineAreaHit->hide(); + m_ui->cbxMineAreaHitMarker->hide(); + m_ui->cbxMineAreaHitMessage->hide(); + } - alarmCheckBox.name = QLatin1String("NuclearAgentEntry"); - alarmCheckBox.checkboxMarker = m_ui->cbxNMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxNMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterNuclear; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("NuclearAgentEntry"); + alarmCheckBox.checkboxMarker = m_ui->cbxNMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxNMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterNuclear; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("DangerAreasEntry"); - alarmCheckBox.checkboxMarker = m_ui->cbxDanerAreaMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxDangerAreaMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterDangerArea; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("DangerAreasEntry"); + alarmCheckBox.checkboxMarker = m_ui->cbxDanerAreaMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxDangerAreaMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterDangerArea; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("MineAreaEntry"); - alarmCheckBox.checkboxMarker = m_ui->cbxMineAreaEntryMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxMineAreaEntryMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterMineArea; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("MineAreaEntry"); + alarmCheckBox.checkboxMarker = m_ui->cbxMineAreaEntryMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxMineAreaEntryMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::EnterMineArea; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("MineAreaHit"); - alarmCheckBox.checkboxMarker = m_ui->cbxMineAreaHitMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxMineAreaHitMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::HitMine; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("MineAreaHit"); + alarmCheckBox.checkboxMarker = m_ui->cbxMineAreaHitMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxMineAreaHitMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::HitMine; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("DirectFire"); - alarmCheckBox.checkboxMarker = m_ui->cbxDirectFireMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxDirectFireMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::Hit; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("DirectFire"); + alarmCheckBox.checkboxMarker = m_ui->cbxDirectFireMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxDirectFireMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::Hit; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("IndirectFire"); - alarmCheckBox.checkboxMarker = m_ui->cbxIndirectFireMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxIndirectFireMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::HitEffectSimulation; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("IndirectFire"); + alarmCheckBox.checkboxMarker = m_ui->cbxIndirectFireMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxIndirectFireMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::HitEffectSimulation; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("CrossLocalBorderlines"); - alarmCheckBox.checkboxMarker = m_ui->cbxLocalBorderMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxLocalBorderMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::CrossLocalBorderline; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("CrossLocalBorderlines"); + alarmCheckBox.checkboxMarker = m_ui->cbxLocalBorderMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxLocalBorderMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::CrossLocalBorderline; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("CrossGlobalBorderlines"); - alarmCheckBox.checkboxMarker = m_ui->cbxGlobalBorderMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxGlobalBorderMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::CrossGlobalBorderline; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("CrossGlobalBorderlines"); + alarmCheckBox.checkboxMarker = m_ui->cbxGlobalBorderMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxGlobalBorderMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::CrossGlobalBorderline; + m_checkBoxes.append(alarmCheckBox); - alarmCheckBox.name = QLatin1String("AirSupport"); - alarmCheckBox.checkboxMarker = m_ui->cbxAirSupportMarker; - alarmCheckBox.checkboxWindow = m_ui->cbxAirSupportMessage; - alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::AirSupport; - m_checkBoxes.append(alarmCheckBox); + alarmCheckBox.name = QLatin1String("AirSupport"); + alarmCheckBox.checkboxMarker = m_ui->cbxAirSupportMarker; + alarmCheckBox.checkboxWindow = m_ui->cbxAirSupportMessage; + alarmCheckBox.eventTypeId = ProjectDataManagement::EventType::AirSupport; + m_checkBoxes.append(alarmCheckBox); - setOnlineHelpFilename(QLatin1String("Situation-Configure_Global_Alarms")); + setOnlineHelpFilename(QLatin1String("Situation-Configure_Global_Alarms")); } AlarmDialog::~AlarmDialog() { - delete m_ui; + delete m_ui; } -bool AlarmDialog::init(const std::shared_ptr &ftc, - const std::shared_ptr &dtc, - const std::shared_ptr &ppmDtc, - AlarmHistoryModel *alarmHistoryModel) +bool AlarmDialog::init(const std::shared_ptr& ftc, + const std::shared_ptr& dtc, + const std::shared_ptr& ppmDtc, + AlarmHistoryModel* alarmHistoryModel) { - if (!ftc) - return false; - if (!dtc) - return false; - if (!ppmDtc) - return false; + if (!ftc) + return false; + if (!dtc) + return false; + if (!ppmDtc) + return false; - m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - m_ftc = ftc; - m_dtc = dtc; + m_ftc = ftc; + m_dtc = dtc; - connect(m_dtc.get(), &AlarmManagement::Interface::Dtc::alarmConfigChanged, - this, &AlarmDialog::onAlarmConfigChanged); - m_dtc->enableAlarmConfig(); + connect(m_dtc.get(), &AlarmManagement::Interface::Dtc::alarmConfigChanged, this, + &AlarmDialog::onAlarmConfigChanged); + m_dtc->enableAlarmConfig(); - auto cbConfig = [this](const AlarmManagement::AlarmConfig & c) - { - onAlarmConfigChanged(c, DataModification::eAdded); - }; - m_dtc->alarmConfigs(cbConfig); + auto cbConfig = [this](const AlarmManagement::AlarmConfig& c) { + onAlarmConfigChanged(c, DataModification::eAdded); + }; + m_dtc->alarmConfigs(cbConfig); - delete m_configAlarmModel; - m_configAlarmModel = new AlarmManagement::ConfigAlarmModel(this); - bool global = true; - m_configAlarmModel->initModel(m_dtc, ppmDtc, alarmHistoryModel, global); + delete m_configAlarmModel; + m_configAlarmModel = new AlarmManagement::ConfigAlarmModel(this); + bool global = true; + m_configAlarmModel->initModel(m_dtc, ppmDtc, alarmHistoryModel, global); - INFO_LOG(m_logger) << "AlarmDialog::init"; - return true; + INFO_LOG(m_logger) << "AlarmDialog::init"; + return true; } void AlarmDialog::retranslate() { - translate(m_ui, tr("Configure Global Alarms")); + translate(m_ui, tr("Configure Global Alarms")); } -void AlarmDialog::onAlarmConfigChanged(const AlarmManagement::AlarmConfig &data, DataModification modType) +void AlarmDialog::onAlarmConfigChanged(const AlarmManagement::AlarmConfig& data, DataModification modType) { - bool setMarker = data.setMarker(); - bool messageWindow = data.messageWindow(); - if (modType == DataModification::eRemoved) - return; + bool setMarker = data.setMarker(); + bool messageWindow = data.messageWindow(); + if (modType == DataModification::eRemoved) + return; - DEBUG_LOG(m_logger) << "************** onAlarmConfigChanged " - << " id=" << data.id() - << " operatorId=" << data.operatorId() - << " m_operatorId=" << m_operatorId - << " participantId=" << data.participantId() - << " eventTypeId=" << data.eventTypeId() - << " messageWindow=" << messageWindow - << " setMarker=" << setMarker; - if (data.global() == false) - return; + DEBUG_LOG(m_logger) << "************** onAlarmConfigChanged " + << " id=" << data.id() << " operatorId=" << data.operatorId() + << " m_operatorId=" << m_operatorId << " participantId=" << data.participantId() + << " eventTypeId=" << data.eventTypeId() << " messageWindow=" << messageWindow + << " setMarker=" << setMarker; + if (data.global() == false) + return; - if (data.operatorId() == m_operatorId) - { - DEBUG_LOG(m_logger) << "************** onAlarmConfig zuweisen "; - switch (data.eventTypeId().underlying()) + if (data.operatorId() == m_operatorId) { - case ProjectDataManagement::EventType_def::EnterNuclear: - { - DEBUG_LOG(m_logger) << "EnterNuclear zuweisen "; - m_ui->cbxNMarker->setChecked(setMarker); - m_ui->cbxNMessage->setChecked(messageWindow); - break; - } - case ProjectDataManagement::EventType_def::EnterDangerArea: - { - DEBUG_LOG(m_logger) << "EnterDangerArea zuweisen "; - m_ui->cbxDanerAreaMarker->setChecked(setMarker); - m_ui->cbxDangerAreaMessage->setChecked(messageWindow); - break; - } - case ProjectDataManagement::EventType_def::EnterMineArea: - { - DEBUG_LOG(m_logger) << "EnterMineArea zuweisen "; - m_ui->cbxMineAreaEntryMarker->setChecked(setMarker); - m_ui->cbxMineAreaEntryMessage->setChecked(messageWindow); - break; - } - case ProjectDataManagement::EventType_def::HitMine: - { - DEBUG_LOG(m_logger) << "HitMine zuweisen "; - m_ui->cbxMineAreaHitMarker->setChecked(setMarker); - m_ui->cbxMineAreaHitMessage->setChecked(messageWindow); - break; - } + DEBUG_LOG(m_logger) << "************** onAlarmConfig zuweisen "; + switch (data.eventTypeId().underlying()) + { + case ProjectDataManagement::EventType_def::EnterNuclear: { + DEBUG_LOG(m_logger) << "EnterNuclear zuweisen "; + m_ui->cbxNMarker->setChecked(setMarker); + m_ui->cbxNMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::EnterDangerArea: { + DEBUG_LOG(m_logger) << "EnterDangerArea zuweisen "; + m_ui->cbxDanerAreaMarker->setChecked(setMarker); + m_ui->cbxDangerAreaMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::EnterMineArea: { + DEBUG_LOG(m_logger) << "EnterMineArea zuweisen "; + m_ui->cbxMineAreaEntryMarker->setChecked(setMarker); + m_ui->cbxMineAreaEntryMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::HitMine: { + DEBUG_LOG(m_logger) << "HitMine zuweisen "; + m_ui->cbxMineAreaHitMarker->setChecked(setMarker); + m_ui->cbxMineAreaHitMessage->setChecked(messageWindow); + break; + } - case ProjectDataManagement::EventType_def::Hit: - { - DEBUG_LOG(m_logger) << "Hit zuweisen "; - m_ui->cbxDirectFireMarker->setChecked(setMarker); - m_ui->cbxDirectFireMessage->setChecked(messageWindow); - break; - } - case ProjectDataManagement::EventType_def::HitEffectSimulation: - { - DEBUG_LOG(m_logger) << "HitEffectSimulation zuweisen "; - m_ui->cbxIndirectFireMarker->setChecked(setMarker); - m_ui->cbxIndirectFireMessage->setChecked(messageWindow); - break; - } + case ProjectDataManagement::EventType_def::Hit: { + DEBUG_LOG(m_logger) << "Hit zuweisen "; + m_ui->cbxDirectFireMarker->setChecked(setMarker); + m_ui->cbxDirectFireMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::HitEffectSimulation: { + DEBUG_LOG(m_logger) << "HitEffectSimulation zuweisen "; + m_ui->cbxIndirectFireMarker->setChecked(setMarker); + m_ui->cbxIndirectFireMessage->setChecked(messageWindow); + break; + } - case ProjectDataManagement::EventType_def::CrossLocalBorderline: - { - DEBUG_LOG(m_logger) << "CrossLocalBorderline zuweisen "; - m_ui->cbxLocalBorderMarker->setChecked(setMarker); - m_ui->cbxLocalBorderMessage->setChecked(messageWindow); - break; + case ProjectDataManagement::EventType_def::CrossLocalBorderline: { + DEBUG_LOG(m_logger) << "CrossLocalBorderline zuweisen "; + m_ui->cbxLocalBorderMarker->setChecked(setMarker); + m_ui->cbxLocalBorderMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::CrossGlobalBorderline: { + DEBUG_LOG(m_logger) << "CrossGlobalBorderline zuweisen "; + m_ui->cbxGlobalBorderMarker->setChecked(setMarker); + m_ui->cbxGlobalBorderMessage->setChecked(messageWindow); + break; + } + case ProjectDataManagement::EventType_def::AirSupport: { + DEBUG_LOG(m_logger) << "AirSupport zuweisen "; + m_ui->cbxAirSupportMarker->setChecked(setMarker); + m_ui->cbxAirSupportMessage->setChecked(messageWindow); + break; + } + default: + ERROR_LOG(m_logger) << "Not possible to set with Operator App!!!"; + break; + } } - case ProjectDataManagement::EventType_def::CrossGlobalBorderline: - { - DEBUG_LOG(m_logger) << "CrossGlobalBorderline zuweisen "; - m_ui->cbxGlobalBorderMarker->setChecked(setMarker); - m_ui->cbxGlobalBorderMessage->setChecked(messageWindow); - break; - } - case ProjectDataManagement::EventType_def::AirSupport: - { - DEBUG_LOG(m_logger) << "AirSupport zuweisen "; - m_ui->cbxAirSupportMarker->setChecked(setMarker); - m_ui->cbxAirSupportMessage->setChecked(messageWindow); - break; - } - default: - ERROR_LOG(m_logger) << "Not possible to set with Operator App!!!"; - break; - } - } - -} - +} std::vector AlarmDialog::getCheckedValues() const { - AlarmManagement::AlarmAction alarmActionDds; - std::vector ret; - ret.clear(); - ret.reserve(m_checkBoxes.size()); - for (const AlarmCheckBox &item : std::as_const(m_checkBoxes)) - { - alarmActionDds.eventTypeId(item.eventTypeId); - if (item.checkboxMarker->isChecked()) + AlarmManagement::AlarmAction alarmActionDds; + std::vector ret; + ret.clear(); + ret.reserve(m_checkBoxes.size()); + for (const AlarmCheckBox& item : std::as_const(m_checkBoxes)) { - alarmActionDds.setMarker(true); - DEBUG_LOG(m_logger) << item.name << " setMarker = true"; + alarmActionDds.eventTypeId(item.eventTypeId); + if (item.checkboxMarker->isChecked()) + { + alarmActionDds.setMarker(true); + DEBUG_LOG(m_logger) << item.name << " setMarker = true"; + } + else + { + alarmActionDds.setMarker(false); + DEBUG_LOG(m_logger) << item.name << " setMarker = false"; + } + if (item.checkboxWindow->isChecked()) + { + alarmActionDds.messageWindow(true); + DEBUG_LOG(m_logger) << item.name << " messageWindow = true"; + } + else + { + alarmActionDds.messageWindow(false); + DEBUG_LOG(m_logger) << item.name << " messageWindow = false"; + } + if (alarmActionDds.setMarker() || alarmActionDds.messageWindow()) + ret.push_back(alarmActionDds); } - else - { - alarmActionDds.setMarker(false); - DEBUG_LOG(m_logger) << item.name << " setMarker = false"; - } - if (item.checkboxWindow->isChecked()) - { - alarmActionDds.messageWindow(true); - DEBUG_LOG(m_logger) << item.name << " messageWindow = true"; - } - else - { - alarmActionDds.messageWindow(false); - DEBUG_LOG(m_logger) << item.name << " messageWindow = false"; - } - if (alarmActionDds.setMarker() || alarmActionDds.messageWindow()) - ret.push_back(alarmActionDds); - } - return ret; + return ret; } bool AlarmDialog::apply() { - std::vector participantIds; - participantIds.push_back(0); - bool globalEvent = true; - bool remove = false; - const ConfigureAlarmsRequest req(getCheckedValues(), m_operatorId, participantIds, globalEvent, remove); + std::vector participantIds; + participantIds.push_back(0); + bool globalEvent = true; + bool remove = false; + const ConfigureAlarmsRequest req(getCheckedValues(), m_operatorId, participantIds, globalEvent, remove); - return m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->configureAlarmsRequest(req, this); - }); -} -} + return m_requestHelper->startSingleRequest([req, this]() { return m_ftc->configureAlarmsRequest(req, this); }); +} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.cpp old mode 100755 new mode 100644 index 6b22abadc..929e861ee --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.cpp @@ -1,163 +1,142 @@ - #include "alm_history.h" + #include "ui_alm_history.h" -#include -#include - #include +#include +#include #include namespace AlarmManagement { -AlarmView::AlarmView(LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_alarmHistoryModel(nullptr) - , m_dtc(nullptr) - , m_sitMapGuiIfc(nullptr) - , m_session(session) - , m_ui(new Ui::AlarmView) +AlarmView::AlarmView(LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_alarmHistoryModel(nullptr), + m_dtc(nullptr), m_sitMapGuiIfc(nullptr), m_session(session), m_ui(new Ui::AlarmView) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " --- AlarmView Konstruktor() "; - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::MultiSelection); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " --- AlarmView Konstruktor() "; + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::MultiSelection); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &AlarmView::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &AlarmView::onSelectionChanged); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &AlarmView::onShowAlarm); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &AlarmView::onShowAlarm); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, - this, &AlarmView::onPrint); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AlarmView::onRemoveAlarm); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &AlarmView::onPrint); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AlarmView::onCenterAlarm); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AlarmView::onRemoveAlarm); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - setOnlineHelpFilename(QStringLiteral("Situation-Alarm_History")); - -} + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AlarmView::onCenterAlarm); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + setOnlineHelpFilename(QStringLiteral("Situation-Alarm_History")); +} AlarmView::~AlarmView() { - INFO_LOG(m_logger) << "--- AlarmView Destruktor() "; - m_sitMapGuiIfc = nullptr; - delete m_ui; -} - + INFO_LOG(m_logger) << "--- AlarmView Destruktor() "; + m_sitMapGuiIfc = nullptr; + delete m_ui; +} void AlarmView::retranslate() { - translate(m_ui, tr("Alarm History")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Center Map")); + translate(m_ui, tr("Alarm History")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Center Map")); } -bool AlarmView::init(const std::shared_ptr &dtc, - AlarmHistoryModel *alarmHistoryModel) +bool AlarmView::init(const std::shared_ptr& dtc, AlarmHistoryModel* alarmHistoryModel) { - INFO_LOG(m_logger) << "--- init() "; - if (!dtc) - return false; + INFO_LOG(m_logger) << "--- init() "; + if (!dtc) + return false; - m_dtc = dtc; - m_alarmHistoryModel = alarmHistoryModel; - - DEBUG_LOG(m_logger) << "--- AlarmView::init "; - m_proxyModel = new AlarmHistoryProxyModel(this); - m_proxyModel->setSourceModel(m_alarmHistoryModel); - m_ui->widget->setModel(m_proxyModel); + m_dtc = dtc; + m_alarmHistoryModel = alarmHistoryModel; + DEBUG_LOG(m_logger) << "--- AlarmView::init "; + m_proxyModel = new AlarmHistoryProxyModel(this); + m_proxyModel->setSourceModel(m_alarmHistoryModel); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(AlarmHistoryModel::Id); - m_ui->widget->hideColumn(AlarmHistoryModel::ParticipantId); - m_ui->widget->hideColumn(AlarmHistoryModel::AesId); + m_ui->widget->hideColumn(AlarmHistoryModel::Id); + m_ui->widget->hideColumn(AlarmHistoryModel::ParticipantId); + m_ui->widget->hideColumn(AlarmHistoryModel::AesId); #endif - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - return true; -} - + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); + m_session->getForeignGuiInterface(m_sitMapGuiIfc); + return true; +} void AlarmView::onSelectionChanged() { - QModelIndexList selectedRows = m_ui->widget->selectedRows(); - const int cntSelectedRows = selectedRows.size(); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows > 0); -} + QModelIndexList selectedRows = m_ui->widget->selectedRows(); + const int cntSelectedRows = selectedRows.size(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows > 0); +} void AlarmView::onShowAlarm() { - INFO_LOG(m_logger) << "--- onShowMAlarm() "; -} - - + INFO_LOG(m_logger) << "--- onShowMAlarm() "; +} void AlarmView::onRemoveAlarm() { - DEBUG_LOG(m_logger) << "onRemoveAlarm selectedRows.size" - << m_ui->widget->selectedRows().size(); - - const QModelIndexList idxList = m_ui->widget->selectedRows(); - QVector rowsToRemove; - rowsToRemove.reserve(idxList.size()); - for (const auto &idx : idxList) - rowsToRemove.push_back(idx.row()); - std::sort(rowsToRemove.begin(), rowsToRemove.end(), std::greater()); - for (int i = 0; i < rowsToRemove.length(); i++) - m_alarmHistoryModel->removeRow(rowsToRemove.at(i)); -} + DEBUG_LOG(m_logger) << "onRemoveAlarm selectedRows.size" << m_ui->widget->selectedRows().size(); + const QModelIndexList idxList = m_ui->widget->selectedRows(); + QVector rowsToRemove; + rowsToRemove.reserve(idxList.size()); + for (const auto& idx : idxList) + rowsToRemove.push_back(idx.row()); + std::sort(rowsToRemove.begin(), rowsToRemove.end(), std::greater()); + for (int i = 0; i < rowsToRemove.length(); i++) + m_alarmHistoryModel->removeRow(rowsToRemove.at(i)); +} void AlarmView::onCenterAlarm() { - DEBUG_LOG(m_logger) << "onCenterAlarm"; - if (!m_sitMapGuiIfc) - return; - const QModelIndexList indexList = m_ui->widget->selectedRows(); - if (indexList.isEmpty()) - return; - const QModelIndex &index = indexList.first(); + DEBUG_LOG(m_logger) << "onCenterAlarm"; + if (!m_sitMapGuiIfc) + return; + const QModelIndexList indexList = m_ui->widget->selectedRows(); + if (indexList.isEmpty()) + return; + const QModelIndex& index = indexList.first(); - const QModelIndex indexPosi = m_alarmHistoryModel->index(index.row(), AlarmHistoryModel::Position, index.parent()); - const QPointF &position = indexPosi.data(Qt::UserRole).toPointF(); + const QModelIndex indexPosi = m_alarmHistoryModel->index(index.row(), AlarmHistoryModel::Position, index.parent()); + const QPointF& position = indexPosi.data(Qt::UserRole).toPointF(); - if (!position.isNull()) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " position=" << position.x() << " - " << position.y(); - m_sitMapGuiIfc->setCenterPoint(position); - } - else - { - const QModelIndex &indexParticipantId = m_alarmHistoryModel->index(index.row(), AlarmHistoryModel::ParticipantId, index.parent()); - const int participantId = indexParticipantId.data().toInt(); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " participantId=" << participantId; - m_sitMapGuiIfc->centerMapToParticipant(participantId); - } -} + if (!position.isNull()) + { + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " position=" << position.x() << " - " << position.y(); + m_sitMapGuiIfc->setCenterPoint(position); + } + else + { + const QModelIndex& indexParticipantId = + m_alarmHistoryModel->index(index.row(), AlarmHistoryModel::ParticipantId, index.parent()); + const int participantId = indexParticipantId.data().toInt(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " participantId=" << participantId; + m_sitMapGuiIfc->centerMapToParticipant(participantId); + } +} void AlarmView::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } void AlarmView::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.h old mode 100755 new mode 100644 index ec30d4cc4..d93ddcc70 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigAlarm/alm_history.h @@ -1,18 +1,18 @@ - #pragma once #include #include -#include #include +#include #include namespace Ui { class AlarmView; } + namespace AlarmManagement { class AlarmHistoryModel; @@ -20,33 +20,31 @@ class AlarmHistoryProxyModel; class AlarmView final : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit AlarmView(LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~AlarmView(); - bool init(const std::shared_ptr &dtc, - AlarmHistoryModel *alarmHistoryModel); + public: + explicit AlarmView(LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~AlarmView(); + bool init(const std::shared_ptr& dtc, AlarmHistoryModel* alarmHistoryModel); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onShowAlarm(); + void onRemoveAlarm(); + void onCenterAlarm(); + void onPrint(); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onShowAlarm(); - void onRemoveAlarm(); - void onCenterAlarm(); - void onPrint(); - void tableColumnOrganiserSetting() override; + private: + AlarmHistoryModel* m_alarmHistoryModel; + AlarmHistoryProxyModel* m_proxyModel; + std::shared_ptr m_dtc; + std::shared_ptr m_sitMapGuiIfc; -private: - AlarmHistoryModel *m_alarmHistoryModel; - AlarmHistoryProxyModel *m_proxyModel; - std::shared_ptr m_dtc; - std::shared_ptr m_sitMapGuiIfc; - - LtsSession::LtsSession *m_session; - Ui::AlarmView *m_ui; + LtsSession::LtsSession* m_session; + Ui::AlarmView* m_ui; }; -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.cpp old mode 100755 new mode 100644 index d7bdaba65..7c04bba7a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.cpp @@ -1,320 +1,306 @@ - - #include "alm_config_participant_dialog.h" + #include "ui_alm_config_participant_dialog.h" #include #include - #include namespace ParticipantAlarms { -ConfigParticipantsDialog::ConfigParticipantsDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::ConfigParticipantsDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_typeClass(ParticipantManagement::TypeClass::Human) - , m_logger(AlarmManagement::getLogger("ConfigParticipantsDialog")) +ConfigParticipantsDialog::ConfigParticipantsDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::ConfigParticipantsDialog), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_typeClass(ParticipantManagement::TypeClass::Human), + m_logger(AlarmManagement::getLogger("ConfigParticipantsDialog")) { - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableNuclearContaminations = ps->value(QStringLiteral("aes"), - QStringLiteral("enableNuclearContaminations")).toBool(); - const bool enableMineAreas = ps->value(QStringLiteral("aes"), - QStringLiteral("enableMineAreas")).toBool(); - m_ui->setupUi(this); + const bool enableNuclearContaminations = + ps->value(QStringLiteral("aes"), QStringLiteral("enableNuclearContaminations")).toBool(); + const bool enableMineAreas = ps->value(QStringLiteral("aes"), QStringLiteral("enableMineAreas")).toBool(); + m_ui->setupUi(this); - if (!enableNuclearContaminations) - { - m_ui->cbxNbcAgent->hide(); - } - if (!enableMineAreas) - { - m_ui->cbxMines->hide(); - m_ui->cbxIndirectFire->hide(); - } + if (!enableNuclearContaminations) + { + m_ui->cbxNbcAgent->hide(); + } + if (!enableMineAreas) + { + m_ui->cbxMines->hide(); + m_ui->cbxIndirectFire->hide(); + } #ifdef ETS_MODE - - m_ui->cbxFriendlyFire->hide(); - m_ui->cbStatusFriendly->hide(); + + m_ui->cbxFriendlyFire->hide(); + m_ui->cbStatusFriendly->hide(); #endif - setNoTopicLock(); + setNoTopicLock(); } ConfigParticipantsDialog::~ConfigParticipantsDialog() { - delete m_ui; + delete m_ui; } void ConfigParticipantsDialog::retranslate() { - if (!m_participantData.equipmentNumber().is_set()) - { - QString hierarchy = m_ppmDtc->hierarchyFromParticipant(m_participantData.id()); - translate(m_ui, m_participantData, hierarchy, tr("Participant Alarm")); - } - else - translate(m_ui, m_participantData, QString::number(m_participantData.equipmentNumber().get()), tr("Participant Alarm")); + if (!m_participantData.equipmentNumber().is_set()) + { + QString hierarchy = m_ppmDtc->hierarchyFromParticipant(m_participantData.id()); + translate(m_ui, m_participantData, hierarchy, tr("Participant Alarm")); + } + else + translate(m_ui, m_participantData, QString::number(m_participantData.equipmentNumber().get()), + tr("Participant Alarm")); - m_uiRequirements->clear(); - m_uiRequirements->addRequirement( { m_ui->lbReaction, [this]() { return m_ui->cbxSetMarker->isChecked() || m_ui->cbxMessageWindow->isChecked(); }, tr("Select at least one reaction") }); + m_uiRequirements->clear(); + m_uiRequirements->addRequirement( + {m_ui->lbReaction, [this]() { return m_ui->cbxSetMarker->isChecked() || m_ui->cbxMessageWindow->isChecked(); }, + tr("Select at least one reaction")}); } -bool ConfigParticipantsDialog::init(const std::shared_ptr &ppmDtc, - const std::shared_ptr &almDtc, - const std::shared_ptr &almFtc, - const ParticipantManagement::ParticipantData &participantData, - const std::vector &participantVector, - const std::vector &equipmentVector) +bool ConfigParticipantsDialog::init(const std::shared_ptr& ppmDtc, + const std::shared_ptr& almDtc, + const std::shared_ptr& almFtc, + const ParticipantManagement::ParticipantData& participantData, + const std::vector& participantVector, const std::vector& equipmentVector) { - if (!ppmDtc || !almDtc || !almFtc) - return false; + if (!ppmDtc || !almDtc || !almFtc) + return false; - m_ppmDtc = ppmDtc; - m_almFtc = almFtc; - m_almDtc = almDtc; - m_participantVector = participantVector; - m_participantData = participantData; + m_ppmDtc = ppmDtc; + m_almFtc = almFtc; + m_almDtc = almDtc; + m_participantVector = participantVector; + m_participantData = participantData; - m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - m_ui->lbHierarchy->setText(m_ppmDtc->hierarchyFromParticipant(m_participantData.id())); + m_ui->lbHierarchy->setText(m_ppmDtc->hierarchyFromParticipant(m_participantData.id())); - QString equipmentNumbersStr; - if (participantData.equipmentNumber().is_set()) - { - equipmentNumbersStr.append(QString::number(participantData.equipmentNumber().get())); - equipmentNumbersStr.append(QStringLiteral(": ")); - } + QString equipmentNumbersStr; + if (participantData.equipmentNumber().is_set()) + { + equipmentNumbersStr.append(QString::number(participantData.equipmentNumber().get())); + equipmentNumbersStr.append(QStringLiteral(": ")); + } - for (const int equipNo : equipmentVector) - equipmentNumbersStr += QString::number(equipNo) + QStringLiteral(", "); - equipmentNumbersStr.chop(2); + for (const int equipNo : equipmentVector) + equipmentNumbersStr += QString::number(equipNo) + QStringLiteral(", "); + equipmentNumbersStr.chop(2); - m_ui->equipmentNoContent->setText(equipmentNumbersStr); + m_ui->equipmentNoContent->setText(equipmentNumbersStr); - DEBUG_LOG(m_logger) << "current participantId = " << participantData.id(); + DEBUG_LOG(m_logger) << "current participantId = " << participantData.id(); - m_typeClass = ppmDtc->type(participantData.typeId()).typeClass(); - DEBUG_LOG(m_logger) << "m_typeClass=" << m_typeClass << " TypeId=" << participantData.typeId(); - fillCbx(); + m_typeClass = ppmDtc->type(participantData.typeId()).typeClass(); + DEBUG_LOG(m_logger) << "m_typeClass=" << m_typeClass << " TypeId=" << participantData.typeId(); + fillCbx(); - m_almDtc->alarmConfigs([this](const AlarmManagement::AlarmConfig &alarm) { setAlaramData(alarm); }); - return true; + m_almDtc->alarmConfigs([this](const AlarmManagement::AlarmConfig& alarm) { setAlaramData(alarm); }); + return true; } -void ConfigParticipantsDialog::setAlaramData(const AlarmManagement::AlarmConfig &alarm) +void ConfigParticipantsDialog::setAlaramData(const AlarmManagement::AlarmConfig& alarm) { - DEBUG_LOG(m_logger) << "setAlaramData:" << alarm; - if (alarm.operatorId() != m_operatorId || - alarm.participantId() != m_participantData.id() || - alarm.global()) - return; + DEBUG_LOG(m_logger) << "setAlaramData:" << alarm; + if (alarm.operatorId() != m_operatorId || alarm.participantId() != m_participantData.id() || alarm.global()) + return; - switch (alarm.eventTypeId().underlying()) - { - case ProjectDataManagement::EventType_def::Hit: - { - DEBUG_LOG(m_logger) << "Hit zuweisen "; - m_ui->cbxDirectFire->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - if (alarm.vulnerabilityState() >= 0) + switch (alarm.eventTypeId().underlying()) { - ProjectDataManagement::VulnerabilityState vulState = static_cast(alarm.vulnerabilityState()); - int index = m_ui->cbStatusDirect->findData(QVariant(vulState.underlying())); - m_ui->cbStatusDirect->setCurrentIndex(index); + case ProjectDataManagement::EventType_def::Hit: { + DEBUG_LOG(m_logger) << "Hit zuweisen "; + m_ui->cbxDirectFire->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + if (alarm.vulnerabilityState() >= 0) + { + ProjectDataManagement::VulnerabilityState vulState = + static_cast(alarm.vulnerabilityState()); + int index = m_ui->cbStatusDirect->findData(QVariant(vulState.underlying())); + m_ui->cbStatusDirect->setCurrentIndex(index); + } + break; + } + case ProjectDataManagement::EventType_def::HitEffectSimulation: { + DEBUG_LOG(m_logger) << "HitIndirect zuweisen "; + m_ui->cbxIndirectFire->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::AirSupport: { + DEBUG_LOG(m_logger) << "AirSupport zuweisen "; + m_ui->cbxAirSupport->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::HitMine: { + DEBUG_LOG(m_logger) << "HitMine zuweisen "; + m_ui->cbxMines->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::HitB: + case ProjectDataManagement::EventType_def::HitN: + case ProjectDataManagement::EventType_def::HitC: { + DEBUG_LOG(m_logger) << "Hit N/B/C zuweisen "; + m_ui->cbxNbcAgent->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::FriendlyFire: { + DEBUG_LOG(m_logger) << "FriendlyFire zuweisen "; + m_ui->cbxFriendlyFire->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + if (alarm.vulnerabilityState() >= 0) + { + ProjectDataManagement::VulnerabilityState vulState = + static_cast(alarm.vulnerabilityState()); + int index = m_ui->cbStatusDirect->findData(QVariant(vulState.underlying())); + m_ui->cbStatusFriendly->setCurrentIndex(index); + } + break; + } + case ProjectDataManagement::EventType_def::Manipulation: { + DEBUG_LOG(m_logger) << "Manipulation zuweisen "; + m_ui->cbxManipulation->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::CrossGlobalBorderline: { + DEBUG_LOG(m_logger) << "CrossGlobalBorderline zuweisen "; + m_ui->cbxGlobalBorderLine->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + case ProjectDataManagement::EventType_def::CrossLocalBorderline: { + DEBUG_LOG(m_logger) << "CrossLocalBorderline zuweisen "; + m_ui->cbxLocalBorderLine->setChecked(true); + m_ui->cbxSetMarker->setChecked(alarm.setMarker()); + m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); + break; + } + default: { + ERROR_LOG(m_logger) << "Not possible to set with Operator App!!!"; + } } - break; - } - case ProjectDataManagement::EventType_def::HitEffectSimulation: - { - DEBUG_LOG(m_logger) << "HitIndirect zuweisen "; - m_ui->cbxIndirectFire->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::AirSupport: - { - DEBUG_LOG(m_logger) << "AirSupport zuweisen "; - m_ui->cbxAirSupport->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::HitMine: - { - DEBUG_LOG(m_logger) << "HitMine zuweisen "; - m_ui->cbxMines->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::HitB: - case ProjectDataManagement::EventType_def::HitN: - case ProjectDataManagement::EventType_def::HitC: - { - DEBUG_LOG(m_logger) << "Hit N/B/C zuweisen "; - m_ui->cbxNbcAgent->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::FriendlyFire: - { - DEBUG_LOG(m_logger) << "FriendlyFire zuweisen "; - m_ui->cbxFriendlyFire->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - if (alarm.vulnerabilityState() >= 0) - { - ProjectDataManagement::VulnerabilityState vulState = static_cast(alarm.vulnerabilityState()); - int index = m_ui->cbStatusDirect->findData(QVariant(vulState.underlying())); - m_ui->cbStatusFriendly->setCurrentIndex(index); - } - break; - } - case ProjectDataManagement::EventType_def::Manipulation: - { - DEBUG_LOG(m_logger) << "Manipulation zuweisen "; - m_ui->cbxManipulation->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::CrossGlobalBorderline: - { - DEBUG_LOG(m_logger) << "CrossGlobalBorderline zuweisen "; - m_ui->cbxGlobalBorderLine->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - case ProjectDataManagement::EventType_def::CrossLocalBorderline: - { - DEBUG_LOG(m_logger) << "CrossLocalBorderline zuweisen "; - m_ui->cbxLocalBorderLine->setChecked(true); - m_ui->cbxSetMarker->setChecked(alarm.setMarker()); - m_ui->cbxMessageWindow->setChecked(alarm.messageWindow()); - break; - } - default: - { - ERROR_LOG(m_logger) << "Not possible to set with Operator App!!!"; - } - } } std::vector ConfigParticipantsDialog::getCheckedValues() const { - AlarmManagement::AlarmAction alarmActionDds; - DEBUG_LOG(m_logger) << "getCheckedValues"; + AlarmManagement::AlarmAction alarmActionDds; + DEBUG_LOG(m_logger) << "getCheckedValues"; - std::vector alarmsDds; + std::vector alarmsDds; - alarmActionDds.setMarker(m_ui->cbxSetMarker->isChecked()); - alarmActionDds.messageWindow(m_ui->cbxMessageWindow->isChecked()); - alarmActionDds.vulnerabilityState(-1); + alarmActionDds.setMarker(m_ui->cbxSetMarker->isChecked()); + alarmActionDds.messageWindow(m_ui->cbxMessageWindow->isChecked()); + alarmActionDds.vulnerabilityState(-1); - if (alarmActionDds.setMarker() || alarmActionDds.messageWindow()) - { - if (m_ui->cbxDirectFire->isChecked()) + if (alarmActionDds.setMarker() || alarmActionDds.messageWindow()) { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::Hit); - int statusDirect = -1; - if (m_ui->cbStatusDirect->currentIndex() > 0) - statusDirect = m_ui->cbStatusDirect->currentData().toInt(); - alarmActionDds.vulnerabilityState(statusDirect); - alarmsDds.push_back(alarmActionDds); + if (m_ui->cbxDirectFire->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::Hit); + int statusDirect = -1; + if (m_ui->cbStatusDirect->currentIndex() > 0) + statusDirect = m_ui->cbStatusDirect->currentData().toInt(); + alarmActionDds.vulnerabilityState(statusDirect); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxFriendlyFire->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::FriendlyFire); + int statusFriendly = -1; + if (m_ui->cbStatusFriendly->currentIndex() > 0) + statusFriendly = m_ui->cbStatusFriendly->currentData().toInt(); + alarmActionDds.vulnerabilityState(statusFriendly); + alarmsDds.push_back(alarmActionDds); + } + alarmActionDds.vulnerabilityState(-1); + if (m_ui->cbxIndirectFire->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitEffectSimulation); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxAirSupport->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::AirSupport); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxMines->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitMine); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxNbcAgent->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitN); + alarmsDds.push_back(alarmActionDds); + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitB); + alarmsDds.push_back(alarmActionDds); + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitC); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxManipulation->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::Manipulation); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxGlobalBorderLine->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::CrossGlobalBorderline); + alarmsDds.push_back(alarmActionDds); + } + if (m_ui->cbxLocalBorderLine->isChecked()) + { + alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::CrossLocalBorderline); + alarmsDds.push_back(alarmActionDds); + } } - if (m_ui->cbxFriendlyFire->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::FriendlyFire); - int statusFriendly = -1; - if (m_ui->cbStatusFriendly->currentIndex() > 0) - statusFriendly = m_ui->cbStatusFriendly->currentData().toInt(); - alarmActionDds.vulnerabilityState(statusFriendly); - alarmsDds.push_back(alarmActionDds); - } - alarmActionDds.vulnerabilityState(-1); - if (m_ui->cbxIndirectFire->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitEffectSimulation); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxAirSupport->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::AirSupport); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxMines->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitMine); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxNbcAgent->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitN); - alarmsDds.push_back(alarmActionDds); - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitB); - alarmsDds.push_back(alarmActionDds); - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::HitC); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxManipulation->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::Manipulation); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxGlobalBorderLine->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::CrossGlobalBorderline); - alarmsDds.push_back(alarmActionDds); - } - if (m_ui->cbxLocalBorderLine->isChecked()) - { - alarmActionDds.eventTypeId(ProjectDataManagement::EventType_def::CrossLocalBorderline); - alarmsDds.push_back(alarmActionDds); - } - } - return alarmsDds; + return alarmsDds; } bool ConfigParticipantsDialog::apply() { - DEBUG_LOG(m_logger) << "apply"; - AlarmManagement::ConfigureAlarmsRequest req; - req.participantIds(m_participantVector); - req.alarms(getCheckedValues()); - req.operatorId(m_operatorId); - req.global(false); - req.remove(false); + DEBUG_LOG(m_logger) << "apply"; + AlarmManagement::ConfigureAlarmsRequest req; + req.participantIds(m_participantVector); + req.alarms(getCheckedValues()); + req.operatorId(m_operatorId); + req.global(false); + req.remove(false); - return m_requestHelper->startSingleRequest([req, this]() - { - return m_almFtc->configureAlarmsRequest(req, this); - }); + return m_requestHelper->startSingleRequest([req, this]() { return m_almFtc->configureAlarmsRequest(req, this); }); } void ConfigParticipantsDialog::fillCbx() { - m_ui->cbStatusDirect->clear(); - m_ui->cbStatusFriendly->clear(); - - m_ui->cbStatusDirect->addItem(tr("All Types"), -1); - m_ui->cbStatusFriendly->addItem(tr("All Types"), -1); - ParticipantManagement::insertVulnerabilityStates(m_ui->cbStatusDirect, m_typeClass); - ParticipantManagement::insertVulnerabilityStates(m_ui->cbStatusFriendly, m_typeClass); - m_ui->cbStatusDirect->removeItem(m_ui->cbStatusDirect->findData(ProjectDataManagement::VulnerabilityState::TemporarySeverance)); - m_ui->cbStatusFriendly->removeItem(m_ui->cbStatusDirect->findData(ProjectDataManagement::VulnerabilityState::TemporarySeverance)); + m_ui->cbStatusDirect->clear(); + m_ui->cbStatusFriendly->clear(); + + m_ui->cbStatusDirect->addItem(tr("All Types"), -1); + m_ui->cbStatusFriendly->addItem(tr("All Types"), -1); + ParticipantManagement::insertVulnerabilityStates(m_ui->cbStatusDirect, m_typeClass); + ParticipantManagement::insertVulnerabilityStates(m_ui->cbStatusFriendly, m_typeClass); + m_ui->cbStatusDirect->removeItem( + m_ui->cbStatusDirect->findData(ProjectDataManagement::VulnerabilityState::TemporarySeverance)); + m_ui->cbStatusFriendly->removeItem( + m_ui->cbStatusDirect->findData(ProjectDataManagement::VulnerabilityState::TemporarySeverance)); } -} - +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.h old mode 100755 new mode 100644 index 12b79bee9..37c5a786a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_config_participant_dialog.h @@ -1,15 +1,14 @@ - #pragma once +#include +#include #include -#include #include #include #include -#include -#include +#include namespace Ui { @@ -18,43 +17,45 @@ class ConfigParticipantsDialog; namespace ParticipantAlarms { -class ConfigParticipantsDialog : public LtsWidgets::LtsDialog - , protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler +class ConfigParticipantsDialog : public LtsWidgets::LtsDialog, + protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ConfigParticipantsDialog(QWidget *parent = nullptr); - ~ConfigParticipantsDialog(); + public: + explicit ConfigParticipantsDialog(QWidget* parent = nullptr); + ~ConfigParticipantsDialog(); - bool init(const std::shared_ptr &ppmDtc, - const std::shared_ptr &almDtc, - const std::shared_ptr &almFtc, - const ParticipantManagement::ParticipantData &participantData, - const std::vector &participantVector, - const std::vector &equipmentVector); + bool init(const std::shared_ptr& ppmDtc, + const std::shared_ptr& almDtc, + const std::shared_ptr& almFtc, + const ParticipantManagement::ParticipantData& participantData, const std::vector& participantVector, + const std::vector& equipmentVector); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onConfigureAlarmsReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onConfigureAlarmsReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - void retranslate() override; - bool apply() override; - std::vector getCheckedValues() const; - void fillCbx(); - void setAlaramData(const AlarmManagement::AlarmConfig &alarm); + private: + void retranslate() override; + bool apply() override; + std::vector getCheckedValues() const; + void fillCbx(); + void setAlaramData(const AlarmManagement::AlarmConfig& alarm); -private: - Ui::ConfigParticipantsDialog *m_ui; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_almDtc; - std::shared_ptr m_almFtc; - int m_operatorId; - LtsUtils::RequestHelper *m_requestHelper; - std::vector m_participantVector; - ParticipantManagement::TypeClass m_typeClass; - ParticipantManagement::ParticipantData m_participantData; + private: + Ui::ConfigParticipantsDialog* m_ui; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_almDtc; + std::shared_ptr m_almFtc; + int m_operatorId; + LtsUtils::RequestHelper* m_requestHelper; + std::vector m_participantVector; + ParticipantManagement::TypeClass m_typeClass; + ParticipantManagement::ParticipantData m_participantData; }; -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.cpp old mode 100755 new mode 100644 index 0e1c28581..72eed83f5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.cpp @@ -1,228 +1,205 @@ - - #include "alm_participant_dialog.h" -#include "ui_alm_participant_dialog.h" + #include "alm_config_participant_dialog.h" #include "alm_participant_model.h" +#include "ui_alm_participant_dialog.h" #include +#include #include #include - #include -#include namespace ParticipantAlarms { int ParticipantsDialog::s_preselectedParty = -1; -ParticipantsDialog::ParticipantsDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent) - , m_session(nullptr) - , m_almDtc(nullptr) - , m_almFtc(nullptr) - , m_ppmDtc(nullptr) - , m_participantModel(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_menuGroup(menuGroup) - , m_ui(new Ui::ParticipantsDialog) - , m_logger(AlarmManagement::getLogger("ParticipantsDialog")) +ParticipantsDialog::ParticipantsDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent), m_session(nullptr), m_almDtc(nullptr), m_almFtc(nullptr), m_ppmDtc(nullptr), + m_participantModel(nullptr), m_requestHelper(new LtsUtils::RequestHelper(this)), m_menuGroup(menuGroup), + m_ui(new Ui::ParticipantsDialog), m_logger(AlarmManagement::getLogger("ParticipantsDialog")) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ParticipantsDialog::onAddButtonClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ParticipantsDialog::onPrint); - + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ParticipantsDialog::onAddButtonClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ParticipantsDialog::onPrint); - m_ui->cbAllParticipants->setVisible(false); + m_ui->cbAllParticipants->setVisible(false); - - setOnlineHelpFilename(QStringLiteral("Situation-Assign_Participant_Alarms")); + setOnlineHelpFilename(QStringLiteral("Situation-Assign_Participant_Alarms")); } ParticipantsDialog::~ParticipantsDialog() { - delete m_ui; + delete m_ui; } void ParticipantsDialog::retranslate() { - translate(m_ui, tr("Assign Participant Alarms")); + translate(m_ui, tr("Assign Participant Alarms")); } -bool ParticipantsDialog::init(LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &almDtc, - const std::shared_ptr &almFtc, - const std::shared_ptr &ppmGuiCbxIfc) +bool ParticipantsDialog::init(LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& almDtc, + const std::shared_ptr& almFtc, + const std::shared_ptr& ppmGuiCbxIfc) { - m_ppmDtc = ppmDtc; - m_almDtc = almDtc; - m_almFtc = almFtc; - m_session = session; + m_ppmDtc = ppmDtc; + m_almDtc = almDtc; + m_almFtc = almFtc; + m_session = session; - if (m_ppmDtc == nullptr || - !ppmDtc->enableDynamicParticipantData() || - !ppmDtc->enableParticipant()) - return false; + if (m_ppmDtc == nullptr || !ppmDtc->enableDynamicParticipantData() || !ppmDtc->enableParticipant()) + return false; - if (m_almFtc == nullptr || - !almFtc->enableConfigureAlarms()) - return false; + if (m_almFtc == nullptr || !almFtc->enableConfigureAlarms()) + return false; - std::shared_ptr asbIfc; - m_session->getForeignDataInterface(asbIfc); - m_participantModel = new ParticipantAlarms::ParticipantAlarmModel(this, - m_ppmDtc, - asbIfc); - m_participantProxyModel = new ParticipantManagement::ParticipantTreeFilterProxyModel(this); - m_participantProxyModel->setSourceModel(m_participantModel); - m_participantProxyModel->setRecursiveFilteringEnabled(true); + std::shared_ptr asbIfc; + m_session->getForeignDataInterface(asbIfc); + m_participantModel = new ParticipantAlarms::ParticipantAlarmModel(this, m_ppmDtc, asbIfc); + m_participantProxyModel = new ParticipantManagement::ParticipantTreeFilterProxyModel(this); + m_participantProxyModel->setSourceModel(m_participantModel); + m_participantProxyModel->setRecursiveFilteringEnabled(true); - m_ui->dvParticipants->setModel(m_participantProxyModel); - connect(m_ui->cbParty, - static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &ParticipantsDialog::onCbPartyChanged); - connect(m_ui->cbAllParticipants, &QCheckBox::clicked, - m_ui->dvParticipants, &LtsDataView::LtsDataView::setDisabled); - connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::selectionChanged, - this, &ParticipantsDialog::onSelectionChanged); - connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ParticipantsDialog::onDoubleClicked); - connect(m_ui->cbAllParticipants, &QCheckBox::clicked, - this, [this](bool checked) - { - if (checked) - m_ui->dvParticipants->treeView()->selectAll(); - else - m_ui->dvParticipants->treeView()->clearSelection(); - }); + m_ui->dvParticipants->setModel(m_participantProxyModel); + connect(m_ui->cbParty, + static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &ParticipantsDialog::onCbPartyChanged); + connect(m_ui->cbAllParticipants, &QCheckBox::clicked, m_ui->dvParticipants, &LtsDataView::LtsDataView::setDisabled); + connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::selectionChanged, this, + &ParticipantsDialog::onSelectionChanged); + connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ParticipantsDialog::onDoubleClicked); + connect(m_ui->cbAllParticipants, &QCheckBox::clicked, this, [this](bool checked) { + if (checked) + m_ui->dvParticipants->treeView()->selectAll(); + else + m_ui->dvParticipants->treeView()->clearSelection(); + }); - ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); - const int idx = m_ui->cbParty->findData(s_preselectedParty); - if (idx >= 0) - m_ui->cbParty->setCurrentIndex(idx); - onCbPartyChanged(); + ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); + const int idx = m_ui->cbParty->findData(s_preselectedParty); + if (idx >= 0) + m_ui->cbParty->setCurrentIndex(idx); + onCbPartyChanged(); - return true; + return true; } void ParticipantsDialog::onSelectionChanged() { - bool configureAlarms = false; - DEBUG_LOG(m_logger) << "onSelectionChanged"; - const QModelIndexList currentlySelectedParticipants = m_ui->dvParticipants->selectedRows(); + bool configureAlarms = false; + DEBUG_LOG(m_logger) << "onSelectionChanged"; + const QModelIndexList currentlySelectedParticipants = m_ui->dvParticipants->selectedRows(); - for (const QModelIndex &index : currentlySelectedParticipants) - { - const ParticipantManagement::ParticipantData data(m_participantModel->getParticipantData(index)); - if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || - m_ppmDtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) - configureAlarms = true; - DEBUG_LOG(m_logger) << "setChildrenSelected row =" << index.row() << " column=" << index.column(); - - } - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, configureAlarms); + for (const QModelIndex& index : currentlySelectedParticipants) + { + const ParticipantManagement::ParticipantData data(m_participantModel->getParticipantData(index)); + if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || + m_ppmDtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) + configureAlarms = true; + DEBUG_LOG(m_logger) << "setChildrenSelected row =" << index.row() << " column=" << index.column(); + } + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, configureAlarms); } void ParticipantsDialog::onCbPartyChanged() { - const int curPartyId = m_ui->cbParty->currentData().toInt(); - s_preselectedParty = curPartyId; - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_participantModel->onReinitModel(curPartyId); - m_ui->dvParticipants->expandAll(); - if (m_ui->cbAllParticipants->isChecked()) - m_ui->dvParticipants->treeView()->selectAll(); - m_ui->dvParticipants->resizeHeadersByContent(); + const int curPartyId = m_ui->cbParty->currentData().toInt(); + s_preselectedParty = curPartyId; + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_participantModel->onReinitModel(curPartyId); + m_ui->dvParticipants->expandAll(); + if (m_ui->cbAllParticipants->isChecked()) + m_ui->dvParticipants->treeView()->selectAll(); + m_ui->dvParticipants->resizeHeadersByContent(); } void ParticipantsDialog::onAddButtonClicked() { - DEBUG_LOG(m_logger) << "onAddButtonClicked"; - - m_participantVector.clear(); - m_equipmentVector.clear(); - if (!m_ui->cbAllParticipants->isChecked()) - { - const QModelIndexList currentlySelectedParticipants = m_ui->dvParticipants->selectedRows(); + DEBUG_LOG(m_logger) << "onAddButtonClicked"; - for (const QModelIndex &index : currentlySelectedParticipants) + m_participantVector.clear(); + m_equipmentVector.clear(); + if (!m_ui->cbAllParticipants->isChecked()) { - DEBUG_LOG(m_logger) << "setChildrenSelected: " << index.row() << " column=" << index.column(); - setChildrenSelected(index); + const QModelIndexList currentlySelectedParticipants = m_ui->dvParticipants->selectedRows(); + + for (const QModelIndex& index : currentlySelectedParticipants) + { + DEBUG_LOG(m_logger) << "setChildrenSelected: " << index.row() << " column=" << index.column(); + setChildrenSelected(index); + } } - } - QModelIndex participantIndex = m_ui->dvParticipants->currentIndex(); - ParticipantManagement::ParticipantData data = m_participantModel->getParticipantData(participantIndex); - DEBUG_LOG(m_logger) << "current participantId = " << data.id(); - m_participantVector.push_back(data.id()); + QModelIndex participantIndex = m_ui->dvParticipants->currentIndex(); + ParticipantManagement::ParticipantData data = m_participantModel->getParticipantData(participantIndex); + DEBUG_LOG(m_logger) << "current participantId = " << data.id(); + m_participantVector.push_back(data.id()); - const auto partData = m_participantModel->getParticipantData(participantIndex); - addDialog(LtsWidgets::initDialog(new ConfigParticipantsDialog(this), - m_ppmDtc, m_almDtc, m_almFtc, partData, m_participantVector, m_equipmentVector), - m_menuGroup, QStringLiteral("ConfigAlarms%1").arg(partData.id())); + const auto partData = m_participantModel->getParticipantData(participantIndex); + addDialog(LtsWidgets::initDialog(new ConfigParticipantsDialog(this), m_ppmDtc, m_almDtc, m_almFtc, partData, + m_participantVector, m_equipmentVector), + m_menuGroup, QStringLiteral("ConfigAlarms%1").arg(partData.id())); } void ParticipantsDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dvParticipants->treeView()); + LtsPrinting::printView(m_session, this, m_ui->dvParticipants->treeView()); } -void ParticipantsDialog::setChildrenSelected(const QModelIndex &parent) +void ParticipantsDialog::setChildrenSelected(const QModelIndex& parent) { - if (!(parent.isValid() && - m_participantModel->hasChildren(parent))) - return; + if (!(parent.isValid() && m_participantModel->hasChildren(parent))) + return; - const int rc = m_participantModel->rowCount(parent); - for (int currentRow = 0; currentRow < rc; ++currentRow) - { - QModelIndex childIndex = m_participantModel->index(currentRow, 0, parent); - - if (m_participantModel->hasChildren(childIndex)) - setChildrenSelected(childIndex); - - DEBUG_LOG(m_logger) << "Setting row " - << childIndex.row() - << " selected"; - - ParticipantManagement::ParticipantData data = m_participantModel->getParticipantData(childIndex); - DEBUG_LOG(m_logger) << "append participantId = " << data.id(); - m_participantVector.push_back(data.id()); - if (data.equipmentNumber().is_set()) + const int rc = m_participantModel->rowCount(parent); + for (int currentRow = 0; currentRow < rc; ++currentRow) { - DEBUG_LOG(m_logger) << "append equipmentNumber = " << data.equipmentNumber().get(); - m_equipmentVector.push_back(data.equipmentNumber().get()); - } + QModelIndex childIndex = m_participantModel->index(currentRow, 0, parent); - m_ui->dvParticipants->selectionModel()->select(m_participantProxyModel->mapFromSource(childIndex), QItemSelectionModel::Select | QItemSelectionModel::Rows); - } + if (m_participantModel->hasChildren(childIndex)) + setChildrenSelected(childIndex); + + DEBUG_LOG(m_logger) << "Setting row " << childIndex.row() << " selected"; + + ParticipantManagement::ParticipantData data = m_participantModel->getParticipantData(childIndex); + DEBUG_LOG(m_logger) << "append participantId = " << data.id(); + m_participantVector.push_back(data.id()); + if (data.equipmentNumber().is_set()) + { + DEBUG_LOG(m_logger) << "append equipmentNumber = " << data.equipmentNumber().get(); + m_equipmentVector.push_back(data.equipmentNumber().get()); + } + + m_ui->dvParticipants->selectionModel()->select(m_participantProxyModel->mapFromSource(childIndex), + QItemSelectionModel::Select | QItemSelectionModel::Rows); + } } void ParticipantsDialog::tableColumnOrganiserSetting() { - - m_ui->dvParticipants->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dvParticipants->setColumnsOrganiserEnabled(identifier(), true); } -void ParticipantsDialog::onConfigureAlarmsReply(const Core::FunctionReplyObject &replyObject) +void ParticipantsDialog::onConfigureAlarmsReply(const Core::FunctionReplyObject& replyObject) { - DEBUG_LOG(m_logger) << "onConfigureAlarmsReply" << replyObject.str(); - m_requestHelper->requestReply(replyObject); + DEBUG_LOG(m_logger) << "onConfigureAlarmsReply" << replyObject.str(); + m_requestHelper->requestReply(replyObject); } void ParticipantsDialog::onDoubleClicked() { - if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) - return; + if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) + return; - DEBUG_LOG(m_logger) << "onDoubleClicked"; - onAddButtonClicked(); + DEBUG_LOG(m_logger) << "onDoubleClicked"; + onAddButtonClicked(); } -} - +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.h old mode 100755 new mode 100644 index 0e8bbaae2..954fd4c46 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_dialog.h @@ -1,18 +1,17 @@ - #pragma once #include "alm_participant_model.h" +#include +#include #include -#include #include +#include #include #include -#include -#include -#include +#include namespace Ui { @@ -23,56 +22,54 @@ namespace ParticipantManagement { class ParticipantTreeFilterProxyModel; class ForeignGuiComboboxInterface; -} +} // namespace ParticipantManagement namespace ParticipantAlarms { class TypeModel; -class ParticipantsDialog : public LtsWidgets::LtsDialog - , protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler +class ParticipantsDialog : public LtsWidgets::LtsDialog, + protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ParticipantsDialog(const QString &menuGroup, QWidget *parent = nullptr); - ~ParticipantsDialog(); + public: + explicit ParticipantsDialog(const QString& menuGroup, QWidget* parent = nullptr); + ~ParticipantsDialog(); - bool init(LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &almDtc, - const std::shared_ptr &almFtc, - const std::shared_ptr &ppmGuiCbxIfc); + bool init(LtsSession::LtsSession* session, const std::shared_ptr& ppmDtc, + const std::shared_ptr& almDtc, + const std::shared_ptr& almFtc, + const std::shared_ptr& ppmGuiCbxIfc); -protected: + protected: + NGL::INGLLogger& m_logger; + void onConfigureAlarmsReply(const Core::FunctionReplyObject& replyObject) override final; -NGL::INGLLogger &m_logger; - void onConfigureAlarmsReply(const Core::FunctionReplyObject &replyObject) override final; + private slots: + void onAddButtonClicked(); + void onPrint(); + void onCbPartyChanged(); + void onDoubleClicked(); + void onSelectionChanged(); -private slots: - void onAddButtonClicked(); - void onPrint(); - void onCbPartyChanged(); - void onDoubleClicked(); - void onSelectionChanged(); + private: + void retranslate() override; + void setChildrenSelected(const QModelIndex& parent); + void tableColumnOrganiserSetting() override; -private: - void retranslate() override; - void setChildrenSelected(const QModelIndex &parent); - void tableColumnOrganiserSetting() override; - -private: - LtsSession::LtsSession *m_session; - std::shared_ptr m_almDtc; - std::shared_ptr m_almFtc; - std::shared_ptr m_ppmDtc; - ParticipantAlarmModel *m_participantModel; - ParticipantManagement::ParticipantTreeFilterProxyModel *m_participantProxyModel; - LtsUtils::RequestHelper *m_requestHelper; - std::vector m_participantVector; - std::vector m_equipmentVector; - QString m_menuGroup; - static int s_preselectedParty; - Ui::ParticipantsDialog *m_ui; + private: + LtsSession::LtsSession* m_session; + std::shared_ptr m_almDtc; + std::shared_ptr m_almFtc; + std::shared_ptr m_ppmDtc; + ParticipantAlarmModel* m_participantModel; + ParticipantManagement::ParticipantTreeFilterProxyModel* m_participantProxyModel; + LtsUtils::RequestHelper* m_requestHelper; + std::vector m_participantVector; + std::vector m_equipmentVector; + QString m_menuGroup; + static int s_preselectedParty; + Ui::ParticipantsDialog* m_ui; }; -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.cpp old mode 100755 new mode 100644 index 16a15d10a..ad3920c4b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.cpp @@ -1,73 +1,68 @@ - #include "alm_participant_model.h" #include - #include - namespace ParticipantAlarms { -ParticipantAlarmModel::ParticipantAlarmModel(QObject *parent, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &asbIfc) - : ParticipantManagement::ParticipantEditModel(parent, ppmDtc, asbIfc) - , m_logger(AlarmManagement::getLogger("ParticipantAlarmModel")) +ParticipantAlarmModel::ParticipantAlarmModel(QObject* parent, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& asbIfc) + : ParticipantManagement::ParticipantEditModel(parent, ppmDtc, asbIfc), + m_logger(AlarmManagement::getLogger("ParticipantAlarmModel")) { - m_titles += tr("Alarm Assignable"); + m_titles += tr("Alarm Assignable"); - DEBUG_LOG(m_logger) << "ParticipantAlarmModel::ParticipantAlarmModel"; + DEBUG_LOG(m_logger) << "ParticipantAlarmModel::ParticipantAlarmModel"; } -QVariant ParticipantAlarmModel::data(const QModelIndex &index, int role) const +QVariant ParticipantAlarmModel::data(const QModelIndex& index, int role) const { - - if (role == Qt::DisplayRole && index.column() == columnCount() - 1) - { - bool bIsSimulated = false; - if (!isSelectableByAlarm(index, &bIsSimulated)) - return QVariant(); - return !bIsSimulated ? tr("Yes") : tr("No"); - } - return ParticipantManagement::ParticipantEditModel::data(index, role); + if (role == Qt::DisplayRole && index.column() == columnCount() - 1) + { + bool bIsSimulated = false; + if (!isSelectableByAlarm(index, &bIsSimulated)) + return QVariant(); + return !bIsSimulated ? tr("Yes") : tr("No"); + } + + return ParticipantManagement::ParticipantEditModel::data(index, role); } -void ParticipantAlarmModel::onParticipantChanged(const ParticipantManagement::Participant &data, DataModification modType) +void ParticipantAlarmModel::onParticipantChanged(const ParticipantManagement::Participant& data, + DataModification modType) { - Q_UNUSED(modType); - if (data.partyId() != partyId()) - return; + Q_UNUSED(modType); + if (data.partyId() != partyId()) + return; - INFO_LOG(m_logger) << "onParticipantChanged isSimulated=" << data.isSimulated(); - onReinitModel(partyId()); - emit newData(); + INFO_LOG(m_logger) << "onParticipantChanged isSimulated=" << data.isSimulated(); + onReinitModel(partyId()); + emit newData(); } -bool ParticipantAlarmModel::isSelectableByAlarm(const QModelIndex &index, bool *bIsSimulated) const +bool ParticipantAlarmModel::isSelectableByAlarm(const QModelIndex& index, bool* bIsSimulated) const { - bool isSimulatable = false; - const ParticipantManagement::ParticipantData data(getParticipantData(index)); + bool isSimulatable = false; + const ParticipantManagement::ParticipantData data(getParticipantData(index)); - if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || - m_dtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) - isSimulatable = true; + if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || + m_dtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) + isSimulatable = true; - DEBUG_LOG(m_logger) << "ParticipantId: " << data.id() - << " isSimulated:" << data.isSimulated() - << " equipmentNo:" << data.equipmentNumber() - << " typeId=" << data.typeId() - << " modId=" << data.modId() - << " typeClass=" << m_dtc->type(data.typeId()).typeClass() - << " isSimulatable=" << isSimulatable; + DEBUG_LOG(m_logger) << "ParticipantId: " << data.id() << " isSimulated:" << data.isSimulated() + << " equipmentNo:" << data.equipmentNumber() << " typeId=" << data.typeId() + << " modId=" << data.modId() << " typeClass=" << m_dtc->type(data.typeId()).typeClass() + << " isSimulatable=" << isSimulatable; - if (bIsSimulated) - *bIsSimulated = data.isSimulated(); + if (bIsSimulated) + *bIsSimulated = data.isSimulated(); - return isSimulatable; + return isSimulatable; } -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.h old mode 100755 new mode 100644 index 4a9941c88..02f742587 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_model.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -9,21 +8,19 @@ namespace ParticipantAlarms { class ParticipantAlarmModel final : public ParticipantManagement::ParticipantEditModel { - Q_OBJECT -public: - ParticipantAlarmModel(QObject *parent, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &asbIfc); + Q_OBJECT + public: + ParticipantAlarmModel(QObject* parent, const std::shared_ptr& ppmDtc, + const std::shared_ptr& asbIfc); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -signals: - void newData(); + signals: + void newData(); -private: - -NGL::INGLLogger &m_logger; - void onParticipantChanged(const ParticipantManagement::Participant &data, DataModification modType); - bool isSelectableByAlarm(const QModelIndex &index, bool *bIsSimulated = nullptr) const; + private: + NGL::INGLLogger& m_logger; + void onParticipantChanged(const ParticipantManagement::Participant& data, DataModification modType); + bool isSelectableByAlarm(const QModelIndex& index, bool* bIsSimulated = nullptr) const; }; -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.cpp old mode 100755 new mode 100644 index cacbf61d4..67f34f2b6 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.cpp @@ -1,150 +1,133 @@ - #include "alm_participant_show_config.h" + #include "ui_alm_participant_show_config.h" -#include - #include +#include #include namespace ParticipantAlarms { -ParticipantShowConfigView::ParticipantShowConfigView(LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_configAlarmModel(nullptr) - , m_alarmHistoryModel(nullptr) - , m_dtc(nullptr) - , m_almFtc(nullptr) - , m_session(session) - , m_ui(new Ui::ParticipantShowConfigView) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_logger(AlarmManagement::getLogger("ParticipantShowConfigView")) +ParticipantShowConfigView::ParticipantShowConfigView(LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_configAlarmModel(nullptr), + m_alarmHistoryModel(nullptr), m_dtc(nullptr), m_almFtc(nullptr), m_session(session), + m_ui(new Ui::ParticipantShowConfigView), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_logger(AlarmManagement::getLogger("ParticipantShowConfigView")) { - DEBUG_LOG(m_logger) << "--- ParticipantShowConfigView Konstruktor() "; - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + DEBUG_LOG(m_logger) << "--- ParticipantShowConfigView Konstruktor() "; + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ParticipantShowConfigView::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &ParticipantShowConfigView::onSelectionChanged); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ParticipantShowConfigView::onShowAlarm); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ParticipantShowConfigView::onShowAlarm); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ParticipantShowConfigView::onRemoveAlarm); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ParticipantShowConfigView::onPrint); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - - setOnlineHelpFilename(QStringLiteral("Situation-Show_Config_Participant_Alarms")); - -} + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ParticipantShowConfigView::onRemoveAlarm); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ParticipantShowConfigView::onPrint); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + setOnlineHelpFilename(QStringLiteral("Situation-Show_Config_Participant_Alarms")); +} ParticipantShowConfigView::~ParticipantShowConfigView() { - INFO_LOG(m_logger) << "--- ParticipantShowConfigView Destruktor() "; - delete m_ui; -} - + INFO_LOG(m_logger) << "--- ParticipantShowConfigView Destruktor() "; + delete m_ui; +} void ParticipantShowConfigView::retranslate() { - translate(m_ui, tr("Show Config Participant Alarms")); + translate(m_ui, tr("Show Config Participant Alarms")); } -bool ParticipantShowConfigView::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc) +bool ParticipantShowConfigView::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc) { - INFO_LOG(m_logger) << "--- init() "; - if (!dtc || !ftc) - return false; + INFO_LOG(m_logger) << "--- init() "; + if (!dtc || !ftc) + return false; - m_dtc = dtc; - m_almFtc = ftc; - m_alarmHistoryModel = new AlarmManagement::AlarmHistoryModel(this); - m_alarmHistoryModel->initModel(dtc, ppmDtc, aesDtc); - - DEBUG_LOG(m_logger) << "--- ParticipantShowConfigView::init "; - m_configAlarmModel = new AlarmManagement::ConfigAlarmModel(this); - m_configAlarmModel->initModel(m_dtc, ppmDtc, m_alarmHistoryModel, false); - m_ui->widget->setModel(m_configAlarmModel); - return true; -} + m_dtc = dtc; + m_almFtc = ftc; + m_alarmHistoryModel = new AlarmManagement::AlarmHistoryModel(this); + m_alarmHistoryModel->initModel(dtc, ppmDtc, aesDtc); + DEBUG_LOG(m_logger) << "--- ParticipantShowConfigView::init "; + m_configAlarmModel = new AlarmManagement::ConfigAlarmModel(this); + m_configAlarmModel->initModel(m_dtc, ppmDtc, m_alarmHistoryModel, false); + m_ui->widget->setModel(m_configAlarmModel); + return true; +} void ParticipantShowConfigView::onSelectionChanged() { - QModelIndexList selectedRows = m_ui->widget->selectedRows(); - const int cntSelectedRows = selectedRows.size(); + QModelIndexList selectedRows = m_ui->widget->selectedRows(); + const int cntSelectedRows = selectedRows.size(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, cntSelectedRows == 1); -} + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, cntSelectedRows == 1); +} - -void ParticipantShowConfigView::onConfigureAlarmsReply(const Core::FunctionReplyObject &replyObject) +void ParticipantShowConfigView::onConfigureAlarmsReply(const Core::FunctionReplyObject& replyObject) { - DEBUG_LOG(m_logger)<<"onConfigureAlarmsReply"<requestReply(replyObject); -} + DEBUG_LOG(m_logger) << "onConfigureAlarmsReply" << replyObject.str(); + m_requestHelper->requestReply(replyObject); +} void ParticipantShowConfigView::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } void ParticipantShowConfigView::onShowAlarm() { - INFO_LOG(m_logger) << "--- onShowAlarm() "; -} - - + INFO_LOG(m_logger) << "--- onShowAlarm() "; +} void ParticipantShowConfigView::onRemoveAlarm() { - DEBUG_LOG(m_logger) << "onRemoveAlarm" - << " id = "<< m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).id() - << " eventTypeId = "<< m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).eventTypeId() - << " operatorId = "<< m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).operatorId() - << " participantId = "<< m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).participantId(); + DEBUG_LOG(m_logger) << "onRemoveAlarm" + << " id = " << m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).id() + << " eventTypeId = " + << m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).eventTypeId() + << " operatorId = " + << m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).operatorId() + << " participantId = " + << m_configAlarmModel->getRowData(m_ui->widget->currentIndex().row()).participantId(); - const QModelIndex curIdx = m_ui->widget->currentIndex(); - if (!curIdx.isValid()) - return; - const AlarmManagement::AlarmConfig &rowdata = m_configAlarmModel->getRowData(curIdx.row()); - int operatorId = rowdata.operatorId(); - std::vector ddsParticipantIds; - ddsParticipantIds.push_back(rowdata.participantId()); - bool globalEvent = true; - bool remove = true; - std::vector alarmsDds; - alarmsDds.resize(1); - alarmsDds[0].setMarker(false); - alarmsDds[0].messageWindow(false); - alarmsDds[0].eventTypeId(rowdata.eventTypeId()); - AlarmManagement::ConfigureAlarmsRequest request(alarmsDds, operatorId, ddsParticipantIds, globalEvent, remove); - - m_requestHelper->startSingleRequest([request, this]() - { - return m_almFtc->configureAlarmsRequest(request, this); - - }); - -} + const QModelIndex curIdx = m_ui->widget->currentIndex(); + if (!curIdx.isValid()) + return; + const AlarmManagement::AlarmConfig& rowdata = m_configAlarmModel->getRowData(curIdx.row()); + int operatorId = rowdata.operatorId(); + std::vector ddsParticipantIds; + ddsParticipantIds.push_back(rowdata.participantId()); + bool globalEvent = true; + bool remove = true; + std::vector alarmsDds; + alarmsDds.resize(1); + alarmsDds[0].setMarker(false); + alarmsDds[0].messageWindow(false); + alarmsDds[0].eventTypeId(rowdata.eventTypeId()); + AlarmManagement::ConfigureAlarmsRequest request(alarmsDds, operatorId, ddsParticipantIds, globalEvent, remove); + m_requestHelper->startSingleRequest([request, this]() { + return m_almFtc->configureAlarmsRequest(request, this); + }); +} void ParticipantShowConfigView::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView() ); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.h old mode 100755 new mode 100644 index 4c63ad58d..4b860fc28 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/ConfigParticipantAlarm/alm_participant_show_config.h @@ -1,65 +1,63 @@ - #pragma once -#include -#include -#include -#include #include #include +#include +#include #include +#include +#include namespace Ui { class ParticipantShowConfigView; } + namespace ParticipantAlarms { -class ParticipantShowConfigView : public LtsWidgets::LtsDialog - , protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler +class ParticipantShowConfigView : public LtsWidgets::LtsDialog, + protected AlarmManagement::Interface::Ftc::ConfigureAlarmsReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ParticipantShowConfigView(LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~ParticipantShowConfigView(); + public: + explicit ParticipantShowConfigView(LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~ParticipantShowConfigView(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &aesDtc); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& aesDtc); + private Q_SLOTS: + void retranslate() override; + void onSelectionChanged(); + void onShowAlarm(); + void onRemoveAlarm(); + void onPrint(); -private Q_SLOTS: - void retranslate() override; - void onSelectionChanged(); - void onShowAlarm(); - void onRemoveAlarm(); - void onPrint(); + protected: + NGL::INGLLogger& m_logger; + void onConfigureAlarmsReply(const Core::FunctionReplyObject& replyObject) override final; -protected: + private: + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void onConfigureAlarmsReply(const Core::FunctionReplyObject &replyObject) override final; + private: + AlarmManagement::ConfigAlarmModel* m_configAlarmModel; + AlarmManagement::AlarmHistoryModel* m_alarmHistoryModel; + std::shared_ptr m_dtc; + std::shared_ptr m_almFtc; -private: - void tableColumnOrganiserSetting() override; + LtsSession::LtsSession* m_session; + Ui::ParticipantShowConfigView* m_ui; + LtsUtils::RequestHelper* m_requestHelper; -private: - AlarmManagement::ConfigAlarmModel *m_configAlarmModel; - AlarmManagement::AlarmHistoryModel *m_alarmHistoryModel; - std::shared_ptr m_dtc; - std::shared_ptr m_almFtc; - - LtsSession::LtsSession *m_session; - Ui::ParticipantShowConfigView *m_ui; - LtsUtils::RequestHelper *m_requestHelper; - - AlarmManagement:: + AlarmManagement:: }; -} +} // namespace ParticipantAlarms diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_dialog.cpp old mode 100755 new mode 100644 index e83efcf58..183494fca --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_dialog.cpp @@ -1,264 +1,232 @@ - #include "alm_emergency_call_dialog.h" -#include "ui_alm_emergency_call_dialog.h" + #include "AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_model.h" -#include +#include "ui_alm_emergency_call_dialog.h" + +#include #include #include -#include - #include #include #include - +#include namespace AlarmManagement { - -EmergencyCallDialog::EmergencyCallDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_session(nullptr) - , m_ui(new Ui::EmergencyCallDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +EmergencyCallDialog::EmergencyCallDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_dtc(nullptr), m_ftc(nullptr), + m_session(nullptr), m_ui(new Ui::EmergencyCallDialog), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); } - void EmergencyCallDialog::retranslate() { - translate(m_ui, tr("Emergency Call ")); + translate(m_ui, tr("Emergency Call ")); } -bool EmergencyCallDialog::init(const std::shared_ptr &ftc, - const std::shared_ptr &dtc, - const std::shared_ptr &sitMapGuiIfc, - const std::shared_ptr &opmDtc, - LtsSession::LtsSession *session) +bool EmergencyCallDialog::init(const std::shared_ptr& ftc, + const std::shared_ptr& dtc, + const std::shared_ptr& sitMapGuiIfc, + const std::shared_ptr& opmDtc, + LtsSession::LtsSession* session) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START "; - if (!ftc || !dtc || !session){ - ERROR_LOG(m_logger)<<" init Emergency call dialog failed !!"; - return false; - } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START "; + if (!ftc || !dtc || !session) + { + ERROR_LOG(m_logger) << " init Emergency call dialog failed !!"; + return false; + } - m_ftc = ftc; - m_dtc = dtc; - m_opmDtc = opmDtc; - m_session = session; - m_dtc->enableAlmEmergencyCall(); - m_ftc->enableEmergencyCallAcknowledge(); - m_sitMapGuiIfc = sitMapGuiIfc; + m_ftc = ftc; + m_dtc = dtc; + m_opmDtc = opmDtc; + m_session = session; + m_dtc->enableAlmEmergencyCall(); + m_ftc->enableEmergencyCallAcknowledge(); + m_sitMapGuiIfc = sitMapGuiIfc; + delete m_model; + m_model = new AlarmManagement::EmergencyCallModel(this); + m_model->initModel(m_dtc, opmDtc); - delete m_model; - m_model = new AlarmManagement::EmergencyCallModel(this); - m_model->initModel(m_dtc, opmDtc); + m_proxyModel = new EmergencyCallProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->emergencyCallView->setModel(m_proxyModel); + m_proxyModel->hideByExerciseStopped(m_session->exerciseState() != LtsWidgets::ExcState::eStarted && + m_session->exerciseState() != LtsWidgets::ExcState::ePaused); + m_ui->emergencyCallView->setSortingEnabled(true); + m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::SAMPLE_TIME, 300); + m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::POSITION, 300); + m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::DELETED_TIMESTAMP, 300); - m_proxyModel = new EmergencyCallProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->emergencyCallView->setModel(m_proxyModel); - m_proxyModel->hideByExerciseStopped(m_session->exerciseState()!=LtsWidgets::ExcState::eStarted && - m_session->exerciseState() != LtsWidgets::ExcState::ePaused); - m_ui->emergencyCallView->setSortingEnabled(true); - m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::SAMPLE_TIME, 300); - m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::POSITION, 300); - m_ui->emergencyCallView->resizeSection(EmergencyCallModel::Columns::DELETED_TIMESTAMP, 300); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Acknowledge")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Show)->setText(tr("Center")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Show)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Acknowledge")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Show)->setText(tr("Center")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Show)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &EmergencyCallDialog::onEditBtCliked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &EmergencyCallDialog::onEditBtCliked); + const bool& hasOperatorRightEmergencyCall = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::EmergencyCall); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(hasOperatorRightEmergencyCall); - const bool &hasOperatorRightEmergencyCall = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::EmergencyCall); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(hasOperatorRightEmergencyCall); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, &EmergencyCallDialog::onFindEmergencyOnMap); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, &EmergencyCallDialog::onFindEmergencyOnMap); + QCheckBox* cbExpired = new QCheckBox(tr("Show expired"), m_ui->emergencyCallView); + cbExpired->setProperty("const", true); + m_ui->emergencyCallView->setCustomWidget(cbExpired); + connect(cbExpired, &QCheckBox::toggled, this, &EmergencyCallDialog::onSetShowExpired); - - - QCheckBox *cbExpired = new QCheckBox(tr("Show expired"), m_ui->emergencyCallView); - cbExpired->setProperty("const", true); - m_ui->emergencyCallView->setCustomWidget(cbExpired); - connect(cbExpired, &QCheckBox::toggled, this, &EmergencyCallDialog::onSetShowExpired); - - connect(m_ui->emergencyCallView, &LtsDataView::LtsDataView::signalSelectionChanged, this, &EmergencyCallDialog::enaDisa); - connect(m_ui->emergencyCallView, &LtsDataView::LtsDataView::doubleClicked, this, &EmergencyCallDialog::onEmergencyIndexDoubleClicked); - enaDisa(); + connect(m_ui->emergencyCallView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &EmergencyCallDialog::enaDisa); + connect(m_ui->emergencyCallView, &LtsDataView::LtsDataView::doubleClicked, this, + &EmergencyCallDialog::onEmergencyIndexDoubleClicked); + enaDisa(); #ifndef LTS_DEBUG - m_ui->emergencyCallView->hideColumn(EmergencyCallModel::ID); - m_ui->emergencyCallView->hideColumn(EmergencyCallModel::SAMPLE_TIME); - m_ui->emergencyCallView->hideColumn(EmergencyCallModel::NAME); - m_ui->emergencyCallView->hideColumn(EmergencyCallModel::EXPIRED); + m_ui->emergencyCallView->hideColumn(EmergencyCallModel::ID); + m_ui->emergencyCallView->hideColumn(EmergencyCallModel::SAMPLE_TIME); + m_ui->emergencyCallView->hideColumn(EmergencyCallModel::NAME); + m_ui->emergencyCallView->hideColumn(EmergencyCallModel::EXPIRED); #endif - INFO_LOG(m_logger) << "EmergencyCallDialog::init done"; - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; - return true; + INFO_LOG(m_logger) << "EmergencyCallDialog::init done"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + return true; } - - void EmergencyCallDialog::enaDisa() { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); - const AlmEmergencyCall &sos = getSelectedSOS(); - if (sos.id() <= 0) - return; + const AlmEmergencyCall& sos = getSelectedSOS(); + if (sos.id() <= 0) + return; - if (!sos.expired()) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); + if (!sos.expired()) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, true); } - - AlmEmergencyCall EmergencyCallDialog::getSelectedSOS() { - QModelIndexList indexList = m_ui->emergencyCallView->selectedRows(); - if (indexList.isEmpty()) - return {}; + QModelIndexList indexList = m_ui->emergencyCallView->selectedRows(); + if (indexList.isEmpty()) + return {}; - return m_model->getRowData(indexList.front().row()); + return m_model->getRowData(indexList.front().row()); } - - - void EmergencyCallDialog::setAcknowledgeUi() { - LtsWidgets::LtsFramelessDialog *popup = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); - LtsWidgets::LtsDialogButtonBox *btnBox = new LtsWidgets::LtsDialogButtonBox(popup); - btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); - QVBoxLayout *lay = new QVBoxLayout(popup); - QLineEdit *le = new QLineEdit(popup); - QLabel *lblTxt = new QLabel(tr("Acknowledged by:"), popup); + LtsWidgets::LtsFramelessDialog* popup = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); + LtsWidgets::LtsDialogButtonBox* btnBox = new LtsWidgets::LtsDialogButtonBox(popup); + btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); + QVBoxLayout* lay = new QVBoxLayout(popup); + QLineEdit* le = new QLineEdit(popup); + QLabel* lblTxt = new QLabel(tr("Acknowledged by:"), popup); - connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, popup, &LtsWidgets::LtsFramelessDialog::accept); + connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, popup, + &LtsWidgets::LtsFramelessDialog::accept); - - connect(le, &QLineEdit::textChanged, this, [btnBox](const QString &text) - { - const int textMinSize = 5; - btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(text.trimmed().size() >= textMinSize); - }); - - connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, [this, le, popup]() - { - sendAcknowledgeEmergency(le->text()); - popup->accept(); - }); + connect(le, &QLineEdit::textChanged, this, [btnBox](const QString& text) { + const int textMinSize = 5; + btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(text.trimmed().size() >= textMinSize); + }); - lay->addWidget(lblTxt); - lay->addWidget(le); - lay->addWidget(btnBox); - popup->setLayout(lay); - popup->setMinimumWidth(350); - popup->show(); - le->setFocus(); + connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, [this, le, popup]() { + sendAcknowledgeEmergency(le->text()); + popup->accept(); + }); + + lay->addWidget(lblTxt); + lay->addWidget(le); + lay->addWidget(btnBox); + popup->setLayout(lay); + popup->setMinimumWidth(350); + popup->show(); + le->setFocus(); } - - void EmergencyCallDialog::onEditBtCliked() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - const AlmEmergencyCall &sos = getSelectedSOS(); - if (sos.id() <= 0) - return; - setAcknowledgeUi(); + const AlmEmergencyCall& sos = getSelectedSOS(); + if (sos.id() <= 0) + return; + setAcknowledgeUi(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } - - - void EmergencyCallDialog::onSetShowExpired(bool show) { - if (m_proxyModel) - m_proxyModel->setShowExpired(show); + if (m_proxyModel) + m_proxyModel->setShowExpired(show); - - if (!m_updateSOSGuard) - m_updateSOSGuard = QSharedPointer(new UpdateSOSGuard(m_sitMapGuiIfc)); - m_updateSOSGuard->showExpiredSOS(show); + if (!m_updateSOSGuard) + m_updateSOSGuard = QSharedPointer(new UpdateSOSGuard(m_sitMapGuiIfc)); + m_updateSOSGuard->showExpiredSOS(show); } - - void EmergencyCallDialog::onFindEmergencyOnMap() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - const AlmEmergencyCall &sos = getSelectedSOS(); - if (sos.id() <= 0) - return; + const AlmEmergencyCall& sos = getSelectedSOS(); + if (sos.id() <= 0) + return; - m_sitMapGuiIfc->setCenterPoint(QPointF(sos.position().lon(), sos.position().lat())); + m_sitMapGuiIfc->setCenterPoint(QPointF(sos.position().lon(), sos.position().lat())); } - - -void EmergencyCallDialog::onEmergencyIndexDoubleClicked(const QModelIndex &index) +void EmergencyCallDialog::onEmergencyIndexDoubleClicked(const QModelIndex& index) { - Q_UNUSED(index) - emit openInfoDlg(getSelectedSOS().id()); + Q_UNUSED(index) + emit openInfoDlg(getSelectedSOS().id()); } - - -void EmergencyCallDialog::sendAcknowledgeEmergency(const QString &comment) +void EmergencyCallDialog::sendAcknowledgeEmergency(const QString& comment) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - const AlmEmergencyCall &sos = getSelectedSOS(); - if (sos.id() <= 0 || sos.expired()) - return; + const AlmEmergencyCall& sos = getSelectedSOS(); + if (sos.id() <= 0 || sos.expired()) + return; - EmergencyCallAcknowledgeRequest request; - request.id(sos.id()); - request.issi(sos.issi()); - request.name(sos.name()); - request.timestamp(QDateTime::currentMSecsSinceEpoch()); - request.incomingTime(sos.incomingTime()); - request.expired(true); - request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - request.comment(comment.toStdString()); - m_requestHelper->startSingleRequest([this, request]() - { - return m_ftc->emergencyCallAcknowledgeRequest(request, this); - }); + EmergencyCallAcknowledgeRequest request; + request.id(sos.id()); + request.issi(sos.issi()); + request.name(sos.name()); + request.timestamp(QDateTime::currentMSecsSinceEpoch()); + request.incomingTime(sos.incomingTime()); + request.expired(true); + request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + request.comment(comment.toStdString()); + m_requestHelper->startSingleRequest( + [this, request]() { return m_ftc->emergencyCallAcknowledgeRequest(request, this); }); - enaDisa(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + enaDisa(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } void EmergencyCallDialog::tableColumnOrganiserSetting() { - - m_ui->emergencyCallView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->emergencyCallView->setColumnsOrganiserEnabled(identifier(), true); } EmergencyCallDialog::~EmergencyCallDialog() { - - - - delete m_ui; + + delete m_ui; } - -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_info_dialog.cpp old mode 100755 new mode 100644 index f22ab1894..a03bcf25b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_info_dialog.cpp @@ -1,242 +1,220 @@ - #include "alm_emergency_call_info_dialog.h" + #include "ui_alm_emergency_call_info_dialog.h" + +#include #include -#include #include #include +#include #include -#include namespace AlarmManagement { QImage renderEmergencySymbol(bool expired = false) { - int size = 64; - QImage image(size, size, QImage::Format_ARGB32); - image.fill(Qt::transparent); + int size = 64; + QImage image(size, size, QImage::Format_ARGB32); + image.fill(Qt::transparent); - QPainter painter(&image); - painter.setRenderHint(QPainter::Antialiasing); + QPainter painter(&image); + painter.setRenderHint(QPainter::Antialiasing); - QPen pen(Qt::white); - pen.setWidth(3); - painter.setPen(pen); + QPen pen(Qt::white); + pen.setWidth(3); + painter.setPen(pen); - painter.setBrush( expired ? QBrush(Qt::gray) : QBrush(Qt::red)); - painter.drawEllipse(QPointF(image.rect().center()), - image.rect().width() * 0.45, - image.rect().height() * 0.45); + painter.setBrush(expired ? QBrush(Qt::gray) : QBrush(Qt::red)); + painter.drawEllipse(QPointF(image.rect().center()), image.rect().width() * 0.45, image.rect().height() * 0.45); - painter.setPen(QPen(Qt::white)); + painter.setPen(QPen(Qt::white)); - QFont font = painter.font(); - font.setBold(true); - font.setPixelSize(26); - painter.setFont(font); + QFont font = painter.font(); + font.setBold(true); + font.setPixelSize(26); + painter.setFont(font); - QPointF pos(image.width() * 0.125, - image.height() * 0.625); + QPointF pos(image.width() * 0.125, image.height() * 0.625); - painter.drawText(pos, QLatin1String("SOS")); + painter.drawText(pos, QLatin1String("SOS")); - return image; + return image; } - - -EmergencyCallInfoDialog::EmergencyCallInfoDialog(int entryId, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::EmergencyCallInfoDialog) +EmergencyCallInfoDialog::EmergencyCallInfoDialog(int entryId, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_dtc(nullptr), m_ftc(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::EmergencyCallInfoDialog) { - m_ui->setupUi(this); - m_emergency.id(entryId); + m_ui->setupUi(this); + m_emergency.id(entryId); } EmergencyCallInfoDialog::~EmergencyCallInfoDialog() { - delete m_ui; + delete m_ui; } - - -bool EmergencyCallInfoDialog::init(const std::shared_ptr &ftc, - const std::shared_ptr &dtc, - const std::shared_ptr &sitMapGuiIfc, - const std::shared_ptr&opmDtc) +bool EmergencyCallInfoDialog::init(const std::shared_ptr& ftc, + const std::shared_ptr& dtc, + const std::shared_ptr& sitMapGuiIfc, + const std::shared_ptr& opmDtc) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - if (!ftc || !dtc) - { - ERROR_LOG(m_logger)<<" init Emergency call Info dialog failed !!"; - return false; - } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + if (!ftc || !dtc) + { + ERROR_LOG(m_logger) << " init Emergency call Info dialog failed !!"; + return false; + } - m_dtc = dtc; - m_ftc = ftc; - m_opmDtc = opmDtc; - m_sitMapGuiIfc = sitMapGuiIfc; + m_dtc = dtc; + m_ftc = ftc; + m_opmDtc = opmDtc; + m_sitMapGuiIfc = sitMapGuiIfc; - m_dtc->enableAlmEmergencyCall(); - m_ftc->enableEmergencyCallAcknowledge(); + m_dtc->enableAlmEmergencyCall(); + m_ftc->enableEmergencyCallAcknowledge(); - - m_emergency = m_dtc->almEmergencyCall(m_emergency.id()); - setUiValues(); + m_emergency = m_dtc->almEmergencyCall(m_emergency.id()); + setUiValues(); - connect(m_dtc.get(), &AlarmManagement::Interface::Dtc::almEmergencyCallChanged, this, &EmergencyCallInfoDialog::onEmergencyCallChanged ); - connect(m_ui->pbAckEmergency, &QPushButton::clicked, this, &EmergencyCallInfoDialog::onPbAckEmergencyClicked ); - connect(m_ui->pbEmergencyCallFindOnMap, &QPushButton::clicked, this, &EmergencyCallInfoDialog::onFindEmergencyOnMap); + connect(m_dtc.get(), &AlarmManagement::Interface::Dtc::almEmergencyCallChanged, this, + &EmergencyCallInfoDialog::onEmergencyCallChanged); + connect(m_ui->pbAckEmergency, &QPushButton::clicked, this, &EmergencyCallInfoDialog::onPbAckEmergencyClicked); + connect(m_ui->pbEmergencyCallFindOnMap, &QPushButton::clicked, this, + &EmergencyCallInfoDialog::onFindEmergencyOnMap); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; - return true; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + return true; } - - QString EmergencyCallInfoDialog::emergencyIdentifier() const { - return QStringLiteral("emergency_") + QString::number(m_emergency.id()); + return QStringLiteral("emergency_") + QString::number(m_emergency.id()); } - - bool EmergencyCallInfoDialog::setUiValues() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - if (!m_dtc || !m_ftc || m_emergency.id() < 0) - { - ERROR_LOG(m_logger)<<" >> unabled to init EmergencyCallInfoDialog"; - return false; - } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + if (!m_dtc || !m_ftc || m_emergency.id() < 0) + { + ERROR_LOG(m_logger) << " >> unabled to init EmergencyCallInfoDialog"; + return false; + } - m_ui->lblEquipNr->setText(QString::number(m_emergency.issi())); - m_ui->lblIncomingTime->setText(DTG::toString(QDateTime::fromMSecsSinceEpoch(m_emergency.incomingTime()))); - m_ui->lblStatus->setText(m_emergency.expired() ? DTG::toString(QDateTime::fromMSecsSinceEpoch(m_emergency.deleted())) : QStringLiteral("--")); - m_ui->lblComment->setText(QString::fromStdString(m_emergency.comment())); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(m_emergency.position().lon(), m_emergency.position().lat()); - m_ui->lblPosition->setText(mgrs); + m_ui->lblEquipNr->setText(QString::number(m_emergency.issi())); + m_ui->lblIncomingTime->setText(DTG::toString(QDateTime::fromMSecsSinceEpoch(m_emergency.incomingTime()))); + m_ui->lblStatus->setText(m_emergency.expired() + ? DTG::toString(QDateTime::fromMSecsSinceEpoch(m_emergency.deleted())) + : QStringLiteral("--")); + m_ui->lblComment->setText(QString::fromStdString(m_emergency.comment())); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(m_emergency.position().lon(), m_emergency.position().lat()); + m_ui->lblPosition->setText(mgrs); - - const bool &hasOperatorRightEmergencyCall = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::EmergencyCall); - m_ui->pbAckEmergency->setIcon(QIcon(QStringLiteral("icon:edit.svg"))); - m_ui->pbAckEmergency->setEnabled(m_emergency.expired() ? false : true); - m_ui->pbAckEmergency->setVisible(hasOperatorRightEmergencyCall); + const bool& hasOperatorRightEmergencyCall = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::EmergencyCall); + m_ui->pbAckEmergency->setIcon(QIcon(QStringLiteral("icon:edit.svg"))); + m_ui->pbAckEmergency->setEnabled(m_emergency.expired() ? false : true); + m_ui->pbAckEmergency->setVisible(hasOperatorRightEmergencyCall); - - QPixmap iconPixmap = QPixmap::fromImage(renderEmergencySymbol(m_emergency.expired())); - m_ui->lblIcon->setPixmap(iconPixmap); + QPixmap iconPixmap = QPixmap::fromImage(renderEmergencySymbol(m_emergency.expired())); + m_ui->lblIcon->setPixmap(iconPixmap); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; - return true; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + return true; } - - void EmergencyCallInfoDialog::onEmergencyCallChanged(AlarmManagement::AlmEmergencyCall data, DataModification modType) { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - if (data.id() != m_emergency.id() || data.id() == 0) - return; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + if (data.id() != m_emergency.id() || data.id() == 0) + return; - if (modType == DataModification::eRemoved) - { - m_ui->pbAckEmergency->setEnabled(false); - m_ui->pbEmergencyCallFindOnMap->setEnabled(false); - return; - } - if (modType == DataModification::eModified) - { - m_emergency = data; - setUiValues(); - } + if (modType == DataModification::eRemoved) + { + m_ui->pbAckEmergency->setEnabled(false); + m_ui->pbEmergencyCallFindOnMap->setEnabled(false); + return; + } + if (modType == DataModification::eModified) + { + m_emergency = data; + setUiValues(); + } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } - - void EmergencyCallInfoDialog::onFindEmergencyOnMap() { - if (!m_sitMapGuiIfc || m_emergency.id() <= 0) - return; - m_sitMapGuiIfc->setCenterPoint(QPointF(m_emergency.position().lon(), m_emergency.position().lat())); + if (!m_sitMapGuiIfc || m_emergency.id() <= 0) + return; + m_sitMapGuiIfc->setCenterPoint(QPointF(m_emergency.position().lon(), m_emergency.position().lat())); } void EmergencyCallInfoDialog::onPbAckEmergencyClicked() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; - LtsWidgets::LtsFramelessDialog *popup = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); - LtsWidgets::LtsDialogButtonBox *btnBox = new LtsWidgets::LtsDialogButtonBox(popup); - btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); - QVBoxLayout *lay = new QVBoxLayout(popup); - QLineEdit *le = new QLineEdit(popup); - QLabel *lblTxt = new QLabel(tr("Acknowledged by:"), popup); + LtsWidgets::LtsFramelessDialog* popup = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); + LtsWidgets::LtsDialogButtonBox* btnBox = new LtsWidgets::LtsDialogButtonBox(popup); + btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); + QVBoxLayout* lay = new QVBoxLayout(popup); + QLineEdit* le = new QLineEdit(popup); + QLabel* lblTxt = new QLabel(tr("Acknowledged by:"), popup); - connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, popup, &LtsWidgets::LtsFramelessDialog::accept); + connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, popup, + &LtsWidgets::LtsFramelessDialog::accept); - - connect(le, &QLineEdit::textChanged, this, [btnBox](const QString &text) - { - const int textMinSize = 5; - btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(text.trimmed().size() >= textMinSize); - }); + connect(le, &QLineEdit::textChanged, this, [btnBox](const QString& text) { + const int textMinSize = 5; + btnBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(text.trimmed().size() >= textMinSize); + }); - connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, [this, le, popup]() - { - const QString c = le->text().trimmed(); - sendAcknowledgeEmergencyCallRequest(c); - popup->accept(); - }); + connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, [this, le, popup]() { + const QString c = le->text().trimmed(); + sendAcknowledgeEmergencyCallRequest(c); + popup->accept(); + }); - lay->addWidget(lblTxt); - lay->addWidget(le); - lay->addWidget(btnBox); - popup->setLayout(lay); - popup->setMinimumWidth(350); - popup->show(); - le->setFocus(); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + lay->addWidget(lblTxt); + lay->addWidget(le); + lay->addWidget(btnBox); + popup->setLayout(lay); + popup->setMinimumWidth(350); + popup->show(); + le->setFocus(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } - - -void EmergencyCallInfoDialog::sendAcknowledgeEmergencyCallRequest(const QString &comment) +void EmergencyCallInfoDialog::sendAcknowledgeEmergencyCallRequest(const QString& comment) { - if (m_emergency.id() <= 0) - return ; + if (m_emergency.id() <= 0) + return; - EmergencyCallAcknowledgeRequest request; - request.id(m_emergency.id()); - request.name(m_emergency.name()); - request.issi(m_emergency.issi()); - request.timestamp(QDateTime::currentMSecsSinceEpoch()); - request.incomingTime(m_emergency.incomingTime()); - request.expired(true); - request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - request.comment(comment.toStdString()); - bool ret = m_requestHelper->startSingleRequest([this, request]() - { - return m_ftc->emergencyCallAcknowledgeRequest(request, this); - }); + EmergencyCallAcknowledgeRequest request; + request.id(m_emergency.id()); + request.name(m_emergency.name()); + request.issi(m_emergency.issi()); + request.timestamp(QDateTime::currentMSecsSinceEpoch()); + request.incomingTime(m_emergency.incomingTime()); + request.expired(true); + request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + request.comment(comment.toStdString()); + bool ret = m_requestHelper->startSingleRequest( + [this, request]() { return m_ftc->emergencyCallAcknowledgeRequest(request, this); }); - if (ret) - setUiValues(); + if (ret) + setUiValues(); } void EmergencyCallInfoDialog::retranslate() { - m_emergency = m_dtc->almEmergencyCall(m_emergency.id()); - const QString lbName = tr("SOS_%1").arg(m_emergency.issi()); - translate(m_ui, lbName); + m_emergency = m_dtc->almEmergencyCall(m_emergency.id()); + const QString lbName = tr("SOS_%1").arg(m_emergency.issi()); + translate(m_ui, lbName); } - -} +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_model.h old mode 100755 new mode 100644 index 2acf75fc1..1ba9cd9bc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AlarmManagement/Gui/EmergencyCalls/alm_emergency_call_model.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -8,7 +7,6 @@ #include #include #include - #include namespace AlarmManagement @@ -16,67 +14,68 @@ namespace AlarmManagement class EmergencyCallModel : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - ID, - SAMPLE_TIME, - INCOMING_TIME, - NAME, - ISSI, - POSITION, - EXPIRED, - OPERATION_ID, - DELETED_TIMESTAMP, - COMMENT - }; - explicit EmergencyCallModel(QObject *parent = nullptr); + Q_OBJECT + public: + enum Columns { + ID, + SAMPLE_TIME, + INCOMING_TIME, + NAME, + ISSI, + POSITION, + EXPIRED, + OPERATION_ID, + DELETED_TIMESTAMP, + COMMENT + }; - QVariant data(const QModelIndex &index, int role) const override final; - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &opmDtc); + explicit EmergencyCallModel(QObject* parent = nullptr); -private slots: - void onAlarmEmergencyCallChanged(const AlarmManagement::AlmEmergencyCall &data, const DataModification modType); -private: -NGL::INGLLogger &m_logger; - std::shared_ptr m_dtc; - std::shared_ptr m_opmDtc; - friend class EmergencyCallProxyModel; + QVariant data(const QModelIndex& index, int role) const override final; + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& opmDtc); + private slots: + void onAlarmEmergencyCallChanged(const AlarmManagement::AlmEmergencyCall& data, const DataModification modType); + + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_dtc; + std::shared_ptr m_opmDtc; + friend class EmergencyCallProxyModel; }; - - - - - - class EmergencyCallProxyModel : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - bool showExpired() const { return m_showExpired; } - bool exerciseStopped()const {return m_hideByExerciseStopped;} - void setSourceModel(QAbstractItemModel *sourceModel) override; - void hideByExerciseStopped(bool show); + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; -public slots: - void setShowExpired(bool show); + bool showExpired() const + { + return m_showExpired; + } -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override final; + bool exerciseStopped() const + { + return m_hideByExerciseStopped; + } -private: - bool checkFilter(int source_row) const; + void setSourceModel(QAbstractItemModel* sourceModel) override; + void hideByExerciseStopped(bool show); -private: - bool m_showExpired{false}; - bool m_hideByExerciseStopped{false}; - EmergencyCallModel *m_sourceModel{nullptr}; + public slots: + void setShowExpired(bool show); + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override final; + + private: + bool checkFilter(int source_row) const; + + private: + bool m_showExpired{false}; + bool m_hideByExerciseStopped{false}; + EmergencyCallModel* m_sourceModel{nullptr}; }; -} - +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_charge_effect_item_info.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_charge_effect_item_info.cpp old mode 100755 new mode 100644 index e1e77881e..51d2e0f4b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_charge_effect_item_info.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_charge_effect_item_info.cpp @@ -1,347 +1,331 @@ -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "aes_charge_effect_item_info.h" #include "aes_translation.h" -#include "aes_charge_effect_item_info.h" #include "ui_aes_charge_effect_item_info.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace AreaEffectSimulation { -AesChargeEffectItemInfo::AesChargeEffectItemInfo(int chargeEffectId, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_session(nullptr) - , m_ChargeEffectId(chargeEffectId) - , m_ui(new Ui::AesChargeEffectItemInfo) +AesChargeEffectItemInfo::AesChargeEffectItemInfo(int chargeEffectId, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_session(nullptr), + m_ChargeEffectId(chargeEffectId), m_ui(new Ui::AesChargeEffectItemInfo) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_ui->lblChargeEffectId->setText(QString::number(m_ChargeEffectId)); - - connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &AesChargeEffectItemInfo::onFindOnMap); - connect(m_ui->pbDetails, &QToolButton::clicked, this, &AesChargeEffectItemInfo::onShowDetails); + m_ui->lblChargeEffectId->setText(QString::number(m_ChargeEffectId)); + connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &AesChargeEffectItemInfo::onFindOnMap); + connect(m_ui->pbDetails, &QToolButton::clicked, this, &AesChargeEffectItemInfo::onShowDetails); } AesChargeEffectItemInfo::~AesChargeEffectItemInfo() { - delete m_ui; + delete m_ui; } -bool AesChargeEffectItemInfo::init(LtsSession::LtsSession *session) +bool AesChargeEffectItemInfo::init(LtsSession::LtsSession* session) { - m_session = session; + m_session = session; - if (!session->getDtc(m_pdmDtc)) - { - ERROR_LOG(m_logger) << " failed to get pdmDtc"; - return false; - } + if (!session->getDtc(m_pdmDtc)) + { + ERROR_LOG(m_logger) << " failed to get pdmDtc"; + return false; + } - if (!session->getDtc(m_aesDtc)) - { - ERROR_LOG(m_logger) << " failed to get aesDtc"; - return false; - } - if (!m_aesDtc->isAesItemViewEnabled()) - m_aesDtc->enableAesItemView(); + if (!session->getDtc(m_aesDtc)) + { + ERROR_LOG(m_logger) << " failed to get aesDtc"; + return false; + } + if (!m_aesDtc->isAesItemViewEnabled()) + m_aesDtc->enableAesItemView(); - if (!m_pdmDtc->isChargeTypeEnabled()) - m_pdmDtc->enableChargeType(); + if (!m_pdmDtc->isChargeTypeEnabled()) + m_pdmDtc->enableChargeType(); + + const ChargeEffect data = m_aesDtc->chargeEffect(m_ChargeEffectId); + + m_ui->lblPosition->hide(); - const ChargeEffect data = m_aesDtc->chargeEffect(m_ChargeEffectId); - - m_ui->lblPosition->hide(); - #ifndef LTS_DEBUG - m_ui->lbxChargeEffectId->hide(); - m_ui->lblChargeEffectId->hide(); - m_ui->lbxChargeTypeId->hide(); - m_ui->lblChargeTypeId->hide(); - m_ui->lbxOriginatorId->hide(); - m_ui->lblOriginatorId->hide(); - m_ui->lbxOriginatorType->hide(); - m_ui->lblOriginatorType->hide(); + m_ui->lbxChargeEffectId->hide(); + m_ui->lblChargeEffectId->hide(); + m_ui->lbxChargeTypeId->hide(); + m_ui->lblChargeTypeId->hide(); + m_ui->lbxOriginatorId->hide(); + m_ui->lblOriginatorId->hide(); + m_ui->lbxOriginatorType->hide(); + m_ui->lblOriginatorType->hide(); #endif - m_ui->lblOriginatorId->setText(QString::number(data.originatorId())); - m_ui->lblOriginatorType->setText(QString::number(data.originatorTypeId().underlying())); + m_ui->lblOriginatorId->setText(QString::number(data.originatorId())); + m_ui->lblOriginatorType->setText(QString::number(data.originatorTypeId().underlying())); - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Charge_Effect")); + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Charge_Effect")); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::chargeEffectChanged, this, + &AesChargeEffectItemInfo::onChargeEffectChanged); - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::chargeEffectChanged, - this, &AesChargeEffectItemInfo::onChargeEffectChanged); + handleChargeEffect(data); - handleChargeEffect(data); - - return true; + return true; } void AesChargeEffectItemInfo::retranslate() { - const ChargeEffect item = m_aesDtc->chargeEffect(m_ChargeEffectId); + const ChargeEffect item = m_aesDtc->chargeEffect(m_ChargeEffectId); translate(m_ui, tr("ChargeEffect: \"%1\"").arg(QString::fromStdString(item.name()), 1, QLatin1Char('?'))); } void AesChargeEffectItemInfo::onFindOnMap() const { - DEBUG_LOG(m_logger) << "onFindOnMap() aesId: "< ifc; - if (m_session->getForeignGuiInterface(ifc)) - ifc->centerMapToChargeEffectObject(m_ChargeEffectId); - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; + DEBUG_LOG(m_logger) << "onFindOnMap() aesId: " << m_ChargeEffectId; + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + ifc->centerMapToChargeEffectObject(m_ChargeEffectId); + else + WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; } -template -bool AesChargeEffectItemInfo::tryShowStandardEditDialog(const AesItemView& aiv) +template bool AesChargeEffectItemInfo::tryShowStandardEditDialog(const AesItemView& aiv) { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(aiv.aesItemId(), this); - if (dialog) + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) { - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(aiv.aesItemId(), this); + if (dialog) + { + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); + } + return true; } - return true; - } - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed for specific AES interface!"; - return false; + WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed for specific AES interface!"; + return false; } void AesChargeEffectItemInfo::onShowDetails() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - const ChargeEffect item = m_aesDtc->chargeEffect(m_ChargeEffectId); + const ChargeEffect item = m_aesDtc->chargeEffect(m_ChargeEffectId); - if (item.originatorTypeId() == ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation) - { - AesItemView aiv; - m_aesDtc->aesItemViewFromEntityId(item.originatorId(), AreaEffectSimulation::AesType::AtUnknown, aiv); - DEBUG_LOG(m_logger) << "aiv.id():" << aiv.id() << ", aesType: " << aiv.aesTypeId(); + if (item.originatorTypeId() == ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation) + { + AesItemView aiv; + m_aesDtc->aesItemViewFromEntityId(item.originatorId(), AreaEffectSimulation::AesType::AtUnknown, aiv); + DEBUG_LOG(m_logger) << "aiv.id():" << aiv.id() << ", aesType: " << aiv.aesTypeId(); - - auto registerDialog = [this](AreaEffectSimulation::BaseEdit* dialog) { - if (dialog) { - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - }; + auto registerDialog = [this](AreaEffectSimulation::BaseEdit* dialog) { + if (dialog) + { + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); + } + }; - switch(aiv.aesTypeId().underlying()) - { - case AreaEffectSimulation::AesType::AtNContamination: - { - tryShowStandardEditDialog(aiv); - break; - } - case AreaEffectSimulation::AesType::AtMineArea: - { - tryShowStandardEditDialog(aiv); - break; - } - - case AreaEffectSimulation::AesType::AtMineCorridor: - { - tryShowStandardEditDialog(aiv); - break; - } - - case AreaEffectSimulation::AesType::AtGasPipe: - { - tryShowStandardEditDialog(aiv); - break; - } - case AreaEffectSimulation::AesType::AtDangerArea: - { - tryShowStandardEditDialog(aiv); - break; - } - case AreaEffectSimulation::AesType::AtBorderline: - { - tryShowStandardEditDialog(aiv); - break; - } - case AreaEffectSimulation::AesType::AtFunctionalArea: - { - tryShowStandardEditDialog(aiv); - break; - } - - case AreaEffectSimulation::AesType::AtBCContamination: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(aiv.chargeStruct().chargeTypeId()); - if (gearClass == ProjectDataManagement::GearClass_def::Biological) - registerDialog(ifc->showEditWindow(aiv.aesItemId(), false, this)); - else if (gearClass == ProjectDataManagement::GearClass_def::Chemical) - registerDialog(ifc->showEditWindow(aiv.aesItemId(), true, this)); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtBoobyTrap: - case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - registerDialog(ifc->showBoobyTrapEditWindow(aiv.aesItemId(), this)); - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtOffRouteMine: - case AreaEffectSimulation::AesType::AtOffRouteMineSecondary: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - registerDialog(ifc->showOffRouteMineEditWindow(aiv.aesItemId(), this)); - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtExplosionSingle: - case AreaEffectSimulation::AesType::AtExplosionArea: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - const bool isExplosionSingle = (aiv.aesTypeId().underlying() == AreaEffectSimulation::AesType::AtExplosionSingle); - const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(aiv.chargeStruct().chargeTypeId()); - - for (auto gc : { ProjectDataManagement::GearClass::Artillery, ProjectDataManagement::GearClass::Mortar, ProjectDataManagement::GearClass::AirSupport }) + switch (aiv.aesTypeId().underlying()) { - if (gc == ProjectDataManagement::GearClass::AirSupport && !isExplosionSingle) continue; + case AreaEffectSimulation::AesType::AtNContamination: { + tryShowStandardEditDialog(aiv); + break; + } + case AreaEffectSimulation::AesType::AtMineArea: { + tryShowStandardEditDialog(aiv); + break; + } - if (gearClass == gc) - { - registerDialog(ifc->showEditWindow(aiv.aesItemId(), isExplosionSingle, false, gc, this)); - break; - } + case AreaEffectSimulation::AesType::AtMineCorridor: { + tryShowStandardEditDialog(aiv); + break; + } + + case AreaEffectSimulation::AesType::AtGasPipe: { + tryShowStandardEditDialog(aiv); + break; + } + case AreaEffectSimulation::AesType::AtDangerArea: { + tryShowStandardEditDialog(aiv); + break; + } + case AreaEffectSimulation::AesType::AtBorderline: { + tryShowStandardEditDialog(aiv); + break; + } + case AreaEffectSimulation::AesType::AtFunctionalArea: { + tryShowStandardEditDialog(aiv); + break; + } + + case AreaEffectSimulation::AesType::AtBCContamination: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(aiv.chargeStruct().chargeTypeId()); + if (gearClass == ProjectDataManagement::GearClass_def::Biological) + registerDialog(ifc->showEditWindow(aiv.aesItemId(), false, this)); + else if (gearClass == ProjectDataManagement::GearClass_def::Chemical) + registerDialog(ifc->showEditWindow(aiv.aesItemId(), true, this)); + } + else + WARNING_LOG(m_logger) + << Q_FUNC_INFO << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtBoobyTrap: + case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + registerDialog(ifc->showBoobyTrapEditWindow(aiv.aesItemId(), this)); + else + WARNING_LOG(m_logger) + << Q_FUNC_INFO << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtOffRouteMine: + case AreaEffectSimulation::AesType::AtOffRouteMineSecondary: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + registerDialog(ifc->showOffRouteMineEditWindow(aiv.aesItemId(), this)); + else + WARNING_LOG(m_logger) + << Q_FUNC_INFO << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtExplosionSingle: + case AreaEffectSimulation::AesType::AtExplosionArea: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + const bool isExplosionSingle = + (aiv.aesTypeId().underlying() == AreaEffectSimulation::AesType::AtExplosionSingle); + const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(aiv.chargeStruct().chargeTypeId()); + + for (auto gc : + {ProjectDataManagement::GearClass::Artillery, ProjectDataManagement::GearClass::Mortar, + ProjectDataManagement::GearClass::AirSupport}) + { + if (gc == ProjectDataManagement::GearClass::AirSupport && !isExplosionSingle) + continue; + + if (gearClass == gc) + { + registerDialog(ifc->showEditWindow(aiv.aesItemId(), isExplosionSingle, false, gc, this)); + break; + } + } + } + else + WARNING_LOG(m_logger) + << Q_FUNC_INFO << " getForeignGuiInterface failed!"; + break; + } + + case AreaEffectSimulation::AesType::AtExplosionCluster: + case AreaEffectSimulation::AesType::AtEffectCluster: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + + AesItem ai; + m_aesDtc->aesItemFromId(aiv.aesItemId(), ai); + registerDialog(ifc->showEditWindow(aiv.aesItemId(), ai.effectSourceId(), this)); + } + else + WARNING_LOG(m_logger) + << Q_FUNC_INFO << " getForeignGuiInterface failed!"; + break; + } + + case AreaEffectSimulation::AesType::AtAirSupportImpact: + case AreaEffectSimulation::AesType::AtDusSingleMine: + case AreaEffectSimulation::AesType::AtExplosionAreaSingleExplosions: + case AreaEffectSimulation::AesType::AtMineAreaSingleMines: + case AreaEffectSimulation::AesType::AtReconArea: + case AreaEffectSimulation::AesType::AtTechnicalArea: + case AreaEffectSimulation::AesType::AtExplosionSingleCentral: + case AreaEffectSimulation::AesType::AtExplosionSingleCentralTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleExplosions: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterGunToTargetLine: + case AreaEffectSimulation::AesType::AtEffectClusterGunToTargetLine: + case AreaEffectSimulation::AesType::AtEffectClusterSingleExplosions: + case AreaEffectSimulation::AesType::AtEffectClusterSingleTrajectory: + + m_ui->pbDetails->hide(); + break; + case AreaEffectSimulation::AesType::AtUnknown: + Q_ASSERT(false); + WARNING_LOG(m_logger) << "Unknown AesType found for aesEntityId: " << aiv.aesTypeId(); + break; + default: + DEBUG_LOG(m_logger) << "Couldn't find AesItem to ChargeEffect (any more). Hiding the button"; + m_ui->pbDetails->hide(); + break; } - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - - case AreaEffectSimulation::AesType::AtExplosionCluster: - case AreaEffectSimulation::AesType::AtEffectCluster: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - - AesItem ai; - m_aesDtc->aesItemFromId(aiv.aesItemId(), ai); - registerDialog(ifc->showEditWindow(aiv.aesItemId(), ai.effectSourceId(), this)); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - - case AreaEffectSimulation::AesType::AtAirSupportImpact: - case AreaEffectSimulation::AesType::AtDusSingleMine: - case AreaEffectSimulation::AesType::AtExplosionAreaSingleExplosions: - case AreaEffectSimulation::AesType::AtMineAreaSingleMines: - case AreaEffectSimulation::AesType::AtReconArea: - case AreaEffectSimulation::AesType::AtTechnicalArea: - case AreaEffectSimulation::AesType::AtExplosionSingleCentral: - case AreaEffectSimulation::AesType::AtExplosionSingleCentralTrajectory: - case AreaEffectSimulation::AesType::AtExplosionClusterSingleExplosions: - case AreaEffectSimulation::AesType::AtExplosionClusterSingleTrajectory: - case AreaEffectSimulation::AesType::AtExplosionClusterGunToTargetLine: - case AreaEffectSimulation::AesType::AtEffectClusterGunToTargetLine: - case AreaEffectSimulation::AesType::AtEffectClusterSingleExplosions: - case AreaEffectSimulation::AesType::AtEffectClusterSingleTrajectory: - - m_ui->pbDetails->hide(); - break; - case AreaEffectSimulation::AesType::AtUnknown: - Q_ASSERT(false); - WARNING_LOG(m_logger) << "Unknown AesType found for aesEntityId: " << aiv.aesTypeId(); - break; - default: - DEBUG_LOG(m_logger) << "Couldn't find AesItem to ChargeEffect (any more). Hiding the button"; - m_ui->pbDetails->hide(); - break; - } - - } - else - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_ChargeEffectId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); } else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface ChargeEffect failed!"; - } + { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_ChargeEffectId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface ChargeEffect failed!"; + } } -void AesChargeEffectItemInfo::onChargeEffectChanged(const ChargeEffect &data, DataModification modType) +void AesChargeEffectItemInfo::onChargeEffectChanged(const ChargeEffect& data, DataModification modType) { - DEBUG_LOG(m_logger) << " [onChargeEffectChanged] id: " << data.id(); - if (data.id() == m_ChargeEffectId && modType != DataModification::eRemoved) - handleChargeEffect(data); + DEBUG_LOG(m_logger) << " [onChargeEffectChanged] id: " << data.id(); + if (data.id() == m_ChargeEffectId && modType != DataModification::eRemoved) + handleChargeEffect(data); } -void AesChargeEffectItemInfo::handleChargeEffect(const ChargeEffect &data) +void AesChargeEffectItemInfo::handleChargeEffect(const ChargeEffect& data) { - - m_ui->lblChargeEffectName->setText(QString::fromStdString(data.name())); - - m_ui->lblEffectStart->setText(DTG::toStringMSec(data.effectStart())); - + m_ui->lblChargeEffectName->setText(QString::fromStdString(data.name())); - m_ui->lblEffectDuration->setVisible(data.effectDuration() > 0); - m_ui->lbxEffectDuration->setVisible(data.effectDuration() > 0); + m_ui->lblEffectStart->setText(DTG::toStringMSec(data.effectStart())); - m_ui->lblEffectDuration->setText(LtsWidgets::readableDuration(data.effectDuration())); + m_ui->lblEffectDuration->setVisible(data.effectDuration() > 0); + m_ui->lbxEffectDuration->setVisible(data.effectDuration() > 0); - - AreaEffectSimulation::AesEffectState st = data.state(); - m_ui->lblStatus->setText(AreaEffectSimulation::toString(st)); + m_ui->lblEffectDuration->setText(LtsWidgets::readableDuration(data.effectDuration())); - - m_ui->lblChargeTypeId->setText(QString::number(data.chargeTypeId())); + AreaEffectSimulation::AesEffectState st = data.state(); + m_ui->lblStatus->setText(AreaEffectSimulation::toString(st)); - - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(data.chargeTypeId())); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(data.chargeTypeId())); + m_ui->lblChargeTypeId->setText(QString::number(data.chargeTypeId())); - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.position().lon(), data.position().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(data.chargeTypeId())); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(data.chargeTypeId())); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.position().lon(), data.position().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_danger_area_aes_item_info.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_danger_area_aes_item_info.cpp old mode 100755 new mode 100644 index 2780a269f..706002147 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_danger_area_aes_item_info.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_danger_area_aes_item_info.cpp @@ -1,160 +1,150 @@ - #include "aes_danger_area_aes_item_info.h" -#include + #include "ui_aes_danger_area_aes_item_info.h" -#include + #include -#include #include #include - +#include +#include #include - #include - +#include namespace AreaEffectSimulation { - -DangerAreaAesItemInfo::DangerAreaAesItemInfo(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_dtc(nullptr) - , m_session(nullptr) - , m_ui(new Ui::DangerAreaAesItemInfo) - , m_aesItemId(-1) +DangerAreaAesItemInfo::DangerAreaAesItemInfo(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_dtc(nullptr), m_session(nullptr), + m_ui(new Ui::DangerAreaAesItemInfo), m_aesItemId(-1) { - m_ui->setupUi(this); + m_ui->setupUi(this); } DangerAreaAesItemInfo::~DangerAreaAesItemInfo() { - for (const auto &item : std::as_const(m_aesItems)) - delete item.item; - delete m_ui; + for (const auto& item : std::as_const(m_aesItems)) + delete item.item; + delete m_ui; } void DangerAreaAesItemInfo::retranslate() { - std::unique_ptr item(new BCContamination(m_dtc->bCContamination(m_aesItemId))); - if (item->id() > 0) - { - translate(m_ui, m_dtc->bCContamination(m_aesItemId), tr("B/C-Contamination")); - return; - } + std::unique_ptr item(new BCContamination(m_dtc->bCContamination(m_aesItemId))); + if (item->id() > 0) + { + translate(m_ui, m_dtc->bCContamination(m_aesItemId), tr("B/C-Contamination")); + return; + } - item.reset(new NContamination(m_dtc->nContamination(m_aesItemId))); - if (item->id() > 0) - { - translate(m_ui, m_dtc->nContamination(m_aesItemId), tr("N-Contamination")); - return; - } + item.reset(new NContamination(m_dtc->nContamination(m_aesItemId))); + if (item->id() > 0) + { + translate(m_ui, m_dtc->nContamination(m_aesItemId), tr("N-Contamination")); + return; + } + item.reset(new ExplosionArea(m_dtc->explosionArea(m_aesItemId))); + if (item->id() > 0) + { + translate(m_ui, m_dtc->explosionArea(m_aesItemId), tr("Explosion Area")); + return; + } - item.reset(new ExplosionArea(m_dtc->explosionArea(m_aesItemId))); - if (item->id() > 0) - { - translate(m_ui, m_dtc->explosionArea(m_aesItemId), tr("Explosion Area")); - return; - } + item.reset(new ExplosionSingle(m_dtc->explosionSingle(m_aesItemId))); + if (item->id() > 0) + { + translate(m_ui, m_dtc->explosionSingle(m_aesItemId), tr("Single Explosion")); + return; + } + item.reset(new MineArea(m_dtc->mineArea(m_aesItemId))); + if (item->id() > 0) + { + translate(m_ui, m_dtc->mineArea(m_aesItemId), tr("Mine Area")); + return; + } - item.reset(new ExplosionSingle(m_dtc->explosionSingle(m_aesItemId))); - if (item->id() > 0) - { - translate(m_ui, m_dtc->explosionSingle(m_aesItemId), tr("Single Explosion")); - return; - } - - - item.reset(new MineArea(m_dtc->mineArea(m_aesItemId))); - if (item->id() > 0) - { - translate(m_ui, m_dtc->mineArea(m_aesItemId), tr("Mine Area")); - return; - } - - translate(m_ui, tr("Unknown Aes Type")); + translate(m_ui, tr("Unknown Aes Type")); } -bool DangerAreaAesItemInfo::init(const QSet &dangerAreaIds, const QSet &aesItemIds, LtsSession::LtsSession *session) +bool DangerAreaAesItemInfo::init(const QSet& dangerAreaIds, const QSet& aesItemIds, + LtsSession::LtsSession* session) { - if (!init(session)) - return false; + if (!init(session)) + return false; - for (int dangerAreaId : dangerAreaIds) - m_dangerAreas.insert(dangerAreaId, m_dtc->dangerArea(dangerAreaId)); - for (int aesItemId : aesItemIds) - insertAesItem(aesItemId); + for (int dangerAreaId : dangerAreaIds) + m_dangerAreas.insert(dangerAreaId, m_dtc->dangerArea(dangerAreaId)); + for (int aesItemId : aesItemIds) + insertAesItem(aesItemId); - m_aesItemId = aesItemIds.empty() ? -1 : *aesItemIds.begin(); - setText(); - return true; + m_aesItemId = aesItemIds.empty() ? -1 : *aesItemIds.begin(); + setText(); + return true; } -bool DangerAreaAesItemInfo::init(LtsSession::LtsSession *session) +bool DangerAreaAesItemInfo::init(LtsSession::LtsSession* session) { - if (m_session && session) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - if (!m_session && !session) - { - ERROR_LOG(m_logger) << "No Session available!"; - return false; - } - if (!m_session) - m_session = session; + if (m_session && session) + { + ERROR_LOG(m_logger) << "double init()!"; + return false; + } + if (!m_session && !session) + { + ERROR_LOG(m_logger) << "No Session available!"; + return false; + } + if (!m_session) + m_session = session; - if(!m_dtc.get()) - if (!m_session->getDtc(m_dtc)) - return false; + if (!m_dtc.get()) + if (!m_session->getDtc(m_dtc)) + return false; - setText(); - return true; + setText(); + return true; } void DangerAreaAesItemInfo::insertAesItem(int aesItemId) { - AesItem *item; - item = new BCContamination(m_dtc->bCContamination(aesItemId)); - if (item->id() > 0) - { - m_aesItems.insert(aesItemId, AesStruct(AesType::AtBCContamination, item)); - return; - } - delete item; + AesItem* item; + item = new BCContamination(m_dtc->bCContamination(aesItemId)); + if (item->id() > 0) + { + m_aesItems.insert(aesItemId, AesStruct(AesType::AtBCContamination, item)); + return; + } + delete item; - WARNING_LOG(m_logger) << "AesItem with id " << aesItemId << " is not of any known type!"; + WARNING_LOG(m_logger) << "AesItem with id " << aesItemId << " is not of any known type!"; } void DangerAreaAesItemInfo::setText() { - for (const DangerArea &dangerArea : std::as_const(m_dangerAreas)) - aesItemInfo(&dangerArea); + for (const DangerArea& dangerArea : std::as_const(m_dangerAreas)) + aesItemInfo(&dangerArea); - - for(const AesStruct &aesStruct : std::as_const(m_aesItems)) - { - if(aesStruct.item->effectStateId() == AreaEffectSimulation::AesEffectState::EsActivated) - aesItemInfo(aesStruct.item); - } + for (const AesStruct& aesStruct : std::as_const(m_aesItems)) + { + if (aesStruct.item->effectStateId() == AreaEffectSimulation::AesEffectState::EsActivated) + aesItemInfo(aesStruct.item); + } } -void DangerAreaAesItemInfo::aesItemInfo(const AesItem *item) +void DangerAreaAesItemInfo::aesItemInfo(const AesItem* item) { - - std::shared_ptr guiInterface; - if (!m_session->getForeignGuiInterface(guiInterface) || !guiInterface) - return; - LtsWidgets::LtsDialog *info = guiInterface->showInfoWindow(item); - m_ui->mainLayout->addWidget(info); - + std::shared_ptr guiInterface; + if (!m_session->getForeignGuiInterface(guiInterface) || !guiInterface) + return; + + LtsWidgets::LtsDialog* info = guiInterface->showInfoWindow(item); + m_ui->mainLayout->addWidget(info); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.cpp old mode 100755 new mode 100644 index 2fc5ceb87..7f13e83ef --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.cpp @@ -1,1381 +1,1303 @@ - #include "aes_info_dialog.h" + #include "ui_aes_info_dialog.h" -#include -#include #include -#include - -#include -#include -#include -#include +#include +#include #include #include #include #include - -#include - #include -#include +#include +#include +#include +#include #include +#include +#include #include #include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include namespace AreaEffectSimulation { -AesInfoDialog::AesInfoDialog(int aesEntityId, AesType aesType, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_aesEntityId(aesEntityId) - , m_aesType(aesType) - , m_bcChargeTypeId(-1) - , m_singleExpChargeTypeId(-1) - , m_areaExpChargeTypeId(-1) - , m_session(nullptr) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_pdmDtc(nullptr) - , m_ui(new Ui::AesInfoDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +AesInfoDialog::AesInfoDialog(int aesEntityId, AesType aesType, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_aesEntityId(aesEntityId), + m_aesType(aesType), m_bcChargeTypeId(-1), m_singleExpChargeTypeId(-1), m_areaExpChargeTypeId(-1), + m_session(nullptr), m_dtc(nullptr), m_ftc(nullptr), m_pdmDtc(nullptr), m_ui(new Ui::AesInfoDialog), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - DEBUG_LOG(m_logger) << "ctor AesInfoDialog() "; - m_ui->setupUi(this); - m_ui->lblAesId->setText(QString::number(aesEntityId)); + DEBUG_LOG(m_logger) << "ctor AesInfoDialog() "; + m_ui->setupUi(this); + m_ui->lblAesId->setText(QString::number(aesEntityId)); - connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &AesInfoDialog::onFindOnMap); - connect(m_ui->pbDetails, &QToolButton::clicked, this, &AesInfoDialog::onShowDetails); - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableGuezDusMines = ps->value(QStringLiteral("aes"), - QStringLiteral("enableGuezDusMines")).toBool(); - m_ui->pbResetDusMines->setVisible(enableGuezDusMines); - connect(m_ui->pbResetDusMines, &QToolButton::clicked, this, &AesInfoDialog::onResetDusMines); -} + connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &AesInfoDialog::onFindOnMap); + connect(m_ui->pbDetails, &QToolButton::clicked, this, &AesInfoDialog::onShowDetails); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableGuezDusMines = ps->value(QStringLiteral("aes"), QStringLiteral("enableGuezDusMines")).toBool(); + m_ui->pbResetDusMines->setVisible(enableGuezDusMines); + connect(m_ui->pbResetDusMines, &QToolButton::clicked, this, &AesInfoDialog::onResetDusMines); +} AesInfoDialog::~AesInfoDialog() { - delete m_ui; -} - - + delete m_ui; +} void AesInfoDialog::retranslate() { - translate(m_ui, tr("%1 \"%2\"").arg(AreaEffectSimulation::toString(m_aesType)).arg(m_aesEntityName, 1, QLatin1Char('?'))); - m_ui->pbResetDusMines->setToolTip(m_mineIsReactivatable ? tr("Reset DUS Mines matched to this Minearea") : tr("Hide DUS Mines matched to this Minearea")); + translate(m_ui, + tr("%1 \"%2\"").arg(AreaEffectSimulation::toString(m_aesType)).arg(m_aesEntityName, 1, QLatin1Char('?'))); + m_ui->pbResetDusMines->setToolTip(m_mineIsReactivatable ? tr("Reset DUS Mines matched to this Minearea") + : tr("Hide DUS Mines matched to this Minearea")); } -bool AesInfoDialog::cbFunc(const AreaEffectSimulation::AesItemView &aesItemView) +bool AesInfoDialog::cbFunc(const AreaEffectSimulation::AesItemView& aesItemView) { - if (aesItemView.aesItemId() != m_aesEntityId) - return false; + if (aesItemView.aesItemId() != m_aesEntityId) + return false; - DEBUG_LOG(m_logger) << "AesItemView found for aesEntityId: " << m_aesEntityId - << " AesItemView.aesTypeId(): " << aesItemView.aesTypeId(); + DEBUG_LOG(m_logger) << "AesItemView found for aesEntityId: " << m_aesEntityId + << " AesItemView.aesTypeId(): " << aesItemView.aesTypeId(); - if (aesItemView.aesTypeId() != m_aesType) - { - - return false; - } - switch (aesItemView.aesTypeId().underlying()) - { - case AreaEffectSimulation::AesType::AtNContamination: - { - handleNContamination(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::nContaminationChanged, this, &AesInfoDialog::onNContaminationChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::NContaminationChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-N-Contamination")); - break; - } - case AreaEffectSimulation::AesType::AtBCContamination: - { - handleBCContamination(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::bCContaminationChanged, this, &AesInfoDialog::onBCContaminationChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::bCContaminationChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-C-Contamination")); - break; - } - case AreaEffectSimulation::AesType::AtBoobyTrap: - case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: - { - handleBoobyTrap(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, this, &AesInfoDialog::onBoobyTrapChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::boobyTrapChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-BoobyTrap")); - break; - } - case AreaEffectSimulation::AesType_def::AtOffRouteMine: - case AreaEffectSimulation::AesType_def::AtOffRouteMineSecondary: - { - handleOffRouteMine(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::offRouteMineChanged, this, &AesInfoDialog::onOffRouteMineChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::offRouteMineChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-OffRouteMine")); - break; - } - case AreaEffectSimulation::AesType::AtExplosionArea: - { - handleExplosionArea(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionAreaChanged, this, &AesInfoDialog::onExplosionAreaChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::explosionAreaChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Area_Artillery")); - break; - } - case AreaEffectSimulation::AesType::AtExplosionSingle: - { - handleExplosionSingle(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionSingleChanged, this, &AesInfoDialog::onExplosionSingleChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::explosionSingleChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Single_Artillery")); - break; - } - case AreaEffectSimulation::AesType::AtMineArea: - { - handleMineArea(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::mineAreaChanged, this, &AesInfoDialog::onMineAreaChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::mineAreaChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Area")); - break; - } - case AreaEffectSimulation::AesType::AtMineCorridor: - { - handleMineCorridor(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::mineCorridorChanged, this, &AesInfoDialog::onMineCorridorChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::mineCorridorChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Corridor")); - break; - } - case AreaEffectSimulation::AesType::AtGasPipe: - { - handleGasPipe(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::gasPipeChanged, this, &AesInfoDialog::onGasPipeChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::gasPipeChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Gas_Pipeline")); - break; - } - case AreaEffectSimulation::AesType::AtDangerArea: - { - handleDangerArea(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dangerAreaChanged, this, &AesInfoDialog::onDangerAreaChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::dangerAreaChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Danger_Area")); - break; - } - case AreaEffectSimulation::AesType::AtBorderline: - { - handleBorderline(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::borderlineChanged, this, &AesInfoDialog::onBorderlineChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::borderlineChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Borderline")); + if (aesItemView.aesTypeId() != m_aesType) + { - - m_ui->lbChargeType->hide(); - m_ui->lblChargeTypeId->hide(); + return false; + } + switch (aesItemView.aesTypeId().underlying()) + { + case AreaEffectSimulation::AesType::AtNContamination: { + handleNContamination(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::nContaminationChanged, this, + &AesInfoDialog::onNContaminationChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::NContaminationChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-N-Contamination")); + break; + } + case AreaEffectSimulation::AesType::AtBCContamination: { + handleBCContamination(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::bCContaminationChanged, this, + &AesInfoDialog::onBCContaminationChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::bCContaminationChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-C-Contamination")); + break; + } + case AreaEffectSimulation::AesType::AtBoobyTrap: + case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: { + handleBoobyTrap(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, this, + &AesInfoDialog::onBoobyTrapChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::boobyTrapChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-BoobyTrap")); + break; + } + case AreaEffectSimulation::AesType_def::AtOffRouteMine: + case AreaEffectSimulation::AesType_def::AtOffRouteMineSecondary: { + handleOffRouteMine(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::offRouteMineChanged, this, + &AesInfoDialog::onOffRouteMineChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::offRouteMineChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-OffRouteMine")); + break; + } + case AreaEffectSimulation::AesType::AtExplosionArea: { + handleExplosionArea(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionAreaChanged, this, + &AesInfoDialog::onExplosionAreaChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::explosionAreaChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Area_Artillery")); + break; + } + case AreaEffectSimulation::AesType::AtExplosionSingle: { + handleExplosionSingle(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionSingleChanged, this, + &AesInfoDialog::onExplosionSingleChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::explosionSingleChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Single_Artillery")); + break; + } + case AreaEffectSimulation::AesType::AtMineArea: { + handleMineArea(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::mineAreaChanged, this, + &AesInfoDialog::onMineAreaChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::mineAreaChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Area")); + break; + } + case AreaEffectSimulation::AesType::AtMineCorridor: { + handleMineCorridor(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::mineCorridorChanged, this, + &AesInfoDialog::onMineCorridorChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::mineCorridorChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Corridor")); + break; + } + case AreaEffectSimulation::AesType::AtGasPipe: { + handleGasPipe(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::gasPipeChanged, this, + &AesInfoDialog::onGasPipeChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::gasPipeChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Gas_Pipeline")); + break; + } + case AreaEffectSimulation::AesType::AtDangerArea: { + handleDangerArea(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dangerAreaChanged, this, + &AesInfoDialog::onDangerAreaChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::dangerAreaChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Danger_Area")); + break; + } + case AreaEffectSimulation::AesType::AtBorderline: { + handleBorderline(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::borderlineChanged, this, + &AesInfoDialog::onBorderlineChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::borderlineChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Borderline")); + + m_ui->lbChargeType->hide(); + m_ui->lblChargeTypeId->hide(); + m_ui->lbChargeTypeId->hide(); + m_ui->lblChargeType->hide(); + m_ui->lbAesStart->hide(); + m_ui->lblAesStart->hide(); + m_ui->lbAesDuration->hide(); + m_ui->lblAesDuration->hide(); + m_ui->lbStatus->hide(); + m_ui->lblStatus->hide(); + break; + } + case AreaEffectSimulation::AesType::AtFunctionalArea: { + handleFunctionalArea(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::functionalAreaChanged, this, + &AesInfoDialog::onFunctionalAreaChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::functionalAreaChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Functional_Area")); + break; + } + case AreaEffectSimulation::AesType::AtAirSupportImpact: { + handleAirSupportImpact(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::airSupportImpactChanged, this, + &AesInfoDialog::onAirSupportImpactChanged); + DEBUG_LOG(m_logger) + << "connect AreaEffectSimulation::Interface::Dtc::airSupportImpactChanged for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Aerial_Ordnance")); + break; + } + case AreaEffectSimulation::AesType::AtExplosionCluster: { + handleExplosionCluster(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionClusterChanged, this, + &AesInfoDialog::onExplosionClusterChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::ExplosionCluster for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Explosion_Cluster")); + break; + } + case AreaEffectSimulation::AesType::AtEffectCluster: { + handleEffectCluster(aesItemView); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::effectClusterChanged, this, + &AesInfoDialog::onEffectClusterChanged); + DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::EffectCluster for aesEntityId: " + << m_aesEntityId; + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Explosion_Cluster")); + break; + } + case AreaEffectSimulation::AesType::AtDusSingleMine: + case AreaEffectSimulation::AesType::AtExplosionAreaSingleExplosions: + case AreaEffectSimulation::AesType::AtMineAreaSingleMines: + case AreaEffectSimulation::AesType::AtReconArea: + case AreaEffectSimulation::AesType::AtTechnicalArea: + case AreaEffectSimulation::AesType::AtExplosionSingleCentral: + case AreaEffectSimulation::AesType::AtExplosionSingleCentralTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleExplosions: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterGunToTargetLine: + + break; + case AreaEffectSimulation::AesType::AtUnknown: + WARNING_LOG(m_logger) << "Unknown AesType found for aesEntityId " << m_aesEntityId << ": " + << aesItemView.aesTypeId(); + Q_ASSERT(false); + break; + } + + return true; +} + +bool AesInfoDialog::init(LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& pdmDtc) +{ + m_session = session; + m_dtc = dtc; + m_ftc = ftc; + m_pdmDtc = pdmDtc; + + if (!m_pdmDtc->isChargeTypeEnabled()) + m_pdmDtc->enableChargeType(); + + m_ui->lblPosition->hide(); + m_ui->pbResetDusMines->hide(); + + m_ui->lbFlightTime->hide(); + m_ui->lblFlightTime->hide(); + +#ifndef LTS_DEBUG + m_ui->lbAesId->hide(); + m_ui->lblAesId->hide(); + m_ui->lbAesItemId->hide(); + m_ui->lblAesItemId->hide(); + m_ui->lbAesTypeId->hide(); + m_ui->lblAesTypeId->hide(); m_ui->lbChargeTypeId->hide(); + m_ui->lblChargeTypeId->hide(); +#endif + + m_ui->lbAesId->setText(tr("AES Id:")); + + if (m_aesType == AreaEffectSimulation::AesType_def::AtMineAreaSingleMines) + { + + handleMineAraeSingleMine(); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dusMineStateChanged, this, + &AesInfoDialog::onDusMineStateChanged); + } + else if (m_aesType == AreaEffectSimulation::AesType_def::AtDusSingleMine) + { + + handleSingleDusMine(); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dusSingleMineChanged, this, + &AesInfoDialog::onDusSingleMineChanged); + } + else + { + std::function cb = + [this](const AreaEffectSimulation::AesItemView& aesItemView) { return cbFunc(aesItemView); }; + m_dtc->aesItemViews(cb); + } + + return true; +} + +void AesInfoDialog::handleNContamination(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + + handleNContamination(m_dtc->nContamination(m_aesEntityId)); +} + +void AesInfoDialog::handleNContamination(const AreaEffectSimulation::NContamination& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::NContamination)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtNContamination); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleBCContamination(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + + handleBCContamination(m_dtc->bCContamination(m_aesEntityId)); +} + +void AesInfoDialog::handleBCContamination(const AreaEffectSimulation::BCContamination& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::BCContamination)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtBCContamination); + + m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleBoobyTrap(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + + handleBoobyTrap(m_dtc->boobyTrap(m_aesEntityId)); +} + +void AesInfoDialog::handleBoobyTrap(const AreaEffectSimulation::BoobyTrap& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::BoobyTrap)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType_def::AtBoobyTrap); + + m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); + + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_bcChargeTypeId, true)); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_bcChargeTypeId, true)); + m_ui->lblChargeType->show(); + m_ui->lblChargeTypeId->setText(QString::number(m_bcChargeTypeId)); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleOffRouteMine(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + + handleOffRouteMine(m_dtc->offRouteMine(m_aesEntityId)); +} + +void AesInfoDialog::handleOffRouteMine(const AreaEffectSimulation::OffRouteMine& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::OffRouteMine)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType_def::AtOffRouteMine); + + m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); + + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_bcChargeTypeId, true)); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_bcChargeTypeId, true)); + m_ui->lblChargeType->show(); + m_ui->lblChargeTypeId->setText(QString::number(m_bcChargeTypeId)); + + m_ui->lblPosition->show(); + QString mgrs = + LtsCoordTrans::mgrsFromGeographic(data.area().cornerBottomLeft().lon(), data.area().cornerBottomLeft().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleExplosionArea(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + + handleExplosionArea(m_dtc->explosionArea(m_aesEntityId)); +} + +void AesInfoDialog::handleExplosionArea(const AreaEffectSimulation::ExplosionArea& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtExplosionArea); + + m_areaExpChargeTypeId = data.chargeStruct().chargeTypeId(); + + const Area& area = data.area(); + if (!qFuzzyCompare(area.cornerBottomLeft().lon(), 0) || !qFuzzyCompare(area.cornerBottomLeft().lat(), 0)) + { + m_ui->lblPosition->show(); + QPointF bottomLeft(area.cornerBottomLeft().lon(), area.cornerBottomLeft().lat()); + const QPointF& center = + Polygons::bottomLeft2CenterPoint(bottomLeft, area.width(), area.height(), area.rotation()); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(center.x(), center.y()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + } +} + +void AesInfoDialog::handleExplosionSingle(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleExplosionSingle(m_dtc->explosionSingle(m_aesEntityId)); +} + +void AesInfoDialog::handleExplosionSingle(const AreaEffectSimulation::ExplosionSingle& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionSingle)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtExplosionSingle); + + m_singleExpChargeTypeId = data.chargeStruct().chargeTypeId(); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleMineArea(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleMineArea(m_dtc->mineArea(m_aesEntityId)); +} + +void AesInfoDialog::handleMineArea(const AreaEffectSimulation::MineArea& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::MineArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtMineArea); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.boundingRectCorner().lon(), data.boundingRectCorner().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + + bool bResetVisbile = + (data.isDus() || data.isConcrete()) && + + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::MineAreasResetDusMines) && + ((m_session->app() == LtsAppDescriptor::App::Situation || + m_session->app() == LtsAppDescriptor::App::SituationTablet) && + (!m_session->isReplayPartition())); + m_ui->pbResetDusMines->setVisible(bResetVisbile); + m_mineIsReactivatable = data.isReactivatable(); + m_ui->pbResetDusMines->setToolTip(data.isDus() ? tr("Reset DUS Mines matched to this Minearea") + : tr("Reset Concrete Mines matched to this Minearea")); +} + +void AesInfoDialog::handleMineCorridor(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleMineCorridor(m_dtc->mineCorridor(m_aesEntityId)); +} + +void AesInfoDialog::handleMineCorridor(const AreaEffectSimulation::MineCorridor& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::MineArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtMineCorridor); + m_ui->lblChargeType->hide(); + m_ui->lbChargeType->hide(); + + m_ui->lbAesDuration->hide(); + m_ui->lblAesDuration->hide(); +} + +void AesInfoDialog::handleGasPipe(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " handleGasPipe: aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleGasPipe(m_dtc->gasPipe(m_aesEntityId)); +} + +void AesInfoDialog::handleGasPipe(const AreaEffectSimulation::GasPipe& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::GasPipe)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtGasPipe); + + m_ui->lblChargeType->hide(); + m_ui->lbChargeType->hide(); + + m_ui->lbAesDuration->hide(); + m_ui->lblAesDuration->hide(); +} + +void AesInfoDialog::handleDangerArea(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleDangerArea(m_dtc->dangerArea(m_aesEntityId)); +} + +void AesInfoDialog::handleDangerArea(const AreaEffectSimulation::DangerArea& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::DangerArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtDangerArea); + + const auto& qv = data.segments(); + if (qv.size() > 0) + { + m_ui->lblPosition->show(); + const Core::GeoPosition2D& pos = qv.at(0); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + } + + m_ui->lbChargeType->hide(); + m_ui->lblChargeType->hide(); +} + +void AesInfoDialog::handleBorderline(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleBorderline(m_dtc->borderline(m_aesEntityId)); +} + +void AesInfoDialog::handleBorderline(const AreaEffectSimulation::Borderline& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::Borderline)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtBorderline); + + const auto& qv = data.segments(); + if (qv.size() > 0) + { + m_ui->lblPosition->show(); + const Core::GeoPosition2D& pos = qv.at(0); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + } +} + +void AesInfoDialog::handleFunctionalArea(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleFunctionalArea(m_dtc->functionalArea(m_aesEntityId)); +} + +void AesInfoDialog::handleFunctionalArea(const FunctionalArea& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::FunctionalArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtFunctionalArea); + + QStringList chargeTypesNames; + QStringList chargeTypesShortNames; + if (data.medicMode() != AesOperatingMode_def::OmNotUsed) + { + chargeTypesNames << m_pdmDtc->trChargeTypeName(411, true); + chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(411, true); + } + if (data.maintMode() != AesOperatingMode_def::OmNotUsed) + { + chargeTypesNames << m_pdmDtc->trChargeTypeName(412, true); + chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(412, true); + } + if (data.deconMode() != AesOperatingMode_def::OmNotUsed) + { + chargeTypesNames << m_pdmDtc->trChargeTypeName(413, true); + chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(413, true); + } + m_ui->lblChargeType->setText(chargeTypesNames.join(QLatin1String(", "))); + m_ui->lblChargeType->setToolTip(chargeTypesShortNames.join(QLatin1String(", "))); + + m_ui->lblPosition->show(); + const QPointF bottomLeft(data.area().cornerBottomLeft().lon(), data.area().cornerBottomLeft().lat()); + const QPointF centerpoint = + Polygons::bottomLeft2CenterPoint(bottomLeft, data.area().width(), data.area().height(), 0.0); + const QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerpoint.x(), centerpoint.y()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); +} + +void AesInfoDialog::handleAirSupportImpact(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleAirSupportImpact(m_dtc->airSupportImpact(m_aesEntityId)); +} + +void AesInfoDialog::handleAirSupportImpact(const AirSupportImpact& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::FunctionalArea)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtAirSupportImpact); + + m_ui->lblPosition->show(); + QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + + m_ui->lbFlightTime->show(); + m_ui->lblFlightTime->show(); + + m_ui->lblFlightTime->setText(LtsWidgets::readableDuration(data.flightTime())); +} + +void AesInfoDialog::handleMineAraeSingleMine() +{ + AesItemView itemView; + if (!m_dtc->aesItemViewFromEntityId(0, m_aesType, itemView)) + return; + const DusMineState dms = m_dtc->dusMineState(0); + for (size_t i = 0; i < dms.mines().size(); ++i) + { + const DusMine& mine = dms.mines().at(i); + if (mine.eqId() == m_aesEntityId) + { + if (itemView.form().size() <= i) + return; + handleMineAraeSingleMine(itemView.form().at(i), mine); + return; + } + } +} + +void AesInfoDialog::handleMineAraeSingleMine(const Core::GeoPosition2D& position, const DusMine& mine) +{ + m_ui->lbAesId->show(); + m_ui->lblAesId->show(); + + m_ui->lbAesItemId->hide(); + m_ui->lblAesItemId->hide(); + m_ui->lbAesName->hide(); + m_ui->lblAesName->hide(); m_ui->lbAesStart->hide(); m_ui->lblAesStart->hide(); m_ui->lbAesDuration->hide(); m_ui->lblAesDuration->hide(); - m_ui->lbStatus->hide(); - m_ui->lblStatus->hide(); - break; - } - case AreaEffectSimulation::AesType::AtFunctionalArea: - { - handleFunctionalArea(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::functionalAreaChanged, this, &AesInfoDialog::onFunctionalAreaChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::functionalAreaChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Functional_Area")); - break; - } - case AreaEffectSimulation::AesType::AtAirSupportImpact: - { - handleAirSupportImpact(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::airSupportImpactChanged, this, &AesInfoDialog::onAirSupportImpactChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::airSupportImpactChanged for aesEntityId: " << m_aesEntityId; - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Aerial_Ordnance")); - break; - } - case AreaEffectSimulation::AesType::AtExplosionCluster: - { - handleExplosionCluster(aesItemView); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionClusterChanged, this, &AesInfoDialog::onExplosionClusterChanged); - DEBUG_LOG(m_logger) << "connect AreaEffectSimulation::Interface::Dtc::ExplosionCluster for aesEntityId: "<pbDetails->hide(); - return true; -} + m_aesEntityName = QString::number(mine.eqId()); + m_ui->lblAesTypeId->setText(QString::number(m_aesType.underlying())); + m_ui->lblAesType->setText(toString(m_aesType)); -bool AesInfoDialog::init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &pdmDtc) -{ - m_session = session; - m_dtc = dtc; - m_ftc = ftc; - m_pdmDtc = pdmDtc; - - if (!m_pdmDtc->isChargeTypeEnabled()) - m_pdmDtc->enableChargeType(); - - m_ui->lblPosition->hide(); - m_ui->pbResetDusMines->hide(); - - - m_ui->lbFlightTime->hide(); - m_ui->lblFlightTime->hide(); - - -#ifndef LTS_DEBUG - m_ui->lbAesId->hide(); - m_ui->lblAesId->hide(); - m_ui->lbAesItemId->hide(); - m_ui->lblAesItemId->hide(); - m_ui->lbAesTypeId->hide(); - m_ui->lblAesTypeId->hide(); - m_ui->lbChargeTypeId->hide(); - m_ui->lblChargeTypeId->hide(); -#endif - - m_ui->lbAesId->setText(tr("AES Id:")); - - - if (m_aesType == AreaEffectSimulation::AesType_def::AtMineAreaSingleMines) - { - - handleMineAraeSingleMine(); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dusMineStateChanged, this, &AesInfoDialog::onDusMineStateChanged); - } - else if (m_aesType == AreaEffectSimulation::AesType_def::AtDusSingleMine) - { - - handleSingleDusMine(); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::dusSingleMineChanged, this, &AesInfoDialog::onDusSingleMineChanged); - } - else - { - std::function cb = [this](const AreaEffectSimulation::AesItemView & aesItemView) + const int ctId = mine.chargeTypeId(); + if (ctId != 0) { - return cbFunc(aesItemView); - }; - m_dtc->aesItemViews(cb); - } - - return true; -} - - -void AesInfoDialog::handleNContamination(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - - handleNContamination(m_dtc->nContamination(m_aesEntityId)); -} - - -void AesInfoDialog::handleNContamination(const AreaEffectSimulation::NContamination &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::NContamination)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtNContamination); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - -void AesInfoDialog::handleBCContamination(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - - handleBCContamination(m_dtc->bCContamination(m_aesEntityId)); -} - - -void AesInfoDialog::handleBCContamination(const AreaEffectSimulation::BCContamination &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::BCContamination)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtBCContamination); - - m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - -void AesInfoDialog::handleBoobyTrap(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - - handleBoobyTrap(m_dtc->boobyTrap(m_aesEntityId)); -} - - -void AesInfoDialog::handleBoobyTrap(const AreaEffectSimulation::BoobyTrap &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::BoobyTrap)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType_def::AtBoobyTrap); - - m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); - - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_bcChargeTypeId, true)); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_bcChargeTypeId, true)); - m_ui->lblChargeType->show(); - m_ui->lblChargeTypeId->setText(QString::number(m_bcChargeTypeId)); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - -void AesInfoDialog::handleOffRouteMine(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - - handleOffRouteMine(m_dtc->offRouteMine(m_aesEntityId)); -} - - -void AesInfoDialog::handleOffRouteMine(const AreaEffectSimulation::OffRouteMine &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::OffRouteMine)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType_def::AtOffRouteMine); - - m_bcChargeTypeId = data.chargeStruct().chargeTypeId(); - - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_bcChargeTypeId, true)); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_bcChargeTypeId, true)); - m_ui->lblChargeType->show(); - m_ui->lblChargeTypeId->setText(QString::number(m_bcChargeTypeId)); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.area().cornerBottomLeft().lon(), data.area().cornerBottomLeft().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - -void AesInfoDialog::handleExplosionArea(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - - handleExplosionArea(m_dtc->explosionArea(m_aesEntityId)); -} - - -void AesInfoDialog::handleExplosionArea(const AreaEffectSimulation::ExplosionArea &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtExplosionArea); - - m_areaExpChargeTypeId = data.chargeStruct().chargeTypeId(); - - const Area &area = data.area(); - if (!qFuzzyCompare(area.cornerBottomLeft().lon(), 0) || - !qFuzzyCompare(area.cornerBottomLeft().lat(), 0)) - { - m_ui->lblPosition->show(); - QPointF bottomLeft(area.cornerBottomLeft().lon(), area.cornerBottomLeft().lat()); - const QPointF ¢er = Polygons::bottomLeft2CenterPoint(bottomLeft, area.width(), area.height(), area.rotation()); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(center.x(), center.y()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - } - -} - - -void AesInfoDialog::handleExplosionSingle(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleExplosionSingle(m_dtc->explosionSingle(m_aesEntityId)); -} - - -void AesInfoDialog::handleExplosionSingle(const AreaEffectSimulation::ExplosionSingle &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionSingle)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtExplosionSingle); - - m_singleExpChargeTypeId = data.chargeStruct().chargeTypeId(); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - -void AesInfoDialog::handleMineArea(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleMineArea(m_dtc->mineArea(m_aesEntityId)); -} - - -void AesInfoDialog::handleMineArea(const AreaEffectSimulation::MineArea &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::MineArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtMineArea); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.boundingRectCorner().lon(), data.boundingRectCorner().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - - - bool bResetVisbile = (data.isDus() || data.isConcrete()) && - - LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::MineAreasResetDusMines) && - ((m_session->app() == LtsAppDescriptor::App::Situation || m_session->app() == LtsAppDescriptor::App::SituationTablet) && - (!m_session->isReplayPartition())); - m_ui->pbResetDusMines->setVisible(bResetVisbile); - m_mineIsReactivatable = data.isReactivatable(); - m_ui->pbResetDusMines->setToolTip(data.isDus() ? tr("Reset DUS Mines matched to this Minearea") : tr("Reset Concrete Mines matched to this Minearea")); -} - - -void AesInfoDialog::handleMineCorridor(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleMineCorridor(m_dtc->mineCorridor(m_aesEntityId)); -} - - -void AesInfoDialog::handleMineCorridor(const AreaEffectSimulation::MineCorridor &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::MineArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtMineCorridor); - - - m_ui->lblChargeType->hide(); - m_ui->lbChargeType->hide(); - - - m_ui->lbAesDuration->hide(); - m_ui->lblAesDuration->hide(); -} - - - -void AesInfoDialog::handleGasPipe(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " handleGasPipe: aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleGasPipe(m_dtc->gasPipe(m_aesEntityId)); -} - - -void AesInfoDialog::handleGasPipe(const AreaEffectSimulation::GasPipe &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::GasPipe)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtGasPipe); - - - m_ui->lblChargeType->hide(); - m_ui->lbChargeType->hide(); - - - m_ui->lbAesDuration->hide(); - m_ui->lblAesDuration->hide(); -} - - -void AesInfoDialog::handleDangerArea(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleDangerArea(m_dtc->dangerArea(m_aesEntityId)); -} - - -void AesInfoDialog::handleDangerArea(const AreaEffectSimulation::DangerArea &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::DangerArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtDangerArea); - - - const auto &qv = data.segments(); - if (qv.size() > 0) - { - m_ui->lblPosition->show(); - const Core::GeoPosition2D &pos = qv.at(0); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - } - - - m_ui->lbChargeType->hide(); - m_ui->lblChargeType->hide(); -} - - -void AesInfoDialog::handleBorderline(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleBorderline(m_dtc->borderline(m_aesEntityId)); -} - - -void AesInfoDialog::handleBorderline(const AreaEffectSimulation::Borderline &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::Borderline)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtBorderline); - - - const auto &qv = data.segments(); - if (qv.size() > 0) - { - m_ui->lblPosition->show(); - const Core::GeoPosition2D &pos = qv.at(0); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - } -} - - - -void AesInfoDialog::handleFunctionalArea(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleFunctionalArea(m_dtc->functionalArea(m_aesEntityId)); -} - - - -void AesInfoDialog::handleFunctionalArea(const FunctionalArea &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::FunctionalArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtFunctionalArea); - - - QStringList chargeTypesNames; - QStringList chargeTypesShortNames; - if (data.medicMode() != AesOperatingMode_def::OmNotUsed) - { - chargeTypesNames << m_pdmDtc->trChargeTypeName(411, true); - chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(411, true); - } - if (data.maintMode() != AesOperatingMode_def::OmNotUsed) - { - chargeTypesNames << m_pdmDtc->trChargeTypeName(412, true); - chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(412, true); - } - if (data.deconMode() != AesOperatingMode_def::OmNotUsed) - { - chargeTypesNames << m_pdmDtc->trChargeTypeName(413, true); - chargeTypesShortNames << m_pdmDtc->trChargeTypeShortName(413, true); - } - m_ui->lblChargeType->setText(chargeTypesNames.join(QLatin1String(", "))); - m_ui->lblChargeType->setToolTip(chargeTypesShortNames.join(QLatin1String(", "))); - - - m_ui->lblPosition->show(); - const QPointF bottomLeft(data.area().cornerBottomLeft().lon(), data.area().cornerBottomLeft().lat()); - const QPointF centerpoint = Polygons::bottomLeft2CenterPoint(bottomLeft, data.area().width(), data.area().height(), 0.0); - const QString mgrs = LtsCoordTrans::mgrsFromGeographic(centerpoint.x(), centerpoint.y()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); -} - - - -void AesInfoDialog::handleAirSupportImpact(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleAirSupportImpact(m_dtc->airSupportImpact(m_aesEntityId)); -} - - - -void AesInfoDialog::handleAirSupportImpact(const AirSupportImpact &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::FunctionalArea)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtAirSupportImpact); - - - m_ui->lblPosition->show(); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(data.impactPosition().lon(), data.impactPosition().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - - m_ui->lbFlightTime->show(); - m_ui->lblFlightTime->show(); - - m_ui->lblFlightTime->setText(LtsWidgets::readableDuration(data.flightTime())); -} - - - -void AesInfoDialog::handleMineAraeSingleMine() -{ - AesItemView itemView; - if (!m_dtc->aesItemViewFromEntityId(0, m_aesType, itemView)) - return; - const DusMineState dms = m_dtc->dusMineState(0); - for (size_t i = 0; i < dms.mines().size(); ++i) - { - const DusMine &mine = dms.mines().at(i); - if (mine.eqId() == m_aesEntityId) - { - if (itemView.form().size() <= i) - return; - handleMineAraeSingleMine(itemView.form().at(i), mine); - return; + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(ctId, true)); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(ctId, true)); + m_ui->lblChargeType->show(); + m_ui->lblChargeTypeId->setText(QString::number(ctId)); } - } -} + const bool isDus = static_cast(m_pdmDtc->mineClass(ctId, 0, 0)) == MineClass::DUS; + if (isDus) + m_ui->lbAesId->setText(tr("DUS Mine Id:")); + else + m_ui->lbAesId->setText(tr("Mine Id:")); + m_ui->lblAesId->setText(QString::number(mine.eqId())); -void AesInfoDialog::handleMineAraeSingleMine(const Core::GeoPosition2D &position, const DusMine &mine) -{ - m_ui->lbAesId->show(); - m_ui->lblAesId->show(); + bool bResetVisible = false; - m_ui->lbAesItemId->hide(); - m_ui->lblAesItemId->hide(); - m_ui->lbAesName->hide(); - m_ui->lblAesName->hide(); - m_ui->lbAesStart->hide(); - m_ui->lblAesStart->hide(); - m_ui->lbAesDuration->hide(); - m_ui->lblAesDuration->hide(); - m_ui->pbDetails->hide(); - - m_aesEntityName = QString::number(mine.eqId()); - - - m_ui->lblAesTypeId->setText(QString::number(m_aesType.underlying())); - m_ui->lblAesType->setText(toString(m_aesType)); - - - const int ctId = mine.chargeTypeId(); - if (ctId != 0) - { - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(ctId, true)); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(ctId, true)); - m_ui->lblChargeType->show(); - m_ui->lblChargeTypeId->setText(QString::number(ctId)); - } - - - - const bool isDus = static_cast(m_pdmDtc->mineClass(ctId, 0, 0)) == MineClass::DUS; - if (isDus) - m_ui->lbAesId->setText(tr("DUS Mine Id:")); - else - m_ui->lbAesId->setText(tr("Mine Id:")); - - m_ui->lblAesId->setText(QString::number(mine.eqId())); - - - bool bResetVisible = false; - - - if (mine.triggered() && isDus) - { - m_ui->lblStatus->setText(tr("Inactive")); - if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::MineAreasResetDusMines) + if (mine.triggered() && isDus) + { + m_ui->lblStatus->setText(tr("Inactive")); + if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::MineAreasResetDusMines) ) - bResetVisible = true; - } - else - { - m_ui->lblStatus->setText(tr("Active")); - } - m_ui->pbResetDusMines->setVisible(bResetVisible && - ((m_session->app() == LtsAppDescriptor::App::Situation || - m_session->app() == LtsAppDescriptor::App::SituationTablet) && - (!m_session->isReplayPartition()))); + bResetVisible = true; + } + else + { + m_ui->lblStatus->setText(tr("Active")); + } + m_ui->pbResetDusMines->setVisible(bResetVisible && ((m_session->app() == LtsAppDescriptor::App::Situation || + m_session->app() == LtsAppDescriptor::App::SituationTablet) && + (!m_session->isReplayPartition()))); - - m_mineIsReactivatable = m_pdmDtc->isReactivatable(ctId,0,0); - m_ui->pbResetDusMines->setToolTip(isDus ? tr("Reset DUS Mines matched to this Minearea") : tr("Reset Concrete Mines matched to this Minearea")); + m_mineIsReactivatable = m_pdmDtc->isReactivatable(ctId, 0, 0); + m_ui->pbResetDusMines->setToolTip(isDus ? tr("Reset DUS Mines matched to this Minearea") + : tr("Reset Concrete Mines matched to this Minearea")); - - const QString mgrs = LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - m_ui->lblPosition->show(); + const QString mgrs = LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + m_ui->lblPosition->show(); - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Area_Single_Mine")); + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Mine_Area_Single_Mine")); } - - void AesInfoDialog::handleSingleDusMine() { - DusSingleMine dsm = m_dtc->dusSingleMine(m_aesEntityId); + DusSingleMine dsm = m_dtc->dusSingleMine(m_aesEntityId); - m_ui->lbAesId->show(); - m_ui->lblAesId->show(); + m_ui->lbAesId->show(); + m_ui->lblAesId->show(); - m_ui->lbAesItemId->hide(); - m_ui->lblAesItemId->hide(); - m_ui->lbAesName->hide(); - m_ui->lblAesName->hide(); - m_ui->lbAesStart->hide(); - m_ui->lblAesStart->hide(); - m_ui->lbAesDuration->hide(); - m_ui->lblAesDuration->hide(); - m_ui->pbDetails->hide(); - - m_aesEntityName = QString::number(dsm.id()); - - - m_ui->lblAesTypeId->setText(QString::number(m_aesType.underlying())); - m_ui->lblAesType->setText(toString(m_aesType)); - - - const int ctId = dsm.chargeStruct().chargeTypeId(); - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(ctId)); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(ctId)); - m_ui->lblChargeType->show(); - m_ui->lblChargeTypeId->setText(QString::number(ctId)); - - - m_ui->lbAesId->setText(tr("DUS Mine Id:")); - m_ui->lblAesId->setText(QString::number(dsm.id())); - - - switch (dsm.effectStateId().underlying()) - { - case AesEffectState_def::EsExpired: - m_ui->lblStatus->setText(tr("Inactive")); - break; - case AesEffectState_def::EsRemoved: - m_ui->lblStatus->setText(tr("Removed")); - break; - case AesEffectState_def::EsCreated: - m_ui->lblStatus->setText(tr("Created")); - break; - case AesEffectState_def::EsPrepared: - m_ui->lblStatus->setText(tr("Prepared")); - break; - case AesEffectState_def::EsActivated: - m_ui->lblStatus->setText(tr("Active")); - break; - case AesEffectState_def::EsPaused: - m_ui->lblStatus->setText(tr("Paused")); - break; - case AesEffectState_def::EsError: - m_ui->lblStatus->setText(tr("Error")); - break; - case AesEffectState_def::EsReceived: - m_ui->lblStatus->setText(tr("Received")); - break; - default: - m_ui->lblStatus->setText(tr("Unknown")); - break; - } - - - const QString mgrs = LtsCoordTrans::mgrsFromGeographic(dsm.position().lon(), dsm.position().lat()); - m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); - m_ui->lblPosition->show(); - - setOnlineHelpFilename(QStringLiteral("Info_Dialog-DUS_Single_Mine")); -} - -void AesInfoDialog::handleExplosionCluster(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleExplosionCluster(m_dtc->explosionCluster(m_aesEntityId)); -} - -void AesInfoDialog::handleExplosionCluster(const ExplosionCluster &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionCluster)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtExplosionCluster); - - const int m_explosionClusterChargeTypeId = data.chargeStruct().chargeTypeId(); - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_explosionClusterChargeTypeId, true)); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_explosionClusterChargeTypeId, true)); - m_ui->lblChargeType->show(); - m_ui->lblChargeTypeId->setText(QString::number(m_explosionClusterChargeTypeId)); -} - -void AesInfoDialog::handleEffectCluster(const AesItemView &aesItemView) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" - << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); - handleEffectCluster(m_dtc->effectCluster(m_aesEntityId)); -} - -void AesInfoDialog::handleEffectCluster(const EffectCluster &data) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::EffectCluster)" - << " data.id(): " << data.id(); - - handleAesItem(data, AesType::AtEffectCluster); -} - - - - -void AesInfoDialog::handleAesItem(const AesItem &aesData, AesType aesTypeId) -{ - m_aesEntityName = QString::fromStdString(aesData.name()); - m_aesEffectSource = aesData.effectSourceId(); - - - m_ui->lblAesItemId->setText(QString::number(aesData.id())); - - - m_ui->lblAesTypeId->setText(QString::number(aesTypeId.underlying())); - const ProjectDataManagement::GearClass gearClass = m_pdmDtc->gearClassFromChargeTypeId(aesData.chargeStruct().chargeTypeId()); - switch (gearClass.underlying()) - { - case ProjectDataManagement::GearClass_def::Biological: - case ProjectDataManagement::GearClass_def::Chemical: - m_ui->lblAesType->setText(ProjectDataManagement::toString(gearClass)); - break; - default: - m_ui->lblAesType->setText(toString(aesTypeId)); - } - - - m_ui->lblAesName->setText(m_aesEntityName); - - - if (aesData.effectStart().is_set()) - m_ui->lblAesStart->setText(DTG::toStringMSec(aesData.effectStart().get())); - else - m_ui->lblAesStart->setText(tr("None")); - - - if (aesData.effectDuration() == 0) - { + m_ui->lbAesItemId->hide(); + m_ui->lblAesItemId->hide(); + m_ui->lbAesName->hide(); + m_ui->lblAesName->hide(); + m_ui->lbAesStart->hide(); + m_ui->lblAesStart->hide(); m_ui->lbAesDuration->hide(); m_ui->lblAesDuration->hide(); - } - if (aesTypeId == AesType::AtEffectCluster && aesData.effectDuration() == DEFAULT_EFFECT_DURATION) - m_ui->lblAesDuration->setText(QStringLiteral("---")); - else - m_ui->lblAesDuration->setText(LtsWidgets::readableDuration(aesData.effectDuration())); + m_ui->pbDetails->hide(); - - AreaEffectSimulation::AesEffectState st = aesData.effectStateId(); - m_ui->lblStatus->setText(toString(st)); + m_aesEntityName = QString::number(dsm.id()); - - m_ui->lblChargeTypeId->setText(QString::number(aesData.chargeStruct().chargeTypeId())); - - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(aesData.chargeStruct().chargeTypeId())); - m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(aesData.chargeStruct().chargeTypeId())); + m_ui->lblAesTypeId->setText(QString::number(m_aesType.underlying())); + m_ui->lblAesType->setText(toString(m_aesType)); -} + const int ctId = dsm.chargeStruct().chargeTypeId(); + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(ctId)); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(ctId)); + m_ui->lblChargeType->show(); + m_ui->lblChargeTypeId->setText(QString::number(ctId)); + m_ui->lbAesId->setText(tr("DUS Mine Id:")); + m_ui->lblAesId->setText(QString::number(dsm.id())); + + switch (dsm.effectStateId().underlying()) + { + case AesEffectState_def::EsExpired: + m_ui->lblStatus->setText(tr("Inactive")); + break; + case AesEffectState_def::EsRemoved: + m_ui->lblStatus->setText(tr("Removed")); + break; + case AesEffectState_def::EsCreated: + m_ui->lblStatus->setText(tr("Created")); + break; + case AesEffectState_def::EsPrepared: + m_ui->lblStatus->setText(tr("Prepared")); + break; + case AesEffectState_def::EsActivated: + m_ui->lblStatus->setText(tr("Active")); + break; + case AesEffectState_def::EsPaused: + m_ui->lblStatus->setText(tr("Paused")); + break; + case AesEffectState_def::EsError: + m_ui->lblStatus->setText(tr("Error")); + break; + case AesEffectState_def::EsReceived: + m_ui->lblStatus->setText(tr("Received")); + break; + default: + m_ui->lblStatus->setText(tr("Unknown")); + break; + } + + const QString mgrs = LtsCoordTrans::mgrsFromGeographic(dsm.position().lon(), dsm.position().lat()); + m_ui->lblPosition->setText(tr("Position: %1").arg(mgrs)); + m_ui->lblPosition->show(); + + setOnlineHelpFilename(QStringLiteral("Info_Dialog-DUS_Single_Mine")); +} + +void AesInfoDialog::handleExplosionCluster(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleExplosionCluster(m_dtc->explosionCluster(m_aesEntityId)); +} + +void AesInfoDialog::handleExplosionCluster(const ExplosionCluster& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::ExplosionCluster)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtExplosionCluster); + + const int m_explosionClusterChargeTypeId = data.chargeStruct().chargeTypeId(); + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_explosionClusterChargeTypeId, true)); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(m_explosionClusterChargeTypeId, true)); + m_ui->lblChargeType->show(); + m_ui->lblChargeTypeId->setText(QString::number(m_explosionClusterChargeTypeId)); +} + +void AesInfoDialog::handleEffectCluster(const AesItemView& aesItemView) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AesItemView)" + << " aesItemView.aesItemId(): " << aesItemView.aesItemId(); + handleEffectCluster(m_dtc->effectCluster(m_aesEntityId)); +} + +void AesInfoDialog::handleEffectCluster(const EffectCluster& data) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "(AreaEffectSimulation::EffectCluster)" + << " data.id(): " << data.id(); + + handleAesItem(data, AesType::AtEffectCluster); +} + +void AesInfoDialog::handleAesItem(const AesItem& aesData, AesType aesTypeId) +{ + m_aesEntityName = QString::fromStdString(aesData.name()); + m_aesEffectSource = aesData.effectSourceId(); + + m_ui->lblAesItemId->setText(QString::number(aesData.id())); + + m_ui->lblAesTypeId->setText(QString::number(aesTypeId.underlying())); + const ProjectDataManagement::GearClass gearClass = + m_pdmDtc->gearClassFromChargeTypeId(aesData.chargeStruct().chargeTypeId()); + switch (gearClass.underlying()) + { + case ProjectDataManagement::GearClass_def::Biological: + case ProjectDataManagement::GearClass_def::Chemical: + m_ui->lblAesType->setText(ProjectDataManagement::toString(gearClass)); + break; + default: + m_ui->lblAesType->setText(toString(aesTypeId)); + } + + m_ui->lblAesName->setText(m_aesEntityName); + + if (aesData.effectStart().is_set()) + m_ui->lblAesStart->setText(DTG::toStringMSec(aesData.effectStart().get())); + else + m_ui->lblAesStart->setText(tr("None")); + + if (aesData.effectDuration() == 0) + { + m_ui->lbAesDuration->hide(); + m_ui->lblAesDuration->hide(); + } + if (aesTypeId == AesType::AtEffectCluster && aesData.effectDuration() == DEFAULT_EFFECT_DURATION) + m_ui->lblAesDuration->setText(QStringLiteral("---")); + else + m_ui->lblAesDuration->setText(LtsWidgets::readableDuration(aesData.effectDuration())); + + AreaEffectSimulation::AesEffectState st = aesData.effectStateId(); + m_ui->lblStatus->setText(toString(st)); + + m_ui->lblChargeTypeId->setText(QString::number(aesData.chargeStruct().chargeTypeId())); + + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(aesData.chargeStruct().chargeTypeId())); + m_ui->lblChargeType->setToolTip(m_pdmDtc->trChargeTypeName(aesData.chargeStruct().chargeTypeId())); +} void AesInfoDialog::onFindOnMap() { - DEBUG_LOG(m_logger) << "onFindOnMap()"; - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - ifc->centerMapToAesObject(m_aesEntityId); - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; -} - + DEBUG_LOG(m_logger) << "onFindOnMap()"; + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + ifc->centerMapToAesObject(m_aesEntityId); + else + WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; +} void AesInfoDialog::onShowDetails() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - switch (m_aesType.underlying()) - { - case AreaEffectSimulation::AesType::AtNContamination: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) + switch (m_aesType.underlying()) { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtBCContamination: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_bcChargeTypeId); - if (gearClass == ProjectDataManagement::GearClass_def::Biological) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, false, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; - } - - if (gearClass == ProjectDataManagement::GearClass_def::Chemical) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, true, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; - } - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtBoobyTrap: - case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showBoobyTrapEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtOffRouteMine: - case AreaEffectSimulation::AesType::AtOffRouteMineSecondary: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showOffRouteMineEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtExplosionSingle: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - const auto gcs = { ProjectDataManagement::GearClass::Artillery, ProjectDataManagement::GearClass::Mortar, ProjectDataManagement::GearClass::AirSupport }; - const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_singleExpChargeTypeId); - for (auto gc : gcs) - { - if (gearClass == gc) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, true, false, gc, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; + case AreaEffectSimulation::AesType::AtNContamination: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; } - } - break; - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtExplosionArea: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - const auto gcs = { ProjectDataManagement::GearClass::Artillery, ProjectDataManagement::GearClass::Mortar }; - const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_areaExpChargeTypeId); - for (auto gc : gcs) - { - if (gearClass == gc) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, false, false, gc, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; + case AreaEffectSimulation::AesType::AtBCContamination: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_bcChargeTypeId); + if (gearClass == ProjectDataManagement::GearClass_def::Biological) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, false, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + + if (gearClass == ProjectDataManagement::GearClass_def::Chemical) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, true, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; } - } - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtExplosionCluster: - case AreaEffectSimulation::AesType::AtEffectCluster: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, m_aesEffectSource, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - break; - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtMineArea: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtMineCorridor: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtGasPipe: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtDangerArea: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtBorderline: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtFunctionalArea: - { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - { - AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); - if (dialog) - addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), LtsWidgets::LayoutArea::eDialogTab); - } - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << " getForeignGuiInterface failed!"; - break; - } - case AreaEffectSimulation::AesType::AtAirSupportImpact: - case AreaEffectSimulation::AesType::AtDusSingleMine: - case AreaEffectSimulation::AesType::AtExplosionAreaSingleExplosions: - case AreaEffectSimulation::AesType::AtMineAreaSingleMines: - case AreaEffectSimulation::AesType::AtReconArea: - case AreaEffectSimulation::AesType::AtTechnicalArea: - case AreaEffectSimulation::AesType::AtExplosionSingleCentral: - case AreaEffectSimulation::AesType::AtExplosionSingleCentralTrajectory: - case AreaEffectSimulation::AesType::AtExplosionClusterSingleExplosions: - case AreaEffectSimulation::AesType::AtExplosionClusterSingleTrajectory: - case AreaEffectSimulation::AesType::AtExplosionClusterGunToTargetLine: - - break; - case AreaEffectSimulation::AesType::AtUnknown: - Q_ASSERT(false); - WARNING_LOG(m_logger) << "Unknown AesType found for aesEntityId: " << m_aesEntityId; - break; - default: - break; - } -} - + case AreaEffectSimulation::AesType::AtBoobyTrap: + case AreaEffectSimulation::AesType::AtBoobyTrapSecondary: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showBoobyTrapEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtOffRouteMine: + case AreaEffectSimulation::AesType::AtOffRouteMineSecondary: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showOffRouteMineEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtExplosionSingle: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + const auto gcs = {ProjectDataManagement::GearClass::Artillery, ProjectDataManagement::GearClass::Mortar, + ProjectDataManagement::GearClass::AirSupport}; + const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_singleExpChargeTypeId); + for (auto gc : gcs) + { + if (gearClass == gc) + { + AreaEffectSimulation::BaseEdit* dialog = + ifc->showEditWindow(m_aesEntityId, true, false, gc, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + } + break; + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtExplosionArea: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + const auto gcs = {ProjectDataManagement::GearClass::Artillery, + ProjectDataManagement::GearClass::Mortar}; + const auto gearClass = m_pdmDtc->gearClassFromChargeTypeId(m_areaExpChargeTypeId); + for (auto gc : gcs) + { + if (gearClass == gc) + { + AreaEffectSimulation::BaseEdit* dialog = + ifc->showEditWindow(m_aesEntityId, false, false, gc, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + } + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtExplosionCluster: + case AreaEffectSimulation::AesType::AtEffectCluster: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, m_aesEffectSource, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + break; + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtMineArea: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtMineCorridor: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtGasPipe: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtDangerArea: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtBorderline: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtFunctionalArea: { + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + { + AreaEffectSimulation::BaseEdit* dialog = ifc->showEditWindow(m_aesEntityId, this); + if (dialog) + addDialog(dialog, dialog->menuGroup(), dialog->dialogIdentifier(), + LtsWidgets::LayoutArea::eDialogTab); + } + else + WARNING_LOG(m_logger) << Q_FUNC_INFO + << " getForeignGuiInterface failed!"; + break; + } + case AreaEffectSimulation::AesType::AtAirSupportImpact: + case AreaEffectSimulation::AesType::AtDusSingleMine: + case AreaEffectSimulation::AesType::AtExplosionAreaSingleExplosions: + case AreaEffectSimulation::AesType::AtMineAreaSingleMines: + case AreaEffectSimulation::AesType::AtReconArea: + case AreaEffectSimulation::AesType::AtTechnicalArea: + case AreaEffectSimulation::AesType::AtExplosionSingleCentral: + case AreaEffectSimulation::AesType::AtExplosionSingleCentralTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleExplosions: + case AreaEffectSimulation::AesType::AtExplosionClusterSingleTrajectory: + case AreaEffectSimulation::AesType::AtExplosionClusterGunToTargetLine: + break; + case AreaEffectSimulation::AesType::AtUnknown: + Q_ASSERT(false); + WARNING_LOG(m_logger) << "Unknown AesType found for aesEntityId: " << m_aesEntityId; + break; + default: + break; + } +} bool AesInfoDialog::onResetDusMines() { - if (m_aesType == AreaEffectSimulation::AesType_def::AtMineAreaSingleMines) - { - DEBUG_LOG(m_logger) << "onResetDusMines() AtMineAreaSingleMines mineId: " << m_aesEntityId; - MineResetRequest req(0, {m_aesEntityId}); - - return m_requestHelper->startSingleRequest([req, this]() + if (m_aesType == AreaEffectSimulation::AesType_def::AtMineAreaSingleMines) { - return m_ftc->mineResetRequest(req, this); - }); - } - else - { - MineResetRequest req(m_aesEntityId, {}); - return m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->mineResetRequest(req, this); - }); - } -} + DEBUG_LOG(m_logger) << "onResetDusMines() AtMineAreaSingleMines mineId: " << m_aesEntityId; + MineResetRequest req(0, {m_aesEntityId}); - -void AesInfoDialog::onNContaminationChanged(const AreaEffectSimulation::NContamination &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleNContamination(data); -} - - -void AesInfoDialog::onBCContaminationChanged(const AreaEffectSimulation::BCContamination &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleBCContamination(data); -} - - -void AesInfoDialog::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleBoobyTrap(data); -} - - -void AesInfoDialog::onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleOffRouteMine(data); -} - - -void AesInfoDialog::onExplosionAreaChanged(const AreaEffectSimulation::ExplosionArea &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleExplosionArea(data); -} - - -void AesInfoDialog::onExplosionSingleChanged(const AreaEffectSimulation::ExplosionSingle &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleExplosionSingle(data); -} - - -void AesInfoDialog::onMineAreaChanged(const AreaEffectSimulation::MineArea &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleMineArea(data); -} - - -void AesInfoDialog::onMineCorridorChanged(const MineCorridor &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleMineCorridor(data); -} - - -void AesInfoDialog::onGasPipeChanged(const GasPipe &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleGasPipe(data); -} - - -void AesInfoDialog::onDangerAreaChanged(const AreaEffectSimulation::DangerArea &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleDangerArea(data); -} - - -void AesInfoDialog::onBorderlineChanged(const AreaEffectSimulation::Borderline &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleBorderline(data); -} - - -void AesInfoDialog::onFunctionalAreaChanged(const FunctionalArea &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleFunctionalArea(data); -} - - -void AesInfoDialog::onAirSupportImpactChanged(const AirSupportImpact &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleAirSupportImpact(data); -} - - -void AesInfoDialog::onDusMineStateChanged(const DusMineState &data, DataModification modType) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - - if (modType == DataModification::eRemoved) - return; - if (data.id() != 0) - return; - - AesItemView itemView; - if (!m_dtc->aesItemViewFromEntityId(0, m_aesType, itemView)) - return; - - for (size_t i = 0; i < data.mines().size(); ++i) - { - const DusMine &mine = data.mines().at(i); - if (mine.eqId() == m_aesEntityId) + return m_requestHelper->startSingleRequest([req, this]() { return m_ftc->mineResetRequest(req, this); }); + } + else { - if (itemView.form().size() <= i) - return; - handleMineAraeSingleMine(itemView.form().at(i), mine); - return; + MineResetRequest req(m_aesEntityId, {}); + return m_requestHelper->startSingleRequest([req, this]() { return m_ftc->mineResetRequest(req, this); }); } - } } - -void AesInfoDialog::onDusSingleMineChanged(const DusSingleMine &data, DataModification modType) +void AesInfoDialog::onNContaminationChanged(const AreaEffectSimulation::NContamination& data, DataModification modType) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleSingleDusMine(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleNContamination(data); } - -void AesInfoDialog::onExplosionClusterChanged(const ExplosionCluster &data, DataModification modType) +void AesInfoDialog::onBCContaminationChanged(const AreaEffectSimulation::BCContamination& data, + DataModification modType) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleExplosionCluster(data); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleBCContamination(data); } -void AesInfoDialog::onEffectClusterChanged(const EffectCluster &data, DataModification modType) +void AesInfoDialog::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& data, DataModification modType) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); - if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) - handleEffectCluster(data); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleBoobyTrap(data); } +void AesInfoDialog::onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleOffRouteMine(data); +} +void AesInfoDialog::onExplosionAreaChanged(const AreaEffectSimulation::ExplosionArea& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleExplosionArea(data); +} -} +void AesInfoDialog::onExplosionSingleChanged(const AreaEffectSimulation::ExplosionSingle& data, + DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleExplosionSingle(data); +} + +void AesInfoDialog::onMineAreaChanged(const AreaEffectSimulation::MineArea& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleMineArea(data); +} + +void AesInfoDialog::onMineCorridorChanged(const MineCorridor& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleMineCorridor(data); +} + +void AesInfoDialog::onGasPipeChanged(const GasPipe& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleGasPipe(data); +} + +void AesInfoDialog::onDangerAreaChanged(const AreaEffectSimulation::DangerArea& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleDangerArea(data); +} + +void AesInfoDialog::onBorderlineChanged(const AreaEffectSimulation::Borderline& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleBorderline(data); +} + +void AesInfoDialog::onFunctionalAreaChanged(const FunctionalArea& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleFunctionalArea(data); +} + +void AesInfoDialog::onAirSupportImpactChanged(const AirSupportImpact& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleAirSupportImpact(data); +} + +void AesInfoDialog::onDusMineStateChanged(const DusMineState& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + + if (modType == DataModification::eRemoved) + return; + if (data.id() != 0) + return; + + AesItemView itemView; + if (!m_dtc->aesItemViewFromEntityId(0, m_aesType, itemView)) + return; + + for (size_t i = 0; i < data.mines().size(); ++i) + { + const DusMine& mine = data.mines().at(i); + if (mine.eqId() == m_aesEntityId) + { + if (itemView.form().size() <= i) + return; + handleMineAraeSingleMine(itemView.form().at(i), mine); + return; + } + } +} + +void AesInfoDialog::onDusSingleMineChanged(const DusSingleMine& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleSingleDusMine(); +} + +void AesInfoDialog::onExplosionClusterChanged(const ExplosionCluster& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleExplosionCluster(data); +} + +void AesInfoDialog::onEffectClusterChanged(const EffectCluster& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id: " << data.id(); + if (data.id() == m_aesEntityId && modType != DataModification::eRemoved) + handleEffectCluster(data); +} + +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.h old mode 100755 new mode 100644 index 679aeae28..7e3cc46ec --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/AesInfo/aes_info_dialog.h @@ -1,131 +1,122 @@ - #pragma once - -#include +#include #include #include - - -#include - - - +#include #include #include - -namespace Ui { +namespace Ui +{ class AesInfoDialog; } namespace AreaEffectSimulation { - - - -class AesInfoDialog : public LtsWidgets::LtsDialog - , protected AreaEffectSimulation::Interface::Ftc::MineResetReplyHandler +class AesInfoDialog : public LtsWidgets::LtsDialog, + protected AreaEffectSimulation::Interface::Ftc::MineResetReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit AesInfoDialog(int aesEntityId, AreaEffectSimulation::AesType aesType, QWidget *parent = nullptr); - ~AesInfoDialog(); + public: + explicit AesInfoDialog(int aesEntityId, AreaEffectSimulation::AesType aesType, QWidget* parent = nullptr); + ~AesInfoDialog(); - bool init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &pdmDtc); + bool init(LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& pdmDtc); - void onMineResetReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onMineResetReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - NGL::INGLLogger &m_logger; - void retranslate() override; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; - void handleNContamination(const AesItemView &aesItemView); - void handleNContamination(const AreaEffectSimulation::NContamination &data); - void handleBCContamination(const AesItemView &aesItemView); - void handleBCContamination(const AreaEffectSimulation::BCContamination &data); - void handleExplosionArea(const AesItemView &aesItemView); - void handleExplosionArea(const AreaEffectSimulation::ExplosionArea &data); - void handleExplosionSingle(const AesItemView &aesItemView); - void handleExplosionSingle(const AreaEffectSimulation::ExplosionSingle &data); - void handleMineArea(const AesItemView &aesItemView); - void handleMineArea(const AreaEffectSimulation::MineArea &data); - void handleMineCorridor(const AesItemView &aesItemView); - void handleMineCorridor(const AreaEffectSimulation::MineCorridor &data); - void handleBoobyTrap(const AesItemView &aesItemView); - void handleBoobyTrap(const AreaEffectSimulation::BoobyTrap &data); - void handleOffRouteMine(const AesItemView &aesItemView); - void handleOffRouteMine(const AreaEffectSimulation::OffRouteMine &data); - void handleGasPipe(const AesItemView &aesItemView); - void handleGasPipe(const AreaEffectSimulation::GasPipe &data); - void handleDangerArea(const AesItemView &aesItemView); - void handleDangerArea(const AreaEffectSimulation::DangerArea &data); - void handleBorderline(const AesItemView &aesItemView); - void handleBorderline(const AreaEffectSimulation::Borderline &data); - void handleFunctionalArea(const AesItemView &aesItemView); - void handleFunctionalArea(const AreaEffectSimulation::FunctionalArea &data); - void handleAirSupportImpact(const AesItemView &aesItemView); - void handleAirSupportImpact(const AreaEffectSimulation::AirSupportImpact &data); - void handleMineAraeSingleMine(); - void handleMineAraeSingleMine(const Core::GeoPosition2D &position, const DusMine &mine); - void handleSingleDusMine(); - void handleExplosionCluster(const AesItemView &aesItemView); - void handleExplosionCluster(const AreaEffectSimulation::ExplosionCluster &data); - void handleEffectCluster(const AesItemView &aesItemView); - void handleEffectCluster(const AreaEffectSimulation::EffectCluster &data); + void handleNContamination(const AesItemView& aesItemView); + void handleNContamination(const AreaEffectSimulation::NContamination& data); + void handleBCContamination(const AesItemView& aesItemView); + void handleBCContamination(const AreaEffectSimulation::BCContamination& data); + void handleExplosionArea(const AesItemView& aesItemView); + void handleExplosionArea(const AreaEffectSimulation::ExplosionArea& data); + void handleExplosionSingle(const AesItemView& aesItemView); + void handleExplosionSingle(const AreaEffectSimulation::ExplosionSingle& data); + void handleMineArea(const AesItemView& aesItemView); + void handleMineArea(const AreaEffectSimulation::MineArea& data); + void handleMineCorridor(const AesItemView& aesItemView); + void handleMineCorridor(const AreaEffectSimulation::MineCorridor& data); + void handleBoobyTrap(const AesItemView& aesItemView); + void handleBoobyTrap(const AreaEffectSimulation::BoobyTrap& data); + void handleOffRouteMine(const AesItemView& aesItemView); + void handleOffRouteMine(const AreaEffectSimulation::OffRouteMine& data); + void handleGasPipe(const AesItemView& aesItemView); + void handleGasPipe(const AreaEffectSimulation::GasPipe& data); + void handleDangerArea(const AesItemView& aesItemView); + void handleDangerArea(const AreaEffectSimulation::DangerArea& data); + void handleBorderline(const AesItemView& aesItemView); + void handleBorderline(const AreaEffectSimulation::Borderline& data); + void handleFunctionalArea(const AesItemView& aesItemView); + void handleFunctionalArea(const AreaEffectSimulation::FunctionalArea& data); + void handleAirSupportImpact(const AesItemView& aesItemView); + void handleAirSupportImpact(const AreaEffectSimulation::AirSupportImpact& data); + void handleMineAraeSingleMine(); + void handleMineAraeSingleMine(const Core::GeoPosition2D& position, const DusMine& mine); + void handleSingleDusMine(); + void handleExplosionCluster(const AesItemView& aesItemView); + void handleExplosionCluster(const AreaEffectSimulation::ExplosionCluster& data); + void handleEffectCluster(const AesItemView& aesItemView); + void handleEffectCluster(const AreaEffectSimulation::EffectCluster& data); - bool cbFunc(const AesItemView &aesItemView); + bool cbFunc(const AesItemView& aesItemView); - void handleAesItem(const AesItem &aesData, AesType aesTypeId); + void handleAesItem(const AesItem& aesData, AesType aesTypeId); -private Q_SLOTS: - void onFindOnMap(); - void onShowDetails(); - bool onResetDusMines(); + private Q_SLOTS: + void onFindOnMap(); + void onShowDetails(); + bool onResetDusMines(); - void onNContaminationChanged(const AreaEffectSimulation::NContamination &data, DataModification modType); - void onBCContaminationChanged(const AreaEffectSimulation::BCContamination &data, DataModification modType); - void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &data, DataModification modType); - void onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine &data, DataModification modType); - void onExplosionAreaChanged(const AreaEffectSimulation::ExplosionArea &data, DataModification modType); - void onExplosionSingleChanged(const AreaEffectSimulation::ExplosionSingle &data, DataModification modType); - void onMineAreaChanged(const AreaEffectSimulation::MineArea &data, DataModification modType); - void onMineCorridorChanged(const AreaEffectSimulation::MineCorridor &data, DataModification modType); - void onGasPipeChanged(const GasPipe &data, DataModification modType); - void onDangerAreaChanged(const AreaEffectSimulation::DangerArea &data, DataModification modType); - void onBorderlineChanged(const AreaEffectSimulation::Borderline &data, DataModification modType); - void onFunctionalAreaChanged(const AreaEffectSimulation::FunctionalArea &data, DataModification modType); - void onAirSupportImpactChanged(const AirSupportImpact &data, DataModification modType); - void onDusMineStateChanged(const DusMineState &data, DataModification modType); - void onDusSingleMineChanged(const DusSingleMine &data, DataModification modType); - void onExplosionClusterChanged(const ExplosionCluster &data, DataModification modType); - void onEffectClusterChanged(const EffectCluster &data, DataModification modType); + void onNContaminationChanged(const AreaEffectSimulation::NContamination& data, DataModification modType); + void onBCContaminationChanged(const AreaEffectSimulation::BCContamination& data, DataModification modType); + void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& data, DataModification modType); + void onOffRouteMineChanged(const AreaEffectSimulation::OffRouteMine& data, DataModification modType); + void onExplosionAreaChanged(const AreaEffectSimulation::ExplosionArea& data, DataModification modType); + void onExplosionSingleChanged(const AreaEffectSimulation::ExplosionSingle& data, DataModification modType); + void onMineAreaChanged(const AreaEffectSimulation::MineArea& data, DataModification modType); + void onMineCorridorChanged(const AreaEffectSimulation::MineCorridor& data, DataModification modType); + void onGasPipeChanged(const GasPipe& data, DataModification modType); + void onDangerAreaChanged(const AreaEffectSimulation::DangerArea& data, DataModification modType); + void onBorderlineChanged(const AreaEffectSimulation::Borderline& data, DataModification modType); + void onFunctionalAreaChanged(const AreaEffectSimulation::FunctionalArea& data, DataModification modType); + void onAirSupportImpactChanged(const AirSupportImpact& data, DataModification modType); + void onDusMineStateChanged(const DusMineState& data, DataModification modType); + void onDusSingleMineChanged(const DusSingleMine& data, DataModification modType); + void onExplosionClusterChanged(const ExplosionCluster& data, DataModification modType); + void onEffectClusterChanged(const EffectCluster& data, DataModification modType); -private: - NGL::INGLLogger &m_logger; - int m_aesEntityId; - QString m_aesEntityName; - AreaEffectSimulation::AesType m_aesType; - ProjectDataManagement::EffectSource m_aesEffectSource; - int m_bcChargeTypeId; - int m_singleExpChargeTypeId; - int m_areaExpChargeTypeId; - bool m_mineIsReactivatable; + private: + NGL::INGLLogger& m_logger; + int m_aesEntityId; + QString m_aesEntityName; + AreaEffectSimulation::AesType m_aesType; + ProjectDataManagement::EffectSource m_aesEffectSource; + int m_bcChargeTypeId; + int m_singleExpChargeTypeId; + int m_areaExpChargeTypeId; + bool m_mineIsReactivatable; - LtsSession::LtsSession *m_session; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_pdmDtc; + LtsSession::LtsSession* m_session; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_pdmDtc; - - Ui::AesInfoDialog* m_ui; - LtsUtils::RequestHelper *m_requestHelper; + Ui::AesInfoDialog* m_ui; + LtsUtils::RequestHelper* m_requestHelper; }; -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_edit.cpp old mode 100755 new mode 100644 index a54bd2a40..99c3b30bc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_edit.cpp @@ -1,351 +1,341 @@ - - #include "aes_base_edit.h" -#include -#include -#include -#include -#include -#include -#include #include -#include +#include +#include +#include +#include +#include +#include +#include #include +#include namespace AreaEffectSimulation { -BaseEdit::BaseEdit(const QString &menuGroup, const QString &loggerName, QWidget *parent, LtsWidgets::ButtonCombination buttonCombination) - : LtsWidgets::LtsDialog(parent, buttonCombination) - , m_aesItem() - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_sitMapGuiIfc(nullptr) - , m_ppmGuiCbxIfc(nullptr) - , m_session(nullptr) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_logger(getLogger(loggerName)) +BaseEdit::BaseEdit(const QString& menuGroup, const QString& loggerName, QWidget* parent, + LtsWidgets::ButtonCombination buttonCombination) + : LtsWidgets::LtsDialog(parent, buttonCombination), m_aesItem(), m_dtc(nullptr), m_ftc(nullptr), + m_sitMapGuiIfc(nullptr), m_ppmGuiCbxIfc(nullptr), m_session(nullptr), m_menuGroup(menuGroup), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_logger(getLogger(loggerName)) { - m_aesItem.id(0); - connect(this, &BaseEdit::visibilityChanged, this, &BaseEdit::onVisibilityChanged); + m_aesItem.id(0); + connect(this, &BaseEdit::visibilityChanged, this, &BaseEdit::onVisibilityChanged); } -void BaseEdit::setCombobxToValueIfPossible(QComboBox *cbx, int val) +void BaseEdit::setCombobxToValueIfPossible(QComboBox* cbx, int val) { - int idx = cbx->findData(val); - if (idx >= 0) - cbx->setCurrentIndex(idx); + int idx = cbx->findData(val); + if (idx >= 0) + cbx->setCurrentIndex(idx); } -void BaseEdit::onAesItemCreateReply(const Core::FunctionReplyObject &replyObject) +void BaseEdit::onAesItemCreateReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); - if (!replyObject.error() && m_sitMapGuiIfc) - m_sitMapGuiIfc->removePreviewObject(); + m_requestHelper->requestReply(replyObject); + if (!replyObject.error() && m_sitMapGuiIfc) + m_sitMapGuiIfc->removePreviewObject(); } -void BaseEdit::onAesItemModifyReply(const Core::FunctionReplyObject &replyObject) +void BaseEdit::onAesItemModifyReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); - if (!replyObject.error() && m_sitMapGuiIfc ) - m_sitMapGuiIfc->removePreviewObject(); + if (!replyObject.error() && m_sitMapGuiIfc) + m_sitMapGuiIfc->removePreviewObject(); } bool BaseEdit::isModifiable() const { - AesEffectState effectState = m_aesItem.effectStateId(); - return (effectState == AreaEffectSimulation::AesEffectState_def::EsPaused || - effectState == AreaEffectSimulation::AesEffectState_def::EsActivated || - effectState == AreaEffectSimulation::AesEffectState_def::EsPrepared || - effectState == AreaEffectSimulation::AesEffectState_def::EsCreated || - effectState == AreaEffectSimulation::AesEffectState_def::EsUnknown || - effectState == AreaEffectSimulation::AesEffectState_def::EsReceived) && - (!m_session->isReplayPartition()) && - (m_session->app() != LtsAppDescriptor::App::OC); + AesEffectState effectState = m_aesItem.effectStateId(); + return (effectState == AreaEffectSimulation::AesEffectState_def::EsPaused || + effectState == AreaEffectSimulation::AesEffectState_def::EsActivated || + effectState == AreaEffectSimulation::AesEffectState_def::EsPrepared || + effectState == AreaEffectSimulation::AesEffectState_def::EsCreated || + effectState == AreaEffectSimulation::AesEffectState_def::EsUnknown || + effectState == AreaEffectSimulation::AesEffectState_def::EsReceived) && + (!m_session->isReplayPartition()) && (m_session->app() != LtsAppDescriptor::App::OC); } bool BaseEdit::isOnlyNameModifiable() const { - AesEffectState effectState = m_aesItem.effectStateId(); - return (effectState == AreaEffectSimulation::AesEffectState_def::EsPaused || - effectState == AreaEffectSimulation::AesEffectState_def::EsActivated) && - (!m_session->isReplayPartition()) && - (m_session->app() != LtsAppDescriptor::App::OC); + AesEffectState effectState = m_aesItem.effectStateId(); + return (effectState == AreaEffectSimulation::AesEffectState_def::EsPaused || + effectState == AreaEffectSimulation::AesEffectState_def::EsActivated) && + (!m_session->isReplayPartition()) && (m_session->app() != LtsAppDescriptor::App::OC); } void BaseEdit::correctSpinBoxValue() { - QSpinBox *sb = qobject_cast(sender()); - if (sb) - return correctSpinBoxValueInternal(sb); + QSpinBox* sb = qobject_cast(sender()); + if (sb) + return correctSpinBoxValueInternal(sb); - QDoubleSpinBox *dsb = qobject_cast(sender()); - if (dsb) - return correctSpinBoxValueInternal(dsb); + QDoubleSpinBox* dsb = qobject_cast(sender()); + if (dsb) + return correctSpinBoxValueInternal(dsb); } void BaseEdit::onVisibilityChanged(bool visible) { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - if (!visible) - m_sitMapGuiIfc->removePreviewObject(); - else - showPreviewObject(); + if (!visible) + m_sitMapGuiIfc->removePreviewObject(); + else + showPreviewObject(); } -void BaseEdit::correctSpinBoxValueInternal(QSpinBox *sb) +void BaseEdit::correctSpinBoxValueInternal(QSpinBox* sb) { - if (!sb) - return; + if (!sb) + return; - int step = sb->singleStep(); - if (step == 1) - return; + int step = sb->singleStep(); + if (step == 1) + return; - int value = sb->value(); - int remainder = (value - sb->minimum()) % step; - if (remainder == 0) - return; + int value = sb->value(); + int remainder = (value - sb->minimum()) % step; + if (remainder == 0) + return; - if (2 * remainder > step) - value += (step - remainder); - else - value -= remainder; + if (2 * remainder > step) + value += (step - remainder); + else + value -= remainder; - if (value > sb->maximum()) - value -= step; + if (value > sb->maximum()) + value -= step; - if(value < sb->minimum()) - value = sb->minimum(); + if (value < sb->minimum()) + value = sb->minimum(); - sb->setValue(value); + sb->setValue(value); } -void BaseEdit::correctSpinBoxValueInternal(QDoubleSpinBox *sb) +void BaseEdit::correctSpinBoxValueInternal(QDoubleSpinBox* sb) { - if (!sb) - return; + if (!sb) + return; - double step = sb->singleStep(); - if (qFuzzyCompare(step, pow(10, sb->decimals()))) - return; + double step = sb->singleStep(); + if (qFuzzyCompare(step, pow(10, sb->decimals()))) + return; - double value = sb->value(); - double remainder = fmod(value - sb->minimum(), step); - if (qFuzzyCompare(remainder, 0)) - return; + double value = sb->value(); + double remainder = fmod(value - sb->minimum(), step); + if (qFuzzyCompare(remainder, 0)) + return; - if (2 * remainder > step) - value += (step - remainder); - else - value -= remainder; + if (2 * remainder > step) + value += (step - remainder); + else + value -= remainder; - if (value > sb->maximum()) - value -= step; + if (value > sb->maximum()) + value -= step; - if (value < sb->minimum()) - value = sb->minimum(); + if (value < sb->minimum()) + value = sb->minimum(); - sb->setValue(value); + sb->setValue(value); } -bool BaseEdit::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit *dte) const +bool BaseEdit::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit* dte) const { - if (isOnlyNameModifiable()) - return true; - - if (dte->isCheckable() && !dte->isChecked()) - return true; - const auto ms = dte->msecsSinceEpoch(); - return ms > m_session->partitionTime(); + if (isOnlyNameModifiable()) + return true; + + if (dte->isCheckable() && !dte->isChecked()) + return true; + const auto ms = dte->msecsSinceEpoch(); + return ms > m_session->partitionTime(); } -void BaseEdit::setEffectStartEnabled(LtsWidgets::LtsDateTimeEdit *dte, bool enable) +void BaseEdit::setEffectStartEnabled(LtsWidgets::LtsDateTimeEdit* dte, bool enable) { - if (enable) - { - int exerciseId = m_session->exerciseId(); - std::shared_ptr exmDtc; - m_session->getDtc(exmDtc); - ExerciseManagement::Exercise exercise = exmDtc->exercise(exerciseId); + if (enable) + { + int exerciseId = m_session->exerciseId(); + std::shared_ptr exmDtc; + m_session->getDtc(exmDtc); + ExerciseManagement::Exercise exercise = exmDtc->exercise(exerciseId); - - enable = (exercise.state() == ExerciseManagement::ExerciseState_def::Started || - exercise.state() == ExerciseManagement::ExerciseState_def::Paused); + enable = (exercise.state() == ExerciseManagement::ExerciseState_def::Started || + exercise.state() == ExerciseManagement::ExerciseState_def::Paused); - - if (exercise.state() == ExerciseManagement::ExerciseState_def::Created) - dte->setChecked(false); - else - dte->setChecked(dte->msecsSinceEpoch() > 0); - } - else - dte->setChecked(dte->msecsSinceEpoch() > 0); - - dte->setEnabled(enable); + if (exercise.state() == ExerciseManagement::ExerciseState_def::Created) + dte->setChecked(false); + else + dte->setChecked(dte->msecsSinceEpoch() > 0); + } + else + dte->setChecked(dte->msecsSinceEpoch() > 0); + + dte->setEnabled(enable); } bool BaseEdit::has2DMap(bool showMsgBoxIfNot2D) { - if (!m_sitMapGuiIfc) - return false; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - if (showMsgBoxIfNot2D) - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return false; - } - return true; + if (!m_sitMapGuiIfc) + return false; + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + if (showMsgBoxIfNot2D) + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return false; + } + return true; } -void BaseEdit::setCoordinates(const QVector &coords, bool reverse) +void BaseEdit::setCoordinates(const QVector& coords, bool reverse) { - - clearCoordinates(); - const auto cWidgets(coordWidgets()); - if (!reverse) - { + + clearCoordinates(); + const auto cWidgets(coordWidgets()); + if (!reverse) + { + for (size_t i = 0; i < cWidgets.size() && i < static_cast(coords.size()); ++i) + cWidgets.at(i)->setCoordinate(coords.at(i)); + } + else + { + auto copy(coords); + std::reverse(std::begin(copy), std::end(copy)); + for (size_t i = 0; i < cWidgets.size() && i < static_cast(copy.size()); ++i) + cWidgets.at(i)->setCoordinate(copy.at(i)); + } +} + +void BaseEdit::setCoordinates(const std::vector& coords) +{ + clearCoordinates(); + const auto cWidgets(coordWidgets()); for (size_t i = 0; i < cWidgets.size() && i < static_cast(coords.size()); ++i) - cWidgets.at(i)->setCoordinate(coords.at(i)); - } - else - { - auto copy(coords); - std::reverse(std::begin(copy), std::end(copy)); - for (size_t i = 0; i < cWidgets.size() && i < static_cast(copy.size()); ++i) - cWidgets.at(i)->setCoordinate(copy.at(i)); - } -} - -void BaseEdit::setCoordinates(const std::vector &coords) -{ - clearCoordinates(); - const auto cWidgets(coordWidgets()); - for (size_t i = 0; i < cWidgets.size() && i < static_cast(coords.size()); ++i) - cWidgets.at(i)->setCoordinate(coords.at(i).lon(), coords.at(i).lat()); + cWidgets.at(i)->setCoordinate(coords.at(i).lon(), coords.at(i).lat()); } std::vector BaseEdit::getCoordinates() const { - std::vector segments; - const auto cWidgets(coordWidgets()); - segments.reserve(cWidgets.size()); - for (const auto cw : cWidgets) - { - const QPointF coord = cw->coordinate(); - if (coord.isNull()) - break; - segments.emplace_back(Core::GeoPosition2D(coord.x(), coord.y())); - } - return segments; + std::vector segments; + const auto cWidgets(coordWidgets()); + segments.reserve(cWidgets.size()); + for (const auto cw : cWidgets) + { + const QPointF coord = cw->coordinate(); + if (coord.isNull()) + break; + segments.emplace_back(Core::GeoPosition2D(coord.x(), coord.y())); + } + return segments; } QVector BaseEdit::getCoordinatesQPointF() const { - QVector segments; - const auto cWidgets(coordWidgets()); - segments.reserve(cWidgets.size()); - for (const auto *cw : cWidgets) - { - const QPointF coord = cw->coordinate(); - if (coord.isNull()) - break; - segments.push_back(coord); - } - return segments; + QVector segments; + const auto cWidgets(coordWidgets()); + segments.reserve(cWidgets.size()); + for (const auto* cw : cWidgets) + { + const QPointF coord = cw->coordinate(); + if (coord.isNull()) + break; + segments.push_back(coord); + } + return segments; } void BaseEdit::clearCoordinates() { - for (auto *cw : coordWidgets()) - cw->clear(); + for (auto* cw : coordWidgets()) + cw->clear(); } void BaseEdit::enabledCoordinates(bool enable) { - for (auto *cw : coordWidgets()) - cw->setEnabled(enable); + for (auto* cw : coordWidgets()) + cw->setEnabled(enable); } - -void BaseEdit::onAreaChanged(const AesItem &data, DataModification modType) +void BaseEdit::onAreaChanged(const AesItem& data, DataModification modType) { - - - if (data.id() != m_aesItem.id()) - return; - if (modType == DataModification::eRemoved || data.effectStateId() == AesEffectState_def::EsRemoved) - { - - __unchange__(); - closeRequest(); - return; - } - m_aesItem = data; - enableUiElements(isModifiable() && !isOnlyNameModifiable()); -} + if (data.id() != m_aesItem.id()) + return; -bool BaseEdit::init(int aesItemId, LtsSession::LtsSession *session) -{ - if (m_session) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - m_session = session; - m_aesItem.id(aesItemId); - - if (!m_session->getDtc(m_dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - if (!m_session->getForeignGuiInterface(m_ppmGuiCbxIfc)) - return false; - - if (m_session->isReplayPartition() || (LtsAppDescriptor::App::OC == m_session->app())) - setUnchangeable(); - - if (aesItemId == 0) - { - m_aesItem.effectSourceId(ProjectDataManagement::EffectSource_def::ES_Internal); - m_buttonBox->setText(LtsWidgets::DialogButton::Ok, tr("Add")); - } - - return true; -} - -double BaseEdit::distance(const Core::GeoPosition2D &p1, const Core::GeoPosition2D &p2) -{ - LtsCoordTrans::UtmCoordinate start = LtsCoordTrans::UtmCoordinate::fromGeographic(p1.lon(), p1.lat()); - LtsCoordTrans::UtmCoordinate end = LtsCoordTrans::UtmCoordinate::fromGeographic(p2.lon(), p2.lat(), start.zone); - double dx = start.x - end.x; - double dy = start.y - end.y; - return std::sqrt(dx*dx + dy*dy); -} - -bool BaseEdit::checkSegementLengths(QWidget *parent) const -{ - auto segments = getCoordinates(); - for (auto i=0; i<((int) segments.size() - 1); ++i) - { - double dis = distance(segments[i], segments[i+1]); - if (getMaxLength() != 0 && dis > getMaxLength()) + if (modType == DataModification::eRemoved || data.effectStateId() == AesEffectState_def::EsRemoved) { - LtsWidgets::LtsMessageDialog::showMessage(parent, tr("The distance between Coordinate %1 and %2 is too long.\nThe segment is %3m long, but the maximum segment length is %4m.") - .arg(i+1).arg(i+2).arg(QString::number(dis,'d',2),QString::number(getMaxLength(),'d',2))); - return false; + + __unchange__(); + closeRequest(); + return; } - } - return true; + m_aesItem = data; + enableUiElements(isModifiable() && !isOnlyNameModifiable()); } -} +bool BaseEdit::init(int aesItemId, LtsSession::LtsSession* session) +{ + if (m_session) + { + ERROR_LOG(m_logger) << "double init()!"; + return false; + } + m_session = session; + m_aesItem.id(aesItemId); + + if (!m_session->getDtc(m_dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; + m_session->getForeignGuiInterface(m_sitMapGuiIfc); + if (!m_session->getForeignGuiInterface(m_ppmGuiCbxIfc)) + return false; + + if (m_session->isReplayPartition() || (LtsAppDescriptor::App::OC == m_session->app())) + setUnchangeable(); + + if (aesItemId == 0) + { + m_aesItem.effectSourceId(ProjectDataManagement::EffectSource_def::ES_Internal); + m_buttonBox->setText(LtsWidgets::DialogButton::Ok, tr("Add")); + } + + return true; +} + +double BaseEdit::distance(const Core::GeoPosition2D& p1, const Core::GeoPosition2D& p2) +{ + LtsCoordTrans::UtmCoordinate start = LtsCoordTrans::UtmCoordinate::fromGeographic(p1.lon(), p1.lat()); + LtsCoordTrans::UtmCoordinate end = LtsCoordTrans::UtmCoordinate::fromGeographic(p2.lon(), p2.lat(), start.zone); + double dx = start.x - end.x; + double dy = start.y - end.y; + return std::sqrt(dx * dx + dy * dy); +} + +bool BaseEdit::checkSegementLengths(QWidget* parent) const +{ + auto segments = getCoordinates(); + for (auto i = 0; i < ((int)segments.size() - 1); ++i) + { + double dis = distance(segments[i], segments[i + 1]); + if (getMaxLength() != 0 && dis > getMaxLength()) + { + LtsWidgets::LtsMessageDialog::showMessage( + parent, tr("The distance between Coordinate %1 and %2 is too long.\nThe segment is %3m long, but the " + "maximum segment length is %4m.") + .arg(i + 1) + .arg(i + 2) + .arg(QString::number(dis, 'd', 2), QString::number(getMaxLength(), 'd', 2))); + return false; + } + } + return true; +} + +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_model.cpp old mode 100755 new mode 100644 index adc4960c1..92fe572a6 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_base_model.cpp @@ -1,349 +1,316 @@ - #include "aes_base_model.h" -#include -#include #include - +#include #include #include -#include #include #include - +#include #include +#include namespace AreaEffectSimulation { +AesGuiBasHelpers::AesGuiBasHelpers() : m_aesDtc(nullptr), m_pdmDtc(nullptr), m_ppmDtc(nullptr) {} - - -AesGuiBasHelpers::AesGuiBasHelpers() - : m_aesDtc(nullptr) - , m_pdmDtc(nullptr) - , m_ppmDtc(nullptr) -{} - -bool AesGuiBasHelpers::initModel(LtsSession::LtsSession *session) +bool AesGuiBasHelpers::initModel(LtsSession::LtsSession* session) { - if (m_aesDtc) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } + if (m_aesDtc) + { + ERROR_LOG(m_logger) << "double init()!"; + return false; + } - if (!session->getDtc(m_aesDtc)) - return false; - if (!session->getDtc(m_pdmDtc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - session->getForeignGuiInterface(m_ppmGuiCbxIfc); + if (!session->getDtc(m_aesDtc)) + return false; + if (!session->getDtc(m_pdmDtc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + session->getForeignGuiInterface(m_ppmGuiCbxIfc); - return true; + return true; } -QVariant AesGuiBasHelpers::stringFromPartyId(const dds::core::optional &id) const +QVariant AesGuiBasHelpers::stringFromPartyId(const dds::core::optional& id) const { - if (!id.is_set()) - return QObject::tr("---"); - auto it = m_partyNames.find(id.get()); - if (it != m_partyNames.end()) - return it.value(); - const QString name = ParticipantManagement::trPartyName(m_ppmDtc->party(id.get()).name()); - m_partyNames.insert(id.get(), name); - return name; + if (!id.is_set()) + return QObject::tr("---"); + auto it = m_partyNames.find(id.get()); + if (it != m_partyNames.end()) + return it.value(); + const QString name = ParticipantManagement::trPartyName(m_ppmDtc->party(id.get()).name()); + m_partyNames.insert(id.get(), name); + return name; } -QIcon AesGuiBasHelpers::iconFromPartyId(const dds::core::optional &id) const +QIcon AesGuiBasHelpers::iconFromPartyId(const dds::core::optional& id) const { - if (!id.is_set() || !m_ppmGuiCbxIfc) - return QIcon(); - auto it = m_partyIcons.find(id.get()); - if (it != m_partyIcons.end()) - return it.value(); - const QRgb col = QRgb(m_ppmDtc->party(id.get()).color()); - const QIcon icon = m_ppmGuiCbxIfc->pixmapFromParty(col); - m_partyIcons.insert(id.get(), icon); - return icon; + if (!id.is_set() || !m_ppmGuiCbxIfc) + return QIcon(); + auto it = m_partyIcons.find(id.get()); + if (it != m_partyIcons.end()) + return it.value(); + const QRgb col = QRgb(m_ppmDtc->party(id.get()).color()); + const QIcon icon = m_ppmGuiCbxIfc->pixmapFromParty(col); + m_partyIcons.insert(id.get(), icon); + return icon; } -QVariant AesGuiBasHelpers::hierarchyFromParticipantId(const dds::core::optional &id) const +QVariant AesGuiBasHelpers::hierarchyFromParticipantId(const dds::core::optional& id) const { - if (!id.is_set()) - return QObject::tr("---"); - auto it = m_participantHierarchy.find(id.get()); - if (it != m_participantHierarchy.end()) - return it.value(); - const QString name = m_ppmDtc->hierarchyFromParticipant(id.get()); - m_participantHierarchy.insert(id.get(), name); - return name; + if (!id.is_set()) + return QObject::tr("---"); + auto it = m_participantHierarchy.find(id.get()); + if (it != m_participantHierarchy.end()) + return it.value(); + const QString name = m_ppmDtc->hierarchyFromParticipant(id.get()); + m_participantHierarchy.insert(id.get(), name); + return name; } QVariant AesGuiBasHelpers::chargeTypeName(int chargeTypeId, bool shortName) const { - if (shortName) - { - auto it = m_chargeTypeShortNames.find(chargeTypeId); - if (it != m_chargeTypeShortNames.end()) - return it.value(); - const QString name = m_pdmDtc->trChargeTypeShortName(chargeTypeId, true); - m_chargeTypeShortNames.insert(chargeTypeId, name); + if (shortName) + { + auto it = m_chargeTypeShortNames.find(chargeTypeId); + if (it != m_chargeTypeShortNames.end()) + return it.value(); + const QString name = m_pdmDtc->trChargeTypeShortName(chargeTypeId, true); + m_chargeTypeShortNames.insert(chargeTypeId, name); + return name; + } + + auto it = m_chargeTypeNames.find(chargeTypeId); + if (it != m_chargeTypeNames.end()) + return it.value(); + const QString name = m_pdmDtc->trChargeTypeName(chargeTypeId, true); + m_chargeTypeNames.insert(chargeTypeId, name); return name; - } - - auto it = m_chargeTypeNames.find(chargeTypeId); - if (it != m_chargeTypeNames.end()) - return it.value(); - const QString name = m_pdmDtc->trChargeTypeName(chargeTypeId, true); - m_chargeTypeNames.insert(chargeTypeId, name); - return name; - } QString AesGuiBasHelpers::simulationTypeText(bool isCentral) { - return isCentral ? QObject::tr("central") : QObject::tr("peripheral"); + return isCentral ? QObject::tr("central") : QObject::tr("peripheral"); } void AesGuiBasHelpers::updateEffectStateComboboxFilterData(bool bWithPause) { - LtsWidgets::ComboboxFilterContent cfc; - LtsWidgets::ComboboxFilterData cfd; - const auto effectStates = { - AesEffectState::EsExpired, - AesEffectState::EsCreated, - AesEffectState::EsPrepared, - AesEffectState::EsActivated, - AesEffectState::EsPaused, - AesEffectState::EsFired, - AesEffectState::EsReceived - }; - for (const auto es : effectStates) { - if (!bWithPause && es == AesEffectState::EsPaused) - continue; - cfd.data = es; - cfd.text = AreaEffectSimulation::toString(es); - cfc.data.push_back(cfd); - } - cfc.sortItems = false; - m_cbxFilterEffectState = cfc.toVariant(); + LtsWidgets::ComboboxFilterContent cfc; + LtsWidgets::ComboboxFilterData cfd; + const auto effectStates = {AesEffectState::EsExpired, AesEffectState::EsCreated, AesEffectState::EsPrepared, + AesEffectState::EsActivated, AesEffectState::EsPaused, AesEffectState::EsFired, + AesEffectState::EsReceived}; + for (const auto es : effectStates) + { + if (!bWithPause && es == AesEffectState::EsPaused) + continue; + cfd.data = es; + cfd.text = AreaEffectSimulation::toString(es); + cfc.data.push_back(cfd); + } + cfc.sortItems = false; + m_cbxFilterEffectState = cfc.toVariant(); } -void AesGuiBasHelpers::updateComboboxFilterData(const QSet &availablePartyIds, - const QSet &availabelChargeIds) +void AesGuiBasHelpers::updateComboboxFilterData(const QSet& availablePartyIds, const QSet& availabelChargeIds) { - LtsWidgets::ComboboxFilterContent cfc; - LtsWidgets::ComboboxFilterData cfd; - for (const int i : std::as_const(availabelChargeIds)) - { - cfd.data = i; - cfd.text = chargeTypeName(i).toString(); - cfc.data.push_back(cfd); - } - cfc.sortItems = true; - m_cbxFilterChargeType = cfc.toVariant(); + LtsWidgets::ComboboxFilterContent cfc; + LtsWidgets::ComboboxFilterData cfd; + for (const int i : std::as_const(availabelChargeIds)) + { + cfd.data = i; + cfd.text = chargeTypeName(i).toString(); + cfc.data.push_back(cfd); + } + cfc.sortItems = true; + m_cbxFilterChargeType = cfc.toVariant(); - cfc.data.clear(); - for (const int i : std::as_const(availablePartyIds)) - { - cfd.data = i; - cfd.text = ParticipantManagement::trPartyName(m_ppmDtc->party(i).name()); - cfd.icon = iconFromPartyId(i); - cfc.data.push_back(cfd); - } - cfc.sortItems = false; - m_cbxFilterParty = cfc.toVariant(); + cfc.data.clear(); + for (const int i : std::as_const(availablePartyIds)) + { + cfd.data = i; + cfd.text = ParticipantManagement::trPartyName(m_ppmDtc->party(i).name()); + cfd.icon = iconFromPartyId(i); + cfc.data.push_back(cfd); + } + cfc.sortItems = false; + m_cbxFilterParty = cfc.toVariant(); } void AreaEffectSimulation::AesGuiBasHelpers::updateSimulationTypeComboboxFilterData() { - LtsWidgets::ComboboxFilterContent cfc; - LtsWidgets::ComboboxFilterData cfd; + LtsWidgets::ComboboxFilterContent cfc; + LtsWidgets::ComboboxFilterData cfd; - cfd.text = simulationTypeText(true); - cfd.data = cfd.text; - cfc.data.push_back(cfd); + cfd.text = simulationTypeText(true); + cfd.data = cfd.text; + cfc.data.push_back(cfd); - cfd.text = simulationTypeText(false); - cfd.data = cfd.text; - cfc.data.push_back(cfd); + cfd.text = simulationTypeText(false); + cfd.data = cfd.text; + cfc.data.push_back(cfd); - cfc.sortItems = false; - m_cbxFilterSimulationType = cfc.toVariant(); + cfc.sortItems = false; + m_cbxFilterSimulationType = cfc.toVariant(); } void AesGuiBasHelpers::fillAvailableChargeIds(ProjectDataManagement::GearClass gc) { - m_availableChargeIds.clear(); - const QVector availableCharges = m_pdmDtc->chargesForGearClass(gc); - for (const auto &charge : availableCharges) - m_availableChargeIds += charge.id(); - - if (m_availableChargeIds.isEmpty()) - m_availableChargeIds += 0; + m_availableChargeIds.clear(); + const QVector availableCharges = m_pdmDtc->chargesForGearClass(gc); + for (const auto& charge : availableCharges) + m_availableChargeIds += charge.id(); + + if (m_availableChargeIds.isEmpty()) + m_availableChargeIds += 0; } -void AesGuiBasHelpers::fillAvailableChargeIds(const QVector &gcs) +void AesGuiBasHelpers::fillAvailableChargeIds(const QVector& gcs) { - m_availableChargeIds.clear(); + m_availableChargeIds.clear(); - for (auto gc : std::as_const(gcs)) - { - const QVector &availableCharges = m_pdmDtc->chargesForGearClass(gc); - for (const auto &charge : std::as_const(availableCharges)) - m_availableChargeIds += charge.id(); - } - - if (m_availableChargeIds.isEmpty()) - m_availableChargeIds += 0; -} - - - - -AesItemSortFilterProxyModel::AesItemSortFilterProxyModel(LtsSession::LtsSession *session, QObject *parent) - : LtsWidgets::LtsColumnFilterProxyModel(parent) - , m_session(session) - , m_showExpired(false) - , m_offset(5 * 60 * 1000) -{ - std::shared_ptr ppmDtc; - if (m_session->getDtc(ppmDtc)) - { - auto cb = [this](const ParticipantManagement::Party &party) + for (auto gc : std::as_const(gcs)) { - m_partyColors[party.id()] = QColor::fromRgb(QRgb(party.color())); - }; - ppmDtc->partys(cb); - } + const QVector& availableCharges = m_pdmDtc->chargesForGearClass(gc); + for (const auto& charge : std::as_const(availableCharges)) + m_availableChargeIds += charge.id(); + } + + if (m_availableChargeIds.isEmpty()) + m_availableChargeIds += 0; +} + +AesItemSortFilterProxyModel::AesItemSortFilterProxyModel(LtsSession::LtsSession* session, QObject* parent) + : LtsWidgets::LtsColumnFilterProxyModel(parent), m_session(session), m_showExpired(false), m_offset(5 * 60 * 1000) +{ + std::shared_ptr ppmDtc; + if (m_session->getDtc(ppmDtc)) + { + auto cb = [this](const ParticipantManagement::Party& party) { + m_partyColors[party.id()] = QColor::fromRgb(QRgb(party.color())); + }; + ppmDtc->partys(cb); + } } void AesItemSortFilterProxyModel::setShowExpired(bool showExpired) { - if (m_showExpired == showExpired) - return; + if (m_showExpired == showExpired) + return; - m_showExpired = showExpired; - invalidateFilter(); + m_showExpired = showExpired; + invalidateFilter(); } void AesItemSortFilterProxyModel::setOffset(int offsetMsecs) { - if (m_offset == offsetMsecs) - return; + if (m_offset == offsetMsecs) + return; - m_offset = offsetMsecs; - invalidateFilter(); + m_offset = offsetMsecs; + invalidateFilter(); } -bool AesItemSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool AesItemSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - bool bRet = checkFilter(source_row); - if (!bRet) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + bool bRet = checkFilter(source_row); + if (!bRet) + return false; + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } -bool AesItemSortFilterProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +bool AesItemSortFilterProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { - if (source_left.column() != source_right.column()) + if (source_left.column() != source_right.column()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + + switch (source_left.column()) + { + case AesGuiBasHelpers::BcEffectStart: { + const auto effectStartLeft = aesEffectStart(source_left.row()); + const auto effectStartRight = aesEffectStart(source_right.row()); + if (effectStartLeft.is_set() && effectStartRight.is_set()) + return effectStartLeft.get() < effectStartRight.get(); + if (effectStartRight.is_set()) + return true; + if (effectStartLeft.is_set()) + return false; + return aesId(source_left.row()) < aesId(source_right.row()); + } + case AesGuiBasHelpers::BcEffectDuration: { + const auto effectDurationLeft = aesEffectDuration(source_left.row()); + const auto effectDurationRight = aesEffectDuration(source_right.row()); + if (effectDurationLeft == effectDurationRight) + return aesId(source_left.row()) < aesId(source_right.row()); + return effectDurationLeft < effectDurationRight; + } + case AesGuiBasHelpers::BcEffectState: { + const auto effectStateLeft = aesEffectStateId(source_left.row()); + const auto effectStateRight = aesEffectStateId(source_right.row()); + if (effectStateLeft == effectStateRight) + return aesId(source_left.row()) < aesId(source_right.row()); + return effectStateLeft < effectStateRight; + } + case AesGuiBasHelpers::BcEffectSource: { + const auto effectSourceLeft = aesEffectSourceId(source_left.row()); + const auto effectSourceRight = aesEffectSourceId(source_right.row()); + if (effectSourceLeft == effectSourceRight) + return aesId(source_left.row()) < aesId(source_right.row()); + return effectSourceLeft < effectSourceRight; + } + case AesGuiBasHelpers::BcParty: { + const auto partyIdLeft = partyId(source_left.row()); + const auto partyIdRight = partyId(source_right.row()); + if (partyIdLeft == partyIdRight) + return aesId(source_left.row()) < aesId(source_right.row()); + return partyIdLeft < partyIdRight; + } + default: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - - switch (source_left.column()) - { - case AesGuiBasHelpers::BcEffectStart: - { - const auto effectStartLeft = aesEffectStart(source_left.row()); - const auto effectStartRight = aesEffectStart(source_right.row()); - if (effectStartLeft.is_set() && effectStartRight.is_set()) - return effectStartLeft.get() < effectStartRight.get(); - if (effectStartRight.is_set()) - return true; - if (effectStartLeft.is_set()) - return false; - return aesId(source_left.row()) < aesId(source_right.row()); - } - case AesGuiBasHelpers::BcEffectDuration: - { - const auto effectDurationLeft = aesEffectDuration(source_left.row()); - const auto effectDurationRight = aesEffectDuration(source_right.row()); - if (effectDurationLeft == effectDurationRight) - return aesId(source_left.row()) < aesId(source_right.row()); - return effectDurationLeft < effectDurationRight; - } - case AesGuiBasHelpers::BcEffectState: - { - const auto effectStateLeft = aesEffectStateId(source_left.row()); - const auto effectStateRight = aesEffectStateId(source_right.row()); - if (effectStateLeft == effectStateRight) - return aesId(source_left.row()) < aesId(source_right.row()); - return effectStateLeft < effectStateRight; - } - case AesGuiBasHelpers::BcEffectSource: - { - const auto effectSourceLeft = aesEffectSourceId(source_left.row()); - const auto effectSourceRight = aesEffectSourceId(source_right.row()); - if (effectSourceLeft == effectSourceRight) - return aesId(source_left.row()) < aesId(source_right.row()); - return effectSourceLeft < effectSourceRight; - } - case AesGuiBasHelpers::BcParty: - { - const auto partyIdLeft = partyId(source_left.row()); - const auto partyIdRight = partyId(source_right.row()); - if (partyIdLeft == partyIdRight) - return aesId(source_left.row()) < aesId(source_right.row()); - return partyIdLeft < partyIdRight; - } - default: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } - bool AesItemSortFilterProxyModel::checkFilter(int source_row) const { - int32_t party = partyId(source_row); - if (party != -1 && !LtsSessionData::LtsSessionData::getInstance()->isVisibleParty(m_session->exerciseId(), party)) + int32_t party = partyId(source_row); + if (party != -1 && !LtsSessionData::LtsSessionData::getInstance()->isVisibleParty(m_session->exerciseId(), party)) + return false; + + const auto effectStateId = aesEffectStateId(source_row); + if (effectStateId == AesEffectState_def::EsRemoved) + return false; + + if (showExpired()) + return true; + + const int id = aesId(source_row); + if (id <= 0) + return false; + + if (effectStateId != AreaEffectSimulation::AesEffectState::EsExpired && + effectStateId != AreaEffectSimulation::AesEffectState::EsRemoved) + return true; + + if (!m_session) + { + + return false; + } + + const auto effectStart = aesEffectStart(source_row); + qint64 effectEnd = 0; + if (effectStart.is_set()) + effectEnd = effectStart.get() + aesEffectDuration(source_row); + + if (effectStart.is_set() && effectEnd + m_offset > m_session->partitionTime()) + return true; + return false; - - const auto effectStateId = aesEffectStateId(source_row); - if (effectStateId == AesEffectState_def::EsRemoved) - return false; - - - if (showExpired()) - return true; - - const int id = aesId(source_row); - if (id <= 0) - return false; - - - if (effectStateId != AreaEffectSimulation::AesEffectState::EsExpired && effectStateId != AreaEffectSimulation::AesEffectState::EsRemoved) - return true; - - if (!m_session) - { - - return false; - } - - const auto effectStart = aesEffectStart(source_row); - qint64 effectEnd = 0; - if (effectStart.is_set()) - effectEnd = effectStart.get() + aesEffectDuration(source_row); - - - if (effectStart.is_set() && - effectEnd + m_offset > m_session->partitionTime()) - return true; - - return false; } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_itemlist.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_itemlist.cpp old mode 100755 new mode 100644 index e1ca19483..48119b295 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_itemlist.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/Base/aes_itemlist.cpp @@ -1,300 +1,318 @@ - #include "aes_itemlist.h" + #include "aes_base_model.h" #include "ui_aes_itemlist.h" -#include -#include - +#include #include #include #include #include #include -#include - +#include #include +#include #include -#include +#include static const auto ADLER_BTN = LtsWidgets::DialogButton::Export; namespace AreaEffectSimulation { -AesItemList::AesItemList(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ftc(nullptr) - , m_dtc(nullptr) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_showExpired(false) - , m_bHasAddEditOperatorRights(true) - , m_bHasAddAdlerOperatorRights(false) - , m_session(nullptr) - , m_ui(new Ui::AesItemList) +AesItemList::AesItemList(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ftc(nullptr), m_dtc(nullptr), + m_menuGroup(menuGroup), m_requestHelper(new LtsUtils::RequestHelper(this)), m_showExpired(false), + m_bHasAddEditOperatorRights(true), m_bHasAddAdlerOperatorRights(false), m_session(nullptr), + m_ui(new Ui::AesItemList) { - m_ui->setupUi(this); + m_ui->setupUi(this); - QCheckBox *cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); - cbExpired->setProperty("const", true); - m_ui->widget->setCustomWidget(cbExpired); - connect(cbExpired, &QCheckBox::toggled, this, &AesItemList::setShowExpired); + QCheckBox* cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); + cbExpired->setProperty("const", true); + m_ui->widget->setCustomWidget(cbExpired); + connect(cbExpired, &QCheckBox::toggled, this, &AesItemList::setShowExpired); } -AesItemList::~AesItemList() { delete m_ui; } - -bool AesItemList::init(LtsSession::LtsSession *session) +AesItemList::~AesItemList() { - if (m_session) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - m_session = session; + delete m_ui; +} - if (!m_session->getFtc(m_ftc)) - return false; - if (!m_session->getDtc(m_dtc)) - return false; - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &AesItemList::onPrint); - if (m_session->app() != LtsAppDescriptor::App::OC) - { - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &AesItemList::onAddAesItem); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AesItemList::onRemoveAesItem); - } +bool AesItemList::init(LtsSession::LtsSession* session) +{ + if (m_session) + { + ERROR_LOG(m_logger) << "double init()!"; + return false; + } + m_session = session; - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AesItemList::onEditAesItem); + if (!m_session->getFtc(m_ftc)) + return false; + if (!m_session->getDtc(m_dtc)) + return false; + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &AesItemList::onPrint); + if (m_session->app() != LtsAppDescriptor::App::OC) + { + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &AesItemList::onAddAesItem); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AesItemList::onRemoveAesItem); + } - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Center on Map")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &AesItemList::onCenterAesItem); - m_buttonBox->getButton(ADLER_BTN)->hide(); - m_buttonBox->connectButton(ADLER_BTN, this, &AesItemList::onAdlerBtn); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AesItemList::onEditAesItem); - QCheckBox *cb = qobject_cast(m_ui->widget->customWidget()); - bool showExpired = (!cb || cb->isChecked()); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Center on Map")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setIcon(QIcon(QStringLiteral("icon:center_to_object.svg"))); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &AesItemList::onCenterAesItem); + m_buttonBox->getButton(ADLER_BTN)->hide(); + m_buttonBox->connectButton(ADLER_BTN, this, &AesItemList::onAdlerBtn); - createModel(); - model()->setShowExpired(showExpired); + QCheckBox* cb = qobject_cast(m_ui->widget->customWidget()); + bool showExpired = (!cb || cb->isChecked()); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &AesItemList::enaDisa); - connect(m_session, &LtsSession::LtsSession::signalExerciseDataChanged, this, &AesItemList::enaDisa); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionClusterChanged, this, &AesItemList::onHandleAdler); - connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::effectClusterChanged, this, &AesItemList::onHandleAdler); + createModel(); + model()->setShowExpired(showExpired); - return true; + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &AesItemList::enaDisa); + connect(m_session, &LtsSession::LtsSession::signalExerciseDataChanged, this, &AesItemList::enaDisa); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::explosionClusterChanged, this, + &AesItemList::onHandleAdler); + connect(m_dtc.get(), &AreaEffectSimulation::Interface::Dtc::effectClusterChanged, this, + &AesItemList::onHandleAdler); + + return true; } void AesItemList::enaDisa() { - const int curSelRow = currentRow(); - onHandleAdler(); - LtsWidgets::ExerciseStates allowedStates = LtsWidgets::ExerciseState::eCreated | LtsWidgets::ExerciseState::eStarted | LtsWidgets::ExerciseState::ePaused; - bool bEnableEditRemove = false; - bool bIsAllowedInState = allowedStates.testFlag(m_session->exerciseState()); - bool isOc = (m_session->app() == LtsAppDescriptor::App::OC); + const int curSelRow = currentRow(); + onHandleAdler(); + LtsWidgets::ExerciseStates allowedStates = + LtsWidgets::ExerciseState::eCreated | LtsWidgets::ExerciseState::eStarted | LtsWidgets::ExerciseState::ePaused; + bool bEnableEditRemove = false; + bool bIsAllowedInState = allowedStates.testFlag(m_session->exerciseState()); + bool isOc = (m_session->app() == LtsAppDescriptor::App::OC); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, !model()->isExpired(curSelRow)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, !model()->isExpired(curSelRow)); - if (curSelRow >= 0) - bEnableEditRemove = !model()->isExpired(curSelRow) && !model()->isExternal(curSelRow); - if (!m_bHasAddEditOperatorRights) - { - bEnableEditRemove = false; - bIsAllowedInState = false; - } - - if (!m_session->isReplayPartition()) - { - if (!model()->isExternal(curSelRow)) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Edit")); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bEnableEditRemove && bIsAllowedInState); - } - else - { - m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Show Details")); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bIsAllowedInState); - } - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, bEnableEditRemove && bIsAllowedInState); - - - bool isEsAdler = false; if (curSelRow >= 0) + bEnableEditRemove = !model()->isExpired(curSelRow) && !model()->isExternal(curSelRow); + if (!m_bHasAddEditOperatorRights) { - const ProjectDataManagement::EffectSource &es = model()->aesEffectSourceId(curSelRow); + bEnableEditRemove = false; + bIsAllowedInState = false; + } - if (es == ProjectDataManagement::EffectSource::ES_ADLER || es == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) - isEsAdler = true; + if (!m_session->isReplayPartition()) + { + if (!model()->isExternal(curSelRow)) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Edit")); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bEnableEditRemove && bIsAllowedInState); + } + else + { + m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Show Details")); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bIsAllowedInState); + } - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, bIsAllowedInState && !isEsAdler); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_bHasAddAdlerOperatorRights && isEsAdler); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, !isOc); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, bEnableEditRemove && bIsAllowedInState); + + bool isEsAdler = false; + if (curSelRow >= 0) + { + const ProjectDataManagement::EffectSource& es = model()->aesEffectSourceId(curSelRow); + + if (es == ProjectDataManagement::EffectSource::ES_ADLER || + es == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) + isEsAdler = true; + + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, bIsAllowedInState && !isEsAdler); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_bHasAddAdlerOperatorRights && isEsAdler); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, !isOc); + } + else + { + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, bIsAllowedInState); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_bHasAddAdlerOperatorRights); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, !isOc); + } + m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Add ADLER")); } else { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, bIsAllowedInState); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_bHasAddAdlerOperatorRights); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, !isOc); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Add, false); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove, false); + + m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Show Details")); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bEnableEditRemove); } - m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Add ADLER")); - } - else - { - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Add, false); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove, false); - m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Show Details")); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bEnableEditRemove); - } - - if (bEnableEditRemove && bIsAllowedInState) - { - m_doubleClickConnection = connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &AesItemList::onEditAesItem, Qt::UniqueConnection); - } - else - { - if (m_doubleClickConnection) - disconnect(m_doubleClickConnection); - } + if (bEnableEditRemove && bIsAllowedInState) + { + m_doubleClickConnection = connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &AesItemList::onEditAesItem, Qt::UniqueConnection); + } + else + { + if (m_doubleClickConnection) + disconnect(m_doubleClickConnection); + } } -void AesItemList::onPrint() { LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } +void AesItemList::onPrint() +{ + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); +} void AesItemList::onAdlerBtn() { - AesEffectState aesEffectState = model()->aesEffectStateId(currentRow()); - ProjectDataManagement::EffectSource effectSource = model()->aesEffectSourceId(currentRow()); + AesEffectState aesEffectState = model()->aesEffectStateId(currentRow()); + ProjectDataManagement::EffectSource effectSource = model()->aesEffectSourceId(currentRow()); - DEBUG_LOG(m_logger) << "onAdlerBtn aesEffectState=" << aesEffectState; + DEBUG_LOG(m_logger) << "onAdlerBtn aesEffectState=" << aesEffectState; - switch (aesEffectState.underlying()) - { - case AreaEffectSimulation::AesEffectState::EsReceived: - { - switch (effectSource.underlying()) + switch (aesEffectState.underlying()) { - case ProjectDataManagement::EffectSource::ES_ADLER: - { - AcknowledgeExternalAesItemRequest req; - int aesId = model()->aesId(currentRow()); - req.aesId(aesId); - m_requestHelper->startSingleRequest([req, this]() { return m_ftc->acknowledgeExternalAesItemRequest(req, this); }); + case AreaEffectSimulation::AesEffectState::EsReceived: { + switch (effectSource.underlying()) + { + case ProjectDataManagement::EffectSource::ES_ADLER: { + AcknowledgeExternalAesItemRequest req; + int aesId = model()->aesId(currentRow()); + req.aesId(aesId); + m_requestHelper->startSingleRequest( + [req, this]() { return m_ftc->acknowledgeExternalAesItemRequest(req, this); }); - break; - } - default: - { - ExplosionClusterReleaseReceivedRequest req; - int aesId = model()->aesId(currentRow()); - req.id(aesId); - m_requestHelper->startSingleRequest([req, this]() { return m_ftc->explosionClusterReleaseReceivedRequest(req, this); }); - break; - } - } + break; + } + default: { + ExplosionClusterReleaseReceivedRequest req; + int aesId = model()->aesId(currentRow()); + req.id(aesId); + m_requestHelper->startSingleRequest( + [req, this]() { return m_ftc->explosionClusterReleaseReceivedRequest(req, this); }); + break; + } + } - break; - } - case AreaEffectSimulation::AesEffectState::EsCreated: - case AreaEffectSimulation::AesEffectState::EsPrepared: - { - if (effectSource == ProjectDataManagement::EffectSource::ES_ADLER || - effectSource == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) - { - AreaEffectSimulation::SetAesItemEffectorStateRequest req; - req.aesId(model()->aesId(currentRow())); - req.newEffectorState(AesEffectorState::EsReadyToFire); - DEBUG_LOG(m_logger) << "Send setAesItemEffectorStateRequest with aesId: " << req.aesId() << ", AesEffectorState: " << req.newEffectorState(); + break; + } + case AreaEffectSimulation::AesEffectState::EsCreated: + case AreaEffectSimulation::AesEffectState::EsPrepared: { + if (effectSource == ProjectDataManagement::EffectSource::ES_ADLER || + effectSource == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) + { + AreaEffectSimulation::SetAesItemEffectorStateRequest req; + req.aesId(model()->aesId(currentRow())); + req.newEffectorState(AesEffectorState::EsReadyToFire); + DEBUG_LOG(m_logger) << "Send setAesItemEffectorStateRequest with aesId: " << req.aesId() + << ", AesEffectorState: " << req.newEffectorState(); - m_requestHelper->startSingleRequest([req, this]() { return m_ftc->setAesItemEffectorStateRequest(req, this); }); + m_requestHelper->startSingleRequest( + [req, this]() { return m_ftc->setAesItemEffectorStateRequest(req, this); }); + } + break; + } + default: + m_buttonBox->getButton(ADLER_BTN)->hide(); } - break; - } - default: - m_buttonBox->getButton(ADLER_BTN)->hide(); - } } - void AesItemList::onHandleAdler() { - AesEffectState aesEffectState = model()->aesEffectStateId(currentRow()); - DEBUG_LOG(m_logger) << "onHandleAdler aesEffectState=" << aesEffectState; - auto *adlerBtn = m_buttonBox->getButton(ADLER_BTN); + AesEffectState aesEffectState = model()->aesEffectStateId(currentRow()); + DEBUG_LOG(m_logger) << "onHandleAdler aesEffectState=" << aesEffectState; + auto* adlerBtn = m_buttonBox->getButton(ADLER_BTN); - switch (aesEffectState.underlying()) - { - case AreaEffectSimulation::AesEffectState::EsReceived: - { - adlerBtn->setText(tr("Mark received")); - adlerBtn->setIcon(QIcon(QStringLiteral("icon:mortar_ammunition_administration.svg"))); - adlerBtn->show(); - break; - } - case AreaEffectSimulation::AesEffectState::EsCreated: - case AreaEffectSimulation::AesEffectState::EsPrepared: - { - ProjectDataManagement::EffectSource effectSource = model()->aesEffectSourceId(currentRow()); - if (effectSource.underlying() == ProjectDataManagement::EffectSource::ES_ADLER || - effectSource.underlying() == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) + switch (aesEffectState.underlying()) { - const EffectCluster &ecData = m_dtc->effectCluster(model()->aesId(currentRow())); - if (ecData.effectorState() == AreaEffectSimulation::AesEffectorState::EsNotReadyToFire) - { - adlerBtn->setText(tr("Ready To Fire")); - adlerBtn->show(); - } - else - adlerBtn->hide(); + case AreaEffectSimulation::AesEffectState::EsReceived: { + adlerBtn->setText(tr("Mark received")); + adlerBtn->setIcon(QIcon(QStringLiteral("icon:mortar_ammunition_administration.svg"))); + adlerBtn->show(); + break; + } + case AreaEffectSimulation::AesEffectState::EsCreated: + case AreaEffectSimulation::AesEffectState::EsPrepared: { + ProjectDataManagement::EffectSource effectSource = model()->aesEffectSourceId(currentRow()); + if (effectSource.underlying() == ProjectDataManagement::EffectSource::ES_ADLER || + effectSource.underlying() == ProjectDataManagement::EffectSource::ES_ADLER_STANDALONE) + { + const EffectCluster& ecData = m_dtc->effectCluster(model()->aesId(currentRow())); + if (ecData.effectorState() == AreaEffectSimulation::AesEffectorState::EsNotReadyToFire) + { + adlerBtn->setText(tr("Ready To Fire")); + adlerBtn->show(); + } + else + adlerBtn->hide(); + } + break; + } + default: + adlerBtn->hide(); } - break; - } - default: - adlerBtn->hide(); - } } void AesItemList::onCenterAesItem() { - int aesId = model()->aesId(currentRow()); - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - ifc->centerMapToAesObject(aesId); + int aesId = model()->aesId(currentRow()); + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + ifc->centerMapToAesObject(aesId); } -void AesItemList::hideColumn(int col) { m_ui->widget->hideColumn(col); } +void AesItemList::hideColumn(int col) +{ + m_ui->widget->hideColumn(col); +} -void AesItemList::showColumn(int col) { m_ui->widget->showColumn(col); } +void AesItemList::showColumn(int col) +{ + m_ui->widget->showColumn(col); +} int AesItemList::currentRow() const { - const auto selRows = m_ui->widget->selectedRows(); - if (selRows.count() != 1) - return -1; - return selRows.first().row(); + const auto selRows = m_ui->widget->selectedRows(); + if (selRows.count() != 1) + return -1; + return selRows.first().row(); } -void AesItemList::setDataViewModel(QAbstractItemModel *model, const std::function &customDisplayWidgetCreator) +void AesItemList::setDataViewModel( + QAbstractItemModel* model, const std::function& customDisplayWidgetCreator) { - m_ui->widget->setModel(model, customDisplayWidgetCreator); + m_ui->widget->setModel(model, customDisplayWidgetCreator); } -void AesItemList::setDataViewModel(QAbstractItemModel *model) { m_ui->widget->setModel(model); } +void AesItemList::setDataViewModel(QAbstractItemModel* model) +{ + m_ui->widget->setModel(model); +} -void AesItemList::setShowExpired(bool show) { model()->setShowExpired(show); } +void AesItemList::setShowExpired(bool show) +{ + model()->setShowExpired(show); +} -void AesItemList::setSortIndicator(int col) { m_ui->widget->setSortIndicator(col, Qt::AscendingOrder); } +void AesItemList::setSortIndicator(int col) +{ + m_ui->widget->setSortIndicator(col, Qt::AscendingOrder); +} -void AesItemList::translateBase(const QString &windowTitle) { translate(m_ui, windowTitle); } +void AesItemList::translateBase(const QString& windowTitle) +{ + translate(m_ui, windowTitle); +} void AesItemList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_list.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_list.cpp old mode 100755 new mode 100644 index 6daae0906..9198252cc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_list.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_list.cpp @@ -1,110 +1,106 @@ - #include "aes_charge_administration_adler_list.h" -#include "ui_aes_charge_administration_list.h" -#include "aes_charge_administration_adler_model.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include "aes_charge_administration_adler_model.h" +#include "ui_aes_charge_administration_list.h" #include +#include +#include +#include +#include +#include +#include +#include +#include #include namespace AreaEffectSimulation { -ChargeAdministrationAdlerList::ChargeAdministrationAdlerList(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_model(nullptr) - , m_sourceModel(nullptr) - , m_session(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::ChargeAdministrationList) +ChargeAdministrationAdlerList::ChargeAdministrationAdlerList(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_model(nullptr), m_sourceModel(nullptr), + m_session(nullptr), m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::ChargeAdministrationList) { - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_ui->cbParty, static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &ChargeAdministrationAdlerList::onPartyChanged); + connect(m_ui->cbParty, + static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &ChargeAdministrationAdlerList::onPartyChanged); - setOnlineHelpFilename(QStringLiteral("Situation-Charge_Administration_Adler")); + setOnlineHelpFilename(QStringLiteral("Situation-Charge_Administration_Adler")); } ChargeAdministrationAdlerList::~ChargeAdministrationAdlerList() { - delete m_ui; + delete m_ui; } void ChargeAdministrationAdlerList::retranslate() { - translate(m_ui, tr("Charge Administration Adler")); + translate(m_ui, tr("Charge Administration Adler")); } void ChargeAdministrationAdlerList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } void ChargeAdministrationAdlerList::onPartyChanged() { - m_model->setParty(m_ui->cbParty->currentData().toInt()); + m_model->setParty(m_ui->cbParty->currentData().toInt()); } -bool ChargeAdministrationAdlerList::init(LtsSession::LtsSession *session) +bool ChargeAdministrationAdlerList::init(LtsSession::LtsSession* session) { - if (m_session) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - m_session = session; + if (m_session) + { + ERROR_LOG(m_logger) << "double init()!"; + return false; + } + m_session = session; - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ChargeAdministrationAdlerList::onPrint); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ChargeAdministrationAdlerList::onPrint); - std::shared_ptr ppmGuiCbxIfc; - if (!m_session->getForeignGuiInterface(ppmGuiCbxIfc)) - return false; + std::shared_ptr ppmGuiCbxIfc; + if (!m_session->getForeignGuiInterface(ppmGuiCbxIfc)) + return false; - m_sourceModel = new ChargeAdministrationAdlerModel(this); + m_sourceModel = new ChargeAdministrationAdlerModel(this); - if (!m_sourceModel->initModel(m_session)) - return false; + if (!m_sourceModel->initModel(m_session)) + return false; - m_model = new ChargeAdministrationAdlerSortFilterProxyModel(this); - m_model->setSourceModel(m_sourceModel); - m_ui->widget->setModel(m_model); - m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColId, true); + m_model = new ChargeAdministrationAdlerSortFilterProxyModel(this); + m_model->setSourceModel(m_sourceModel); + m_ui->widget->setModel(m_model); + m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColId, true); #ifndef LTS_DEBUG - bool onlydebugMode =true; - m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColTypeId, onlydebugMode); - m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColChanged, onlydebugMode); + bool onlydebugMode = true; + m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColTypeId, onlydebugMode); + m_ui->widget->hideColumn(ChargeAdministrationAdlerModel::ColChanged, onlydebugMode); #endif - m_ui->widget->setSortIndicator(ChargeAdministrationAdlerModel::ColTypeName, Qt::AscendingOrder); + m_ui->widget->setSortIndicator(ChargeAdministrationAdlerModel::ColTypeName, Qt::AscendingOrder); - ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); - onPartyChanged(); + ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); + onPartyChanged(); - return true; + return true; } void ChargeAdministrationAdlerList::onPrint() { - QString header; - header += QStringLiteral("

"); - header += tr("Party: %1").arg(m_ui->cbParty->currentText()); - header += QStringLiteral("
"); - header += QStringLiteral("

"); + QString header; + header += QStringLiteral("

"); + header += tr("Party: %1").arg(m_ui->cbParty->currentText()); + header += QStringLiteral("
"); + header += QStringLiteral("

"); - LtsPrinting::printView(m_session, this, m_ui->widget->treeView(), header ); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView(), header); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_model.cpp old mode 100755 new mode 100644 index 2d8a1d093..a3925ea5e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_adler_model.cpp @@ -1,263 +1,256 @@ - #include "aes_charge_administration_adler_model.h" -#include -#include -#include + #include #include #include -#include -#include #include - +#include +#include +#include +#include +#include namespace AreaEffectSimulation { - - - -void ChargeAdministrationAdlerSortFilterProxyModel::setSourceModel(QAbstractItemModel *model) +void ChargeAdministrationAdlerSortFilterProxyModel::setSourceModel(QAbstractItemModel* model) { - m_sourceModel = qobject_cast(model); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(model); + m_sourceModel = qobject_cast(model); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(model); } -bool ChargeAdministrationAdlerSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool ChargeAdministrationAdlerSortFilterProxyModel::filterAcceptsRow(int source_row, + const QModelIndex& source_parent) const { - if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->rowCount()) - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->rowCount()) + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - const ChargeAdministrationAdler &item = m_sourceModel->m_vecData.at(source_row); - if (item.partyId != m_party) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + const ChargeAdministrationAdler& item = m_sourceModel->m_vecData.at(source_row); + if (item.partyId != m_party) + return false; + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } int ChargeAdministrationAdlerSortFilterProxyModel::party() const { - return m_party; + return m_party; } void ChargeAdministrationAdlerSortFilterProxyModel::setParty(int party) { - m_party = party; - invalidateFilter(); + m_party = party; + invalidateFilter(); } - - - -ChargeAdministrationAdlerModel::ChargeAdministrationAdlerModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Charge Type Id"), - tr("Changed"), - tr("Charge Type Name"), - tr("Total Stock"), - tr("Gear Class")}, - parent) -{} - -bool ChargeAdministrationAdlerModel::initModel(LtsSession::LtsSession *session) +ChargeAdministrationAdlerModel::ChargeAdministrationAdlerModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Charge Type Id"), tr("Changed"), tr("Charge Type Name"), tr("Total Stock"), tr("Gear Class")}, + parent) { - if (!session->getDtc(m_pdmDtc)) - return false; - - if (!session->getDtc(m_ppmDtc)) - return false; - - m_DynamicParticipantDataMap = m_ppmDtc->dynamicParticipantDatas(); - QMapIterator iter(m_DynamicParticipantDataMap); - while(iter.hasNext()) - { - iter.next(); - updateParticipantChargeTypeMap(iter.value()); - } - - QMap parties; - if (!m_ppmDtc->visibleParties(parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(session->exerciseId()))) - { - DEBUG_LOG(m_logger) << "Could not retrieve visible Parties!"; - return false; - } - - - for (const ParticipantManagement::Party &p : std::as_const(parties)) - { - updateItem(p.id()); - } - - connect (m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, - this, &ChargeAdministrationAdlerModel::onStateChanged); - connect (m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, - this, &ChargeAdministrationAdlerModel::onParticipantChanged); - - return true; } -void ChargeAdministrationAdlerModel::onStateChanged(const ParticipantManagement::DynamicParticipantData &data, DataModification modType) +bool ChargeAdministrationAdlerModel::initModel(LtsSession::LtsSession* session) { - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - DEBUG_LOG(m_logger) << "+++++++++ DataModification --> " << modType; - updateParticipantChargeTypeMap(data); - - updateItem(m_ppmDtc->participant(data.participantId()).partyId()); - break; - } - case DataModification::eRemoved: - { - break; - } - } + if (!session->getDtc(m_pdmDtc)) + return false; + + if (!session->getDtc(m_ppmDtc)) + return false; + + m_DynamicParticipantDataMap = m_ppmDtc->dynamicParticipantDatas(); + QMapIterator iter(m_DynamicParticipantDataMap); + while (iter.hasNext()) + { + iter.next(); + updateParticipantChargeTypeMap(iter.value()); + } + + QMap parties; + if (!m_ppmDtc->visibleParties( + parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(session->exerciseId()))) + { + DEBUG_LOG(m_logger) << "Could not retrieve visible Parties!"; + return false; + } + + for (const ParticipantManagement::Party& p : std::as_const(parties)) + { + updateItem(p.id()); + } + + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, this, + &ChargeAdministrationAdlerModel::onStateChanged); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, this, + &ChargeAdministrationAdlerModel::onParticipantChanged); + + return true; } -void ChargeAdministrationAdlerModel::onParticipantChanged(const ParticipantManagement::Participant &data, +void ChargeAdministrationAdlerModel::onStateChanged(const ParticipantManagement::DynamicParticipantData& data, + DataModification modType) +{ + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: { + DEBUG_LOG(m_logger) << "+++++++++ DataModification --> " << modType; + updateParticipantChargeTypeMap(data); + + updateItem(m_ppmDtc->participant(data.participantId()).partyId()); + break; + } + case DataModification::eRemoved: { + break; + } + } +} + +void ChargeAdministrationAdlerModel::onParticipantChanged(const ParticipantManagement::Participant& data, DataModification modType) { - Q_UNUSED(modType) - qint32 typeId = data.typeId(); - qint32 participantId = data.id(); + Q_UNUSED(modType) + qint32 typeId = data.typeId(); + qint32 participantId = data.id(); - - if (!data.isDeleted() || (!m_ppmDtc->isAdlerType(typeId) && - (m_ppmDtc->type(typeId).typeClass().underlying() != ParticipantManagement::TypeClass::Unit))) - return; + if (!data.isDeleted() || (!m_ppmDtc->isAdlerType(typeId) && (m_ppmDtc->type(typeId).typeClass().underlying() != + ParticipantManagement::TypeClass::Unit))) + return; - if (m_participantChargeTypeMap.contains(participantId)) - { - - QList keys = m_participantChargeTypeMap.value(participantId).chargeTypeTotalStockMap.keys(); - for ( int key : keys) + if (m_participantChargeTypeMap.contains(participantId)) { - int row = findRowForChargeTypeId(key, m_participantChargeTypeMap.value(participantId).partyId); - if (row != -1) - removeRow(row); - } - - m_participantChargeTypeMap.remove(participantId); - } - - updateItem(data.partyId()); + QList keys = m_participantChargeTypeMap.value(participantId).chargeTypeTotalStockMap.keys(); + for (int key : keys) + { + int row = findRowForChargeTypeId(key, m_participantChargeTypeMap.value(participantId).partyId); + if (row != -1) + removeRow(row); + } + + m_participantChargeTypeMap.remove(participantId); + } + + updateItem(data.partyId()); } -void ChargeAdministrationAdlerModel::updateParticipantChargeTypeMap(const ParticipantManagement::DynamicParticipantData &data) +void ChargeAdministrationAdlerModel::updateParticipantChargeTypeMap( + const ParticipantManagement::DynamicParticipantData& data) { - qint32 participantId = data.participantId(); - qint64 sampleTime = data.sampleTime(); - qint32 typeId = m_ppmDtc->participant(participantId).typeId(); - bool isDeleted = m_ppmDtc->participant(participantId).isDeleted(); + qint32 participantId = data.participantId(); + qint64 sampleTime = data.sampleTime(); + qint32 typeId = m_ppmDtc->participant(participantId).typeId(); + bool isDeleted = m_ppmDtc->participant(participantId).isDeleted(); - if (isDeleted || (!m_ppmDtc->isAdlerType(typeId) && - (m_ppmDtc->type(typeId).typeClass().underlying() != ParticipantManagement::TypeClass::Unit))) - return; + if (isDeleted || (!m_ppmDtc->isAdlerType(typeId) && + (m_ppmDtc->type(typeId).typeClass().underlying() != ParticipantManagement::TypeClass::Unit))) + return; - QMap chargeTypeGearData; - for (const ParticipantManagement::GearInformation &ct : data.gear()) - { - if (m_pdmDtc->adlerChargeTypeName(ct.chargeTypeId()).isEmpty()) - continue; - - GearData gearData; - gearData.remain = ct.remain(); - gearData.lastUpdate = ct.lastUpdate(); - if (chargeTypeGearData.contains(ct.chargeTypeId())) + QMap chargeTypeGearData; + for (const ParticipantManagement::GearInformation& ct : data.gear()) { - gearData.remain += chargeTypeGearData.value(ct.chargeTypeId()).remain; + if (m_pdmDtc->adlerChargeTypeName(ct.chargeTypeId()).isEmpty()) + continue; + + GearData gearData; + gearData.remain = ct.remain(); + gearData.lastUpdate = ct.lastUpdate(); + if (chargeTypeGearData.contains(ct.chargeTypeId())) + { + gearData.remain += chargeTypeGearData.value(ct.chargeTypeId()).remain; + } + chargeTypeGearData.insert(ct.chargeTypeId(), gearData); } - chargeTypeGearData.insert(ct.chargeTypeId(), gearData); - } - m_participantChargeTypeMap.insert(participantId, - ChargeStruct(participantId, m_ppmDtc->participant(participantId).partyId(), - sampleTime, chargeTypeGearData)); + m_participantChargeTypeMap.insert( + participantId, + ChargeStruct(participantId, m_ppmDtc->participant(participantId).partyId(), sampleTime, chargeTypeGearData)); } void ChargeAdministrationAdlerModel::updateItem(int partyId) { - QMap chargeTypeGearData; - qint64 sampleTime=0; - ChargeAdministrationAdler item; + QMap chargeTypeGearData; + qint64 sampleTime = 0; + ChargeAdministrationAdler item; - for (const ChargeStruct &participantCharges : std::as_const(m_participantChargeTypeMap)) - { - if (participantCharges.partyId != partyId) - continue; - DEBUG_LOG(m_logger) << "+++++++++ ParticipantId -> " << participantCharges.participantId << ", sampleTime ->" << sampleTime; - for (auto it = participantCharges.chargeTypeTotalStockMap.cbegin(), end = participantCharges.chargeTypeTotalStockMap.cend(); it != end; ++it) + for (const ChargeStruct& participantCharges : std::as_const(m_participantChargeTypeMap)) { - DEBUG_LOG(m_logger) << "+++++++++ chargeRemain ->" << it.key() << ": " << it.value().remain - << it.value().lastUpdate; - GearData data; - data.lastUpdate = it.value().lastUpdate; - data.remain = it.value().remain; - if (chargeTypeGearData.contains(it.key())) - { - data.remain += chargeTypeGearData.value(it.key()).remain; - } - if (chargeTypeGearData.contains(it.key())) - if (chargeTypeGearData.value(it.key()).lastUpdate > data.lastUpdate) - data.lastUpdate = chargeTypeGearData.value(it.key()).lastUpdate; + if (participantCharges.partyId != partyId) + continue; + DEBUG_LOG(m_logger) << "+++++++++ ParticipantId -> " << participantCharges.participantId << ", sampleTime ->" + << sampleTime; + for (auto it = participantCharges.chargeTypeTotalStockMap.cbegin(), + end = participantCharges.chargeTypeTotalStockMap.cend(); + it != end; ++it) + { + DEBUG_LOG(m_logger) << "+++++++++ chargeRemain ->" << it.key() << ": " << it.value().remain + << it.value().lastUpdate; + GearData data; + data.lastUpdate = it.value().lastUpdate; + data.remain = it.value().remain; + if (chargeTypeGearData.contains(it.key())) + { + data.remain += chargeTypeGearData.value(it.key()).remain; + } + if (chargeTypeGearData.contains(it.key())) + if (chargeTypeGearData.value(it.key()).lastUpdate > data.lastUpdate) + data.lastUpdate = chargeTypeGearData.value(it.key()).lastUpdate; - chargeTypeGearData.insert(it.key(), data); + chargeTypeGearData.insert(it.key(), data); + } } - } - item.partyId = partyId; - for (auto gearData = chargeTypeGearData.cbegin(), end = chargeTypeGearData.cend(); gearData != end; ++gearData) - { - DEBUG_LOG(m_logger) << "### PartyId " << item.partyId << " insert item -> chargeTypeId: " << gearData.key() << ", amount: " << gearData.value().remain - << ", lastUpdate:" << gearData.value().lastUpdate; + item.partyId = partyId; + for (auto gearData = chargeTypeGearData.cbegin(), end = chargeTypeGearData.cend(); gearData != end; ++gearData) + { + DEBUG_LOG(m_logger) << "### PartyId " << item.partyId << " insert item -> chargeTypeId: " << gearData.key() + << ", amount: " << gearData.value().remain + << ", lastUpdate:" << gearData.value().lastUpdate; - item.chargeTypeId = gearData.key(); - item.sampleTime = gearData.value().lastUpdate; - item.amount = gearData.value().remain; - int row = findRowForChargeTypeId(item.chargeTypeId, item.partyId); - if (row < 0) - insertRow(item); - else - setRowData(row, item); - } + item.chargeTypeId = gearData.key(); + item.sampleTime = gearData.value().lastUpdate; + item.amount = gearData.value().remain; + int row = findRowForChargeTypeId(item.chargeTypeId, item.partyId); + if (row < 0) + insertRow(item); + else + setRowData(row, item); + } } int ChargeAdministrationAdlerModel::findRowForChargeTypeId(qint32 typeId, qint32 partyId) const { - for (int i = 0; i < m_vecData.size(); ++i) - { - if (m_vecData.at(i).chargeTypeId == typeId && m_vecData.at(i).partyId == partyId) - return i; - } - return -1; + for (int i = 0; i < m_vecData.size(); ++i) + { + if (m_vecData.at(i).chargeTypeId == typeId && m_vecData.at(i).partyId == partyId) + return i; + } + return -1; } -QVariant ChargeAdministrationAdlerModel::data(const QModelIndex &index, int role) const +QVariant ChargeAdministrationAdlerModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole || !indexIsValid(index)) + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const ChargeAdministrationAdler& item = m_vecData.at(index.row()); + + switch (index.column()) + { + case ColId: + return item.id; + case ColTypeId: + return item.chargeTypeId; + case ColChanged: + return QDateTime::fromMSecsSinceEpoch(item.sampleTime); + case ColTypeName: + return m_pdmDtc->trChargeTypeShortName(item.chargeTypeId, true); + case ColStock: + return item.amount; + case ColGearClass: + return ProjectDataManagement::toString(m_pdmDtc->gearClassFromChargeTypeId(item.chargeTypeId)); + } return QVariant(); - - const ChargeAdministrationAdler &item = m_vecData.at(index.row()); - - switch (index.column()) - { - case ColId: - return item.id; - case ColTypeId: - return item.chargeTypeId; - case ColChanged: - return QDateTime::fromMSecsSinceEpoch(item.sampleTime); - case ColTypeName: - return m_pdmDtc->trChargeTypeShortName(item.chargeTypeId, true); - case ColStock: - return item.amount; - case ColGearClass: - return ProjectDataManagement::toString(m_pdmDtc->gearClassFromChargeTypeId(item.chargeTypeId)); - } - return QVariant(); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_list.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_list.cpp old mode 100755 new mode 100644 index 07f81e77b..6bbda4640 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_list.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_list.cpp @@ -1,188 +1,190 @@ - #include "aes_charge_administration_list.h" -#include + #include "CustomView/aes_charge_administration.h" #include "aes_charge_administration_model.h" #include "aes_charge_edit.h" #include "ui_aes_charge_administration_list.h" + +#include #include #include #include #include - -#include +#include #include #include -#include - +#include #include -#include +#include namespace AreaEffectSimulation { -ChargeAdministrationList::ChargeAdministrationList(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_model(nullptr) - , m_sourceModel(nullptr) - , m_session(nullptr) - , m_ftc(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::ChargeAdministrationList) +ChargeAdministrationList::ChargeAdministrationList(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_model(nullptr), m_sourceModel(nullptr), + m_session(nullptr), m_ftc(nullptr), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_ui(new Ui::ChargeAdministrationList) { - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_ui->cbParty, - static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, - &ChargeAdministrationList::onPartyChanged); + connect(m_ui->cbParty, + static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &ChargeAdministrationList::onPartyChanged); - setOnlineHelpFilename(QStringLiteral("Situation-Charge_Administration")); + setOnlineHelpFilename(QStringLiteral("Situation-Charge_Administration")); } -ChargeAdministrationList::~ChargeAdministrationList() { delete m_ui; } +ChargeAdministrationList::~ChargeAdministrationList() +{ + delete m_ui; +} -void ChargeAdministrationList::retranslate() { translate(m_ui, tr("Charge Administration")); } +void ChargeAdministrationList::retranslate() +{ + translate(m_ui, tr("Charge Administration")); +} void ChargeAdministrationList::enaDisa() { - LtsWidgets::ExerciseStates allowedStates = LtsWidgets::ExerciseState::eCreated | LtsWidgets::ExerciseState::eStarted | LtsWidgets::ExerciseState::ePaused; - bool bIsAllowedInState = allowedStates.testFlag(m_session->exerciseState()); + LtsWidgets::ExerciseStates allowedStates = + LtsWidgets::ExerciseState::eCreated | LtsWidgets::ExerciseState::eStarted | LtsWidgets::ExerciseState::ePaused; + bool bIsAllowedInState = allowedStates.testFlag(m_session->exerciseState()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bIsAllowedInState && m_ui->widget->selectedRows().count() > 0); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, bIsAllowedInState && m_ui->widget->selectedRows().count() > 0); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, + bIsAllowedInState && m_ui->widget->selectedRows().count() > 0); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, + bIsAllowedInState && m_ui->widget->selectedRows().count() > 0); } -void ChargeAdministrationList::onPartyChanged() { m_model->setParty(m_ui->cbParty->currentData().toInt()); } +void ChargeAdministrationList::onPartyChanged() +{ + m_model->setParty(m_ui->cbParty->currentData().toInt()); +} -void ChargeAdministrationList::onChargeAdministrationModifyReply(const Core::FunctionReplyObject &replyObject) { m_requestHelper->requestReply(replyObject); } +void ChargeAdministrationList::onChargeAdministrationModifyReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); +} void ChargeAdministrationList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } -bool ChargeAdministrationList::init(LtsSession::LtsSession *session) +bool ChargeAdministrationList::init(LtsSession::LtsSession* session) { - if (m_session) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - m_session = session; - - if (m_session->app() != LtsAppDescriptor::App::OC) - { - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ChargeAdministrationList::onEditCharge); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &ChargeAdministrationList::onEditCharge); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &ChargeAdministrationList::onEditCharge); - } - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ChargeAdministrationList::onPrint); - - - - - if (!m_session->getFtc(m_ftc)) - return false; - - std::shared_ptr ppmGuiCbxIfc; - if (!m_session->getForeignGuiInterface(ppmGuiCbxIfc)) - return false; - - m_sourceModel = new ChargeAdministrationModel(this); - - QVector reqs; - if (!m_sourceModel->initModel(m_session, reqs)) - return false; - - if (!reqs.isEmpty()) - { - for (const ChargeAdministrationModifyRequest &req : std::as_const(reqs)) + if (m_session) { - m_requestHelper->addRequest([this, req]() { return m_ftc->chargeAdministrationModifyRequest(req, this); }); + ERROR_LOG(m_logger) << "double init()!"; + return false; } - m_requestHelper->startRequests(); - } + m_session = session; - m_model = new ChargeAdministrationSortFilterProxyModel(this); - m_model->setSourceModel(m_sourceModel); - m_ui->widget->setModel(m_model, [this]() { return new CustomViewChargeAdministration(this); }); + if (m_session->app() != LtsAppDescriptor::App::OC) + { + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ChargeAdministrationList::onEditCharge); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ChargeAdministrationList::onEditCharge); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, + &ChargeAdministrationList::onEditCharge); + } - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ChargeAdministrationList::enaDisa); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ChargeAdministrationList::onPrint); + + if (!m_session->getFtc(m_ftc)) + return false; + + std::shared_ptr ppmGuiCbxIfc; + if (!m_session->getForeignGuiInterface(ppmGuiCbxIfc)) + return false; + + m_sourceModel = new ChargeAdministrationModel(this); + + QVector reqs; + if (!m_sourceModel->initModel(m_session, reqs)) + return false; + + if (!reqs.isEmpty()) + { + for (const ChargeAdministrationModifyRequest& req : std::as_const(reqs)) + { + m_requestHelper->addRequest([this, req]() { return m_ftc->chargeAdministrationModifyRequest(req, this); }); + } + m_requestHelper->startRequests(); + } + + m_model = new ChargeAdministrationSortFilterProxyModel(this); + m_model->setSourceModel(m_sourceModel); + m_ui->widget->setModel(m_model, [this]() { return new CustomViewChargeAdministration(this); }); + + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ChargeAdministrationList::enaDisa); #ifndef LTS_DEBUG - bool onlydebugMode = true; - m_ui->widget->hideColumn(ChargeAdministrationModel::ColId, onlydebugMode); - m_ui->widget->hideColumn(ChargeAdministrationModel::ColTypeId, onlydebugMode); - m_ui->widget->hideColumn(ChargeAdministrationModel::ColChanged, onlydebugMode); + bool onlydebugMode = true; + m_ui->widget->hideColumn(ChargeAdministrationModel::ColId, onlydebugMode); + m_ui->widget->hideColumn(ChargeAdministrationModel::ColTypeId, onlydebugMode); + m_ui->widget->hideColumn(ChargeAdministrationModel::ColChanged, onlydebugMode); #endif - + m_ui->widget->setSortIndicator(ChargeAdministrationModel::ColTypeName, Qt::AscendingOrder); - m_ui->widget->setSortIndicator(ChargeAdministrationModel::ColTypeName, Qt::AscendingOrder); + enaDisa(); - enaDisa(); + ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); + onPartyChanged(); - ppmGuiCbxIfc->fillPartyComboBox(m_ui->cbParty); - onPartyChanged(); - - return true; + return true; } void ChargeAdministrationList::onPrint() { - QString header; - header += QStringLiteral("

"); - header += tr("Party: %1").arg(m_ui->cbParty->currentText()); - header += QStringLiteral("
"); - header += QStringLiteral("

"); + QString header; + header += QStringLiteral("

"); + header += tr("Party: %1").arg(m_ui->cbParty->currentText()); + header += QStringLiteral("
"); + header += QStringLiteral("

"); - LtsPrinting::printView(m_session, this, m_ui->widget->treeView(), header); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView(), header); } void ChargeAdministrationList::onEditCharge() { - ChargeAdministration item = m_sourceModel->getRowData(m_ui->widget->currentIndex().row()); + ChargeAdministration item = m_sourceModel->getRowData(m_ui->widget->currentIndex().row()); - if (item.id() < 0) - return; + if (item.id() < 0) + return; - ProjectDataManagement::ChargeType ct = m_sourceModel->chargeType(item.chargeTypeId()); + ProjectDataManagement::ChargeType ct = m_sourceModel->chargeType(item.chargeTypeId()); - const QModelIndex temp = m_ui->widget->currentIndex(); + const QModelIndex temp = m_ui->widget->currentIndex(); - const QModelIndex mi = temp.sibling(temp.row(), ChargeAdministrationModel::ColTypeName); - auto ce = new ChargeEdit(ct.id(), m_sourceModel->data(mi).toString(), item.amount(), this); - connect(ce, &ChargeEdit::newStock, this, &ChargeAdministrationList::onChargeEditFinished); - connect(ce, &ChargeEdit::newStock, ce, &ChargeEdit::deleteLater); - ce->show(); + const QModelIndex mi = temp.sibling(temp.row(), ChargeAdministrationModel::ColTypeName); + auto ce = new ChargeEdit(ct.id(), m_sourceModel->data(mi).toString(), item.amount(), this); + connect(ce, &ChargeEdit::newStock, this, &ChargeAdministrationList::onChargeEditFinished); + connect(ce, &ChargeEdit::newStock, ce, &ChargeEdit::deleteLater); + ce->show(); } void ChargeAdministrationList::onChargeEditFinished(int chargeId, int newStock) { - ChargeAdministration item = m_sourceModel->getRowData(m_ui->widget->currentIndex().row()); + ChargeAdministration item = m_sourceModel->getRowData(m_ui->widget->currentIndex().row()); - if (item.chargeTypeId() != chargeId) - return; + if (item.chargeTypeId() != chargeId) + return; - if (item.amount() == newStock) - return; - item.amount(newStock); + if (item.amount() == newStock) + return; + item.amount(newStock); - bool amountChangedByOperator = true; - const ChargeAdministrationModifyRequest req(item.id(), - item.chargeTypeId(), - item.partyId(), - item.effectSourceId(), - item.amount(), - amountChangedByOperator); + bool amountChangedByOperator = true; + const ChargeAdministrationModifyRequest req(item.id(), item.chargeTypeId(), item.partyId(), item.effectSourceId(), + item.amount(), amountChangedByOperator); - m_requestHelper->addRequest([this, req]() { return m_ftc->chargeAdministrationModifyRequest(req, this); }); - m_requestHelper->startRequests(); + m_requestHelper->addRequest([this, req]() { return m_ftc->chargeAdministrationModifyRequest(req, this); }); + m_requestHelper->startRequests(); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_model.cpp old mode 100755 new mode 100644 index d818059ab..4db865bfa --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AreaEffectSimulation/Gui/ChargeAdministration/aes_charge_administration_model.cpp @@ -1,172 +1,167 @@ - #include "aes_charge_administration_model.h" -#include + #include #include #include #include -#include #include +#include #include #include #include +#include namespace AreaEffectSimulation { - - - - -void ChargeAdministrationSortFilterProxyModel::setSourceModel(QAbstractItemModel *model) +void ChargeAdministrationSortFilterProxyModel::setSourceModel(QAbstractItemModel* model) { - m_sourceModel = qobject_cast(model); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(model); + m_sourceModel = qobject_cast(model); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(model); } -bool ChargeAdministrationSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool ChargeAdministrationSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->rowCount()) + if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->rowCount()) + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + + const ChargeAdministration& item = m_sourceModel->m_vecData.at(source_row); + if (item.partyId() != m_party) + return false; return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - - const ChargeAdministration &item = m_sourceModel->m_vecData.at(source_row); - if (item.partyId() != m_party) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } -int ChargeAdministrationSortFilterProxyModel::party() const { return m_party; } +int ChargeAdministrationSortFilterProxyModel::party() const +{ + return m_party; +} void ChargeAdministrationSortFilterProxyModel::setParty(int party) { - m_party = party; - invalidateFilter(); + m_party = party; + invalidateFilter(); } - - - -ChargeAdministrationModel::ChargeAdministrationModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Charge Type Id"), - tr("Changed"), - tr("Charge Type Name"), - tr("Total Stock"), - tr("Planned"), - tr("Available"), - tr("Used"), - tr("Gear Class")}, +ChargeAdministrationModel::ChargeAdministrationModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel({tr("Id"), tr("Charge Type Id"), tr("Changed"), + tr("Charge Type Name"), tr("Total Stock"), tr("Planned"), + tr("Available"), tr("Used"), tr("Gear Class")}, parent) { } -bool ChargeAdministrationModel::initModel(LtsSession::LtsSession *session, QVector &reqs) +bool ChargeAdministrationModel::initModel(LtsSession::LtsSession* session, + QVector& reqs) { - if (m_aesDtc) - { - ERROR_LOG(m_logger) << "double init()!"; - return false; - } - - if (!session->getDtc(m_aesDtc)) - return false; - - std::shared_ptr ppmDtc; - - if (!session->getDtc(m_pdmDtc)) - return false; - - if (!session->getDtc(ppmDtc)) - return false; - - m_chargeTypeMap = m_pdmDtc->chargeTypes(); - - connect(m_aesDtc.get(), &Interface::Dtc::chargeAdministrationChanged, this, &ChargeAdministrationModel::onChargeAdministrationChanged); - - QVector> chargesInserted; - auto cb = [this, &chargesInserted](const ChargeAdministration &item) - { - - const int chargeTypeId = item.chargeTypeId(); - if (m_pdmDtc->isAdlerChargeType(chargeTypeId)) - return; - - insertRow(item); - chargesInserted.append(qMakePair(item.chargeTypeId(), item.partyId())); - }; - m_aesDtc->chargeAdministrations(cb); - - QMap parties; - if (!ppmDtc->visibleParties(parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(session->exerciseId()))) - { - ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; - return false; - } - - QVector chargesForGearClass - = m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Artillery) + m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Mortar); - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableRocket = ps->value(QStringLiteral("aes"), QStringLiteral("enableRocket"), false).toBool(); - if (enableRocket) - chargesForGearClass += m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Rocket); - for (const ParticipantManagement::Party &p : std::as_const(parties)) - { - for (const ProjectDataManagement::ChargeType &ct : std::as_const(chargesForGearClass)) + if (m_aesDtc) { - if (chargesInserted.contains(qMakePair(ct.id(), p.id())) || isDummy(ct) || m_pdmDtc->isAdlerChargeType(ct.id())) - continue; - - reqs << ChargeAdministrationModifyRequest(0, ct.id(), p.id(), ProjectDataManagement::EffectSource::ES_Internal, 0, true); + ERROR_LOG(m_logger) << "double init()!"; + return false; } - } - return true; + + if (!session->getDtc(m_aesDtc)) + return false; + + std::shared_ptr ppmDtc; + + if (!session->getDtc(m_pdmDtc)) + return false; + + if (!session->getDtc(ppmDtc)) + return false; + + m_chargeTypeMap = m_pdmDtc->chargeTypes(); + + connect(m_aesDtc.get(), &Interface::Dtc::chargeAdministrationChanged, this, + &ChargeAdministrationModel::onChargeAdministrationChanged); + + QVector> chargesInserted; + auto cb = [this, &chargesInserted](const ChargeAdministration& item) { + const int chargeTypeId = item.chargeTypeId(); + if (m_pdmDtc->isAdlerChargeType(chargeTypeId)) + return; + + insertRow(item); + chargesInserted.append(qMakePair(item.chargeTypeId(), item.partyId())); + }; + m_aesDtc->chargeAdministrations(cb); + + QMap parties; + if (!ppmDtc->visibleParties( + parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(session->exerciseId()))) + { + ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; + return false; + } + + QVector chargesForGearClass = + m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Artillery) + + m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Mortar); + + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableRocket = ps->value(QStringLiteral("aes"), QStringLiteral("enableRocket"), false).toBool(); + if (enableRocket) + chargesForGearClass += m_pdmDtc->chargesForGearClass(ProjectDataManagement::GearClass_def::Rocket); + for (const ParticipantManagement::Party& p : std::as_const(parties)) + { + for (const ProjectDataManagement::ChargeType& ct : std::as_const(chargesForGearClass)) + { + if (chargesInserted.contains(qMakePair(ct.id(), p.id())) || isDummy(ct) || + m_pdmDtc->isAdlerChargeType(ct.id())) + continue; + + reqs << ChargeAdministrationModifyRequest(0, ct.id(), p.id(), + ProjectDataManagement::EffectSource::ES_Internal, 0, true); + } + } + return true; } -bool ChargeAdministrationModel::isDummy(const ProjectDataManagement::ChargeType &ct) +bool ChargeAdministrationModel::isDummy(const ProjectDataManagement::ChargeType& ct) { - return LtsUtils::JsonObject::fromJson(ct.properties()).valueOr("isDummy", false); + return LtsUtils::JsonObject::fromJson(ct.properties()).valueOr("isDummy", false); } -QVariant ChargeAdministrationModel::data(const QModelIndex &index, int role) const +QVariant ChargeAdministrationModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole || !indexIsValid(index)) + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const ChargeAdministration& item = m_vecData.at(index.row()); + + switch (index.column()) + { + case ColId: + return item.id(); + case ColTypeId: + return item.chargeTypeId(); + case ColChanged: + return QDateTime::fromMSecsSinceEpoch(item.sampleTime()); + case ColTypeName: + return m_pdmDtc->trChargeTypeShortName(item.chargeTypeId(), true); + case ColStock: + return item.amount(); + case ColAvailable: + return item.amount() - item.planned(); + case ColPlanned: + return item.planned(); + case ColUsed: + return item.used(); + case ColGearClass: + return ProjectDataManagement::toString(m_pdmDtc->gearClassFromChargeTypeId(item.chargeTypeId())); + } return QVariant(); - - const ChargeAdministration &item = m_vecData.at(index.row()); - - switch (index.column()) - { - case ColId: - return item.id(); - case ColTypeId: - return item.chargeTypeId(); - case ColChanged: - return QDateTime::fromMSecsSinceEpoch(item.sampleTime()); - case ColTypeName: - return m_pdmDtc->trChargeTypeShortName(item.chargeTypeId(), true); - case ColStock: - return item.amount(); - case ColAvailable: - return item.amount() - item.planned(); - case ColPlanned: - return item.planned(); - case ColUsed: - return item.used(); - case ColGearClass: - return ProjectDataManagement::toString(m_pdmDtc->gearClassFromChargeTypeId(item.chargeTypeId())); - } - return QVariant(); } -void ChargeAdministrationModel::onChargeAdministrationChanged(const ChargeAdministration &data, DataModification modType) +void ChargeAdministrationModel::onChargeAdministrationChanged(const ChargeAdministration& data, + DataModification modType) { - - if (m_pdmDtc->isAdlerChargeType(data.chargeTypeId())) - return; - onDataChanged(data, modType); + + if (m_pdmDtc->isAdlerChargeType(data.chargeTypeId())) + return; + onDataChanged(data, modType); } -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.cpp old mode 100755 new mode 100644 index c868fedb4..a3f9dc216 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.cpp @@ -1,372 +1,329 @@ - - #include "asm_edit_training_area_dialog.h" + #include "ui_asm_edit_training_area_dialog.h" -#include +#include #include #include #include -#include +#include #include #include +static constexpr double s_minWidth{10}; +static constexpr double s_maxWidth{50000}; - -static constexpr double s_minWidth {10}; -static constexpr double s_maxWidth {50000}; - -static constexpr double s_minHeight {10}; -static constexpr double s_maxHeight {50000}; - +static constexpr double s_minHeight{10}; +static constexpr double s_maxHeight{50000}; using namespace CombatNetRadio; + namespace AssetManagement { -Core::GeoPosition2D convert(const QPointF &coord) +Core::GeoPosition2D convert(const QPointF& coord) { - return Core::GeoPosition2D(coord.x(), coord.y()); + return Core::GeoPosition2D(coord.x(), coord.y()); } -QPointF convert(const Core::GeoPosition2D &geoPos) +QPointF convert(const Core::GeoPosition2D& geoPos) { - return QPointF(geoPos.lon(), geoPos.lat()); + return QPointF(geoPos.lon(), geoPos.lat()); } - - - - -AsmEditTrainingAreaDialog::AsmEditTrainingAreaDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::AsmEditTrainingAreaDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_menuGroup() +AsmEditTrainingAreaDialog::AsmEditTrainingAreaDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::AsmEditTrainingAreaDialog), m_requestHelper(new LtsUtils::RequestHelper(this)), m_menuGroup() { - m_ui->setupUi(this); + m_ui->setupUi(this); } - AsmEditTrainingAreaDialog::~AsmEditTrainingAreaDialog() { - delete m_ui; + delete m_ui; } - void AsmEditTrainingAreaDialog::retranslate() { - translate(m_ui, m_dialogTitle); + translate(m_ui, m_dialogTitle); } - -bool AsmEditTrainingAreaDialog::init(LtsSession::LtsSessionDataDds *session, - const int &trainingAreaId, - const std::shared_ptr &sitMapGuiIfc, - const QString &menuGroup) +bool AsmEditTrainingAreaDialog::init(LtsSession::LtsSessionDataDds* session, const int& trainingAreaId, + const std::shared_ptr& sitMapGuiIfc, + const QString& menuGroup) { - m_menuGroup = menuGroup; - m_session = session; - if (!m_session->getDtc(m_asmDtc)) - { - ERROR_LOG(m_logger) << "AsmEditTrainingAreaDialog::init() Could not enable DTC from ASM"; - return false; - } - if(!m_session->getFtc(m_asmFtc)) - { - ERROR_LOG(m_logger) << "AsmEditTrainingAreaDialog::init() Could not enable FTC from ASM"; - return false; - } - m_asmFtc->enableTrainingAreaRemove(true); - m_asmFtc->enableTrainingAreaModify(true); - - - - if (!sitMapGuiIfc) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " Invalid shared_ptr sitMapGuiIfc!"; - return false; - } - - m_trainingArea = AssetManagement::TrainingArea(); - AssetManagement::TrainingArea ta = AssetManagement::TrainingArea(); - if(trainingAreaId == 0) - { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " New training area "; - ta.id() = 0; - ta.name() = QStringLiteral("newArea").toStdString(); - ta.width() = 12800; - ta.height() = 12800; - m_dialogTitle = tr("New Training Area"); - } - else - { - ta = m_asmDtc->trainingArea(trainingAreaId); - if(ta.id()<= 0) + m_menuGroup = menuGroup; + m_session = session; + if (!m_session->getDtc(m_asmDtc)) { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " training area not valid id: "<< trainingAreaId; - return false; + ERROR_LOG(m_logger) << "AsmEditTrainingAreaDialog::init() Could not enable DTC from ASM"; + return false; + } + if (!m_session->getFtc(m_asmFtc)) + { + ERROR_LOG(m_logger) << "AsmEditTrainingAreaDialog::init() Could not enable FTC from ASM"; + return false; + } + m_asmFtc->enableTrainingAreaRemove(true); + m_asmFtc->enableTrainingAreaModify(true); + + if (!sitMapGuiIfc) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " Invalid shared_ptr sitMapGuiIfc!"; + return false; } - m_dialogTitle = tr("Edit Training Area: %1").arg(QString::fromStdString(ta.name())); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " edit training area " <trainingArea(trainingAreaId); + if (ta.id() <= 0) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " training area not valid id: " << trainingAreaId; + return false; + } - m_trainingArea = ta; - m_sitMapGuiIfc = sitMapGuiIfc; - if (m_sitMapGuiIfc) - { - connect(m_ui->pbPosition, &QPushButton::clicked, this, &AsmEditTrainingAreaDialog::getPosition); - } - else - { - m_ui->pbPosition->setEnabled(false); - } - m_ui->name_lineEdit->setText(QString::fromStdString(m_trainingArea.name())); + m_dialogTitle = tr("Edit Training Area: %1").arg(QString::fromStdString(ta.name())); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " edit training area " << trainingAreaId; + } - connect(m_ui->pbClear, &QPushButton::clicked, - m_ui->positionEdit, &LtsCoordWidget::LtsCoordWidget::clear); + m_trainingArea = ta; + m_sitMapGuiIfc = sitMapGuiIfc; + if (m_sitMapGuiIfc) + { + connect(m_ui->pbPosition, &QPushButton::clicked, this, &AsmEditTrainingAreaDialog::getPosition); + } + else + { + m_ui->pbPosition->setEnabled(false); + } + m_ui->name_lineEdit->setText(QString::fromStdString(m_trainingArea.name())); - onEditClicked(); - + connect(m_ui->pbClear, &QPushButton::clicked, m_ui->positionEdit, &LtsCoordWidget::LtsCoordWidget::clear); - setData(); - enaDisa(); + onEditClicked(); - return true; + setData(); + enaDisa(); + + return true; } - - void AsmEditTrainingAreaDialog::enaDisa() { - m_ui->pbPosition->setEnabled(m_sitMapGuiIfc.get()); + m_ui->pbPosition->setEnabled(m_sitMapGuiIfc.get()); } - - bool AsmEditTrainingAreaDialog::has2DMap() { - if (!m_sitMapGuiIfc) - return false; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return false; - } - return true; + if (!m_sitMapGuiIfc) + return false; + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return false; + } + return true; } - - void AsmEditTrainingAreaDialog::getPosition() { - const SituationMap::MapMode mode = m_sitMapGuiIfc->mapMode(); + const SituationMap::MapMode mode = m_sitMapGuiIfc->mapMode(); - switch (mode) - { - case SituationMap::MapMode::MapMode_2D: - m_sitMapGuiIfc->getRectangleNorth(this, - SLOT(onRectData(QPointF,double,double,QPolygonF)), - nullptr, - s_minWidth, - s_maxWidth, - s_minHeight, - s_maxHeight, - m_ui->positionEdit->coordinate(), - m_ui->sbWidth->value(), - m_ui->sbHeight->value()); - - break; - case SituationMap::MapMode::MapMode_3D: - m_sitMapGuiIfc->getCoordinate(this, SLOT(onCoordinate(QPointF)), nullptr); - break; - case SituationMap::MapMode::Undefined: - ERROR_LOG(m_logger) << Q_FUNC_INFO << " ModeMode == Undefined "; - break; - } + switch (mode) + { + case SituationMap::MapMode::MapMode_2D: + m_sitMapGuiIfc->getRectangleNorth(this, SLOT(onRectData(QPointF, double, double, QPolygonF)), nullptr, + s_minWidth, s_maxWidth, s_minHeight, s_maxHeight, + m_ui->positionEdit->coordinate(), m_ui->sbWidth->value(), + m_ui->sbHeight->value()); + break; + case SituationMap::MapMode::MapMode_3D: + m_sitMapGuiIfc->getCoordinate(this, SLOT(onCoordinate(QPointF)), nullptr); + break; + case SituationMap::MapMode::Undefined: + ERROR_LOG(m_logger) << Q_FUNC_INFO << " ModeMode == Undefined "; + break; + } } -void AsmEditTrainingAreaDialog::onRectData(const QPointF ¢erPoint, double width, double height, const QPolygonF &coordinates) +void AsmEditTrainingAreaDialog::onRectData(const QPointF& centerPoint, double width, double height, + const QPolygonF& coordinates) { - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(centerPoint.x(), centerPoint.y()); - const QPointF &btmLeft = utmCoordinate.geographic(-1*(width/2.0), -1*(height/2.0)); + LtsCoordTrans::UtmCoordinate utmCoordinate = + LtsCoordTrans::UtmCoordinate::fromGeographic(centerPoint.x(), centerPoint.y()); + const QPointF& btmLeft = utmCoordinate.geographic(-1 * (width / 2.0), -1 * (height / 2.0)); m_previewPolygon = coordinates; - m_ui->positionEdit->setCoordinate(centerPoint.x(),centerPoint.y()); + m_ui->positionEdit->setCoordinate(centerPoint.x(), centerPoint.y()); m_ui->sbWidth->setValue(width); m_ui->sbHeight->setValue(height); m_trainingArea.height() = height; m_trainingArea.width() = width; m_trainingArea.bottomLeft() = convert(btmLeft); - DEBUG_LOG(m_logger) << "Pos X: " << centerPoint.x() << " Y: " << centerPoint.y() << " W: " << width << " H: " << height; + DEBUG_LOG(m_logger) << "Pos X: " << centerPoint.x() << " Y: " << centerPoint.y() << " W: " << width + << " H: " << height; - showPreviewObject(); + showPreviewObject(); } -void AsmEditTrainingAreaDialog::onCoordinate(const QPointF ¢erPoint) +void AsmEditTrainingAreaDialog::onCoordinate(const QPointF& centerPoint) { - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(centerPoint.x(), centerPoint.y()); + LtsCoordTrans::UtmCoordinate utmCoordinate = + LtsCoordTrans::UtmCoordinate::fromGeographic(centerPoint.x(), centerPoint.y()); - const double height = m_ui->sbHeight->value(); - const double width = m_ui->sbWidth->value(); - const QPointF btmLeft = utmCoordinate.geographic(-1*(width/2.0), -1*(height/2.0)); + const double height = m_ui->sbHeight->value(); + const double width = m_ui->sbWidth->value(); + const QPointF btmLeft = utmCoordinate.geographic(-1 * (width / 2.0), -1 * (height / 2.0)); - m_ui->positionEdit->setCoordinate(centerPoint.x(),centerPoint.y()); + m_ui->positionEdit->setCoordinate(centerPoint.x(), centerPoint.y()); - { - const QPointF topLeft = utmCoordinate.geographic(-1*(width/2.0), 1*(height/2.0)); - const QPointF topRight = utmCoordinate.geographic( 1*(width/2.0), 1*(height/2.0)); - const QPointF btmRight = utmCoordinate.geographic( 1*(width/2.0),-1*(height/2.0)); + { + const QPointF topLeft = utmCoordinate.geographic(-1 * (width / 2.0), 1 * (height / 2.0)); + const QPointF topRight = utmCoordinate.geographic(1 * (width / 2.0), 1 * (height / 2.0)); + const QPointF btmRight = utmCoordinate.geographic(1 * (width / 2.0), -1 * (height / 2.0)); - m_previewPolygon.clear(); - m_previewPolygon.append(btmLeft); - m_previewPolygon.append(topLeft); - m_previewPolygon.append(topRight); - m_previewPolygon.append(btmRight); - } + m_previewPolygon.clear(); + m_previewPolygon.append(btmLeft); + m_previewPolygon.append(topLeft); + m_previewPolygon.append(topRight); + m_previewPolygon.append(btmRight); + } - m_ui->sbWidth->setValue(width); - m_ui->sbHeight->setValue(height); - m_trainingArea.height() = height; - m_trainingArea.width() = width; - m_trainingArea.bottomLeft() = convert(btmLeft); + m_ui->sbWidth->setValue(width); + m_ui->sbHeight->setValue(height); + m_trainingArea.height() = height; + m_trainingArea.width() = width; + m_trainingArea.bottomLeft() = convert(btmLeft); - DEBUG_LOG(m_logger) << "Pos X: " << centerPoint.x() << " Y: " << centerPoint.y() << " W: " << width << " H: " << height; - - showPreviewObject(); + DEBUG_LOG(m_logger) << "Pos X: " << centerPoint.x() << " Y: " << centerPoint.y() << " W: " << width + << " H: " << height; + showPreviewObject(); } - - void AsmEditTrainingAreaDialog::onEditClicked() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START Editing.."; - if (!m_sitMapGuiIfc || m_trainingArea.id() < 0) - { - ERROR_LOG(m_logger) << "onEditClicked: sitMapGuiIfc or trainingArea_id: "<getRectangleNorth(this, - SLOT(onRectData(QPointF,double,double,QPolygonF)), - nullptr, - s_minWidth, - s_maxWidth, - s_minHeight, - s_maxHeight, - m_ui->positionEdit->coordinate(), - m_ui->sbWidth->value(), - m_ui->sbHeight->value()); + m_sitMapGuiIfc->getRectangleNorth(this, SLOT(onRectData(QPointF, double, double, QPolygonF)), nullptr, s_minWidth, + s_maxWidth, s_minHeight, s_maxHeight, m_ui->positionEdit->coordinate(), + m_ui->sbWidth->value(), m_ui->sbHeight->value()); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END Edit"; - - onSelectionChanged(); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END Edit"; + onSelectionChanged(); } void AsmEditTrainingAreaDialog::onSelectionChanged() { - m_previewPolygon= getTrainingArea(m_trainingArea); - showPreviewObject(); + m_previewPolygon = getTrainingArea(m_trainingArea); + showPreviewObject(); } void AsmEditTrainingAreaDialog::showPreviewObject() { - if (!m_sitMapGuiIfc || m_previewPolygon.size() == 0) - { - TRACE_LOG(m_logger) << " AsmEditTrainingAreaDialog::showPreviewObject(): m_sitMapGuiIfc invalid or polygon empty "; - return; - } - m_sitMapGuiIfc->displayPreviewObject(this, m_previewPolygon, true); + if (!m_sitMapGuiIfc || m_previewPolygon.size() == 0) + { + TRACE_LOG(m_logger) + << " AsmEditTrainingAreaDialog::showPreviewObject(): m_sitMapGuiIfc invalid or polygon empty "; + return; + } + m_sitMapGuiIfc->displayPreviewObject(this, m_previewPolygon, true); } QPointF AsmEditTrainingAreaDialog::getCentPos(TrainingArea ta) { - - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(ta.bottomLeft().lon(), - ta.bottomLeft().lat()); - QPointF centerPoint = utmCoordinate.geographic((ta.width() / 2.0), ta.height() / 2.0); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " coord: x: "<< centerPoint.x() <<" y: "<< centerPoint.y(); + LtsCoordTrans::UtmCoordinate utmCoordinate = + LtsCoordTrans::UtmCoordinate::fromGeographic(ta.bottomLeft().lon(), ta.bottomLeft().lat()); - return centerPoint; + QPointF centerPoint = utmCoordinate.geographic((ta.width() / 2.0), ta.height() / 2.0); + TRACE_LOG(m_logger) << Q_FUNC_INFO << " coord: x: " << centerPoint.x() << " y: " << centerPoint.y(); + + return centerPoint; } - - bool AsmEditTrainingAreaDialog::apply() { - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(m_ui->positionEdit->coordinate().x(), - m_ui->positionEdit->coordinate().y()); + LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic( + m_ui->positionEdit->coordinate().x(), m_ui->positionEdit->coordinate().y()); - if(!m_asmFtc) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " Can not retrieve AssetManagement::FTC"; - return false; - } - double height = m_ui->sbHeight->value(); - double width = m_ui->sbWidth->value(); - const QPointF btmLeft = utmCoordinate.geographic(-1*(width/2.0), -1*(height/2.0)); + if (!m_asmFtc) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " Can not retrieve AssetManagement::FTC"; + return false; + } + double height = m_ui->sbHeight->value(); + double width = m_ui->sbWidth->value(); + const QPointF btmLeft = utmCoordinate.geographic(-1 * (width / 2.0), -1 * (height / 2.0)); - TrainingArea req = m_trainingArea; + TrainingArea req = m_trainingArea; - req.name() = m_ui->name_lineEdit->text().toStdString(); - req.width() = m_ui->sbWidth->value(); - req.height() = m_ui->sbHeight->value(); - req.bottomLeft(convert(btmLeft)); + req.name() = m_ui->name_lineEdit->text().toStdString(); + req.width() = m_ui->sbWidth->value(); + req.height() = m_ui->sbHeight->value(); + req.bottomLeft(convert(btmLeft)); - bool success = m_requestHelper->startSingleRequest([this, req]() - { - return m_asmFtc->trainingAreaModifyRequest(req, this); - }); + bool success = + m_requestHelper->startSingleRequest([this, req]() { return m_asmFtc->trainingAreaModifyRequest(req, this); }); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " scucess=" << success; - return success; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " scucess=" << success; + return success; } void AsmEditTrainingAreaDialog::setData() { - if(m_trainingArea.id() > 0) - { - m_ui->name_lineEdit->setText(QString::fromStdString(m_trainingArea.name())); - QPointF coord = getCentPos(m_trainingArea); - m_ui->positionEdit->setCoordinate(coord.x(), coord.y()); - m_ui->sbWidth->setValue(m_trainingArea.width()); - m_ui->sbHeight->setValue(m_trainingArea.height()); - } + if (m_trainingArea.id() > 0) + { + m_ui->name_lineEdit->setText(QString::fromStdString(m_trainingArea.name())); + QPointF coord = getCentPos(m_trainingArea); + m_ui->positionEdit->setCoordinate(coord.x(), coord.y()); + m_ui->sbWidth->setValue(m_trainingArea.width()); + m_ui->sbHeight->setValue(m_trainingArea.height()); + } } -QPolygonF AsmEditTrainingAreaDialog::getTrainingArea(const TrainingArea &ta) +QPolygonF AsmEditTrainingAreaDialog::getTrainingArea(const TrainingArea& ta) { - QPolygonF polygonF; - if(!m_asmDtc) - { - ERROR_LOG(m_logger) << " m_asmDtc is not valid!"; - return{}; - } - AssetManagement::TrainingArea ddsTrainingArea = ta; - + QPolygonF polygonF; + if (!m_asmDtc) + { + ERROR_LOG(m_logger) << " m_asmDtc is not valid!"; + return {}; + } + AssetManagement::TrainingArea ddsTrainingArea = ta; - - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(ddsTrainingArea.bottomLeft().lon(), ddsTrainingArea.bottomLeft().lat()); - polygonF.push_back(QPointF((ddsTrainingArea.bottomLeft().lon()),(ddsTrainingArea.bottomLeft().lat()))); + LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic( + ddsTrainingArea.bottomLeft().lon(), ddsTrainingArea.bottomLeft().lat()); + polygonF.push_back(QPointF((ddsTrainingArea.bottomLeft().lon()), (ddsTrainingArea.bottomLeft().lat()))); - - polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width())); + polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width())); - - polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width(), ddsTrainingArea.height())); + polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width(), ddsTrainingArea.height())); - - polygonF.push_back(utmCoordinate.geographic(0, ddsTrainingArea.height())); + polygonF.push_back(utmCoordinate.geographic(0, ddsTrainingArea.height())); - return polygonF; + return polygonF; } - -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.h old mode 100755 new mode 100644 index 9903c7554..5d1870fd4 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_edit_training_area_dialog.h @@ -1,18 +1,16 @@ - #pragma once #include #include #include -#include -#include +#include #include - +#include +#include #include #include -#include namespace Ui { @@ -22,64 +20,66 @@ class AsmEditTrainingAreaDialog; namespace AssetManagement { - - - - -class AsmEditTrainingAreaDialog final : public LtsWidgets::LtsDialog - , protected Interface::Ftc::TrainingAreaModifyReplyHandler - , protected Interface::Ftc::TrainingAreaRemoveReplyHandler +class AsmEditTrainingAreaDialog final : public LtsWidgets::LtsDialog, + protected Interface::Ftc::TrainingAreaModifyReplyHandler, + protected Interface::Ftc::TrainingAreaRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit AsmEditTrainingAreaDialog(QWidget *parent = nullptr); + public: + explicit AsmEditTrainingAreaDialog(QWidget* parent = nullptr); - bool init(LtsSession::LtsSessionDataDds *session, - const int &trainingAreaId, const std::shared_ptr &sitMapGuiIfc, - const QString &menuGroup); + bool init(LtsSession::LtsSessionDataDds* session, const int& trainingAreaId, + const std::shared_ptr& sitMapGuiIfc, const QString& menuGroup); - ~AsmEditTrainingAreaDialog(); + ~AsmEditTrainingAreaDialog(); -private slots: - void getPosition(); - void onRectData(const QPointF ¢erPoint, double width, double height, const QPolygonF &coordinates); - void onCoordinate(const QPointF ¢erPoint); - void onEditClicked(); - void onSelectionChanged(); -private: - NGL::INGLLogger &m_logger; - void retranslate() override; - void onTrainingAreaModifyReply(const Core::FunctionReplyObject &reply) override final { m_requestHelper->requestReply(reply); } - void onTrainingAreaRemoveReply(const Core::FunctionReplyObject &reply) override final { m_requestHelper->requestReply(reply); } + private slots: + void getPosition(); + void onRectData(const QPointF& centerPoint, double width, double height, const QPolygonF& coordinates); + void onCoordinate(const QPointF& centerPoint); + void onEditClicked(); + void onSelectionChanged(); - bool has2DMap(); - void enaDisa(); - void showPreviewObject(); - QPointF getCentPos(AssetManagement::TrainingArea ta); - bool apply() override; - void setData(); - QPolygonF getTrainingArea(const AssetManagement::TrainingArea &ta); + private: + NGL::INGLLogger& m_logger; + void retranslate() override; - Ui::AsmEditTrainingAreaDialog *m_ui{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; - - QPointF m_Coordinates; - bool m_rubberbandEditMode{false}; + void onTrainingAreaModifyReply(const Core::FunctionReplyObject& reply) override final + { + m_requestHelper->requestReply(reply); + } - std::shared_ptr m_asmFtc; - std::shared_ptr m_asmDtc; + void onTrainingAreaRemoveReply(const Core::FunctionReplyObject& reply) override final + { + m_requestHelper->requestReply(reply); + } + bool has2DMap(); + void enaDisa(); + void showPreviewObject(); + QPointF getCentPos(AssetManagement::TrainingArea ta); + bool apply() override; + void setData(); + QPolygonF getTrainingArea(const AssetManagement::TrainingArea& ta); - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - QString m_dialogTitle{}; + Ui::AsmEditTrainingAreaDialog* m_ui{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; - QString m_menuGroup; - QString m_trainingAreaName{}; - AssetManagement::TrainingArea m_trainingArea; - std::shared_ptr m_sitMapGuiIfc; - QPolygonF m_previewPolygon; - bool m_taExist{false}; + QPointF m_Coordinates; + bool m_rubberbandEditMode{false}; + std::shared_ptr m_asmFtc; + std::shared_ptr m_asmDtc; + + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + QString m_dialogTitle{}; + + QString m_menuGroup; + QString m_trainingAreaName{}; + AssetManagement::TrainingArea m_trainingArea; + std::shared_ptr m_sitMapGuiIfc; + QPolygonF m_previewPolygon; + bool m_taExist{false}; }; -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.cpp old mode 100755 new mode 100644 index cacc4a78c..7ab1f85e7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.cpp @@ -1,301 +1,286 @@ - - #include "asm_training_area_dialog.h" -#include "ui_asm_training_area_dialog.h" + #include "asm_edit_training_area_dialog.h" -#include -#include +#include "ui_asm_training_area_dialog.h" + +#include +#include #include #include -#include +#include +#include #include -#include using namespace CombatNetRadio; + namespace AssetManagement { - - -AsmTrainingAreaDialog::AsmTrainingAreaDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::AsmTrainingAreaDialog) - , m_session(nullptr) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +AsmTrainingAreaDialog::AsmTrainingAreaDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ui(new Ui::AsmTrainingAreaDialog), + m_session(nullptr), m_menuGroup(menuGroup), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Asset_Management-Training_Area")); + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Asset_Management-Training_Area")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &AsmTrainingAreaDialog::onAddTrainingArea); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AsmTrainingAreaDialog::onEditTrainingArea); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AsmTrainingAreaDialog::onRemoveTrainingArea); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &AsmTrainingAreaDialog::onAddTrainingArea); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &AsmTrainingAreaDialog::onEditTrainingArea); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &AsmTrainingAreaDialog::onRemoveTrainingArea); - - connect(m_ui->trainingAreaView, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &AsmTrainingAreaDialog::onSelectionChanged); - enaDisa(); + connect(m_ui->trainingAreaView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &AsmTrainingAreaDialog::onSelectionChanged); + enaDisa(); } AsmTrainingAreaDialog::~AsmTrainingAreaDialog() { - delete m_ui; + delete m_ui; } void AsmTrainingAreaDialog::retranslate() { - translate(m_ui, tr("Training Area Overview")); + translate(m_ui, tr("Training Area Overview")); } void AsmTrainingAreaDialog::tableColumnOrganiserSetting() { - - m_ui->trainingAreaView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->trainingAreaView->setColumnsOrganiserEnabled(identifier(), true); } - - -bool AsmTrainingAreaDialog::init(LtsSession::LtsSessionDataDds *session, const std::shared_ptr &sitMapGuiIfc) +bool AsmTrainingAreaDialog::init(LtsSession::LtsSessionDataDds* session, + const std::shared_ptr& sitMapGuiIfc) { - m_session = session; + m_session = session; - if (!m_session->getDtc(m_asmDtc)) - { - ERROR_LOG(m_logger) << "Could not enable DTC from ASM"; - return false; - } - if(!m_session->getFtc(m_asmFtc)) - { - ERROR_LOG(m_logger) << "Could not enable FTC from ASM"; - return false; - } + if (!m_session->getDtc(m_asmDtc)) + { + ERROR_LOG(m_logger) << "Could not enable DTC from ASM"; + return false; + } + if (!m_session->getFtc(m_asmFtc)) + { + ERROR_LOG(m_logger) << "Could not enable FTC from ASM"; + return false; + } - m_sitMapGuiIfc = sitMapGuiIfc; - if(!m_sitMapGuiIfc) - { - ERROR_LOG(m_logger) << "m_sitMapGuiIfc is invalid "; - return false; - } - bool bRet = true; - bRet &= m_asmDtc->enableTrainingArea(true); + m_sitMapGuiIfc = sitMapGuiIfc; + if (!m_sitMapGuiIfc) + { + ERROR_LOG(m_logger) << "m_sitMapGuiIfc is invalid "; + return false; + } + bool bRet = true; + bRet &= m_asmDtc->enableTrainingArea(true); - bRet &= m_asmFtc->enableTrainingAreaModify(true); - bRet &= m_asmFtc->enableTrainingAreaRemove(true); + bRet &= m_asmFtc->enableTrainingAreaModify(true); + bRet &= m_asmFtc->enableTrainingAreaRemove(true); - if(!bRet) - { - ERROR_LOG(m_logger) << "Could not enable dtc or ftc from ASM"; - return false; - } + if (!bRet) + { + ERROR_LOG(m_logger) << "Could not enable dtc or ftc from ASM"; + return false; + } - INFO_LOG(m_logger) << "Ftc && Dtc enabled from ASM"; + INFO_LOG(m_logger) << "Ftc && Dtc enabled from ASM"; - delete m_model; - m_model = new AsmTrainingAreaDialogModel(this); - m_model->initModel(m_asmDtc, false); - m_ui->trainingAreaView->setModel(m_model); - connect(m_ui->trainingAreaView, &LtsDataView::LtsDataView::signalDoubleClicked, this, &AsmTrainingAreaDialog::onEditTrainingArea); + delete m_model; + m_model = new AsmTrainingAreaDialogModel(this); + m_model->initModel(m_asmDtc, false); + m_ui->trainingAreaView->setModel(m_model); + connect(m_ui->trainingAreaView, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &AsmTrainingAreaDialog::onEditTrainingArea); - - showAllTrainingAreas(); + showAllTrainingAreas(); - return true; + return true; } void AsmTrainingAreaDialog::enaDisa() { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); - if (indexList.size() == 0) - return; - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (indexList.size() == 1) ); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (indexList.size() == 1) ); + QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); + if (indexList.size() == 0) + return; + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (indexList.size() == 1)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (indexList.size() == 1)); } void AsmTrainingAreaDialog::onAddTrainingArea() { - const QString identifier = QStringLiteral("AsmAddTrainingArea"); + const QString identifier = QStringLiteral("AsmAddTrainingArea"); - if(!focusDialog(m_menuGroup,identifier, LtsWidgets::LayoutArea::eDialogTab)) - { - - AsmEditTrainingAreaDialog *dialog = new AsmEditTrainingAreaDialog(this); - - if(!dialog->init(m_session,0,m_sitMapGuiIfc,m_menuGroup)) + if (!focusDialog(m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab)) { - delete dialog; - return; - } - connect(this, &AsmTrainingAreaDialog::destroyed, dialog, &QObject::deleteLater); - addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); - } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " adding temp training Area "; + AsmEditTrainingAreaDialog* dialog = new AsmEditTrainingAreaDialog(this); + + if (!dialog->init(m_session, 0, m_sitMapGuiIfc, m_menuGroup)) + { + delete dialog; + return; + } + connect(this, &AsmTrainingAreaDialog::destroyed, dialog, &QObject::deleteLater); + addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); + } + + TRACE_LOG(m_logger) << Q_FUNC_INFO << " adding temp training Area "; } void AsmTrainingAreaDialog::onRemoveTrainingArea() { - TRACE_LOG(m_logger) << Q_FUNC_INFO << " START" ; - QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); - if (indexList.size() == 0) - return; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " START"; + QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); + if (indexList.size() == 0) + return; - TrainingArea req = m_model->getRowData(indexList.front().row()); - if (req.id() < 0) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " invalid id:bt"<< req.id(); - return; - } - if (!m_viewedTaIds.contains(req.id())) - { - bool success = m_requestHelper->startSingleRequest([this, req]() + TrainingArea req = m_model->getRowData(indexList.front().row()); + if (req.id() < 0) { - return m_asmFtc->trainingAreaRemoveRequest(TrainingAreaRemoveRequest(req.id()), this); - }); + ERROR_LOG(m_logger) << Q_FUNC_INFO << " invalid id:bt" << req.id(); + return; + } + if (!m_viewedTaIds.contains(req.id())) + { + bool success = m_requestHelper->startSingleRequest( + [this, req]() { return m_asmFtc->trainingAreaRemoveRequest(TrainingAreaRemoveRequest(req.id()), this); }); - TRACE_LOG(m_logger) << Q_FUNC_INFO << " success = " << success; - } - else - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Warning"), - tr("Cannot remove currently edited Training Area")); - } + TRACE_LOG(m_logger) << Q_FUNC_INFO << " success = " << success; + } + else + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Warning"), + tr("Cannot remove currently edited Training Area")); + } - TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; + TRACE_LOG(m_logger) << Q_FUNC_INFO << " END"; } void AsmTrainingAreaDialog::onEditTrainingArea() { - QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); - if (indexList.size() == 0) - return; - TrainingArea taItem = m_model->getRowData(indexList.front().row()); - if (taItem.id() < 0) - { - ERROR_LOG(m_logger) << "onEditTrainingArea invalid id = "<< taItem.id(); - return; - } + QModelIndexList indexList = m_ui->trainingAreaView->selectedRows(); + if (indexList.size() == 0) + return; + TrainingArea taItem = m_model->getRowData(indexList.front().row()); + if (taItem.id() < 0) + { + ERROR_LOG(m_logger) << "onEditTrainingArea invalid id = " << taItem.id(); + return; + } - const QString identifier = QStringLiteral("AsmEditTrainingArea_%1").arg(taItem.id()); - if(focusDialog(m_menuGroup,identifier, LtsWidgets::LayoutArea::eDialogTab)) - { - return; - } + const QString identifier = QStringLiteral("AsmEditTrainingArea_%1").arg(taItem.id()); + if (focusDialog(m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab)) + { + return; + } - AsmEditTrainingAreaDialog *dialog = new AsmEditTrainingAreaDialog(this); + AsmEditTrainingAreaDialog* dialog = new AsmEditTrainingAreaDialog(this); - if(!dialog->init(m_session,taItem.id(),m_sitMapGuiIfc,m_menuGroup)) - { - delete dialog; - return; - } + if (!dialog->init(m_session, taItem.id(), m_sitMapGuiIfc, m_menuGroup)) + { + delete dialog; + return; + } - connect(this, &AsmTrainingAreaDialog::destroyed, dialog, &QObject::deleteLater); - - connect(dialog, &AsmEditTrainingAreaDialog::destroyed, this, [this](){ - clearSelection(); }); - addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); + connect(this, &AsmTrainingAreaDialog::destroyed, dialog, &QObject::deleteLater); + connect(dialog, &AsmEditTrainingAreaDialog::destroyed, this, [this]() { clearSelection(); }); + addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); } void AsmTrainingAreaDialog::onSelectionChanged() { - enaDisa(); - DEBUG_LOG(m_logger) << "onSelectionChanged() called !"; - const QModelIndex curIdx = m_ui->trainingAreaView->currentIndex(); - if (!curIdx.isValid()) - return; + enaDisa(); + DEBUG_LOG(m_logger) << "onSelectionChanged() called !"; + const QModelIndex curIdx = m_ui->trainingAreaView->currentIndex(); + if (!curIdx.isValid()) + return; - AssetManagement::TrainingArea taItem = m_model->getRowData(curIdx.row()); - DEBUG_LOG(m_logger) << "onSelectionChanged() selected training area id: "<getRowData(curIdx.row()); + DEBUG_LOG(m_logger) << "onSelectionChanged() selected training area id: " << taItem.id(); + if (taItem.id() < 0) + { + ERROR_LOG(m_logger) << "onEditTrainingArea invalid id" << taItem.id(); + return; + } + m_previewPolygon = getTrainingArea(taItem.id()); + showPreviewObject(); } void AsmTrainingAreaDialog::clearSelection() { - m_ui->trainingAreaView->clearSelection(); - if(m_sitMapGuiIfc) - { - m_sitMapGuiIfc->removePreviewObject(); - } + m_ui->trainingAreaView->clearSelection(); + if (m_sitMapGuiIfc) + { + m_sitMapGuiIfc->removePreviewObject(); + } } QPolygonF AsmTrainingAreaDialog::getTrainingArea(int trainingAreaId) { - if(!m_asmDtc) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " m_asmDtc is not valid!"; - return {}; - } - const AssetManagement::TrainingArea &ddsTrainingArea = m_asmDtc->trainingArea(trainingAreaId); - if (ddsTrainingArea.id() != trainingAreaId) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << " TrainingArea not found, trainingAreaId = " << trainingAreaId; - return {}; - } + if (!m_asmDtc) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " m_asmDtc is not valid!"; + return {}; + } + const AssetManagement::TrainingArea& ddsTrainingArea = m_asmDtc->trainingArea(trainingAreaId); + if (ddsTrainingArea.id() != trainingAreaId) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << " TrainingArea not found, trainingAreaId = " << trainingAreaId; + return {}; + } - return getTrainingArea(ddsTrainingArea); + return getTrainingArea(ddsTrainingArea); } -QPolygonF AsmTrainingAreaDialog::getTrainingArea(const TrainingArea &ddsTrainingArea) +QPolygonF AsmTrainingAreaDialog::getTrainingArea(const TrainingArea& ddsTrainingArea) { - QPolygonF polygonF; + QPolygonF polygonF; - - LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(ddsTrainingArea.bottomLeft().lon(), ddsTrainingArea.bottomLeft().lat()); - polygonF.push_back(QPointF((ddsTrainingArea.bottomLeft().lon()),(ddsTrainingArea.bottomLeft().lat()))); + LtsCoordTrans::UtmCoordinate utmCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic( + ddsTrainingArea.bottomLeft().lon(), ddsTrainingArea.bottomLeft().lat()); + polygonF.push_back(QPointF((ddsTrainingArea.bottomLeft().lon()), (ddsTrainingArea.bottomLeft().lat()))); - - polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width())); + polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width())); - - polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width(), ddsTrainingArea.height())); + polygonF.push_back(utmCoordinate.geographic(ddsTrainingArea.width(), ddsTrainingArea.height())); - - polygonF.push_back(utmCoordinate.geographic(0, ddsTrainingArea.height())); + polygonF.push_back(utmCoordinate.geographic(0, ddsTrainingArea.height())); - return polygonF; + return polygonF; } - void AsmTrainingAreaDialog::showAllTrainingAreas() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - QVector polyVec; - const int rowCount = m_model->rowCount(); - for (int row = 0; row < rowCount; ++row) - { - const TrainingArea ¤tArea = m_model->getRowData(row); - INFO_LOG(m_logger) << " row = " << row << " ; currentArea = " << currentArea; - const QPolygonF &poly = getTrainingArea(currentArea); - polyVec.append(poly); - } - if (!polyVec.isEmpty()) - m_sitMapGuiIfc->displayPreviewObjects(this, polyVec, true); + QVector polyVec; + const int rowCount = m_model->rowCount(); + for (int row = 0; row < rowCount; ++row) + { + const TrainingArea& currentArea = m_model->getRowData(row); + INFO_LOG(m_logger) << " row = " << row << " ; currentArea = " << currentArea; + const QPolygonF& poly = getTrainingArea(currentArea); + polyVec.append(poly); + } + if (!polyVec.isEmpty()) + m_sitMapGuiIfc->displayPreviewObjects(this, polyVec, true); } void AsmTrainingAreaDialog::showPreviewObject() { - if (!this->m_sitMapGuiIfc || m_previewPolygon.size() == 0) - { - TRACE_LOG(m_logger) << " showPreviewObject(): m_sitMapGuiIfc invalid or polygon empty "; - return; - } - this->m_sitMapGuiIfc->displayPreviewObject(this, m_previewPolygon, true); + if (!this->m_sitMapGuiIfc || m_previewPolygon.size() == 0) + { + TRACE_LOG(m_logger) << " showPreviewObject(): m_sitMapGuiIfc invalid or polygon empty "; + return; + } + this->m_sitMapGuiIfc->displayPreviewObject(this, m_previewPolygon, true); } -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.h old mode 100755 new mode 100644 index 5d09aac7d..6bf14dd58 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_dialog.h @@ -1,74 +1,81 @@ - #pragma once -#include -#include +#include "asm_training_area_model.h" + #include -#include -#include -#include #include #include - -#include "asm_training_area_model.h" +#include +#include +#include +#include +#include namespace Ui { class AsmTrainingAreaDialog; } + namespace LtsUtils { class RequestHelper; } + namespace AssetManagement { - - -class AsmTrainingAreaDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::TrainingAreaModifyReplyHandler - , protected Interface::Ftc::TrainingAreaRemoveReplyHandler +class AsmTrainingAreaDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::TrainingAreaModifyReplyHandler, + protected Interface::Ftc::TrainingAreaRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit AsmTrainingAreaDialog(const QString &menuGroup, QWidget *parent = nullptr); - ~AsmTrainingAreaDialog(); + public: + explicit AsmTrainingAreaDialog(const QString& menuGroup, QWidget* parent = nullptr); + ~AsmTrainingAreaDialog(); - bool init(LtsSession::LtsSessionDataDds *session, - const std::shared_ptr &sitMapGuiIfc); - QPolygonF getTrainingArea(int trainingAreaId); - QPolygonF getTrainingArea(const TrainingArea &ddsTrainingArea); - void showAllTrainingAreas(); - void showPreviewObject(); - void clearSelection(); + bool init(LtsSession::LtsSessionDataDds* session, + const std::shared_ptr& sitMapGuiIfc); + QPolygonF getTrainingArea(int trainingAreaId); + QPolygonF getTrainingArea(const TrainingArea& ddsTrainingArea); + void showAllTrainingAreas(); + void showPreviewObject(); + void clearSelection(); -private slots: - void enaDisa(); - void onAddTrainingArea(); - void onEditTrainingArea(); - void onRemoveTrainingArea(); - void onSelectionChanged(); + private slots: + void enaDisa(); + void onAddTrainingArea(); + void onEditTrainingArea(); + void onRemoveTrainingArea(); + void onSelectionChanged(); -private: - NGL::INGLLogger &m_logger; - void retranslate() override; - void onTrainingAreaModifyReply(const Core::FunctionReplyObject &reply) override final { m_requestHelper->requestReply(reply); } - void onTrainingAreaRemoveReply(const Core::FunctionReplyObject &reply) override final { m_requestHelper->requestReply(reply); } - void tableColumnOrganiserSetting() override; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; - Ui::AsmTrainingAreaDialog *m_ui; - AsmTrainingAreaDialogModel *m_model{nullptr}; - LtsSession::LtsSessionDataDds *m_session; - QString m_menuGroup; - std::shared_ptr m_asmDtc; - std::shared_ptr m_asmFtc; - LtsUtils::RequestHelper *m_requestHelper; - QPolygonF m_previewPolygon; - std::shared_ptr m_sitMapGuiIfc; - QSet m_viewedTaIds{}; + void onTrainingAreaModifyReply(const Core::FunctionReplyObject& reply) override final + { + m_requestHelper->requestReply(reply); + } + void onTrainingAreaRemoveReply(const Core::FunctionReplyObject& reply) override final + { + m_requestHelper->requestReply(reply); + } + + void tableColumnOrganiserSetting() override; + + Ui::AsmTrainingAreaDialog* m_ui; + AsmTrainingAreaDialogModel* m_model{nullptr}; + LtsSession::LtsSessionDataDds* m_session; + QString m_menuGroup; + std::shared_ptr m_asmDtc; + std::shared_ptr m_asmFtc; + LtsUtils::RequestHelper* m_requestHelper; + QPolygonF m_previewPolygon; + std::shared_ptr m_sitMapGuiIfc; + QSet m_viewedTaIds{}; }; -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.cpp old mode 100755 new mode 100644 index b6e21b677..1e95592ff --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.cpp @@ -1,75 +1,64 @@ #include "asm_training_area_model.h" - namespace AssetManagement { -AsmTrainingAreaDialogModel::AsmTrainingAreaDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Name"), - tr("Botton Left x"), - tr("Bottom Left y"), - tr("Height"), - tr("Width")}, - - parent) - ,m_asmDtc(nullptr) -{} +AsmTrainingAreaDialogModel::AsmTrainingAreaDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Name"), tr("Botton Left x"), tr("Bottom Left y"), tr("Height"), tr("Width")}, -AsmTrainingAreaDialogModel::~AsmTrainingAreaDialogModel() -{} - -bool AsmTrainingAreaDialogModel::initModel(const std::shared_ptr &dtc, bool hideRemoved) + parent), + m_asmDtc(nullptr) { - m_asmDtc = dtc; - m_hideRemoved = hideRemoved; - - if (m_asmDtc) - { - connect(m_asmDtc.get(), &Interface::Dtc::trainingAreaChanged, this, &AsmTrainingAreaDialogModel::onDataChanged); - - m_asmDtc->trainingAreas([this](const AssetManagement::TrainingArea &data) - { - onDataChanged(data, DataModification::eAdded); - }); - - } else { - WARNING_LOG(m_logger) << Q_FUNC_INFO << " no m_asmDtc"; - } - - return true; } -QVariant AsmTrainingAreaDialogModel::data(const QModelIndex &index, int role) const -{ - if (!indexIsValid(index)) - return QVariant(); +AsmTrainingAreaDialogModel::~AsmTrainingAreaDialogModel() {} - const AssetManagement::TrainingArea &asmTrainingArea = m_vecData.at(index.row()); - if (role == Qt::DisplayRole) - { - switch (index.column()) +bool AsmTrainingAreaDialogModel::initModel(const std::shared_ptr& dtc, bool hideRemoved) +{ + m_asmDtc = dtc; + m_hideRemoved = hideRemoved; + + if (m_asmDtc) { - case Id: - return asmTrainingArea.id(); - case Name: - return QString::fromStdString(asmTrainingArea.name()); - case BottomLeft_x: - return asmTrainingArea.bottomLeft().lon(); - case BottomLeft_y: - return asmTrainingArea.bottomLeft().lat(); - case Height: - return asmTrainingArea.height(); - case Width: - return asmTrainingArea.width(); - - + connect(m_asmDtc.get(), &Interface::Dtc::trainingAreaChanged, this, &AsmTrainingAreaDialogModel::onDataChanged); + + m_asmDtc->trainingAreas( + [this](const AssetManagement::TrainingArea& data) { onDataChanged(data, DataModification::eAdded); }); } - } - return QVariant(); + else + { + WARNING_LOG(m_logger) << Q_FUNC_INFO << " no m_asmDtc"; + } + + return true; } +QVariant AsmTrainingAreaDialogModel::data(const QModelIndex& index, int role) const +{ + if (!indexIsValid(index)) + return QVariant(); - - + const AssetManagement::TrainingArea& asmTrainingArea = m_vecData.at(index.row()); + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case Id: + return asmTrainingArea.id(); + case Name: + return QString::fromStdString(asmTrainingArea.name()); + case BottomLeft_x: + return asmTrainingArea.bottomLeft().lon(); + case BottomLeft_y: + return asmTrainingArea.bottomLeft().lat(); + case Height: + return asmTrainingArea.height(); + case Width: + return asmTrainingArea.width(); + } + } + return QVariant(); } + +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.h old mode 100755 new mode 100644 index 14c6411b8..6bd030e87 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AssetManagement/Gui/AsmTrainingAreaEdit/asm_training_area_model.h @@ -1,47 +1,38 @@ #pragma once -#include #include #include - +#include namespace AssetManagement { -class AsmTrainingAreaDialogModel - : public LtsWidgets::LtsAbstractTableModel +class AsmTrainingAreaDialogModel : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Id, - Name, - BottomLeft_x, - BottomLeft_y, - Height, - Width, - Image, - }; + public: + enum Columns { + Id, + Name, + BottomLeft_x, + BottomLeft_y, + Height, + Width, + Image, + }; - explicit AsmTrainingAreaDialogModel(QObject *parent = nullptr); - ~AsmTrainingAreaDialogModel(); - bool initModel(const std::shared_ptr &asmDtc, bool hideRemoved); + explicit AsmTrainingAreaDialogModel(QObject* parent = nullptr); + ~AsmTrainingAreaDialogModel(); + bool initModel(const std::shared_ptr& asmDtc, bool hideRemoved); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; - -private: - - -NGL::INGLLogger &m_logger; - bool m_hideRemoved; - std::shared_ptr m_asmDtc; + private: + NGL::INGLLogger& m_logger; + bool m_hideRemoved; + std::shared_ptr m_asmDtc; }; -} - - - +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.cpp old mode 100755 new mode 100644 index 451f9c253..e75e271f5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.cpp @@ -1,71 +1,60 @@ - #include "audio_settings_avail_streams_model.h" -#include + #include +#include namespace AudioVideoManagement { -QDataStream &operator<<(QDataStream &ds, const StreamData &sd) +QDataStream& operator<<(QDataStream& ds, const StreamData& sd) { - ds << sd.topicId << sd.name << sd.bIsCnr; - return ds; -} -QDataStream &operator>>(QDataStream &ds, StreamData &sd) -{ - ds >> sd.topicId >> sd.name >> sd.bIsCnr ; - return ds; + ds << sd.topicId << sd.name << sd.bIsCnr; + return ds; } - - - -AvailStreamsModel::AvailStreamsModel(Interface::Dtc *avmDtc, - int32_t exerciseId, - QObject *parent) - : NGLTreeModel(parent, new NGLTreeItem(QVariant()), {tr("Available")}) - , m_exerciseId(exerciseId) - , m_avmDtc(avmDtc) - , m_cnrRoot(new NGLTreeItem(QVariant())) - , m_tvcRoot(new NGLTreeItem(QVariant())) - , m_changes(false) +QDataStream& operator>>(QDataStream& ds, StreamData& sd) { - Q_ASSERT(avmDtc); - - qRegisterMetaTypeStreamOperators(); - - setMimeType(StreamData::mimeType()); - - StreamData data; - data.name = tr("CNR"); - data.bIsCnr = true; - m_cnrRoot->setData(QVariant::fromValue(data)); - m_rootItem->appendChild(m_cnrRoot); - - data.name = tr("TVC"); - data.bIsCnr = false; - m_tvcRoot->setData(QVariant::fromValue(data)); - m_rootItem->appendChild(m_tvcRoot); + ds >> sd.topicId >> sd.name >> sd.bIsCnr; + return ds; } - - - -void AvailStreamsModel::setStreamChanged(const QVector &streams) +AvailStreamsModel::AvailStreamsModel(Interface::Dtc* avmDtc, int32_t exerciseId, QObject* parent) + : NGLTreeModel(parent, new NGLTreeItem(QVariant()), {tr("Available")}), m_exerciseId(exerciseId), m_avmDtc(avmDtc), + m_cnrRoot(new NGLTreeItem(QVariant())), m_tvcRoot(new NGLTreeItem(QVariant())), m_changes(false) { - for (const StreamData &d : streams) - if (!m_changedStreams.contains(QPair(d.bIsCnr, d.topicId))) - m_changedStreams += QPair(d.bIsCnr, d.topicId); - emit modelDataChanged(); + Q_ASSERT(avmDtc); + + qRegisterMetaTypeStreamOperators(); + + setMimeType(StreamData::mimeType()); + + StreamData data; + data.name = tr("CNR"); + data.bIsCnr = true; + m_cnrRoot->setData(QVariant::fromValue(data)); + m_rootItem->appendChild(m_cnrRoot); + + data.name = tr("TVC"); + data.bIsCnr = false; + m_tvcRoot->setData(QVariant::fromValue(data)); + m_rootItem->appendChild(m_tvcRoot); } +void AvailStreamsModel::setStreamChanged(const QVector& streams) +{ + for (const StreamData& d : streams) + if (!m_changedStreams.contains(QPair(d.bIsCnr, d.topicId))) + m_changedStreams += QPair(d.bIsCnr, d.topicId); + emit modelDataChanged(); +} bool AvailStreamsModel::initModel() { - connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, - this, &AvailStreamsModel::onCnrConfigChanged, Qt::UniqueConnection); - m_avmDtc->cnrConfigs([this](const AudioVideoManagement::CnrConfig & ch) { onCnrConfigChanged(ch, DataModification::eAdded); }); + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, this, + &AvailStreamsModel::onCnrConfigChanged, Qt::UniqueConnection); + m_avmDtc->cnrConfigs( + [this](const AudioVideoManagement::CnrConfig& ch) { onCnrConfigChanged(ch, DataModification::eAdded); }); #if 0 AudioVideoManagement::CnrConfig data; @@ -85,200 +74,190 @@ bool AvailStreamsModel::initModel() onTvcConfigChanged(data2, DataModification::eAdded); #endif - connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, - this, &AvailStreamsModel::onTvcConfigChanged, Qt::UniqueConnection); - m_avmDtc->tvcConfigs([this](const AudioVideoManagement::TvcConfig & ch) { onTvcConfigChanged(ch, DataModification::eAdded); }); + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, this, + &AvailStreamsModel::onTvcConfigChanged, Qt::UniqueConnection); + m_avmDtc->tvcConfigs( + [this](const AudioVideoManagement::TvcConfig& ch) { onTvcConfigChanged(ch, DataModification::eAdded); }); - return true; + return true; } -Qt::ItemFlags AvailStreamsModel::flags(const QModelIndex &index) const +Qt::ItemFlags AvailStreamsModel::flags(const QModelIndex& index) const { - Qt::ItemFlags f = NGLTreeModel::flags(index) | Qt::ItemIsDropEnabled; - if (!index.parent().isValid()) - f &= ~Qt::ItemIsDragEnabled; + Qt::ItemFlags f = NGLTreeModel::flags(index) | Qt::ItemIsDropEnabled; + if (!index.parent().isValid()) + f &= ~Qt::ItemIsDragEnabled; - return f; + return f; } -QVariant AvailStreamsModel::data(const QModelIndex &index, int role) const +QVariant AvailStreamsModel::data(const QModelIndex& index, int role) const { - switch (role) - { - case Qt::DisplayRole: + switch (role) { - NGLTreeItem *item = privateData(index); - StreamData data = item->data().value(); - DEBUG_LOG(m_logger) << data.name; - return data.name; + case Qt::DisplayRole: { + NGLTreeItem* item = privateData(index); + StreamData data = item->data().value(); + DEBUG_LOG(m_logger) << data.name; + return data.name; + } + + case Qt::FontRole: { + NGLTreeItem* item = privateData(index); + StreamData data = item->data().value(); + if (!m_changedStreams.contains(QPair(data.bIsCnr, data.topicId))) + return {}; + QFont f; + f.setBold(true); + return f; + } + + default: { + break; + } } - case Qt::FontRole: - { - NGLTreeItem *item = privateData(index); - StreamData data = item->data().value(); - if (!m_changedStreams.contains(QPair(data.bIsCnr, data.topicId))) - return {}; - QFont f; - f.setBold(true); - return f; - } - - default: - { - break; - } - } - - return NGLTreeModel::data(index, role); + return NGLTreeModel::data(index, role); } -bool AvailStreamsModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const +bool AvailStreamsModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const { - Q_UNUSED(data); - Q_UNUSED(row); - Q_UNUSED(column); - Q_UNUSED(parent); - if (action != supportedDropActions()) - return false; - return true; + Q_UNUSED(data); + Q_UNUSED(row); + Q_UNUSED(column); + Q_UNUSED(parent); + if (action != supportedDropActions()) + return false; + return true; } -bool AvailStreamsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool AvailStreamsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - Q_UNUSED(action); - Q_UNUSED(row); - Q_UNUSED(column); - Q_UNUSED(parent); + Q_UNUSED(action); + Q_UNUSED(row); + Q_UNUSED(column); + Q_UNUSED(parent); - const QVector droppedItems = getMimeDataItems(data, m_mimeType); - QVector streams; - streams.reserve(droppedItems.size()); - for (const NGLTreeItem *item : droppedItems) - streams += item->data().value(); - qDeleteAll(droppedItems); - emit droppedStreamNames(streams); - m_changes = true; - return true; + const QVector droppedItems = getMimeDataItems(data, m_mimeType); + QVector streams; + streams.reserve(droppedItems.size()); + for (const NGLTreeItem* item : droppedItems) + streams += item->data().value(); + qDeleteAll(droppedItems); + emit droppedStreamNames(streams); + m_changes = true; + return true; } -void AvailStreamsModel::onCnrConfigChanged(const AudioVideoManagement::CnrConfig &data, DataModification modType) +void AvailStreamsModel::onCnrConfigChanged(const AudioVideoManagement::CnrConfig& data, DataModification modType) { - insertUpdateData(data, modType, m_cnrRoot); + insertUpdateData(data, modType, m_cnrRoot); } -void AvailStreamsModel::onTvcConfigChanged(const AudioVideoManagement::TvcConfig &data, DataModification modType) +void AvailStreamsModel::onTvcConfigChanged(const AudioVideoManagement::TvcConfig& data, DataModification modType) { - insertUpdateData(data, modType, m_tvcRoot); + insertUpdateData(data, modType, m_tvcRoot); } template -void AvailStreamsModel::insertUpdateData(const T &config, DataModification modType, NGLTreeItem *parent) +void AvailStreamsModel::insertUpdateData(const T& config, DataModification modType, NGLTreeItem* parent) { - DataModification action = modType; - if (modType == DataModification::eModified) - { - - - if (config.exerciseId().is_set() && config.exerciseId().get() != m_exerciseId) - action = DataModification::eRemoved; - } - - StreamData newData(config); - - switch (action) - { - case DataModification::eAdded: - if (config.exerciseId().is_set() && config.exerciseId().get() != m_exerciseId) - break; - Q_FALLTHROUGH(); - case DataModification::eModified: - { - bool bFound = false; - for (int i = 0; i < parent->childCount(); ++i) + DataModification action = modType; + if (modType == DataModification::eModified) { - NGLTreeItem *child = parent->child(i); - StreamData data = child->data().value(); - if (data == newData) - { - bFound = true; - setItemData(indexFromItem(child), QVariant::fromValue(newData), child->icon()); - emit updateEntry(newData); - break; - } + + if (config.exerciseId().is_set() && config.exerciseId().get() != m_exerciseId) + action = DataModification::eRemoved; } - if (!bFound) + + StreamData newData(config); + + switch (action) { - NGLTreeItem *child = new NGLTreeItem(QVariant::fromValue(newData)); - insertRow(parent->childCount(), indexFromItem(parent), child); + case DataModification::eAdded: + if (config.exerciseId().is_set() && config.exerciseId().get() != m_exerciseId) + break; + Q_FALLTHROUGH(); + case DataModification::eModified: { + bool bFound = false; + for (int i = 0; i < parent->childCount(); ++i) + { + NGLTreeItem* child = parent->child(i); + StreamData data = child->data().value(); + if (data == newData) + { + bFound = true; + setItemData(indexFromItem(child), QVariant::fromValue(newData), child->icon()); + emit updateEntry(newData); + break; + } + } + if (!bFound) + { + NGLTreeItem* child = new NGLTreeItem(QVariant::fromValue(newData)); + insertRow(parent->childCount(), indexFromItem(parent), child); + } + break; + } + case DataModification::eRemoved: { + for (int i = 0; i < parent->childCount(); ++i) + { + NGLTreeItem* child = parent->child(i); + StreamData data = child->data().value(); + if (data == newData) + { + removeRows(i, 1, indexFromItem(parent)); + emit removeEntry(newData); + break; + } + } + } } - break; - } - case DataModification::eRemoved: - { - for (int i = 0; i < parent->childCount(); ++i) - { - NGLTreeItem *child = parent->child(i); - StreamData data = child->data().value(); - if (data == newData) - { - removeRows(i, 1, indexFromItem(parent)); - emit removeEntry(newData); - break; - } - } - } - } } - - - - - -AvailStreamsFilter::AvailStreamsFilter(AvailStreamsModel *sourceModel, QObject *parent) - : QSortFilterProxyModel(parent) - , m_sourceModel(sourceModel) +AvailStreamsFilter::AvailStreamsFilter(AvailStreamsModel* sourceModel, QObject* parent) + : QSortFilterProxyModel(parent), m_sourceModel(sourceModel) { - Q_ASSERT(sourceModel); - setSourceModel(m_sourceModel); + Q_ASSERT(sourceModel); + setSourceModel(m_sourceModel); } -void AvailStreamsFilter::addAllocatedStreams(const QVector &streams) +void AvailStreamsFilter::addAllocatedStreams(const QVector& streams) { - m_allocatedStreams.insert(streams.begin(), streams.end()); - invalidateFilter(); + m_allocatedStreams.insert(streams.begin(), streams.end()); + invalidateFilter(); } -void AvailStreamsFilter::setAllocatedStreams(const QVector &streams) +void AvailStreamsFilter::setAllocatedStreams(const QVector& streams) { - m_allocatedStreams.clear(); - m_allocatedStreams.insert(streams.begin(), streams.end()); - invalidateFilter(); + m_allocatedStreams.clear(); + m_allocatedStreams.insert(streams.begin(), streams.end()); + invalidateFilter(); } -void AvailStreamsFilter::removeAllocatedStreams(const QVector &streams) +void AvailStreamsFilter::removeAllocatedStreams(const QVector& streams) { - for (const StreamData &stream : streams) - m_allocatedStreams.erase(stream); - invalidateFilter(); + for (const StreamData& stream : streams) + m_allocatedStreams.erase(stream); + invalidateFilter(); } -bool AvailStreamsFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool AvailStreamsFilter::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - if (!m_sourceModel || !source_parent.isValid()) - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); + if (!m_sourceModel || !source_parent.isValid()) + return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - NGLTreeItem *parent = m_sourceModel->privateData(source_parent); - if (!parent) - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - NGLTreeItem *child = parent->child(source_row); - if (!child) - return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); + NGLTreeItem* parent = m_sourceModel->privateData(source_parent); + if (!parent) + return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); + NGLTreeItem* child = parent->child(source_row); + if (!child) + return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent); - StreamData data = child->data().value(); - return m_allocatedStreams.count(data) == 0; + StreamData data = child->data().value(); + return m_allocatedStreams.count(data) == 0; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.h old mode 100755 new mode 100644 index affbdea36..d7cdb554e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_avail_streams_model.h @@ -1,13 +1,13 @@ - #pragma once -#include +#include "audio_stream_type.h" + #include #include #include #include -#include "audio_stream_type.h" +#include #include #include @@ -15,68 +15,84 @@ namespace AudioVideoManagement { class AvailStreamsModel final : public NGLTreeModel { - Q_OBJECT -public: - explicit AvailStreamsModel(AudioVideoManagement::Interface::Dtc *avmDtc, int32_t exerciseId, - QObject *parent = nullptr); - ~AvailStreamsModel() = default; - bool getChangeState() {bool result = m_changes; m_changes = false; return result;} - void resetChangeState() {m_changes = false;m_changedStreams.clear();} + Q_OBJECT + public: + explicit AvailStreamsModel(AudioVideoManagement::Interface::Dtc* avmDtc, int32_t exerciseId, + QObject* parent = nullptr); + ~AvailStreamsModel() = default; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QVariant data(const QModelIndex &index, int role) const override; + bool getChangeState() + { + bool result = m_changes; + m_changes = false; + return result; + } - - Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; } - Qt::DropActions supportedDragActions() const override { return Qt::CopyAction; } - bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction, int, int, const QModelIndex &) override; - void setStreamChanged(const QVector &streams); + void resetChangeState() + { + m_changes = false; + m_changedStreams.clear(); + } - bool initModel(); + Qt::ItemFlags flags(const QModelIndex& index) const override; + QVariant data(const QModelIndex& index, int role) const override; -signals: - void droppedStreamNames(const QVector &streamNamesDropped); - void updateEntry(const AudioVideoManagement::StreamData &stream); - void removeEntry(const AudioVideoManagement::StreamData &stream); + Qt::DropActions supportedDropActions() const override + { + return Qt::MoveAction; + } -private slots: - void onCnrConfigChanged(const AudioVideoManagement::CnrConfig &data, DataModification modType); - void onTvcConfigChanged(const AudioVideoManagement::TvcConfig &data, DataModification modType); + Qt::DropActions supportedDragActions() const override + { + return Qt::CopyAction; + } -private: + bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const override; + bool dropMimeData(const QMimeData* data, Qt::DropAction, int, int, const QModelIndex&) override; + void setStreamChanged(const QVector& streams); -NGL::INGLLogger &m_logger; - template - void insertUpdateData(const T &data, DataModification modType, NGLTreeItem *parent); + bool initModel(); - int32_t m_exerciseId; - AudioVideoManagement::Interface::Dtc *m_avmDtc; - NGLTreeItem *m_cnrRoot; - NGLTreeItem *m_tvcRoot; - bool m_changes; - QVector > m_changedStreams; + signals: + void droppedStreamNames(const QVector& streamNamesDropped); + void updateEntry(const AudioVideoManagement::StreamData& stream); + void removeEntry(const AudioVideoManagement::StreamData& stream); + + private slots: + void onCnrConfigChanged(const AudioVideoManagement::CnrConfig& data, DataModification modType); + void onTvcConfigChanged(const AudioVideoManagement::TvcConfig& data, DataModification modType); + + private: + NGL::INGLLogger& m_logger; + template void insertUpdateData(const T& data, DataModification modType, NGLTreeItem* parent); + + int32_t m_exerciseId; + AudioVideoManagement::Interface::Dtc* m_avmDtc; + NGLTreeItem* m_cnrRoot; + NGLTreeItem* m_tvcRoot; + bool m_changes; + QVector> m_changedStreams; }; class AvailStreamsFilter final : public QSortFilterProxyModel { - Q_OBJECT -public: - explicit AvailStreamsFilter(AvailStreamsModel *sourceModel, QObject *parent); + Q_OBJECT + public: + explicit AvailStreamsFilter(AvailStreamsModel* sourceModel, QObject* parent); - void addAllocatedStreams(const QVector &streams); - void setAllocatedStreams(const QVector &streams); - void removeAllocatedStreams(const QVector &streams); + void addAllocatedStreams(const QVector& streams); + void setAllocatedStreams(const QVector& streams); + void removeAllocatedStreams(const QVector& streams); -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; -private: - - using QSortFilterProxyModel::setSourceModel; + private: + using QSortFilterProxyModel::setSourceModel; - AvailStreamsModel *m_sourceModel; - std::set m_allocatedStreams; + AvailStreamsModel* m_sourceModel; + std::set m_allocatedStreams; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_dialog.cpp old mode 100755 new mode 100644 index a667ddb58..52a301ac1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_dialog.cpp @@ -1,434 +1,404 @@ - #include "audio_settings_dialog.h" -#include -#include "ui_audio_settings_dialog.h" + #include "audio_settings_avail_streams_model.h" #include "audio_settings_used_streams_model.h" #include "audio_stream_type.h" -#include -#include -#include +#include "ui_audio_settings_dialog.h" + #include +#include +#include +#include +#include namespace AudioVideoManagement { -AudioSettingsDialog::AudioSettingsDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::AudioSettingsDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +AudioSettingsDialog::AudioSettingsDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ui(new Ui::AudioSettingsDialog), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - setAttribute(Qt::WA_DeleteOnClose); + m_ui->setupUi(this); + setAttribute(Qt::WA_DeleteOnClose); - setOnlineHelpFilename(QStringLiteral("Situation-Voice_Communication_Access")); + setOnlineHelpFilename(QStringLiteral("Situation-Voice_Communication_Access")); } AudioSettingsDialog::~AudioSettingsDialog() { - delete m_ui; + delete m_ui; } -bool AudioSettingsDialog::init(OperatorManagement::Interface::Dtc *opmDtc, - Interface::Dtc *avmDtc, - Interface::Ftc *avmFtc, - LtsSession::LtsSessionDataDds *session) +bool AudioSettingsDialog::init(OperatorManagement::Interface::Dtc* opmDtc, Interface::Dtc* avmDtc, + Interface::Ftc* avmFtc, LtsSession::LtsSessionDataDds* session) { - Q_ASSERT(opmDtc); - Q_ASSERT(avmDtc); - Q_ASSERT(avmFtc); - Q_ASSERT(session); + Q_ASSERT(opmDtc); + Q_ASSERT(avmDtc); + Q_ASSERT(avmFtc); + Q_ASSERT(session); - setUnchangeable(true); + setUnchangeable(true); - m_session = session; - m_avmDtc = avmDtc; - m_avmFtc = avmFtc; - - + m_session = session; + m_avmDtc = avmDtc; + m_avmFtc = avmFtc; - m_modelAvailable = new AvailStreamsModel(avmDtc, m_session->exerciseId(), this); - if (!m_modelAvailable->initModel()) - return false; + m_modelAvailable = new AvailStreamsModel(avmDtc, m_session->exerciseId(), this); + if (!m_modelAvailable->initModel()) + return false; - m_filterAvailable = new AvailStreamsFilter(m_modelAvailable, this); - m_modelAllocated = new AllocatedStreamsModel(this); + m_filterAvailable = new AvailStreamsFilter(m_modelAvailable, this); + m_modelAllocated = new AllocatedStreamsModel(this); - connect(m_modelAvailable, &AvailStreamsModel::droppedStreamNames, this, &AudioSettingsDialog::onDroppedInAvailable); - connect(m_modelAllocated, &AllocatedStreamsModel::droppedStreamNames, this, &AudioSettingsDialog::onDroppedInAllocated); + connect(m_modelAvailable, &AvailStreamsModel::droppedStreamNames, this, &AudioSettingsDialog::onDroppedInAvailable); + connect(m_modelAllocated, &AllocatedStreamsModel::droppedStreamNames, this, + &AudioSettingsDialog::onDroppedInAllocated); - connect(m_modelAvailable, &AvailStreamsModel::updateEntry, m_modelAllocated, &AllocatedStreamsModel::updateEntry); - connect(m_modelAvailable, &AvailStreamsModel::removeEntry, this, &AudioSettingsDialog::onEntryRemoved); + connect(m_modelAvailable, &AvailStreamsModel::updateEntry, m_modelAllocated, &AllocatedStreamsModel::updateEntry); + connect(m_modelAvailable, &AvailStreamsModel::removeEntry, this, &AudioSettingsDialog::onEntryRemoved); - - m_ui->treeViewAvailable->setModel(m_filterAvailable); - m_ui->treeViewAvailable->expandAll(); - m_ui->treeViewAllocated->setModel(m_modelAllocated); + m_ui->treeViewAvailable->setModel(m_filterAvailable); + m_ui->treeViewAvailable->expandAll(); + m_ui->treeViewAllocated->setModel(m_modelAllocated); - - connect(opmDtc, &OperatorManagement::Interface::Dtc::userChanged, - this, &AudioSettingsDialog::onOperatorChanged); - auto cbOperator = [this](const OperatorManagement::User & u) - { - onOperatorChanged(u, DataModification::eAdded); - }; - opmDtc->users(cbOperator); + connect(opmDtc, &OperatorManagement::Interface::Dtc::userChanged, this, &AudioSettingsDialog::onOperatorChanged); + auto cbOperator = [this](const OperatorManagement::User& u) { onOperatorChanged(u, DataModification::eAdded); }; + opmDtc->users(cbOperator); - fillOperatorBox(); + fillOperatorBox(); - connect(m_avmDtc, &Interface::Dtc::cnrTvcProfileChanged, - this, &AudioSettingsDialog::onCnrTvcProfileChanged); - auto cbRadioCircuits = [this](const CnrTvcProfile & rc) - { - onCnrTvcProfileChanged(rc, DataModification::eAdded); - }; - m_avmDtc->cnrTvcProfiles(cbRadioCircuits); + connect(m_avmDtc, &Interface::Dtc::cnrTvcProfileChanged, this, &AudioSettingsDialog::onCnrTvcProfileChanged); + auto cbRadioCircuits = [this](const CnrTvcProfile& rc) { onCnrTvcProfileChanged(rc, DataModification::eAdded); }; + m_avmDtc->cnrTvcProfiles(cbRadioCircuits); - connect(m_ui->pushButtonUp, &QPushButton::clicked, this, &AudioSettingsDialog::onUpButtonClicked); - connect(m_ui->pushButtonDown, &QPushButton::clicked, this, &AudioSettingsDialog::onDownButtonClicked); - connect(m_ui->operatorComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, &AudioSettingsDialog::onSelectionOperatorChanged); - connect(m_ui->treeViewAllocated->selectionModel(), &QItemSelectionModel::selectionChanged, this, &AudioSettingsDialog::onSelectionChangedAllocation); - + connect(m_ui->pushButtonUp, &QPushButton::clicked, this, &AudioSettingsDialog::onUpButtonClicked); + connect(m_ui->pushButtonDown, &QPushButton::clicked, this, &AudioSettingsDialog::onDownButtonClicked); + connect(m_ui->operatorComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, + &AudioSettingsDialog::onSelectionOperatorChanged); + connect(m_ui->treeViewAllocated->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &AudioSettingsDialog::onSelectionChangedAllocation); - m_ui->treeViewAllocated->setSelectionMode(QAbstractItemView::MultiSelection); - m_ui->treeViewAvailable->setSelectionMode(QAbstractItemView::MultiSelection); + m_ui->treeViewAllocated->setSelectionMode(QAbstractItemView::MultiSelection); + m_ui->treeViewAvailable->setSelectionMode(QAbstractItemView::MultiSelection); - m_ui->treeViewAllocated->setSelectionMode(QAbstractItemView::ExtendedSelection); - m_ui->treeViewAvailable->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_ui->treeViewAllocated->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_ui->treeViewAvailable->setSelectionMode(QAbstractItemView::ExtendedSelection); - - + m_ui->pushButtonUp->setEnabled(false); + m_ui->pushButtonDown->setEnabled(false); - m_ui->pushButtonUp->setEnabled(false); - m_ui->pushButtonDown->setEnabled(false); + m_avmFtc->enableAll(); - m_avmFtc->enableAll(); - - int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - if (m_ui->operatorComboBox->currentIndex() != m_ui->operatorComboBox->findData(opId)) - m_ui->operatorComboBox->setCurrentIndex(m_ui->operatorComboBox->findData(opId)); - else - onSelectionOperatorChanged(0); - setUnchangeable(false); - return true; -} + int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + if (m_ui->operatorComboBox->currentIndex() != m_ui->operatorComboBox->findData(opId)) + m_ui->operatorComboBox->setCurrentIndex(m_ui->operatorComboBox->findData(opId)); + else + onSelectionOperatorChanged(0); + setUnchangeable(false); + return true; +} void AudioSettingsDialog::retranslate() { - translate(m_ui, tr("Voice Communication Access")); -} + translate(m_ui, tr("Voice Communication Access")); +} -void AudioSettingsDialog::onOperatorChanged(const OperatorManagement::User &data, DataModification modType) +void AudioSettingsDialog::onOperatorChanged(const OperatorManagement::User& data, DataModification modType) { - - DEBUG_LOG(m_logger) << "************** onOperatorChanged "; - switch (modType) - { - case DataModification::eRemoved: + + DEBUG_LOG(m_logger) << "************** onOperatorChanged "; + switch (modType) { - Q_ASSERT(m_operatorMap.contains(data.id())); + case DataModification::eRemoved: { + Q_ASSERT(m_operatorMap.contains(data.id())); - - if (m_ui->operatorComboBox->currentData().toInt() == data.id()) - { - __unchange__(); - m_modelAllocated->resetChangeState(); - m_modelAvailable->resetChangeState(); - m_filterAvailable->invalidate(); - } + if (m_ui->operatorComboBox->currentData().toInt() == data.id()) + { + __unchange__(); + m_modelAllocated->resetChangeState(); + m_modelAvailable->resetChangeState(); + m_filterAvailable->invalidate(); + } - m_operatorMap.remove(data.id()); - m_ui->operatorComboBox->removeItem(m_ui->operatorComboBox->findData(data.id())); - break; + m_operatorMap.remove(data.id()); + m_ui->operatorComboBox->removeItem(m_ui->operatorComboBox->findData(data.id())); + break; + } + + case DataModification::eAdded: { + Q_ASSERT(!m_operatorMap.contains(data.id())); + const QString operatorName = QString::fromStdString(data.name()); + m_operatorMap.insert(data.id(), operatorName); + m_ui->operatorComboBox->addItem(operatorName, data.id()); + m_ui->operatorComboBox->model()->sort(0); + break; + } + + case DataModification::eModified: { + Q_ASSERT(m_operatorMap.contains(data.id())); + const QString operatorName = QString::fromStdString(data.name()); + m_operatorMap.insert(data.id(), operatorName); + int i = m_ui->operatorComboBox->findData(data.id()); + Q_ASSERT(i != -1); + m_ui->operatorComboBox->setItemText(i, operatorName); + m_ui->operatorComboBox->model()->sort(0); + break; + } } +} - case DataModification::eAdded: - { - Q_ASSERT(!m_operatorMap.contains(data.id())); - const QString operatorName = QString::fromStdString(data.name()); - m_operatorMap.insert(data.id(), operatorName); - m_ui->operatorComboBox->addItem(operatorName, data.id()); - m_ui->operatorComboBox->model()->sort(0); - break; - } - - case DataModification::eModified: - { - Q_ASSERT(m_operatorMap.contains(data.id())); - const QString operatorName = QString::fromStdString(data.name()); - m_operatorMap.insert(data.id(), operatorName); - int i = m_ui->operatorComboBox->findData(data.id()); - Q_ASSERT(i != -1); - m_ui->operatorComboBox->setItemText(i, operatorName); - m_ui->operatorComboBox->model()->sort(0); - break; - } - } -} - -void AudioSettingsDialog::onCnrTvcProfileChanged(const CnrTvcProfile &data, DataModification modType) +void AudioSettingsDialog::onCnrTvcProfileChanged(const CnrTvcProfile& data, DataModification modType) { - if (m_session->exerciseId() == data.exerciseId()) - { - if (modType == DataModification::eRemoved) + if (m_session->exerciseId() == data.exerciseId()) { - m_cnrTvcProfileMap.remove(data.id()); + if (modType == DataModification::eRemoved) + { + m_cnrTvcProfileMap.remove(data.id()); + } + else + { + m_cnrTvcProfileMap.insert(data.id(), data); + fillOperatorList(); + } } - else - { - m_cnrTvcProfileMap.insert(data.id(), data); - fillOperatorList(); - } - } -} +} void AudioSettingsDialog::fillOperatorList() { - QVector newStreamData; + QVector newStreamData; - for (const auto &rc : std::as_const(m_cnrTvcProfileMap)) - { - if ((rc.exerciseId() != m_session->exerciseId()) - || (rc.operatorId() != m_ui->operatorComboBox->currentData().toInt())) - continue; + for (const auto& rc : std::as_const(m_cnrTvcProfileMap)) + { + if ((rc.exerciseId() != m_session->exerciseId()) || + (rc.operatorId() != m_ui->operatorComboBox->currentData().toInt())) + continue; - - newStreamData.reserve(rc.data().size()); - for (const CnrTvcProfileData &profileEntry : rc.data()) - newStreamData += toStreamData(profileEntry); + newStreamData.reserve(rc.data().size()); + for (const CnrTvcProfileData& profileEntry : rc.data()) + newStreamData += toStreamData(profileEntry); - break; - } - m_modelAllocated->setNewStreamData(newStreamData); - m_filterAvailable->setAllocatedStreams(newStreamData); -} + break; + } + m_modelAllocated->setNewStreamData(newStreamData); + m_filterAvailable->setAllocatedStreams(newStreamData); +} void AudioSettingsDialog::fillOperatorBox() { - m_ui->operatorComboBox->clear(); - QMap::iterator i = m_operatorMap.begin(); - while (i != m_operatorMap.end()) - { - m_ui->operatorComboBox->addItem(i.value(), i.key()); - ++i; - } - m_ui->operatorComboBox->model()->sort(0); + m_ui->operatorComboBox->clear(); + QMap::iterator i = m_operatorMap.begin(); + while (i != m_operatorMap.end()) + { + m_ui->operatorComboBox->addItem(i.value(), i.key()); + ++i; + } + m_ui->operatorComboBox->model()->sort(0); } void AudioSettingsDialog::onUpButtonClicked() { - const QModelIndexList mil = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); - if (mil.isEmpty()) - return; - m_modelAllocated->changeOrder(mil.first(), true); + const QModelIndexList mil = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); + if (mil.isEmpty()) + return; + m_modelAllocated->changeOrder(mil.first(), true); - if (mil.first().row() > 0) - { - const QModelIndex newRow = m_modelAllocated->index(mil.first().row() - 1, 0); - m_ui->treeViewAllocated->setCurrentIndex(newRow); - } + if (mil.first().row() > 0) + { + const QModelIndex newRow = m_modelAllocated->index(mil.first().row() - 1, 0); + m_ui->treeViewAllocated->setCurrentIndex(newRow); + } - slotChangesMade(); -} + slotChangesMade(); +} void AudioSettingsDialog::onDownButtonClicked() { - const QModelIndexList mil = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); - if (mil.isEmpty()) - return; - m_modelAllocated->changeOrder(mil.first(), false); - const QModelIndex newRow = m_modelAllocated->index(mil.first().row() + 1, 0); - m_ui->treeViewAllocated->setCurrentIndex(newRow); - slotChangesMade(); -} + const QModelIndexList mil = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); + if (mil.isEmpty()) + return; + m_modelAllocated->changeOrder(mil.first(), false); + const QModelIndex newRow = m_modelAllocated->index(mil.first().row() + 1, 0); + m_ui->treeViewAllocated->setCurrentIndex(newRow); + slotChangesMade(); +} -void AudioSettingsDialog::onSelectionChangedAllocation(const QItemSelection &selected, const QItemSelection &deselected) +void AudioSettingsDialog::onSelectionChangedAllocation(const QItemSelection& selected, const QItemSelection& deselected) { - DEBUG_LOG(m_logger) << "onSelectionChangedAllocation selected.isEmpty()=" << selected.isEmpty(); - Q_UNUSED(deselected); - QModelIndex first = m_ui->treeViewAllocated->model()->index(0, 0); - int rowCnt = m_ui->treeViewAllocated->model()->rowCount(); - QModelIndex last = m_ui->treeViewAllocated->model()->index(rowCnt - 1, 0); - QModelIndexList selectedRows = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); - const int cntSelectedRows = selectedRows.size(); - if (cntSelectedRows > 1) - { - m_ui->pushButtonUp->setEnabled(false); - m_ui->pushButtonDown->setEnabled(false); - return; - } - if (selected.size() > 0) - { - m_ui->pushButtonUp->setEnabled(selected.first().indexes().first() != first); - m_ui->pushButtonDown->setEnabled(selected.first().indexes().first() != last); - } -} - + DEBUG_LOG(m_logger) << "onSelectionChangedAllocation selected.isEmpty()=" << selected.isEmpty(); + Q_UNUSED(deselected); + QModelIndex first = m_ui->treeViewAllocated->model()->index(0, 0); + int rowCnt = m_ui->treeViewAllocated->model()->rowCount(); + QModelIndex last = m_ui->treeViewAllocated->model()->index(rowCnt - 1, 0); + QModelIndexList selectedRows = m_ui->treeViewAllocated->selectionModel()->selectedIndexes(); + const int cntSelectedRows = selectedRows.size(); + if (cntSelectedRows > 1) + { + m_ui->pushButtonUp->setEnabled(false); + m_ui->pushButtonDown->setEnabled(false); + return; + } + if (selected.size() > 0) + { + m_ui->pushButtonUp->setEnabled(selected.first().indexes().first() != first); + m_ui->pushButtonDown->setEnabled(selected.first().indexes().first() != last); + } +} bool AudioSettingsDialog::apply() { - if (m_modelAllocated->getStreamDataVector().isEmpty()) - applyRemove(); - else - applyModify(); - m_modelAllocated->resetChangeState(); - m_modelAvailable->resetChangeState(); - m_filterAvailable->invalidate(); - return true; + if (m_modelAllocated->getStreamDataVector().isEmpty()) + applyRemove(); + else + applyModify(); + m_modelAllocated->resetChangeState(); + m_modelAvailable->resetChangeState(); + m_filterAvailable->invalidate(); + return true; } bool AudioSettingsDialog::applyRemove() { - RemoveCnrTvcProfileRequest removeRequest; - DEBUG_LOG(m_logger) << "AudioSettingsDialog::applyRemove"; + RemoveCnrTvcProfileRequest removeRequest; + DEBUG_LOG(m_logger) << "AudioSettingsDialog::applyRemove"; + + for (const auto& profile : std::as_const(m_cnrTvcProfileMap)) + { + if (profile.operatorId() != m_operatorId) + continue; + removeRequest.id(profile.id()); + break; + } + if (removeRequest.id() <= 0) + return true; + + m_requestHelper->startSingleRequest( + [this, removeRequest]() { return m_avmFtc->removeCnrTvcProfileRequest(removeRequest, this); }); - for (const auto &profile : std::as_const(m_cnrTvcProfileMap)) - { - if (profile.operatorId() != m_operatorId) - continue; - removeRequest.id(profile.id()); - break; - } - if (removeRequest.id() <= 0) return true; - - m_requestHelper->startSingleRequest([this, removeRequest]() - { - return m_avmFtc->removeCnrTvcProfileRequest(removeRequest, this); - }); - - return true; -} +} bool AudioSettingsDialog::applyModify() { - ModifyCnrTvcProfileRequest modifyRequest; - DEBUG_LOG(m_logger) << "AudioSettingsDialog::applyModify"; + ModifyCnrTvcProfileRequest modifyRequest; + DEBUG_LOG(m_logger) << "AudioSettingsDialog::applyModify"; - for (const auto &profile : std::as_const(m_cnrTvcProfileMap)) - { - if (profile.operatorId() != m_operatorId) - continue; - modifyRequest.id(profile.id()); - break; - } + for (const auto& profile : std::as_const(m_cnrTvcProfileMap)) + { + if (profile.operatorId() != m_operatorId) + continue; + modifyRequest.id(profile.id()); + break; + } - modifyRequest.exerciseId(m_session->exerciseId()); - modifyRequest.operatorId(m_operatorId); + modifyRequest.exerciseId(m_session->exerciseId()); + modifyRequest.operatorId(m_operatorId); - const QVector allocatedList = m_modelAllocated->getStreamDataVector(); - modifyRequest.data().reserve(allocatedList.size()); - for (const StreamData &stream : allocatedList) - { - CnrTvcProfileData circuitData; - circuitData.radioSystemId(stream.bIsCnr ? RadioSystem::Cnr : RadioSystem::Tvc); - circuitData.radioCircuitId(stream.topicId); - modifyRequest.data().push_back(std::move(circuitData)); - } + const QVector allocatedList = m_modelAllocated->getStreamDataVector(); + modifyRequest.data().reserve(allocatedList.size()); + for (const StreamData& stream : allocatedList) + { + CnrTvcProfileData circuitData; + circuitData.radioSystemId(stream.bIsCnr ? RadioSystem::Cnr : RadioSystem::Tvc); + circuitData.radioCircuitId(stream.topicId); + modifyRequest.data().push_back(std::move(circuitData)); + } - m_requestHelper->startSingleRequest([this, modifyRequest]() - { - return m_avmFtc->modifyCnrTvcProfileRequest(modifyRequest, this); - }); + m_requestHelper->startSingleRequest( + [this, modifyRequest]() { return m_avmFtc->modifyCnrTvcProfileRequest(modifyRequest, this); }); - return true; -} + return true; +} -void AudioSettingsDialog::onModifyCnrTvcProfileReply(const Core::FunctionReplyObject &replyObject) +void AudioSettingsDialog::onModifyCnrTvcProfileReply(const Core::FunctionReplyObject& replyObject) { - __unchange__(); - m_requestHelper->requestReply(replyObject); -} + __unchange__(); + m_requestHelper->requestReply(replyObject); +} -void AudioSettingsDialog::onRemoveCnrTvcProfileReply(const Core::FunctionReplyObject &replyObject) +void AudioSettingsDialog::onRemoveCnrTvcProfileReply(const Core::FunctionReplyObject& replyObject) { - __unchange__(); - m_requestHelper->requestReply(replyObject); -} - + __unchange__(); + m_requestHelper->requestReply(replyObject); +} void AudioSettingsDialog::onSelectionOperatorChanged(const int index) { - Q_UNUSED(index); - if (hasUnsavedChanges() || - m_modelAllocated->getChangeState() || - m_modelAvailable->getChangeState()) - { - switch (askApplyDiscardCancel()) + Q_UNUSED(index); + if (hasUnsavedChanges() || m_modelAllocated->getChangeState() || m_modelAvailable->getChangeState()) { - case LtsWidgets::Button::Apply: - if (!apply()) - return; - break; - case LtsWidgets::Button::Cancel: - { - - - + switch (askApplyDiscardCancel()) { - QSignalBlocker blockSignals(m_ui->operatorComboBox); - m_ui->operatorComboBox->setCurrentIndex(m_ui->operatorComboBox->findData(m_operatorId)); + case LtsWidgets::Button::Apply: + if (!apply()) + return; + break; + case LtsWidgets::Button::Cancel: { + + { + QSignalBlocker blockSignals(m_ui->operatorComboBox); + m_ui->operatorComboBox->setCurrentIndex(m_ui->operatorComboBox->findData(m_operatorId)); + } + return; + } + case LtsWidgets::Button::Discard: + __unchange__(); + break; + default: + break; } - return; - } - case LtsWidgets::Button::Discard: - __unchange__(); - break; - default: - break; } - } - m_ui->pushButtonUp->setEnabled(false); - m_ui->pushButtonDown->setEnabled(false); - m_operatorId = m_ui->operatorComboBox->currentData().toInt(); - DEBUG_LOG(m_logger) << "onSelectionOperatorChanged" << " operatorStr=" << m_ui->operatorComboBox->currentText() << " m_operatorId= " << m_operatorId; - fillOperatorList(); - m_modelAllocated->resetChangeState(); - m_modelAvailable->resetChangeState(); - m_filterAvailable->invalidate(); + m_ui->pushButtonUp->setEnabled(false); + m_ui->pushButtonDown->setEnabled(false); + m_operatorId = m_ui->operatorComboBox->currentData().toInt(); + DEBUG_LOG(m_logger) << "onSelectionOperatorChanged" << " operatorStr=" << m_ui->operatorComboBox->currentText() + << " m_operatorId= " << m_operatorId; + fillOperatorList(); + m_modelAllocated->resetChangeState(); + m_modelAvailable->resetChangeState(); + m_filterAvailable->invalidate(); } -void AudioSettingsDialog::onDroppedInAllocated(const QVector &streams) +void AudioSettingsDialog::onDroppedInAllocated(const QVector& streams) { - slotChangesMade(); - m_filterAvailable->addAllocatedStreams(streams); - m_modelAllocated->setStreamChanged(streams); - m_modelAvailable->setStreamChanged(streams); + slotChangesMade(); + m_filterAvailable->addAllocatedStreams(streams); + m_modelAllocated->setStreamChanged(streams); + m_modelAvailable->setStreamChanged(streams); } -void AudioSettingsDialog::onDroppedInAvailable(const QVector &streams) +void AudioSettingsDialog::onDroppedInAvailable(const QVector& streams) { - slotChangesMade(); - m_filterAvailable->removeAllocatedStreams(streams); - m_modelAllocated->setStreamChanged(streams); - m_modelAvailable->setStreamChanged(streams); + slotChangesMade(); + m_filterAvailable->removeAllocatedStreams(streams); + m_modelAllocated->setStreamChanged(streams); + m_modelAvailable->setStreamChanged(streams); } -void AudioSettingsDialog::onEntryRemoved(const StreamData &stream) +void AudioSettingsDialog::onEntryRemoved(const StreamData& stream) { - m_modelAllocated->removeEntry(stream); - m_filterAvailable->removeAllocatedStreams({stream}); + m_modelAllocated->removeEntry(stream); + m_filterAvailable->removeAllocatedStreams({stream}); } -StreamData AudioSettingsDialog::toStreamData(const CnrTvcProfileData &profileEntry) const +StreamData AudioSettingsDialog::toStreamData(const CnrTvcProfileData& profileEntry) const { - int configId = profileEntry.radioCircuitId(); - StreamData streamData; - streamData.topicId = configId; + int configId = profileEntry.radioCircuitId(); + StreamData streamData; + streamData.topicId = configId; - if (profileEntry.radioSystemId() == RadioSystem::Cnr) - { - streamData.name = QString::fromStdString(m_avmDtc->cnrConfig(configId).radioCircuit()); - streamData.bIsCnr = true; - } - else - { - streamData.name = QString::fromStdString(m_avmDtc->tvcConfig(configId).radioCircuit()); - streamData.bIsCnr = false; - } + if (profileEntry.radioSystemId() == RadioSystem::Cnr) + { + streamData.name = QString::fromStdString(m_avmDtc->cnrConfig(configId).radioCircuit()); + streamData.bIsCnr = true; + } + else + { + streamData.name = QString::fromStdString(m_avmDtc->tvcConfig(configId).radioCircuit()); + streamData.bIsCnr = false; + } - return streamData; + return streamData; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.cpp old mode 100755 new mode 100644 index f469c7c97..5c8818195 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.cpp @@ -1,179 +1,165 @@ - #include "audio_settings_used_streams_model.h" -#include -#include + #include +#include +#include namespace AudioVideoManagement { - - - -AllocatedStreamsModel::AllocatedStreamsModel(QObject *parent) - : NGLTreeModel(parent, new NGLTreeItem(QVariant(QLatin1String("root"))), { tr("Allocated") }) +AllocatedStreamsModel::AllocatedStreamsModel(QObject* parent) + : NGLTreeModel(parent, new NGLTreeItem(QVariant(QLatin1String("root"))), {tr("Allocated")}) { - setMimeType(StreamData::mimeType()); + setMimeType(StreamData::mimeType()); } -Qt::ItemFlags AllocatedStreamsModel::flags(const QModelIndex &index) const +Qt::ItemFlags AllocatedStreamsModel::flags(const QModelIndex& index) const { - return NGLTreeModel::flags(index) | Qt::ItemIsDropEnabled; + return NGLTreeModel::flags(index) | Qt::ItemIsDropEnabled; } -QVariant AllocatedStreamsModel::data(const QModelIndex &index, int role) const +QVariant AllocatedStreamsModel::data(const QModelIndex& index, int role) const { - switch (role) - { - case Qt::DisplayRole: + switch (role) { - NGLTreeItem *item = privateData(index); - StreamData data = item->data().value(); - DEBUG_LOG(m_logger) << data.name; - return data.name; + case Qt::DisplayRole: { + NGLTreeItem* item = privateData(index); + StreamData data = item->data().value(); + DEBUG_LOG(m_logger) << data.name; + return data.name; + } + + case Qt::FontRole: { + NGLTreeItem* item = privateData(index); + StreamData data = item->data().value(); + if (!m_changedStreams.contains(QPair(data.bIsCnr, data.topicId))) + return {}; + QFont f; + f.setBold(true); + return f; + } + + default: { + break; + } } - case Qt::FontRole: - { - NGLTreeItem *item = privateData(index); - StreamData data = item->data().value(); - if (!m_changedStreams.contains(QPair(data.bIsCnr, data.topicId))) - return {}; - QFont f; - f.setBold(true); - return f; - } - - default: - { - break; - } - } - - return NGLTreeModel::data(index, role); + return NGLTreeModel::data(index, role); } - -void AllocatedStreamsModel::setStreamChanged(const QVector &streams) +void AllocatedStreamsModel::setStreamChanged(const QVector& streams) { - for (const StreamData &d : streams) - if (!m_changedStreams.contains(QPair(d.bIsCnr, d.topicId))) - m_changedStreams += QPair(d.bIsCnr, d.topicId); - emit modelDataChanged(); + for (const StreamData& d : streams) + if (!m_changedStreams.contains(QPair(d.bIsCnr, d.topicId))) + m_changedStreams += QPair(d.bIsCnr, d.topicId); + emit modelDataChanged(); } - -bool AllocatedStreamsModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const +bool AllocatedStreamsModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const { - Q_UNUSED(data); - Q_UNUSED(row); - Q_UNUSED(column); - Q_UNUSED(parent); - if (action != supportedDropActions()) - return false; - return true; + Q_UNUSED(data); + Q_UNUSED(row); + Q_UNUSED(column); + Q_UNUSED(parent); + if (action != supportedDropActions()) + return false; + return true; } - -bool AllocatedStreamsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool AllocatedStreamsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - Q_UNUSED(row); - Q_UNUSED(column); - Q_UNUSED(parent); + Q_UNUSED(row); + Q_UNUSED(column); + Q_UNUSED(parent); - const QVector droppedItems = getMimeDataItems(data, m_mimeType); - QVector streams; - streams.reserve(droppedItems.size()); - for (const NGLTreeItem *item : droppedItems) - streams += item->data().value(); - qDeleteAll(droppedItems); - emit droppedStreamNames(streams); - m_changes = true; - DEBUG_LOG(m_logger) << data->data(QStringLiteral("NGLTreeModel/dragDrop")); - return NGLTreeModel::dropMimeData(data, action, row, 0, QModelIndex()); + const QVector droppedItems = getMimeDataItems(data, m_mimeType); + QVector streams; + streams.reserve(droppedItems.size()); + for (const NGLTreeItem* item : droppedItems) + streams += item->data().value(); + qDeleteAll(droppedItems); + emit droppedStreamNames(streams); + m_changes = true; + DEBUG_LOG(m_logger) << data->data(QStringLiteral("NGLTreeModel/dragDrop")); + return NGLTreeModel::dropMimeData(data, action, row, 0, QModelIndex()); } - -void AllocatedStreamsModel::setNewStreamData(const QVector &newData) +void AllocatedStreamsModel::setNewStreamData(const QVector& newData) { - DEBUG_LOG(m_logger) << "set new stream data, count: " << newData.size(); - resetModel(); - for (const StreamData &sd : newData) - m_rootItem->appendChild(new NGLTreeItem(QVariant::fromValue(sd))); + DEBUG_LOG(m_logger) << "set new stream data, count: " << newData.size(); + resetModel(); + for (const StreamData& sd : newData) + m_rootItem->appendChild(new NGLTreeItem(QVariant::fromValue(sd))); - emit modelDataChanged(); + emit modelDataChanged(); } QVector AllocatedStreamsModel::getStreamDataVector() const { - QVector result; - result.reserve(m_rootItem->childCount()); - for (int i = 0; i < m_rootItem->childCount(); i++) - { - const NGLTreeItem *item = m_rootItem->child(i); - const StreamData sd = item->data().value(); - result.append(sd); - DEBUG_LOG(m_logger) << "result.append(sd.name):" << sd.name; - } - DEBUG_LOG(m_logger) << "getStreamDataVector() size: " << result.size(); - return result; -} - -void AllocatedStreamsModel::changeOrder(const QModelIndex &idx, bool up) -{ - DEBUG_LOG(m_logger) << "changeOrder " - << " index = " << idx.row() - << " up = " << up - << " m_rootItem->childCount()= " << m_rootItem->childCount(); - if (up) - { - moveRow(idx.parent(), idx.row(), - idx.parent(), idx.row() - 1); - } - else - { - moveRow(idx.parent(), idx.row(), - idx.parent(), idx.row() + 1); - } - emit modelDataChanged(); -} - - -void AllocatedStreamsModel::updateEntry(const StreamData &stream) -{ - for (int i = 0; i < m_rootItem->childCount(); i++) - { - NGLTreeItem *child = m_rootItem->child(i); - StreamData data = child->data().value(); - - if (data == stream) + QVector result; + result.reserve(m_rootItem->childCount()); + for (int i = 0; i < m_rootItem->childCount(); i++) { - setItemData(indexFromItem(child), QVariant::fromValue(stream), child->icon()); - break; + const NGLTreeItem* item = m_rootItem->child(i); + const StreamData sd = item->data().value(); + result.append(sd); + DEBUG_LOG(m_logger) << "result.append(sd.name):" << sd.name; } - } - - emit modelDataChanged(); + DEBUG_LOG(m_logger) << "getStreamDataVector() size: " << result.size(); + return result; } - -void AllocatedStreamsModel::removeEntry(const StreamData &stream) +void AllocatedStreamsModel::changeOrder(const QModelIndex& idx, bool up) { - for (int i = 0; i < m_rootItem->childCount(); i++) - { - NGLTreeItem *child = m_rootItem->child(i); - StreamData data = child->data().value(); - if (data == stream) + DEBUG_LOG(m_logger) << "changeOrder " + << " index = " << idx.row() << " up = " << up + << " m_rootItem->childCount()= " << m_rootItem->childCount(); + if (up) { - removeRows(i, 1, indexFromItem(m_rootItem)); - break; + moveRow(idx.parent(), idx.row(), idx.parent(), idx.row() - 1); } - } - - emit modelDataChanged(); + else + { + moveRow(idx.parent(), idx.row(), idx.parent(), idx.row() + 1); + } + emit modelDataChanged(); } -} +void AllocatedStreamsModel::updateEntry(const StreamData& stream) +{ + for (int i = 0; i < m_rootItem->childCount(); i++) + { + NGLTreeItem* child = m_rootItem->child(i); + StreamData data = child->data().value(); + + if (data == stream) + { + setItemData(indexFromItem(child), QVariant::fromValue(stream), child->icon()); + break; + } + } + + emit modelDataChanged(); +} + +void AllocatedStreamsModel::removeEntry(const StreamData& stream) +{ + for (int i = 0; i < m_rootItem->childCount(); i++) + { + NGLTreeItem* child = m_rootItem->child(i); + StreamData data = child->data().value(); + if (data == stream) + { + removeRows(i, 1, indexFromItem(m_rootItem)); + break; + } + } + + emit modelDataChanged(); +} + +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.h old mode 100755 new mode 100644 index 17cd0798f..128b8c19b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/AudioSettings/audio_settings_used_streams_model.h @@ -1,49 +1,68 @@ - #pragma once -#include -#include #include "audio_stream_type.h" +#include +#include + namespace AudioVideoManagement { class AllocatedStreamsModel final : public NGLTreeModel { - Q_OBJECT -public: - explicit AllocatedStreamsModel(QObject *parent = nullptr); + Q_OBJECT + public: + explicit AllocatedStreamsModel(QObject* parent = nullptr); - bool getChangeState() {bool result = m_changes; m_changes = false; return result;} - void resetChangeState() {m_changes = false;m_changedStreams.clear();} + bool getChangeState() + { + bool result = m_changes; + m_changes = false; + return result; + } - Qt::ItemFlags flags(const QModelIndex &index) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - Qt::DropActions supportedDropActions() const override { return Qt::CopyAction; } - Qt::DropActions supportedDragActions() const override { return Qt::MoveAction; } - bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) override; - void setStreamChanged(const QVector &streams); + void resetChangeState() + { + m_changes = false; + m_changedStreams.clear(); + } - void setNewStreamData(const QVector &newData); + Qt::ItemFlags flags(const QModelIndex& index) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - QVector getStreamDataVector() const; + Qt::DropActions supportedDropActions() const override + { + return Qt::CopyAction; + } - void changeOrder(const QModelIndex &idx, bool up); - void updateEntry(const StreamData &stream); - void removeEntry(const StreamData &stream); + Qt::DropActions supportedDragActions() const override + { + return Qt::MoveAction; + } -signals: - void droppedStreamNames(const QVector &streamNamesDropped); + bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const override; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) override; + void setStreamChanged(const QVector& streams); -private: + void setNewStreamData(const QVector& newData); -NGL::INGLLogger &m_logger; - bool m_changes{false}; - QVector > m_changedStreams; + QVector getStreamDataVector() const; + + void changeOrder(const QModelIndex& idx, bool up); + void updateEntry(const StreamData& stream); + void removeEntry(const StreamData& stream); + + signals: + void droppedStreamNames(const QVector& streamNamesDropped); + + private: + NGL::INGLLogger& m_logger; + bool m_changes{false}; + QVector> m_changedStreams; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/avm_sequence_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/avm_sequence_model.h old mode 100755 new mode 100644 index 90e390f3d..de3b1fdf7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/avm_sequence_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/avm_sequence_model.h @@ -1,13 +1,11 @@ - #pragma once +#include +#include #include #include -#include -#include - #include namespace AudioVideoManagement @@ -15,67 +13,63 @@ namespace AudioVideoManagement class AvsSequence { -public: - QString internalStreamName; - AvaSpeed speed{100}; - AvaVolume volume{0}; - AvaTimePoint start; - AvaDuration duration; - bool pint = false; - QString description; + public: + QString internalStreamName; + AvaSpeed speed{100}; + AvaVolume volume{0}; + AvaTimePoint start; + AvaDuration duration; + bool pint = false; + QString description; }; - class AvmSequenceModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Order = 0, - Start, - End, - Duration, - Streams, - Speed, - Volume, - Description - }; + Q_OBJECT + public: + enum Columns { Order = 0, Start, End, Duration, Streams, Speed, Volume, Description }; - explicit AvmSequenceModel(QObject *parent = nullptr); - void moveUp(const QModelIndex &idx); - void moveDown(const QModelIndex &idx); - bool initModel(const QJsonArray &data); - bool moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) override; - QJsonArray getSequencesAsJsonArray() const; - QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override; - QVector highlightedRows() const { return m_highlightedRows; } - void setHighlightedRow(int highlighted, bool reset = true); + explicit AvmSequenceModel(QObject* parent = nullptr); + void moveUp(const QModelIndex& idx); + void moveDown(const QModelIndex& idx); + bool initModel(const QJsonArray& data); + bool moveRows(const QModelIndex& sourceParent, int sourceRow, int count, const QModelIndex& destinationParent, + int destinationChild) override; + QJsonArray getSequencesAsJsonArray() const; + QVariant data(const QModelIndex& idx, int role = Qt::DisplayRole) const override; - friend class AvmSequenceProxyModel; + QVector highlightedRows() const + { + return m_highlightedRows; + } -public slots: - void setTimezoneHoursOffset(int timezoneHoursOffset); + void setHighlightedRow(int highlighted, bool reset = true); -private: + friend class AvmSequenceProxyModel; -NGL::INGLLogger &m_logger; - QString dateTimeToStringx(const QDateTime &dt) const; - QString msecsSinceEpochToStringx(qint64 msecs) const; + public slots: + void setTimezoneHoursOffset(int timezoneHoursOffset); - QVector m_highlightedRows; - int m_timezoneHoursOffset = 0; + private: + NGL::INGLLogger& m_logger; + QString dateTimeToStringx(const QDateTime& dt) const; + QString msecsSinceEpochToStringx(qint64 msecs) const; + + QVector m_highlightedRows; + int m_timezoneHoursOffset = 0; }; class AvmSequenceProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - AvmSequenceModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + AvmSequenceModel* m_sourceModel = nullptr; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.cpp old mode 100755 new mode 100644 index ff9aca229..9edb6a5de --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.cpp @@ -1,677 +1,617 @@ - #include "topic_editor.h" -#include + #include "ui_topic_editor.h" +#include #include #include #include #include -#include #include +#include #include - #include #include - -#include +#include #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) #include #endif - -static constexpr int s_defaultOffset = 10 * 1000; - +static constexpr int s_defaultOffset = 10 * 1000; namespace AudioVideoManagement { -QString dateTimeToStringz(const QDateTime &dt) +QString dateTimeToStringz(const QDateTime& dt) { - return dt.toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")); + return dt.toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")); } QString msecsSinceEpochToStringz(qint64 msecs) { - return dateTimeToStringz(QDateTime::fromMSecsSinceEpoch(msecs)); + return dateTimeToStringz(QDateTime::fromMSecsSinceEpoch(msecs)); } -qint64 timePointToMsecs(const AvaTimePoint &atp) +qint64 timePointToMsecs(const AvaTimePoint& atp) { - return std::chrono::duration_cast(atp.time_since_epoch()).count(); + return std::chrono::duration_cast(atp.time_since_epoch()).count(); } AvaDuration msecsToAvaDuration(qint64 msecs) { - return std::chrono::duration_cast(std::chrono::milliseconds(msecs)); + return std::chrono::duration_cast(std::chrono::milliseconds(msecs)); } AvaTimePoint msecsToAvaTimePoint(qint64 msecs) { - return AvaTimePoint(msecsToAvaDuration(msecs)); + return AvaTimePoint(msecsToAvaDuration(msecs)); } - -TopicEditor::TopicEditor(LtsSession::LtsSession *session, const TopicEditorBase::TopicData &data, QWidget *parent) - : TopicEditorBase::TopicEditor(parent) - , m_session(session) - , m_avmDataIfc(nullptr) - , m_model(new AvmSequenceModel(this)) - , m_playbackMenu(nullptr) - , m_ui(new Ui::AVTopicEditor) +TopicEditor::TopicEditor(LtsSession::LtsSession* session, const TopicEditorBase::TopicData& data, QWidget* parent) + : TopicEditorBase::TopicEditor(parent), m_session(session), m_avmDataIfc(nullptr), + m_model(new AvmSequenceModel(this)), m_playbackMenu(nullptr), m_ui(new Ui::AVTopicEditor) { - Q_ASSERT(session); + Q_ASSERT(session); - m_ui->setupUi(this); - m_ui->tvSequences->hideColumn(AvmSequenceModel::Order); - init(m_ui->widget); + m_ui->setupUi(this); + m_ui->tvSequences->hideColumn(AvmSequenceModel::Order); + init(m_ui->widget); - m_isAudio = (data.topicType == TopicEditorBase::TopicType::Audio); - if (m_isAudio) - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Audio_Topic")); - else - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Video_Topic")); + m_isAudio = (data.topicType == TopicEditorBase::TopicType::Audio); + if (m_isAudio) + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Audio_Topic")); + else + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Video_Topic")); - setTopicData(data); - m_topicData.properties[QStringLiteral("IsAudio")] = bool(m_topicData.topicType == TopicEditorBase::TopicType::Audio); - m_ui->widget->previewer()->setTopicData(m_topicData); + setTopicData(data); + m_topicData.properties[QStringLiteral("IsAudio")] = + bool(m_topicData.topicType == TopicEditorBase::TopicType::Audio); + m_ui->widget->previewer()->setTopicData(m_topicData); - QJsonArray arr = getTopicVDataAsArray(QLatin1String("Sequences")); - m_model->initModel(arr); - m_ui->tvSequences->resizeColumnsToContents(); - refreshDurationText(); - m_proxyModel = new AvmSequenceProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->tvSequences->setModel(m_proxyModel); - connect(m_ui->tvSequences, SIGNAL(doubleClicked(QModelIndex)), - m_ui->tvSequences->selectionModel(), SLOT(select(QModelIndex, QItemSelectionModel::Toggle))); + QJsonArray arr = getTopicVDataAsArray(QLatin1String("Sequences")); + m_model->initModel(arr); + m_ui->tvSequences->resizeColumnsToContents(); + refreshDurationText(); + m_proxyModel = new AvmSequenceProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->tvSequences->setModel(m_proxyModel); + connect(m_ui->tvSequences, SIGNAL(doubleClicked(QModelIndex)), m_ui->tvSequences->selectionModel(), + SLOT(select(QModelIndex, QItemSelectionModel::Toggle))); - connect(m_ui->tvSequences->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &TopicEditor::onEnaDisa); - connect(m_ui->pbDelete, &QToolButton::clicked, - this, &TopicEditor::onDeleteSequences); - connect(m_ui->pbUp, &QToolButton::clicked, - this, &TopicEditor::onSequenceUp); - connect(m_ui->pbDown, &QToolButton::clicked, - this, &TopicEditor::onSequenceDown); - connect(m_ui->pbPreview, &QPushButton::clicked, this, [this]() - { - m_playbackMenu->setStreamTime(m_ui->dtStart->msecsSinceEpoch()); - }); + connect(m_ui->tvSequences->selectionModel(), &QItemSelectionModel::selectionChanged, this, &TopicEditor::onEnaDisa); + connect(m_ui->pbDelete, &QToolButton::clicked, this, &TopicEditor::onDeleteSequences); + connect(m_ui->pbUp, &QToolButton::clicked, this, &TopicEditor::onSequenceUp); + connect(m_ui->pbDown, &QToolButton::clicked, this, &TopicEditor::onSequenceDown); + connect(m_ui->pbPreview, &QPushButton::clicked, this, + [this]() { m_playbackMenu->setStreamTime(m_ui->dtStart->msecsSinceEpoch()); }); - if (!m_session->getForeignDataInterface_NEW(m_avmDataIfc)) - { - playbackDlgNotAvailable(tr("The audio/video interface is not available in this session.")); - return; - } - - PlaybackApp *app = m_isAudio ? m_avmDataIfc->audioPlaybackApp() : m_avmDataIfc->videoPlaybackApp(); - if (app == nullptr) - { - playbackDlgNotAvailable(tr("The audio/video interface is currently not available.")); - return; - } - - if (app->inUse()) - { - playbackDlgNotAvailable(tr("The audio/video interface is already in use by another dialog.")); - return; - } - - - - m_ui->pbApply->setEnabled(false); - m_ui->pbDelete->setEnabled(false); - m_ui->pbUp->setEnabled(false); - m_ui->pbDown->setEnabled(false); - - - boost::optional stream = boost::none; - if (m_topicData.properties.contains(QStringLiteral("stream"))) - stream = m_topicData.properties.value(QStringLiteral("stream")).toString(); - - - qint64 startMsecs = 0; - boost::optional start = boost::none; - { - const QJsonValue jsonValue(getTopicDataValue(QStringLiteral("start"))); - if (jsonValue.isDouble()) + if (!m_session->getForeignDataInterface_NEW(m_avmDataIfc)) { - startMsecs = static_cast(jsonValue.toDouble()); - start = boost::optional(toTimePoint(startMsecs)); + playbackDlgNotAvailable(tr("The audio/video interface is not available in this session.")); + return; } - } - - qint64 endMsecs = 0; - { - const QJsonValue jsonValue(getTopicDataValue(QStringLiteral("end"))); - if (jsonValue.isDouble()) - endMsecs = static_cast(jsonValue.toDouble()); - } + PlaybackApp* app = m_isAudio ? m_avmDataIfc->audioPlaybackApp() : m_avmDataIfc->videoPlaybackApp(); + if (app == nullptr) + { + playbackDlgNotAvailable(tr("The audio/video interface is currently not available.")); + return; + } - m_playbackMenu = new AvmPlaybackMenu(this); - m_playbackMenu->init( - m_session, m_avmDataIfc->avaSession(), PlaybackAppHandle(app), m_avmDataIfc->streamNameMapping(), m_isAudio, true , - stream, start - ); - m_ui->playbackParent->layout()->addWidget(m_playbackMenu); - + if (app->inUse()) + { + playbackDlgNotAvailable(tr("The audio/video interface is already in use by another dialog.")); + return; + } - connect(m_playbackMenu, &AvmPlaybackMenu::setTopicButtonStates, - this, &TopicEditor::onSetTopicButtonStates); - connect(m_playbackMenu, &AvmPlaybackMenu::markerSelected, - this, &TopicEditor::onMarkerSelected); - connect(m_playbackMenu, &AvmPlaybackMenu::signalCurrentStreamChanged, this, [this](const QString &displayName) - { - m_ui->lblStream->setText(displayName); - }); - connect(m_playbackMenu, &AvmPlaybackMenu::signalSetStart, this, [this](qint64 start) - { - m_ui->dtStart->setMsecsSinceEpoch(start); - if (m_ui->dtEnd->msecsSinceEpoch() < start) - m_ui->dtEnd->setMsecsSinceEpoch(start + s_defaultOffset); - }); - connect(m_playbackMenu, &AvmPlaybackMenu::signalSetEnd, this, [this](qint64 end) - { - m_ui->dtEnd->setMsecsSinceEpoch(end); - if (m_ui->dtStart->msecsSinceEpoch() > end) - m_ui->dtStart->setMsecsSinceEpoch(end - s_defaultOffset); - }); - m_playbackMenu->show(); + m_ui->pbApply->setEnabled(false); + m_ui->pbDelete->setEnabled(false); + m_ui->pbUp->setEnabled(false); + m_ui->pbDown->setEnabled(false); - + boost::optional stream = boost::none; + if (m_topicData.properties.contains(QStringLiteral("stream"))) + stream = m_topicData.properties.value(QStringLiteral("stream")).toString(); - - if (m_topicData.startTime > -1) - { - m_ui->dtStart->setMsecsSinceEpoch(static_cast(m_topicData.startTime) * 1000); - if (m_topicData.duration > 0) - m_ui->dtEnd->setMsecsSinceEpoch(static_cast(m_topicData.startTime + m_topicData.duration) * 1000); - } + qint64 startMsecs = 0; + boost::optional start = boost::none; + { + const QJsonValue jsonValue(getTopicDataValue(QStringLiteral("start"))); + if (jsonValue.isDouble()) + { + startMsecs = static_cast(jsonValue.toDouble()); + start = boost::optional(toTimePoint(startMsecs)); + } + } - - connect(m_ui->tvSequences, &QTableView::doubleClicked, - this, &TopicEditor::onEditSequence); - connect(m_ui->dtStart, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, - this, &TopicEditor::onTimeChanged); - connect(m_ui->dtEnd, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, - this, &TopicEditor::onTimeChanged); - connect(m_ui->pbAdd, &QToolButton::clicked, - this, &TopicEditor::onAddSequence); - connect(m_ui->pbApply, &QToolButton::clicked, - this, &TopicEditor::onApplySequence); - connect(m_ui->pbEditSequence, &QPushButton::clicked, - this, &TopicEditor::onEditSequence); + qint64 endMsecs = 0; + { + const QJsonValue jsonValue(getTopicDataValue(QStringLiteral("end"))); + if (jsonValue.isDouble()) + endMsecs = static_cast(jsonValue.toDouble()); + } - - if (startMsecs > 0 && endMsecs > 0) - { - m_ui->dtStart->setMsecsSinceEpoch(startMsecs); - m_ui->dtEnd->setMsecsSinceEpoch(endMsecs); - } + m_playbackMenu = new AvmPlaybackMenu(this); + m_playbackMenu->init(m_session, m_avmDataIfc->avaSession(), PlaybackAppHandle(app), + m_avmDataIfc->streamNameMapping(), m_isAudio, true, stream, start); + m_ui->playbackParent->layout()->addWidget(m_playbackMenu); - connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, - m_ui->dtStart, &LtsWidgets::LtsMSecDateTimeEdit::setTimezoneHoursOffset); - connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, - m_ui->dtEnd, &LtsWidgets::LtsMSecDateTimeEdit::setTimezoneHoursOffset); - connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, - m_model, &AvmSequenceModel::setTimezoneHoursOffset); + connect(m_playbackMenu, &AvmPlaybackMenu::setTopicButtonStates, this, &TopicEditor::onSetTopicButtonStates); + connect(m_playbackMenu, &AvmPlaybackMenu::markerSelected, this, &TopicEditor::onMarkerSelected); + connect(m_playbackMenu, &AvmPlaybackMenu::signalCurrentStreamChanged, this, + [this](const QString& displayName) { m_ui->lblStream->setText(displayName); }); + connect(m_playbackMenu, &AvmPlaybackMenu::signalSetStart, this, [this](qint64 start) { + m_ui->dtStart->setMsecsSinceEpoch(start); + if (m_ui->dtEnd->msecsSinceEpoch() < start) + m_ui->dtEnd->setMsecsSinceEpoch(start + s_defaultOffset); + }); + connect(m_playbackMenu, &AvmPlaybackMenu::signalSetEnd, this, [this](qint64 end) { + m_ui->dtEnd->setMsecsSinceEpoch(end); + if (m_ui->dtStart->msecsSinceEpoch() > end) + m_ui->dtStart->setMsecsSinceEpoch(end - s_defaultOffset); + }); + m_playbackMenu->show(); - int offset = m_playbackMenu->currentOffset(); - m_model->setTimezoneHoursOffset(offset); - m_ui->dtStart->setTimezoneHoursOffset(offset); - m_ui->dtEnd->setTimezoneHoursOffset(offset); + if (m_topicData.startTime > -1) + { + m_ui->dtStart->setMsecsSinceEpoch(static_cast(m_topicData.startTime) * 1000); + if (m_topicData.duration > 0) + m_ui->dtEnd->setMsecsSinceEpoch(static_cast(m_topicData.startTime + m_topicData.duration) * 1000); + } + + connect(m_ui->tvSequences, &QTableView::doubleClicked, this, &TopicEditor::onEditSequence); + connect(m_ui->dtStart, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, this, &TopicEditor::onTimeChanged); + connect(m_ui->dtEnd, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, this, &TopicEditor::onTimeChanged); + connect(m_ui->pbAdd, &QToolButton::clicked, this, &TopicEditor::onAddSequence); + connect(m_ui->pbApply, &QToolButton::clicked, this, &TopicEditor::onApplySequence); + connect(m_ui->pbEditSequence, &QPushButton::clicked, this, &TopicEditor::onEditSequence); + + if (startMsecs > 0 && endMsecs > 0) + { + m_ui->dtStart->setMsecsSinceEpoch(startMsecs); + m_ui->dtEnd->setMsecsSinceEpoch(endMsecs); + } + + connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, m_ui->dtStart, + &LtsWidgets::LtsMSecDateTimeEdit::setTimezoneHoursOffset); + connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, m_ui->dtEnd, + &LtsWidgets::LtsMSecDateTimeEdit::setTimezoneHoursOffset); + connect(m_playbackMenu, &AvmPlaybackMenu::signalTimezoneChanged, m_model, + &AvmSequenceModel::setTimezoneHoursOffset); + + int offset = m_playbackMenu->currentOffset(); + m_model->setTimezoneHoursOffset(offset); + m_ui->dtStart->setTimezoneHoursOffset(offset); + m_ui->dtEnd->setTimezoneHoursOffset(offset); } TopicEditor::~TopicEditor() { - delete m_ui; - delete m_model; + delete m_ui; + delete m_model; } - - - void TopicEditor::updateInternalData() { - if (hasTopicDataProperties()) - { - m_topicStartTime = getTopicDataValue(QStringLiteral("start")).toDouble(); - m_topicStreamName = getTopicDataValue(QStringLiteral("stream")).toString(); - QJsonArray arr = getTopicVDataAsArray(QLatin1String("Sequences")); - m_model->initModel(arr); - m_ui->tvSequences->resizeColumnsToContents(); - setDurationText(calcTrackLength(arr)); - } + if (hasTopicDataProperties()) + { + m_topicStartTime = getTopicDataValue(QStringLiteral("start")).toDouble(); + m_topicStreamName = getTopicDataValue(QStringLiteral("stream")).toString(); + QJsonArray arr = getTopicVDataAsArray(QLatin1String("Sequences")); + m_model->initModel(arr); + m_ui->tvSequences->resizeColumnsToContents(); + setDurationText(calcTrackLength(arr)); + } - m_ui->pbApply->setEnabled(false); - m_ui->pbDelete->setEnabled(false); + m_ui->pbApply->setEnabled(false); + m_ui->pbDelete->setEnabled(false); } void TopicEditor::retranslate() { - - translate(m_ui, m_topicData.topicType == TopicEditorBase::TopicType::Audio ? tr("Audio Topic Editor") : tr("Video Topic Editor") ); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Apply to topic", "Auf Topic übernehmen")); + translate(m_ui, m_topicData.topicType == TopicEditorBase::TopicType::Audio ? tr("Audio Topic Editor") + : tr("Video Topic Editor")); + + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Apply to topic", "Auf Topic übernehmen")); } - -AvsSequence TopicEditor::createSequence(const AvaTimePoint &start, const AvaTimePoint &end) const +AvsSequence TopicEditor::createSequence(const AvaTimePoint& start, const AvaTimePoint& end) const { - AvsSequence seq; + AvsSequence seq; - seq.start = start; - seq.duration = end - start; - seq.description = m_ui->leDescription->text(); + seq.start = start; + seq.duration = end - start; + seq.description = m_ui->leDescription->text(); - if (m_playbackMenu != nullptr) - { - seq.speed = m_playbackMenu->getSpeed(); - seq.volume = m_playbackMenu->getVolume(); - seq.internalStreamName = m_playbackMenu->getInternalStreamName(); - seq.pint = m_playbackMenu->getSkipPause(); - } + if (m_playbackMenu != nullptr) + { + seq.speed = m_playbackMenu->getSpeed(); + seq.volume = m_playbackMenu->getVolume(); + seq.internalStreamName = m_playbackMenu->getInternalStreamName(); + seq.pint = m_playbackMenu->getSkipPause(); + } - return seq; + return seq; } AvsSequence TopicEditor::createCurrentSequence() const { - return createSequence(AvaTimePoint(std::chrono::duration_cast(std::chrono::milliseconds(m_ui->dtStart->msecsSinceEpoch()))), - AvaTimePoint(std::chrono::duration_cast(std::chrono::milliseconds(m_ui->dtEnd->msecsSinceEpoch())))); + return createSequence(AvaTimePoint(std::chrono::duration_cast( + std::chrono::milliseconds(m_ui->dtStart->msecsSinceEpoch()))), + AvaTimePoint(std::chrono::duration_cast( + std::chrono::milliseconds(m_ui->dtEnd->msecsSinceEpoch())))); } void TopicEditor::refreshDurationText() { - setDurationText(calcTrackLength(m_model->getSequencesAsJsonArray())); + setDurationText(calcTrackLength(m_model->getSequencesAsJsonArray())); } void TopicEditor::setDurationText(qint64 length) { - if (length > s_durationLimit) - m_ui->lblDuration->setText(tr("Playback too long!")); - else - m_ui->lblDuration->setText(QTime::fromMSecsSinceStartOfDay(length).toString(QStringLiteral("HH:mm:ss.zzz"))); + if (length > s_durationLimit) + m_ui->lblDuration->setText(tr("Playback too long!")); + else + m_ui->lblDuration->setText(QTime::fromMSecsSinceStartOfDay(length).toString(QStringLiteral("HH:mm:ss.zzz"))); } -qint64 TopicEditor::calcTrackLength(const QJsonArray &arr) const +qint64 TopicEditor::calcTrackLength(const QJsonArray& arr) const { - qint64 length = 0; - for (const auto &ele : arr) - { - const QJsonObject &seqObj = ele.toObject(); - if (seqObj.isEmpty()) - continue; - - length += std::ceil(seqObj.value(QLatin1String("duration")).toDouble() / (std::fabs(seqObj.value(QLatin1String("speed")).toDouble(100))) * 100 ); - } + qint64 length = 0; + for (const auto& ele : arr) + { + const QJsonObject& seqObj = ele.toObject(); + if (seqObj.isEmpty()) + continue; - return length; + length += std::ceil(seqObj.value(QLatin1String("duration")).toDouble() / + (std::fabs(seqObj.value(QLatin1String("speed")).toDouble(100))) * 100); + } + + return length; } -void TopicEditor::playbackDlgNotAvailable(const QString &msg) +void TopicEditor::playbackDlgNotAvailable(const QString& msg) { - new LtsWidgets::LtsMessageDialogNew(this, msg); - m_ui->groupBox->hide(); - m_ui->line->hide(); + new LtsWidgets::LtsMessageDialogNew(this, msg); + m_ui->groupBox->hide(); + m_ui->line->hide(); - - m_ui->pbEditSequence->hide(); + m_ui->pbEditSequence->hide(); } - - - bool TopicEditor::apply2() { - const QJsonArray &arr = m_model->getSequencesAsJsonArray(); - qint64 duration = calcTrackLength(arr); + const QJsonArray& arr = m_model->getSequencesAsJsonArray(); + qint64 duration = calcTrackLength(arr); - if (duration > s_durationLimit) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("This topic has exceeded the maximum length of %1 seconds.").arg(s_durationLimit)); - return false; - } - - setDurationText(duration); - - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("AVM.AllowIncompleteTopic")) != QVariant(true)) - { - if (duration <= 0) + if (duration > s_durationLimit) { - new LtsWidgets::LtsMessageDialogNew( - this, tr("The total playback length is less than 1 second long.
" - "Please verify that you have one or more sequences in the sequences list and that these sequences are of at least 1 second length."), - tr("Playback length too short") - ); - return false; + new LtsWidgets::LtsMessageDialogNew( + this, tr("This topic has exceeded the maximum length of %1 seconds.").arg(s_durationLimit)); + return false; } - qint64 secs = duration / 1000; - qint64 msecs = duration - (secs * 1000); - qWarning() << "secs" << secs << "msecs" << msecs; + setDurationText(duration); - - if (msecs >= 500) - ++secs; - qWarning() << "secs now" << secs; - m_topicData.duration = secs; - } - else - m_topicData.duration = 10; + if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("AVM.AllowIncompleteTopic")) != + QVariant(true)) + { + if (duration <= 0) + { + new LtsWidgets::LtsMessageDialogNew(this, + tr("The total playback length is less than 1 second long.
" + "Please verify that you have one or more sequences in the sequences " + "list and that these sequences are of at least 1 second length."), + tr("Playback length too short")); + return false; + } - setTopicDataProperty(QStringLiteral("Sequences"), m_model->getSequencesAsJsonArray()); - setTopicDataProperty(QStringLiteral("ScriptName"), QString(QStringLiteral("S") + QString::number(m_topicData.id))); - setTopicDataProperty(QStringLiteral("IsAudio"), bool(m_topicData.topicType == TopicEditorBase::TopicType::Audio)); - setDescription(m_ui->widget->description()); - m_ui->widget->previewer()->setTopicData(m_topicData); - return true; + qint64 secs = duration / 1000; + qint64 msecs = duration - (secs * 1000); + qWarning() << "secs" << secs << "msecs" << msecs; + + if (msecs >= 500) + ++secs; + qWarning() << "secs now" << secs; + m_topicData.duration = secs; + } + else + m_topicData.duration = 10; + + setTopicDataProperty(QStringLiteral("Sequences"), m_model->getSequencesAsJsonArray()); + setTopicDataProperty(QStringLiteral("ScriptName"), QString(QStringLiteral("S") + QString::number(m_topicData.id))); + setTopicDataProperty(QStringLiteral("IsAudio"), bool(m_topicData.topicType == TopicEditorBase::TopicType::Audio)); + setDescription(m_ui->widget->description()); + m_ui->widget->previewer()->setTopicData(m_topicData); + return true; } - void TopicEditor::onEditSequence() { - if (!m_playbackMenu) - return; + if (!m_playbackMenu) + return; - DEBUG_LOG(m_logger) << "slotEditSequence "; - const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); + DEBUG_LOG(m_logger) << "slotEditSequence "; + const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); - if (selRows.size() != 1) - { - m_model->setHighlightedRow(-1); - return; - } + if (selRows.size() != 1) + { + m_model->setHighlightedRow(-1); + return; + } - int row = selRows.at(0).row(); - m_model->setHighlightedRow(row); - const AvsSequence selectedSeq = m_model->getRowData(row); + int row = selRows.at(0).row(); + m_model->setHighlightedRow(row); + const AvsSequence selectedSeq = m_model->getRowData(row); - DEBUG_LOG(m_logger) << "selectedSeq.internalStreamName=" << selectedSeq.internalStreamName; - m_playbackMenu->setStreamName(selectedSeq.internalStreamName); + DEBUG_LOG(m_logger) << "selectedSeq.internalStreamName=" << selectedSeq.internalStreamName; + m_playbackMenu->setStreamName(selectedSeq.internalStreamName); - m_ui->dtStart->setMsecsSinceEpoch(std::chrono::milliseconds(selectedSeq.start.time_since_epoch()).count()); - m_ui->dtEnd->setMsecsSinceEpoch(std::chrono::milliseconds((selectedSeq.start + selectedSeq.duration).time_since_epoch()).count()); + m_ui->dtStart->setMsecsSinceEpoch(std::chrono::milliseconds(selectedSeq.start.time_since_epoch()).count()); + m_ui->dtEnd->setMsecsSinceEpoch( + std::chrono::milliseconds((selectedSeq.start + selectedSeq.duration).time_since_epoch()).count()); - m_ui->leDescription->setText(selectedSeq.description); - m_playbackMenu->setStreamByName(selectedSeq.internalStreamName); - m_playbackMenu->setSpeed(selectedSeq.speed); - m_playbackMenu->setVolume(selectedSeq.volume); - m_playbackMenu->setSkipPause(selectedSeq.pint); - m_playbackMenu->setSavedPos(m_ui->dtStart->msecsSinceEpoch()); + m_ui->leDescription->setText(selectedSeq.description); + m_playbackMenu->setStreamByName(selectedSeq.internalStreamName); + m_playbackMenu->setSpeed(selectedSeq.speed); + m_playbackMenu->setVolume(selectedSeq.volume); + m_playbackMenu->setSkipPause(selectedSeq.pint); + m_playbackMenu->setSavedPos(m_ui->dtStart->msecsSinceEpoch()); - m_ui->pbApply->setEnabled(true); + m_ui->pbApply->setEnabled(true); } -void TopicEditor::onTimeChanged() -{ - - - - - - - - - - - - - - - - - - - - - - - - -} +void TopicEditor::onTimeChanged() {} void TopicEditor::onApplySequence() { - const auto seq = createCurrentSequence(); - if (seq.start.time_since_epoch().count() == 0 || seq.duration.count() == 0) - return; + const auto seq = createCurrentSequence(); + if (seq.start.time_since_epoch().count() == 0 || seq.duration.count() == 0) + return; - const auto rows = m_model->highlightedRows(); + const auto rows = m_model->highlightedRows(); - if (rows.count() != 1) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("Please select a sequence from the sequence list first, then click 'Edit' to edit a sequence in the editor.")); - return; - } + if (rows.count() != 1) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("Please select a sequence from the sequence list first, then " + "click 'Edit' to edit a sequence in the editor.")); + return; + } - m_model->setRowData(rows.first(), seq); + m_model->setRowData(rows.first(), seq); - refreshDurationText(); - slotChangesMade(); + refreshDurationText(); + slotChangesMade(); } void TopicEditor::onAddSequence() { - qint64 start = m_ui->dtStart->msecsSinceEpoch(); - qint64 end = m_ui->dtEnd->msecsSinceEpoch(); + qint64 start = m_ui->dtStart->msecsSinceEpoch(); + qint64 end = m_ui->dtEnd->msecsSinceEpoch(); - if (start == 0 || end == 0 || end < start) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("Please check if start and end times are set and the end time is not lower than the start time."), - tr("The start and/or end time you entered is invalid")); - return; - } - - AvsSequence seq = createCurrentSequence(); - - if (seq.pint) - { - - - AvaTimePoint theStart = msecsToAvaTimePoint(m_ui->dtStart->msecsSinceEpoch()); - AvaTimePoint theEnd = msecsToAvaTimePoint(m_ui->dtEnd->msecsSinceEpoch()); - - QueryTimeline *qt = m_playbackMenu->queryTimeline(theStart, theEnd); - - if (qt == nullptr) + if (start == 0 || end == 0 || end < start) { - new LtsWidgets::LtsMessageDialogNew(this, tr("Currently unable to request sequences from the audio / video system.
Please try again later.")); - return; + new LtsWidgets::LtsMessageDialogNew( + this, tr("Please check if start and end times are set and the end time is not lower than the start time."), + tr("The start and/or end time you entered is invalid")); + return; } + AvsSequence seq = createCurrentSequence(); - setOverlay(new QWidget()); - - - connect(qt, &QueryTimeline::signalTimelineComplete, - this, [this, theStart, theEnd](const AvaTimeline &timeline) + if (seq.pint) { + + AvaTimePoint theStart = msecsToAvaTimePoint(m_ui->dtStart->msecsSinceEpoch()); + AvaTimePoint theEnd = msecsToAvaTimePoint(m_ui->dtEnd->msecsSinceEpoch()); + + QueryTimeline* qt = m_playbackMenu->queryTimeline(theStart, theEnd); + + if (qt == nullptr) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("Currently unable to request sequences from the audio / video " + "system.
Please try again later.")); + return; + } + + setOverlay(new QWidget()); + + connect( + qt, &QueryTimeline::signalTimelineComplete, this, [this, theStart, theEnd](const AvaTimeline& timeline) { #if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0) - auto unchangableReset = qScopeGuard([this] { unsetOverlay(); }); + auto unchangableReset = qScopeGuard([this] { unsetOverlay(); }); #else std::shared_ptr unchangeableReset(nullptr, [this](int *) { unsetOverlay(); }); #endif - static const QString msgTitle(tr("Sequences needed to be determined for audio / video clips with skipped silence")); - const QVector &parts = timeline.parts(); + static const QString msgTitle( + tr("Sequences needed to be determined for audio / video clips with skipped silence")); + const QVector& parts = timeline.parts(); - if (parts.isEmpty()) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("No sequences could be found inside the specified range.
Please select another range that contains audio / video."), - msgTitle); - return; - } + if (parts.isEmpty()) + { + new LtsWidgets::LtsMessageDialogNew( + this, + tr("No sequences could be found inside the specified range.
Please select another range " + "that contains audio / video."), + msgTitle); + return; + } - QStringList partsStrings; + QStringList partsStrings; - for (const AvaTimelinePart &part : parts) - { - AvaTimePoint start = part.first; - AvaTimePoint end = part.second; + for (const AvaTimelinePart& part : parts) + { + AvaTimePoint start = part.first; + AvaTimePoint end = part.second; - if (theStart > start) - start = theStart; - if (theEnd < end) - end = theEnd; + if (theStart > start) + start = theStart; + if (theEnd < end) + end = theEnd; - qint64 duration = std::chrono::duration_cast(end - start).count(); - qint64 secs = duration / 1000; - qint64 msecs = (duration % 1000); - QString durationString(QStringLiteral("%1.%2").arg(secs).arg(msecs, 3, 10, QLatin1Char('0'))); + qint64 duration = std::chrono::duration_cast(end - start).count(); + qint64 secs = duration / 1000; + qint64 msecs = (duration % 1000); + QString durationString(QStringLiteral("%1.%2").arg(secs).arg(msecs, 3, 10, QLatin1Char('0'))); - partsStrings += QStringLiteral("%1 - %2 (%3 %4)").arg(msecsSinceEpochToStringz(std::chrono::milliseconds(start.time_since_epoch()).count()), - msecsSinceEpochToStringz(std::chrono::milliseconds(end.time_since_epoch()).count()), - durationString, - tr("seconds")); - } + partsStrings += + QStringLiteral("%1 - %2 (%3 %4)") + .arg(msecsSinceEpochToStringz(std::chrono::milliseconds(start.time_since_epoch()).count()), + msecsSinceEpochToStringz(std::chrono::milliseconds(end.time_since_epoch()).count()), + durationString, tr("seconds")); + } - - - #ifdef AskUserSequenceList - auto msg = new LtsWidgets::LtsMessageDialogNew(this, tr("The following sequences were determined:

%1

Do you want to add the listed sequences to the sequences list?").arg(partsStrings.join(QStringLiteral("
"))), - msgTitle, LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel, { { LtsWidgets::Button::Yes, tr("Add") } }); + auto msg = new LtsWidgets::LtsMessageDialogNew( + this, + tr("The following sequences were determined:

%1

Do you want to add the " + "listed sequences to the sequences list?") + .arg(partsStrings.join(QStringLiteral("
"))), + msgTitle, LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel, + {{LtsWidgets::Button::Yes, tr("Add")}}); - connect(msg, &LtsWidgets::LtsMessageDialogNew::yes, - this, [this, parts, theStart, theEnd]() - #endif - { - m_model->setHighlightedRow(-1); - - for (const AvaTimelinePart &part : parts) - { - AvaTimePoint start = part.first; - AvaTimePoint end = part.second; - - if (theStart > start) - start = theStart; - if (theEnd < end) - end = theEnd; - - m_model->insertRow(createSequence(start, end)); - int row = m_model->rowCount() - 1; - QModelIndex idx = m_model->index(row, 0); - - if (!idx.isValid()) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("One or more sequences could not be added to the sequences list.
Please try again later."), - msgTitle); - return; - } - - m_model->setHighlightedRow(row, false ); - m_ui->tvSequences->setCurrentIndex(idx); - } - - refreshDurationText(); - m_ui->pbApply->setEnabled(true); - slotChangesMade(); - } -#ifdef AskUserSequenceList - ); + connect(msg, &LtsWidgets::LtsMessageDialogNew::yes, this, + [this, parts, theStart, theEnd]() #endif + { + m_model->setHighlightedRow(-1); - }); + for (const AvaTimelinePart& part : parts) + { + AvaTimePoint start = part.first; + AvaTimePoint end = part.second; - return; - } + if (theStart > start) + start = theStart; + if (theEnd < end) + end = theEnd; + m_model->insertRow(createSequence(start, end)); + int row = m_model->rowCount() - 1; + QModelIndex idx = m_model->index(row, 0); - if (seq.start.time_since_epoch().count() == 0 || seq.duration.count() == 0) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("Start and end times are not valid. Please check if your input values are valid.")); - return; - } + if (!idx.isValid()) + { + new LtsWidgets::LtsMessageDialogNew( + this, + tr("One or more sequences could not be added to the sequences list.
Please try again later."), + msgTitle); + return; + } - m_model->insertRow(seq); + m_model->setHighlightedRow(row, false); + m_ui->tvSequences->setCurrentIndex(idx); + } - int row = m_model->rowCount() - 1; - QModelIndex idx = m_model->index(row, 0); + refreshDurationText(); + m_ui->pbApply->setEnabled(true); + slotChangesMade(); + } +#ifdef AskUserSequenceList + ); +#endif + }); - if (!idx.isValid()) - return; + return; + } - m_model->setHighlightedRow(row); - m_ui->tvSequences->setCurrentIndex(idx); + if (seq.start.time_since_epoch().count() == 0 || seq.duration.count() == 0) + { + new LtsWidgets::LtsMessageDialogNew( + this, tr("Start and end times are not valid. Please check if your input values are valid.")); + return; + } - refreshDurationText(); - m_ui->pbApply->setEnabled(true); - slotChangesMade(); + m_model->insertRow(seq); + + int row = m_model->rowCount() - 1; + QModelIndex idx = m_model->index(row, 0); + + if (!idx.isValid()) + return; + + m_model->setHighlightedRow(row); + m_ui->tvSequences->setCurrentIndex(idx); + + refreshDurationText(); + m_ui->pbApply->setEnabled(true); + slotChangesMade(); } void TopicEditor::onDeleteSequences() { - const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); - QVector rowIds; - rowIds.reserve(selRows.size()); - for (const QModelIndex &idx : selRows) - rowIds += idx.row(); - std::sort(rowIds.begin(), rowIds.end(), std::greater()); + const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); + QVector rowIds; + rowIds.reserve(selRows.size()); + for (const QModelIndex& idx : selRows) + rowIds += idx.row(); + std::sort(rowIds.begin(), rowIds.end(), std::greater()); - const auto rows = m_model->highlightedRows(); - int curEditedRow = -1; + const auto rows = m_model->highlightedRows(); + int curEditedRow = -1; - if (rows.count() == 1) - curEditedRow = rows.first(); + if (rows.count() == 1) + curEditedRow = rows.first(); - for (int row : std::as_const(rowIds)) - { - m_model->removeRow(row); - if (curEditedRow == row) + for (int row : std::as_const(rowIds)) { - curEditedRow = -1; - m_model->setHighlightedRow(curEditedRow); - m_ui->pbApply->setEnabled(false); - onEnaDisa(); + m_model->removeRow(row); + if (curEditedRow == row) + { + curEditedRow = -1; + m_model->setHighlightedRow(curEditedRow); + m_ui->pbApply->setEnabled(false); + onEnaDisa(); + } + if (curEditedRow > row) + --curEditedRow; } - if (curEditedRow > row) - --curEditedRow; - } - m_model->setHighlightedRow(curEditedRow); - refreshDurationText(); - slotChangesMade(); + m_model->setHighlightedRow(curEditedRow); + refreshDurationText(); + slotChangesMade(); } void TopicEditor::onSequenceUp() { - m_model->moveUp(m_ui->tvSequences->currentIndex()); - slotChangesMade(); + m_model->moveUp(m_ui->tvSequences->currentIndex()); + slotChangesMade(); } void TopicEditor::onSequenceDown() { - m_model->moveDown(m_ui->tvSequences->currentIndex()); - slotChangesMade(); + m_model->moveDown(m_ui->tvSequences->currentIndex()); + slotChangesMade(); } void TopicEditor::onSetTopicButtonStates(bool enable) { - if (enable && m_topicStartTime) - m_ui->dtStart->setMsecsSinceEpoch(m_topicStartTime); + if (enable && m_topicStartTime) + m_ui->dtStart->setMsecsSinceEpoch(m_topicStartTime); } void TopicEditor::onEnaDisa() { - const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); - const bool hasSelection = (selRows.size() != 0); - const bool hasSingleSelection = (selRows.size() == 1); + const auto selRows = m_ui->tvSequences->selectionModel()->selectedRows(); + const bool hasSelection = (selRows.size() != 0); + const bool hasSingleSelection = (selRows.size() == 1); - m_ui->pbEditSequence->setEnabled(hasSingleSelection); - m_ui->pbDelete->setEnabled(hasSelection); - m_ui->pbDown->setEnabled(hasSingleSelection); - m_ui->pbUp->setEnabled(hasSingleSelection); + m_ui->pbEditSequence->setEnabled(hasSingleSelection); + m_ui->pbDelete->setEnabled(hasSelection); + m_ui->pbDown->setEnabled(hasSingleSelection); + m_ui->pbUp->setEnabled(hasSingleSelection); } -void TopicEditor::onMarkerSelected(const QString &description) +void TopicEditor::onMarkerSelected(const QString& description) { - m_ui->leDescription->setText(description); + m_ui->leDescription->setText(description); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.h old mode 100755 new mode 100644 index 52b6d0003..fd977db9d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/TopicEditor/topic_editor.h @@ -1,10 +1,9 @@ - #pragma once -#include "avm_sequence_model.h" #include "../avm_playback_menu.h" +#include "avm_sequence_model.h" #include #include @@ -12,63 +11,65 @@ #include #include - -namespace Ui { class AVTopicEditor; } - +namespace Ui +{ +class AVTopicEditor; +} namespace AudioVideoManagement { class TopicEditor : public TopicEditorBase::TopicEditor { - Q_OBJECT + Q_OBJECT -public: - explicit TopicEditor(LtsSession::LtsSession *session, const TopicEditorBase::TopicData &data, QWidget *parent = nullptr); - ~TopicEditor(); + public: + explicit TopicEditor(LtsSession::LtsSession* session, const TopicEditorBase::TopicData& data, + QWidget* parent = nullptr); + ~TopicEditor(); -private: - NGL::INGLLogger &m_logger; - void updateInternalData() override final; - void retranslate() override final; + private: + NGL::INGLLogger& m_logger; + void updateInternalData() override final; + void retranslate() override final; - AvsSequence createSequence(const AvaTimePoint &start, const AvaTimePoint &end) const; - AvsSequence createCurrentSequence() const; - void refreshDurationText(); - void setDurationText(qint64 length); - qint64 calcTrackLength(const QJsonArray &arr) const; - void playbackDlgNotAvailable(const QString &msg); + AvsSequence createSequence(const AvaTimePoint& start, const AvaTimePoint& end) const; + AvsSequence createCurrentSequence() const; + void refreshDurationText(); + void setDurationText(qint64 length); + qint64 calcTrackLength(const QJsonArray& arr) const; + void playbackDlgNotAvailable(const QString& msg); -private slots: - bool apply2() override final; + private slots: + bool apply2() override final; - void onEditSequence(); - void onTimeChanged(); - void onApplySequence(); - void onAddSequence(); - void onDeleteSequences(); - void onSequenceUp(); - void onSequenceDown(); - void onSetTopicButtonStates(bool enable); - void onEnaDisa(); - void onMarkerSelected(const QString &description); + void onEditSequence(); + void onTimeChanged(); + void onApplySequence(); + void onAddSequence(); + void onDeleteSequences(); + void onSequenceUp(); + void onSequenceDown(); + void onSetTopicButtonStates(bool enable); + void onEnaDisa(); + void onMarkerSelected(const QString& description); -private: - NGL::INGLLogger &m_logger; - const int s_durationLimit{86400000}; + private: + NGL::INGLLogger& m_logger; + const int s_durationLimit{86400000}; - LtsSession::LtsSession *m_session{nullptr}; - std::shared_ptr m_avmDataIfc{nullptr}; + LtsSession::LtsSession* m_session{nullptr}; + std::shared_ptr m_avmDataIfc{nullptr}; - AvmSequenceModel *m_model{nullptr}; - AvmSequenceProxyModel *m_proxyModel{nullptr}; - AvmPlaybackMenu *m_playbackMenu{nullptr}; + AvmSequenceModel* m_model{nullptr}; + AvmSequenceProxyModel* m_proxyModel{nullptr}; + AvmPlaybackMenu* m_playbackMenu{nullptr}; - bool m_isAudio{false}; - qint64 m_topicStartTime{0}; - QString m_topicStreamName; + bool m_isAudio{false}; + qint64 m_topicStartTime{0}; + QString m_topicStreamName; - Ui::AVTopicEditor *m_ui{nullptr}; + Ui::AVTopicEditor* m_ui{nullptr}; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.cpp old mode 100755 new mode 100644 index 0d20abd55..bf90483de --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.cpp @@ -1,317 +1,273 @@ - #include "avm_available_streams_model.h" + #include #include -#include - -#include -#include #include +#include +#include +#include namespace { -bool isMountingPointOfInterest(const InfrastructureManagement::StructureElement &se, bool isAudio) +bool isMountingPointOfInterest(const InfrastructureManagement::StructureElement& se, bool isAudio) { - if (se.structureElementTypeId() != InfrastructureManagement::StructureElementType::MountingPoint) + if (se.structureElementTypeId() != InfrastructureManagement::StructureElementType::MountingPoint) + return false; + + if (se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::IndoorCamera || + se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::OutdoorCamera) + return true; + + if (isAudio && se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::AnnouncementUnit) + return true; + return false; - - - - - if (se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::IndoorCamera || - se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::OutdoorCamera) - return true; - - if (isAudio && se.mountingPointTypeId() == InfrastructureManagement::MountingPointType::AnnouncementUnit) - return true; - - return false; } -} - - +} // namespace namespace AudioVideoManagement { const QString AvailableStreamsModel::s_MimeType = QStringLiteral("AvailStreamsModel/DragDrop"); - - struct sorter { - bool operator()(const StreamModelData &i, const StreamModelData &j) - { - QCollator col; - col.setNumericMode(true); - return col.compare(j.name, i.name) > 0 ; - } + bool operator()(const StreamModelData& i, const StreamModelData& j) + { + QCollator col; + col.setNumericMode(true); + return col.compare(j.name, i.name) > 0; + } } sortStuff; - -AvailableStreamsModel::AvailableStreamsModel(const std::shared_ptr &avmDtc, - const std::shared_ptr &ismDtc, - LtsSession::LtsSession *session, - StreamNameMapping *streamNameMapping, - QObject *parent, - bool isAudio) : NGLTreeModel(parent, new NGLTreeItem(QVariant(), QIcon()),, - m_logger(NGL::NGLLoggerBootstrap::getLogger()) {tr("Available Streams")}) -, m_isAudio(isAudio) -, m_avmDtc(avmDtc) -, m_ismDtc(ismDtc) -, m_session(session) -, m_streamNameMapping(streamNameMapping) +AvailableStreamsModel::AvailableStreamsModel(const std::shared_ptr& avmDtc, + const std::shared_ptr& ismDtc, + LtsSession::LtsSession* session, StreamNameMapping* streamNameMapping, + QObject* parent, bool isAudio) + : NGLTreeModel(parent, new NGLTreeItem(QVariant(), QIcon()), , + m_logger(NGL::NGLLoggerBootstrap::getLogger()){tr("Available Streams")}), + m_isAudio(isAudio), m_avmDtc(avmDtc), m_ismDtc(ismDtc), m_session(session), m_streamNameMapping(streamNameMapping) { - Q_ASSERT(ismDtc); - Q_ASSERT(streamNameMapping); - qRegisterMetaTypeStreamOperators("StreamModelData"); - qRegisterMetaType("StreamModelData"); + Q_ASSERT(ismDtc); + Q_ASSERT(streamNameMapping); + qRegisterMetaTypeStreamOperators("StreamModelData"); + qRegisterMetaType("StreamModelData"); - setMimeType(s_MimeType); - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, - this, [ this]() - { + setMimeType(s_MimeType); + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + [this]() { initModel(); }); + + connect(m_streamNameMapping, &StreamNameMapping::changed, this, [this]() { initModel(); }); + + if (!m_isAudio) + { + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, this, + [this]() { initModel(); }); + } initModel(); - }); - - connect(m_streamNameMapping, &StreamNameMapping::changed, - this, [ this]() - { - initModel(); - }); - - if (!m_isAudio) - { - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, - this, [ this]() - { - initModel(); - }); - } - initModel(); } -QVariant AvailableStreamsModel::data(const QModelIndex &index, int role) const +QVariant AvailableStreamsModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) - return QVariant(); + if (!index.isValid()) + return QVariant(); - NGLTreeItem *item = privateData(index); - if (!item->data().canConvert()) - return QVariant(); + NGLTreeItem* item = privateData(index); + if (!item->data().canConvert()) + return QVariant(); - const StreamModelData availStream = item->data().value(); + const StreamModelData availStream = item->data().value(); - switch (role) - { - case Qt::DisplayRole: - { - switch (index.column()) + switch (role) { - case 0 : - return availStream.name; - default: - return QStringLiteral("??"); + case Qt::DisplayRole: { + switch (index.column()) + { + case 0: + return availStream.name; + default: + return QStringLiteral("??"); + } + break; + } + case Qt::DecorationRole: { + switch (index.column()) + { + case 0: { + static const QIcon folder(QStringLiteral("icon:evaluation_folder.svg")); + static const QIcon camera(QStringLiteral("icon:camera_control.svg")); + return availStream.isGroup ? folder : camera; + } + default: + break; + } + break; + } + default: + break; } - break; - } - case Qt::DecorationRole: - { - switch (index.column()) - { - case 0: - { - static const QIcon folder(QStringLiteral("icon:evaluation_folder.svg")); - static const QIcon camera(QStringLiteral("icon:camera_control.svg")); - return availStream.isGroup ? folder : camera; - } - default: - break; - } - break; - } - default: - break; - } - return NGLTreeModel::data(index, role); + return NGLTreeModel::data(index, role); } - -Qt::ItemFlags AvailableStreamsModel::flags(const QModelIndex &index) const +Qt::ItemFlags AvailableStreamsModel::flags(const QModelIndex& index) const { - Qt::ItemFlags defaultFlags = NGLTreeModel::flags(index); - NGLTreeItem *item = privateData(index); + Qt::ItemFlags defaultFlags = NGLTreeModel::flags(index); + NGLTreeItem* item = privateData(index); - if (item == m_rootItem) - return defaultFlags; + if (item == m_rootItem) + return defaultFlags; - return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags; + return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags; } - -QMimeData *AvailableStreamsModel::mimeData(const QModelIndexList &indexes) const +QMimeData* AvailableStreamsModel::mimeData(const QModelIndexList& indexes) const { - - QMimeData *pData = NGLTreeModel::mimeData(indexes); - pData->setText(data(indexes[0]).toString()); - return pData; + + QMimeData* pData = NGLTreeModel::mimeData(indexes); + pData->setText(data(indexes[0]).toString()); + return pData; } - -bool AvailableStreamsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool AvailableStreamsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - INFO_LOG(m_logger) << "dropMimeData: action = " << action - << ", row = " << row - << ", parent: valid = " << parent.isValid(); + INFO_LOG(m_logger) << "dropMimeData: action = " << action << ", row = " << row + << ", parent: valid = " << parent.isValid(); - if (action == Qt::IgnoreAction) - return true; + if (action == Qt::IgnoreAction) + return true; - if (!data->hasFormat(s_MimeType)) - return false; + if (!data->hasFormat(s_MimeType)) + return false; - if ((action != Qt::MoveAction) && (action != Qt::CopyAction)) - return false; + if ((action != Qt::MoveAction) && (action != Qt::CopyAction)) + return false; - return NGLTreeModel::dropMimeData(data, action, row, column, parent); + return NGLTreeModel::dropMimeData(data, action, row, column, parent); } - void AvailableStreamsModel::initModel() { - beginResetModel(); - INFO_LOG(m_logger) << "initModel"; - - - m_rootItem->removeAllChildren(); - - StreamModelData availStream; - availStream.id = 0; - availStream.name = tr("New group"); - availStream.parentId = -1; - availStream.isGroup = true; + beginResetModel(); + INFO_LOG(m_logger) << "initModel"; - QVariant data; - data.setValue(availStream); - m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); + m_rootItem->removeAllChildren(); - std::vector toAddIndoor; - std::vector toAddOutdoor; + StreamModelData availStream; + availStream.id = 0; + availStream.name = tr("New group"); + availStream.parentId = -1; + availStream.isGroup = true; - std::vector toAddMvs; + QVariant data; + data.setValue(availStream); + m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); + std::vector toAddIndoor; + std::vector toAddOutdoor; - const auto &mountedAssets = m_ismDtc->mountingPointAssets(); - const auto &buildings = m_ismDtc->mainStructureElements(); - for (const auto &building : buildings) - { - for (const auto &mountingPoint : building.elements()) + std::vector toAddMvs; + + const auto& mountedAssets = m_ismDtc->mountingPointAssets(); + const auto& buildings = m_ismDtc->mainStructureElements(); + for (const auto& building : buildings) { - if (!isMountingPointOfInterest(mountingPoint, m_isAudio)) - continue; - - - bool isMounted = false; - for (const auto &mountedAsset : mountedAssets) - { - if (mountedAsset.structureElementId() == mountingPoint.id()) + for (const auto& mountingPoint : building.elements()) { - isMounted = true; - break; + if (!isMountingPointOfInterest(mountingPoint, m_isAudio)) + continue; + + bool isMounted = false; + for (const auto& mountedAsset : mountedAssets) + { + if (mountedAsset.structureElementId() == mountingPoint.id()) + { + isMounted = true; + break; + } + } + + if (!isMounted) + continue; + StreamModelData item; + item.name = m_streamNameMapping->displayName(mountingPoint.id()); + item.mountingPointId = mountingPoint.id(); + item.isGroup = false; + + if (mountingPoint.mountingPointTypeId() == InfrastructureManagement::MountingPointType::IndoorCamera) + toAddIndoor.push_back(item); + else + toAddOutdoor.push_back(item); } - } - - if (!isMounted) - continue; - StreamModelData item; - item.name = m_streamNameMapping->displayName(mountingPoint.id()); - item.mountingPointId = mountingPoint.id(); - item.isGroup = false; - - - if (mountingPoint.mountingPointTypeId() == InfrastructureManagement::MountingPointType::IndoorCamera) - toAddIndoor.push_back(item); - else - toAddOutdoor.push_back(item); - } - } - - - if (!m_isAudio) - { - const auto &mvsStreams = m_avmDtc->videoTeams(); - for (const auto &videoTeam : mvsStreams) + if (!m_isAudio) { - if (videoTeam.exerciseId() != m_session->exerciseId()) - continue; - DEBUG_LOG(m_logger) << "add new videoteam" << videoTeam; - StreamModelData item; - item.name = QString::fromStdString(videoTeam.streamName().c_str()); - item.mountingPointId = -1 * videoTeam.id(); - item.isGroup = false; + const auto& mvsStreams = m_avmDtc->videoTeams(); + for (const auto& videoTeam : mvsStreams) + { + if (videoTeam.exerciseId() != m_session->exerciseId()) + continue; + DEBUG_LOG(m_logger) << "add new videoteam" << videoTeam; + StreamModelData item; + item.name = QString::fromStdString(videoTeam.streamName().c_str()); + item.mountingPointId = -1 * videoTeam.id(); + item.isGroup = false; - - toAddMvs.push_back(item); - + toAddMvs.push_back(item); + } } - } + std::sort(toAddOutdoor.begin(), toAddOutdoor.end(), sortStuff); + for (const auto& item : toAddOutdoor) + { + data.setValue(item); + m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); + } - + std::sort(toAddIndoor.begin(), toAddIndoor.end(), sortStuff); + for (const auto& item : toAddIndoor) + { + data.setValue(item); + m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); + } - - std::sort(toAddOutdoor.begin(), toAddOutdoor.end(), sortStuff); - for (const auto &item : toAddOutdoor) - { - data.setValue(item); - m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); - } - - std::sort(toAddIndoor.begin(), toAddIndoor.end(), sortStuff); - for (const auto &item : toAddIndoor) - { - data.setValue(item); - m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); - } - - std::sort(toAddMvs.begin(), toAddMvs.end(), sortStuff); - for (const auto &item : toAddMvs) - { - data.setValue(item); - m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); - } - endResetModel(); + std::sort(toAddMvs.begin(), toAddMvs.end(), sortStuff); + for (const auto& item : toAddMvs) + { + data.setValue(item); + m_rootItem->appendChild(new NGLTreeItem(data, QIcon())); + } + endResetModel(); } -StreamModelData StreamModelData::createFromServiceItem(const AvMenuEntry &entry, StreamNameMapping *streamNameMapping, const QMap &videoTeamList) +StreamModelData StreamModelData::createFromServiceItem(const AvMenuEntry& entry, StreamNameMapping* streamNameMapping, + const QMap& videoTeamList) { - StreamModelData data; - data.id = entry.id(); - data.parentId = entry.parentId(); - data.isGroup = entry.isGroup(); - if (entry.isGroup()) - data.name = QString::fromStdString(entry.name().get()); - else - { - if (entry.mountingPointId().is_set() && (entry.mountingPointId().get() > 0)) - { - data.mountingPointId = entry.mountingPointId().get(); - data.name = streamNameMapping->displayName(entry.mountingPointId().get()); - } + StreamModelData data; + data.id = entry.id(); + data.parentId = entry.parentId(); + data.isGroup = entry.isGroup(); + if (entry.isGroup()) + data.name = QString::fromStdString(entry.name().get()); else { - data.mountingPointId = entry.mountingPointId().get(); - data.name = QString::fromStdString(videoTeamList.value(entry.mountingPointId().get() * -1).streamName()); + if (entry.mountingPointId().is_set() && (entry.mountingPointId().get() > 0)) + { + data.mountingPointId = entry.mountingPointId().get(); + data.name = streamNameMapping->displayName(entry.mountingPointId().get()); + } + else + { + data.mountingPointId = entry.mountingPointId().get(); + data.name = QString::fromStdString(videoTeamList.value(entry.mountingPointId().get() * -1).streamName()); + } } - } - return data; + return data; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.h old mode 100755 new mode 100644 index 5686c3be6..1ced322df --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_available_streams_model.h @@ -2,103 +2,86 @@ #pragma once -#include #include #include -#include +#include #include -#include +#include #include +#include class NGLTreeItem; - namespace InfrastructureManagement { namespace Interface { class Dtc; } -} - +} // namespace InfrastructureManagement namespace AudioVideoManagement { class StreamNameMapping; - - struct StreamModelData { - qint64 id = 0; - qint64 parentId = 0; - bool isGroup = false; - QString name; - qint32 mountingPointId = 0; + qint64 id = 0; + qint64 parentId = 0; + bool isGroup = false; + QString name; + qint32 mountingPointId = 0; - static StreamModelData createFromServiceItem(const AvMenuEntry &entry, StreamNameMapping *streamNameMapping, const QMap &videoTeamList); + static StreamModelData createFromServiceItem(const AvMenuEntry& entry, StreamNameMapping* streamNameMapping, + const QMap& videoTeamList); - friend QDataStream &operator<<(QDataStream &out, - const StreamModelData &myObj) - { - out << myObj.id - << myObj.parentId - << myObj.isGroup - << myObj.name - << myObj.mountingPointId; - return out; - } + friend QDataStream& operator<<(QDataStream& out, const StreamModelData& myObj) + { + out << myObj.id << myObj.parentId << myObj.isGroup << myObj.name << myObj.mountingPointId; + return out; + } - friend QDataStream &operator>>(QDataStream &in, - StreamModelData &myObj) - { - in >> myObj.id - >> myObj.parentId - >> myObj.isGroup - >> myObj.name - >> myObj.mountingPointId; + friend QDataStream& operator>>(QDataStream& in, StreamModelData& myObj) + { + in >> myObj.id >> myObj.parentId >> myObj.isGroup >> myObj.name >> myObj.mountingPointId; - return in; - } + return in; + } }; - - - class AvailableStreamsModel : public NGLTreeModel { - Q_OBJECT -public: - static const QString s_MimeType; + Q_OBJECT + public: + static const QString s_MimeType; - AvailableStreamsModel(const std::shared_ptr &avmDtc, - const std::shared_ptr &ismDtc, - LtsSession::LtsSession *session, - StreamNameMapping *streamNameMapping, - QObject *parent, - bool isAudio); + AvailableStreamsModel(const std::shared_ptr& avmDtc, + const std::shared_ptr& ismDtc, + LtsSession::LtsSession* session, StreamNameMapping* streamNameMapping, QObject* parent, + bool isAudio); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QMimeData *mimeData(const QModelIndexList &indexes) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QMimeData* mimeData(const QModelIndexList& indexes) const override; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) override; - Qt::DropActions supportedDragActions() const override { return Qt::CopyAction; } + Qt::DropActions supportedDragActions() const override + { + return Qt::CopyAction; + } -private: + private: + NGL::INGLLogger& m_logger; + void initModel(); -NGL::INGLLogger &m_logger; - void initModel(); - - const bool m_isAudio; - const std::shared_ptr m_avmDtc; - const std::shared_ptr m_ismDtc; - LtsSession::LtsSession *m_session; - StreamNameMapping *m_streamNameMapping; + const bool m_isAudio; + const std::shared_ptr m_avmDtc; + const std::shared_ptr m_ismDtc; + LtsSession::LtsSession* m_session; + StreamNameMapping* m_streamNameMapping; }; -} +} // namespace AudioVideoManagement Q_DECLARE_METATYPE(AudioVideoManagement::StreamModelData) - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.cpp old mode 100755 new mode 100644 index 41bb26cfa..da67098a1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.cpp @@ -1,121 +1,108 @@ - #include "avm_choose_menu.h" -#include "ui_avm_choose_menu.h" -#include -#include -#include -#include -#include +#include "ui_avm_choose_menu.h" + +#include +#include +#include +#include +#include namespace AudioVideoManagement { -ChooseMenu::ChooseMenu(Interface::Dtc *dtc, AvsMenus *avsMenus, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_dtc(dtc) - , m_avsMenus(avsMenus) - , m_ui(new Ui::ChooseMenuStruct) +ChooseMenu::ChooseMenu(Interface::Dtc* dtc, AvsMenus* avsMenus, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_dtc(dtc), m_avsMenus(avsMenus), + m_ui(new Ui::ChooseMenuStruct) { - Q_ASSERT(dtc); - Q_ASSERT(avsMenus); + Q_ASSERT(dtc); + Q_ASSERT(avsMenus); - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(dtc, &Interface::Dtc::menuStructChanged, this, &ChooseMenu::onMenuStructChanged); - m_dtc->menuStructs([this](const MenuStruct & menu) { onMenuStructChanged(menu, DataModification::eAdded);}); - selectCurrent(); + connect(dtc, &Interface::Dtc::menuStructChanged, this, &ChooseMenu::onMenuStructChanged); + m_dtc->menuStructs([this](const MenuStruct& menu) { onMenuStructChanged(menu, DataModification::eAdded); }); + selectCurrent(); - connect(m_ui->cbAudio, &QComboBox::currentTextChanged, this, &ChooseMenu::slotChangesMade); - connect(m_ui->cbVideo, &QComboBox::currentTextChanged, this, &ChooseMenu::slotChangesMade); + connect(m_ui->cbAudio, &QComboBox::currentTextChanged, this, &ChooseMenu::slotChangesMade); + connect(m_ui->cbVideo, &QComboBox::currentTextChanged, this, &ChooseMenu::slotChangesMade); - setOnlineHelpFilename(QStringLiteral("Situation-Choose_AV_Menu")); + setOnlineHelpFilename(QStringLiteral("Situation-Choose_AV_Menu")); } - - ChooseMenu::~ChooseMenu() { - delete m_ui; + delete m_ui; } void ChooseMenu::retranslate() { - translate(m_ui, tr("Choose AV Menu")); + translate(m_ui, tr("Choose AV Menu")); } - - -void ChooseMenu::onMenuStructChanged(const MenuStruct &data, DataModification modType) +void ChooseMenu::onMenuStructChanged(const MenuStruct& data, DataModification modType) { - switch (modType) - { - case DataModification::eAdded: - { - if (data.isAudio()) - m_ui->cbAudio->addItem(QString::fromStdString(data.name()), data.id()); - else - m_ui->cbVideo->addItem(QString::fromStdString(data.name()), data.id()); - break; - } + switch (modType) + { + case DataModification::eAdded: { + if (data.isAudio()) + m_ui->cbAudio->addItem(QString::fromStdString(data.name()), data.id()); + else + m_ui->cbVideo->addItem(QString::fromStdString(data.name()), data.id()); + break; + } - case DataModification::eRemoved: - { - if (data.isAudio()) - { - int index = m_ui->cbAudio->findData(data.id()); - m_ui->cbAudio->removeItem(index); + case DataModification::eRemoved: { + if (data.isAudio()) + { + int index = m_ui->cbAudio->findData(data.id()); + m_ui->cbAudio->removeItem(index); + } + else + { + int index = m_ui->cbVideo->findData(data.id()); + m_ui->cbVideo->removeItem(index); + } + break; + } + case DataModification::eModified: + break; } - else - { - int index = m_ui->cbVideo->findData(data.id()); - m_ui->cbVideo->removeItem(index); - } - break; - } - case DataModification::eModified: - break; - } } - - bool ChooseMenu::apply() { - int menuId = m_ui->cbAudio->currentData().toInt(); - INFO_LOG(m_logger) << "MenuId Audio: " << menuId; - m_avsMenus->setAnnouncementMenu(menuId); + int menuId = m_ui->cbAudio->currentData().toInt(); + INFO_LOG(m_logger) << "MenuId Audio: " << menuId; + m_avsMenus->setAnnouncementMenu(menuId); - menuId = m_ui->cbVideo->currentData().toInt(); - INFO_LOG(m_logger) << "MenuId Video: " << menuId; - m_avsMenus->setVideoMenu(menuId); - - return true; + menuId = m_ui->cbVideo->currentData().toInt(); + INFO_LOG(m_logger) << "MenuId Video: " << menuId; + m_avsMenus->setVideoMenu(menuId); + return true; } void ChooseMenu::selectCurrent() { - selectMenu(m_avsMenus->currentAnnouncementMenu(), m_ui->cbAudio); - selectMenu(m_avsMenus->currentVideoMenu(), m_ui->cbVideo); + selectMenu(m_avsMenus->currentAnnouncementMenu(), m_ui->cbAudio); + selectMenu(m_avsMenus->currentVideoMenu(), m_ui->cbVideo); } -void ChooseMenu::selectMenu(int menuId, QComboBox *cb) +void ChooseMenu::selectMenu(int menuId, QComboBox* cb) { - Q_ASSERT(cb); + Q_ASSERT(cb); - if (menuId < 0) - return; + if (menuId < 0) + return; - int index = cb->findData(menuId); - if (index < 0) - return; + int index = cb->findData(menuId); + if (index < 0) + return; - cb->setCurrentIndex(index); + cb->setCurrentIndex(index); } - - -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.h old mode 100755 new mode 100644 index a6ef676d1..dc852f65c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_choose_menu.h @@ -1,11 +1,9 @@ - #pragma once - -#include #include +#include enum class DataModification; @@ -32,26 +30,25 @@ class AvsMenus; class ChooseMenu : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - ChooseMenu(Interface::Dtc *dtc, AvsMenus *avsMenus, QWidget *parent = nullptr); - ~ChooseMenu() override; + public: + ChooseMenu(Interface::Dtc* dtc, AvsMenus* avsMenus, QWidget* parent = nullptr); + ~ChooseMenu() override; -private slots: - void onMenuStructChanged(const MenuStruct &data, DataModification modType); + private slots: + void onMenuStructChanged(const MenuStruct& data, DataModification modType); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override final; + void selectCurrent(); + void selectMenu(int menuId, QComboBox* cb); -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override final; - void selectCurrent(); - void selectMenu(int menuId, QComboBox *cb); - - Interface::Dtc *m_dtc; - AvsMenus *m_avsMenus; - Ui::ChooseMenuStruct *m_ui; + Interface::Dtc* m_dtc; + AvsMenus* m_avsMenus; + Ui::ChooseMenuStruct* m_ui; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.cpp old mode 100755 new mode 100644 index db39cdff2..15b573410 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.cpp @@ -1,152 +1,128 @@ - #include "avm_menu_edit.h" + #include "ui_avm_menu_edit.h" + #include namespace AudioVideoManagement { -MenuEdit::MenuEdit(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ftc(nullptr) - , m_ui(new Ui::MenuEdit) - , m_availStreamsModel(nullptr) - , m_usedStreamsModel(nullptr) - , m_isAudio(false) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +MenuEdit::MenuEdit(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ftc(nullptr), + m_ui(new Ui::MenuEdit), m_availStreamsModel(nullptr), m_usedStreamsModel(nullptr), m_isAudio(false), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - -} - + m_ui->setupUi(this); +} MenuEdit::~MenuEdit() { - delete m_ui; -} - - + delete m_ui; +} void MenuEdit::retranslate() { - if (m_isAudio) - translate(m_ui, tr("Edit Audio Menu: %1").arg(m_name)); - else - translate(m_ui, tr("Edit Video Menu: %1").arg(m_name)); -} + if (m_isAudio) + translate(m_ui, tr("Edit Audio Menu: %1").arg(m_name)); + else + translate(m_ui, tr("Edit Video Menu: %1").arg(m_name)); +} - - -bool MenuEdit::init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ismDtc, - StreamNameMapping *streamNameMapping, - const MenuStruct &ms) +bool MenuEdit::init(LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ismDtc, + StreamNameMapping* streamNameMapping, const MenuStruct& ms) { - DEBUG_LOG(m_logger) << "MenuEdit::init()"; + DEBUG_LOG(m_logger) << "MenuEdit::init()"; - if (!ftc || !dtc) - { - ERROR_LOG(m_logger) << "MenuEdit::init() Invalid shared_ptr!"; - return false; - } + if (!ftc || !dtc) + { + ERROR_LOG(m_logger) << "MenuEdit::init() Invalid shared_ptr!"; + return false; + } - m_ftc = ftc; - m_isAudio = ms.isAudio(); - m_name = QString::fromStdString(ms.name()); + m_ftc = ftc; + m_isAudio = ms.isAudio(); + m_name = QString::fromStdString(ms.name()); - m_availStreamsModel = new AvailableStreamsModel(dtc, ismDtc, session, streamNameMapping, this, m_isAudio); - m_ui->availTreeView->setModel(m_availStreamsModel); + m_availStreamsModel = new AvailableStreamsModel(dtc, ismDtc, session, streamNameMapping, this, m_isAudio); + m_ui->availTreeView->setModel(m_availStreamsModel); - m_usedStreamsModel = new UsedStreamsModel(dtc, ismDtc, ms, streamNameMapping, this); - m_ui->menuTreeView->setModel(m_usedStreamsModel); - m_ui->menuTreeView->expandAll(); + m_usedStreamsModel = new UsedStreamsModel(dtc, ismDtc, ms, streamNameMapping, this); + m_ui->menuTreeView->setModel(m_usedStreamsModel); + m_ui->menuTreeView->expandAll(); - connect(m_ui->menuTreeView, &QTreeView::clicked, - this, &MenuEdit::onStreamSelected); - connect(m_usedStreamsModel, &UsedStreamsModel::modelDataChanged, - this, &MenuEdit::slotChangesMade); + connect(m_ui->menuTreeView, &QTreeView::clicked, this, &MenuEdit::onStreamSelected); + connect(m_usedStreamsModel, &UsedStreamsModel::modelDataChanged, this, &MenuEdit::slotChangesMade); - connect(m_usedStreamsModel, &UsedStreamsModel::modelDataChanged, - this, &MenuEdit::onModelDataChanged); + connect(m_usedStreamsModel, &UsedStreamsModel::modelDataChanged, this, &MenuEdit::onModelDataChanged); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove); - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Remove), &QPushButton::clicked, - this, &MenuEdit::onRemove); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove); + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Remove), &QPushButton::clicked, this, &MenuEdit::onRemove); - onStreamSelected(QModelIndex()); + onStreamSelected(QModelIndex()); - - if (m_isAudio) - setOnlineHelpFilename(QStringLiteral("Situation-Audio_Menu")); - else - setOnlineHelpFilename(QStringLiteral("Situation-Video_Menu")); + if (m_isAudio) + setOnlineHelpFilename(QStringLiteral("Situation-Audio_Menu")); + else + setOnlineHelpFilename(QStringLiteral("Situation-Video_Menu")); - if (ms.id() <= 0) - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Apply, false); - - return true; -} + if (ms.id() <= 0) + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Apply, false); + return true; +} bool MenuEdit::apply() { - MenuStruct ms = m_usedStreamsModel->getMenuStruct(); - ms.isAudio(m_isAudio); + MenuStruct ms = m_usedStreamsModel->getMenuStruct(); + ms.isAudio(m_isAudio); - bool ret = m_requestHelper->startSingleRequest([this, ms]() - { - - return m_ftc->modifyMenuStructRequest(ms, this); - }); - - return ret; -} + bool ret = m_requestHelper->startSingleRequest([this, ms]() { return m_ftc->modifyMenuStructRequest(ms, this); }); + return ret; +} void MenuEdit::onRemove() { - - if (0 == m_ui->menuTreeView->selectionModel()->selectedIndexes().size()) - { - - QModelIndex index = m_ui->menuTreeView->currentIndex(); - if (!index.isValid()) - return; - slotChangesMade(); - - DEBUG_LOG(m_logger) << "index row: " << index.row(); - m_usedStreamsModel->removeRow(index.row(), index.parent()); - } - else - { - while (m_ui->menuTreeView->selectionModel()->selectedIndexes().size() > 0) + if (0 == m_ui->menuTreeView->selectionModel()->selectedIndexes().size()) { - QModelIndex index = m_ui->menuTreeView->selectionModel()->selectedIndexes().front(); - if (!index.isValid()) - return; - slotChangesMade(); - DEBUG_LOG(m_logger) << "index row: " << index.row(); - m_usedStreamsModel->removeRow(index.row(), index.parent()); + QModelIndex index = m_ui->menuTreeView->currentIndex(); + if (!index.isValid()) + return; + slotChangesMade(); + DEBUG_LOG(m_logger) << "index row: " << index.row(); + m_usedStreamsModel->removeRow(index.row(), index.parent()); + } + else + { + while (m_ui->menuTreeView->selectionModel()->selectedIndexes().size() > 0) + { + QModelIndex index = m_ui->menuTreeView->selectionModel()->selectedIndexes().front(); + if (!index.isValid()) + return; + slotChangesMade(); + + DEBUG_LOG(m_logger) << "index row: " << index.row(); + m_usedStreamsModel->removeRow(index.row(), index.parent()); + } } - } } void MenuEdit::onModelDataChanged() { - INFO_LOG(m_logger) << "onModelDataChanged"; - m_ui->menuTreeView->expandAll(); + INFO_LOG(m_logger) << "onModelDataChanged"; + m_ui->menuTreeView->expandAll(); } -void MenuEdit::onStreamSelected(const QModelIndex &idx) +void MenuEdit::onStreamSelected(const QModelIndex& idx) { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, idx.isValid()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, idx.isValid()); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.h old mode 100755 new mode 100644 index e9b2a86fa..a112d9d99 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit.h @@ -1,32 +1,28 @@ - #pragma once #include "avm_available_streams_model.h" #include "avm_used_streams_model.h" -#include -#include -#include #include +#include #include - +#include +#include namespace Ui { class MenuEdit; } - namespace InfrastructureManagement { namespace Interface { class Dtc; } -} - +} // namespace InfrastructureManagement namespace AudioVideoManagement { @@ -34,46 +30,45 @@ namespace AudioVideoManagement class StreamNameMapping; class MenuEdit : public LtsWidgets::LtsDialog, - protected AudioVideoManagement::Interface::Ftc::ModifyMenuStructReplyHandler + protected AudioVideoManagement::Interface::Ftc::ModifyMenuStructReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit MenuEdit(QWidget *parent = nullptr); + public: + explicit MenuEdit(QWidget* parent = nullptr); - ~MenuEdit(); + ~MenuEdit(); - bool init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ismDtc, - StreamNameMapping *streamNameMapping, - const MenuStruct &ms); + bool init(LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ismDtc, + StreamNameMapping* streamNameMapping, const MenuStruct& ms); - - void onModifyMenuStructReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onModifyMenuStructReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -public slots: - void onRemove(); - void onModelDataChanged(); - void onStreamSelected(const QModelIndex &idx); + public slots: + void onRemove(); + void onModelDataChanged(); + void onStreamSelected(const QModelIndex& idx); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override final; -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override final; + std::shared_ptr m_ftc; + Ui::MenuEdit* m_ui; + AvailableStreamsModel* m_availStreamsModel; + UsedStreamsModel* m_usedStreamsModel; + bool m_isAudio; + QString m_name; + LtsUtils::RequestHelper* m_requestHelper; - std::shared_ptr m_ftc; - Ui::MenuEdit *m_ui; - AvailableStreamsModel *m_availStreamsModel; - UsedStreamsModel *m_usedStreamsModel; - bool m_isAudio; - QString m_name; - LtsUtils::RequestHelper *m_requestHelper; - - AudioVideoManagement::MenuStruct m_lastDdsMenuStruct; - AudioVideoManagement::MenuStruct m_modifiedMenuStruct; + AudioVideoManagement::MenuStruct m_lastDdsMenuStruct; + AudioVideoManagement::MenuStruct m_modifiedMenuStruct; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.cpp old mode 100755 new mode 100644 index f6cb3b841..1e5c8d52b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.cpp @@ -1,245 +1,209 @@ - #include "avm_menu_edit_view.h" -#include "ui_avm_menu_edit_view.h" + #include "avm_menu_edit.h" #include "avm_new_menu_struct.h" +#include "ui_avm_menu_edit_view.h" +#include +#include #include #include -#include - -#include #include namespace AudioVideoManagement { -MenuEditView::MenuEditView(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_menuGroup(menuGroup) - , m_model(nullptr) - , m_isAudio(false) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_session(session) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::MenuEditView) +MenuEditView::MenuEditView(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_menuGroup(menuGroup), m_model(nullptr), + m_isAudio(false), m_dtc(nullptr), m_ftc(nullptr), m_session(session), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::MenuEditView) { - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &MenuEditView::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &MenuEditView::onSelectionChanged); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &MenuEditView::onEditMenuStruct); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &MenuEditView::onEditMenuStruct); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MenuEditView::onEditMenuStruct); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MenuEditView::onRemoveMenuStruct); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MenuEditView::onAddMenuStruct); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &MenuEditView::onPrint); - -} + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MenuEditView::onEditMenuStruct); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MenuEditView::onRemoveMenuStruct); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MenuEditView::onAddMenuStruct); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &MenuEditView::onPrint); +} MenuEditView::~MenuEditView() { - delete m_ui; -} - + delete m_ui; +} void MenuEditView::retranslate() { - if (m_isAudio) - translate(m_ui, tr("Audio Menu")); - else - translate(m_ui, tr("Video Menu")); -} + if (m_isAudio) + translate(m_ui, tr("Audio Menu")); + else + translate(m_ui, tr("Video Menu")); +} - -bool MenuEditView::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ismDtc, - StreamNameMapping *streamNameMapping, - bool isAudio) +bool MenuEditView::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ismDtc, + StreamNameMapping* streamNameMapping, bool isAudio) { - Q_ASSERT(dtc); - Q_ASSERT(ftc); - Q_ASSERT(ismDtc); - Q_ASSERT(streamNameMapping); + Q_ASSERT(dtc); + Q_ASSERT(ftc); + Q_ASSERT(ismDtc); + Q_ASSERT(streamNameMapping); - m_dtc = dtc; - m_ftc = ftc; - m_ismDtc = ismDtc; - m_streamNameMapping = streamNameMapping; - m_model = new MenuViewModel(this); - m_model->initModel(m_dtc, isAudio); - m_ui->widget->setModel(m_model); - m_isAudio = isAudio; + m_dtc = dtc; + m_ftc = ftc; + m_ismDtc = ismDtc; + m_streamNameMapping = streamNameMapping; + m_model = new MenuViewModel(this); + m_model->initModel(m_dtc, isAudio); + m_ui->widget->setModel(m_model); + m_isAudio = isAudio; #ifndef LTS_DEBUG - m_ui->widget->hideColumn(0); + m_ui->widget->hideColumn(0); #endif - m_ui->widget->setSortIndicator(1, Qt::AscendingOrder); + m_ui->widget->setSortIndicator(1, Qt::AscendingOrder); - - m_buttonBox->connectLibraryButton(this, - &MenuEditView::onImportButtonClicked, - &MenuEditView::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &MenuEditView::onImportButtonClicked, &MenuEditView::onExportButtonClicked); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - if (m_isAudio) - setOnlineHelpFilename(QStringLiteral("Situation-Audio_Menu")); - else - setOnlineHelpFilename(QStringLiteral("Situation-Video_Menu")); - - return true; -} + if (m_isAudio) + setOnlineHelpFilename(QStringLiteral("Situation-Audio_Menu")); + else + setOnlineHelpFilename(QStringLiteral("Situation-Video_Menu")); + return true; +} void MenuEditView::onSelectionChanged() { - const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (row >= 0)); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (row >= 0)); + const QModelIndex idx = m_ui->widget->currentIndex(); + int row = idx.row(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (row >= 0)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (row >= 0)); } void MenuEditView::onAddMenuStruct() { - NewMenuStruct *newDialog = new NewMenuStruct(this); + NewMenuStruct* newDialog = new NewMenuStruct(this); - connect(newDialog, &NewMenuStruct::newName, this, [this](const QString & name) - { - MenuStruct ms; - ms.name(name.toStdString()); - ms.isAudio(m_isAudio); - MenuEdit *dialog = new MenuEdit(this); - dialog->init(m_session, m_dtc, m_ftc, m_ismDtc, m_streamNameMapping, ms); + connect(newDialog, &NewMenuStruct::newName, this, [this](const QString& name) { + MenuStruct ms; + ms.name(name.toStdString()); + ms.isAudio(m_isAudio); + MenuEdit* dialog = new MenuEdit(this); + dialog->init(m_session, m_dtc, m_ftc, m_ismDtc, m_streamNameMapping, ms); - addDialog(dialog, m_menuGroup, QLatin1String("avmNewMenu") + name, LtsWidgets::LayoutArea::eDialogTab); - }); - newDialog->show(); - - connect(newDialog, &NewMenuStruct::accepted, newDialog, &NewMenuStruct::deleteLater); - -} + addDialog(dialog, m_menuGroup, QLatin1String("avmNewMenu") + name, LtsWidgets::LayoutArea::eDialogTab); + }); + newDialog->show(); + connect(newDialog, &NewMenuStruct::accepted, newDialog, &NewMenuStruct::deleteLater); +} void MenuEditView::onEditMenuStruct() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - AudioVideoManagement::MenuStruct ms = m_model->getRowData(row); - ms.isAudio(m_isAudio); + AudioVideoManagement::MenuStruct ms = m_model->getRowData(row); + ms.isAudio(m_isAudio); - DEBUG_LOG(m_logger) << "---onEditMenuStruct () " - << " id: " << ms.id() - << " name: " << ms.name(); + DEBUG_LOG(m_logger) << "---onEditMenuStruct () " + << " id: " << ms.id() << " name: " << ms.name(); - MenuEdit *dialog = new MenuEdit(this); - dialog->init(m_session, m_dtc, m_ftc, m_ismDtc, m_streamNameMapping, ms); + MenuEdit* dialog = new MenuEdit(this); + dialog->init(m_session, m_dtc, m_ftc, m_ismDtc, m_streamNameMapping, ms); - addDialog(dialog, m_menuGroup, QLatin1String("avmMenuEdit") + QString::number(ms.id()), LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, QLatin1String("avmMenuEdit") + QString::number(ms.id()), + LtsWidgets::LayoutArea::eDialogTab); } - void MenuEditView::onRemoveMenuStruct() { - const QModelIndex idx = m_ui->widget->currentIndex(); - if (!idx.isValid()) - return; - const AudioVideoManagement::MenuStruct ms = m_model->getRowData(idx.row()); - const Core::RemoveElementRequest req(ms.id()); - m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->removeMenuStructRequest(req, this); - }); + const QModelIndex idx = m_ui->widget->currentIndex(); + if (!idx.isValid()) + return; + const AudioVideoManagement::MenuStruct ms = m_model->getRowData(idx.row()); + const Core::RemoveElementRequest req(ms.id()); + m_requestHelper->startSingleRequest([req, this]() { return m_ftc->removeMenuStructRequest(req, this); }); - if (m_model->rowCount() == 0) - { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - } + if (m_model->rowCount() == 0) + { + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + } } void MenuEditView::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } void MenuEditView::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } - - void MenuEditView::onExportButtonClicked() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - QByteArray byteArray = m_model->modelToJson(row); - - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + QByteArray byteArray = m_model->modelToJson(row); + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void MenuEditView::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMMenuEditView)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMMenuEditView))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMMenuEditView)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - const QVector menuStructs = m_model->jsonToMenuStructs(content); - for (const AudioVideoManagement::MenuStruct &request : menuStructs) - { - m_requestHelper->startSingleRequest([this, request]() + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMMenuEditView))) { - return m_ftc->modifyMenuStructRequest(request, this); - }); - } + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + const QVector menuStructs = m_model->jsonToMenuStructs(content); + for (const AudioVideoManagement::MenuStruct& request : menuStructs) + { + m_requestHelper->startSingleRequest( + [this, request]() { return m_ftc->modifyMenuStructRequest(request, this); }); + } + } + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; } - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; - } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.h old mode 100755 new mode 100644 index e2cd0c69b..9cb636810 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_edit_view.h @@ -1,31 +1,28 @@ - #pragma once #include "avm_menu_view_model.h" -#include -#include -#include #include #include +#include #include +#include +#include namespace Ui { class MenuEditView; } - namespace InfrastructureManagement { namespace Interface { class Dtc; } -} - +} // namespace InfrastructureManagement namespace AudioVideoManagement { @@ -33,51 +30,56 @@ namespace AudioVideoManagement class StreamNameMapping; class MenuEditView : public LtsWidgets::LtsDialog, - protected AudioVideoManagement::Interface::Ftc::ModifyMenuStructReplyHandler, - protected AudioVideoManagement::Interface::Ftc::RemoveMenuStructReplyHandler + protected AudioVideoManagement::Interface::Ftc::ModifyMenuStructReplyHandler, + protected AudioVideoManagement::Interface::Ftc::RemoveMenuStructReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit MenuEditView(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~MenuEditView(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ismDtc, - StreamNameMapping *streamNameMapping, - bool isAudio); + public: + explicit MenuEditView(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~MenuEditView(); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ismDtc, + StreamNameMapping* streamNameMapping, bool isAudio); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onAddMenuStruct(); + void onEditMenuStruct(); + void onRemoveMenuStruct(); -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onAddMenuStruct(); - void onEditMenuStruct(); - void onRemoveMenuStruct(); + void onModifyMenuStructReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - void onModifyMenuStructReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onRemoveMenuStructReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onRemoveMenuStructReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - void onPrint(); - void tableColumnOrganiserSetting() override; + void onPrint(); + void tableColumnOrganiserSetting() override; -private slots: - void onExportButtonClicked(); - void onImportButtonClicked(); + private slots: + void onExportButtonClicked(); + void onImportButtonClicked(); -private: - QString m_menuGroup; - MenuViewModel *m_model; - bool m_isAudio; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_flmGui; - std::shared_ptr m_ismDtc; - StreamNameMapping *m_streamNameMapping{nullptr}; - LtsSession::LtsSession *m_session; - LtsUtils::RequestHelper *m_requestHelper; - Ui::MenuEditView *m_ui; + private: + QString m_menuGroup; + MenuViewModel* m_model; + bool m_isAudio; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_flmGui; + std::shared_ptr m_ismDtc; + StreamNameMapping* m_streamNameMapping{nullptr}; + LtsSession::LtsSession* m_session; + LtsUtils::RequestHelper* m_requestHelper; + Ui::MenuEditView* m_ui; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.cpp old mode 100755 new mode 100644 index bd08bc14b..11d178bca --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.cpp @@ -1,150 +1,136 @@ - #include "avm_menu_view_model.h" -#include +#include #include -#include #include +#include namespace AudioVideoManagement { - - - - -MenuViewModel::MenuViewModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Name")}, - parent) - , m_isAudio(false) - , m_dtc(nullptr) -{} - - -bool MenuViewModel::initModel(const std::shared_ptr &dtc, bool isAudio) +MenuViewModel::MenuViewModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel({tr("Id"), tr("Name")}, parent), + m_isAudio(false), m_dtc(nullptr) { - m_isAudio = isAudio; - m_dtc = dtc; - - connect(m_dtc.get(), &AudioVideoManagement::Interface::Dtc::menuStructChanged, - this, &MenuViewModel::onDataChanged); - - - m_dtc->menuStructs([this](const AudioVideoManagement::MenuStruct &ms) { insertRow(ms); }); - - return true; } - -QVariant MenuViewModel::data(const QModelIndex &index, int role) const +bool MenuViewModel::initModel(const std::shared_ptr& dtc, bool isAudio) { - if (role != Qt::DisplayRole || !indexIsValid(index)) + m_isAudio = isAudio; + m_dtc = dtc; + + connect(m_dtc.get(), &AudioVideoManagement::Interface::Dtc::menuStructChanged, this, &MenuViewModel::onDataChanged); + + m_dtc->menuStructs([this](const AudioVideoManagement::MenuStruct& ms) { insertRow(ms); }); + + return true; +} + +QVariant MenuViewModel::data(const QModelIndex& index, int role) const +{ + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const AudioVideoManagement::MenuStruct& ms = m_vecData.at(index.row()); + + switch (index.column()) + { + case 0: + return ms.id(); + case 1: + return QString::fromStdString(ms.name()); + default: + break; + } + return QVariant(); - - const AudioVideoManagement::MenuStruct &ms = m_vecData.at(index.row()); - - switch (index.column()) - { - case 0: - return ms.id(); - case 1: - return QString::fromStdString(ms.name()); - default: - break; - } - - return QVariant(); } -bool MenuViewModel::isFiltered(const MenuStruct &data, DataModification modType) const +bool MenuViewModel::isFiltered(const MenuStruct& data, DataModification modType) const { - Q_UNUSED(modType); - if (data.isAudio() != m_isAudio) - return true; - if (data.isDefault()) - return true; - return false; + Q_UNUSED(modType); + if (data.isAudio() != m_isAudio) + return true; + if (data.isDefault()) + return true; + return false; } QByteArray MenuViewModel::modelToJson(int row) const { - if (row < 0 || row >= m_vecData.size()) - return QByteArray("{}"); + if (row < 0 || row >= m_vecData.size()) + return QByteArray("{}"); - QJsonObject obj; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMMenuEditView); + QJsonObject obj; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMMenuEditView); - DEBUG_LOG(m_logger) << "row =" << ": " << row; - const AudioVideoManagement::MenuStruct &menuStruct = m_vecData.at(row); + DEBUG_LOG(m_logger) << "row =" << ": " << row; + const AudioVideoManagement::MenuStruct& menuStruct = m_vecData.at(row); - obj[QStringLiteral("id")] = 0; - obj[QStringLiteral("isAudio")] = menuStruct.isAudio(); - obj[QStringLiteral("isDefault")] = menuStruct.isDefault(); - obj[QStringLiteral("name")] = QString::fromStdString(menuStruct.name()); + obj[QStringLiteral("id")] = 0; + obj[QStringLiteral("isAudio")] = menuStruct.isAudio(); + obj[QStringLiteral("isDefault")] = menuStruct.isDefault(); + obj[QStringLiteral("name")] = QString::fromStdString(menuStruct.name()); - - QJsonArray arrData; - for (const AudioVideoManagement::AvMenuEntry &avMenuEntry : menuStruct.menuEntries()) - { - QJsonObject innerData; - innerData[QStringLiteral("id")] = avMenuEntry.id(); - innerData[QStringLiteral("isGroup")] = avMenuEntry.isGroup(); - if (avMenuEntry.mountingPointId().is_set()) - innerData[QStringLiteral("mountingPointId")] = avMenuEntry.mountingPointId().get(); - if (avMenuEntry.name().is_set()) - innerData[QStringLiteral("name")] = QString::fromStdString(avMenuEntry.name().get()); - innerData[QStringLiteral("parentId")] = avMenuEntry.parentId(); - innerData[QStringLiteral("rowId")] = avMenuEntry.rowId(); + QJsonArray arrData; + for (const AudioVideoManagement::AvMenuEntry& avMenuEntry : menuStruct.menuEntries()) + { + QJsonObject innerData; + innerData[QStringLiteral("id")] = avMenuEntry.id(); + innerData[QStringLiteral("isGroup")] = avMenuEntry.isGroup(); + if (avMenuEntry.mountingPointId().is_set()) + innerData[QStringLiteral("mountingPointId")] = avMenuEntry.mountingPointId().get(); + if (avMenuEntry.name().is_set()) + innerData[QStringLiteral("name")] = QString::fromStdString(avMenuEntry.name().get()); + innerData[QStringLiteral("parentId")] = avMenuEntry.parentId(); + innerData[QStringLiteral("rowId")] = avMenuEntry.rowId(); - arrData += innerData; - } - obj[QStringLiteral("menuEntries")] = arrData; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + arrData += innerData; + } + obj[QStringLiteral("menuEntries")] = arrData; + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -QVector MenuViewModel::jsonToMenuStructs(const QByteArray &content) const +QVector MenuViewModel::jsonToMenuStructs(const QByteArray& content) const { - - QVector result; - AudioVideoManagement::MenuStruct menuStruct; - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); - menuStruct.id(0); - menuStruct.isAudio(obj[QStringLiteral("isAudio")].toBool()); - menuStruct.isDefault(obj[QStringLiteral("isDefault")].toBool()); - menuStruct.name(obj[QStringLiteral("name")].toString().toStdString()); - + QVector result; + AudioVideoManagement::MenuStruct menuStruct; + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); + menuStruct.id(0); + menuStruct.isAudio(obj[QStringLiteral("isAudio")].toBool()); + menuStruct.isDefault(obj[QStringLiteral("isDefault")].toBool()); + menuStruct.name(obj[QStringLiteral("name")].toString().toStdString()); - const QJsonArray arrEntry(obj.value(QStringLiteral("menuEntries")).toArray()); - menuStruct.menuEntries().resize(arrEntry.size()); - INFO_LOG(m_logger) << "arrEntry.size()=" << arrEntry.size(); - for (int j = 0; j < arrEntry.size(); ++j) - { - const QJsonObject objEntry(arrEntry.at(j).toObject()); - AudioVideoManagement::AvMenuEntry avMenuEntry; + const QJsonArray arrEntry(obj.value(QStringLiteral("menuEntries")).toArray()); + menuStruct.menuEntries().resize(arrEntry.size()); + INFO_LOG(m_logger) << "arrEntry.size()=" << arrEntry.size(); + for (int j = 0; j < arrEntry.size(); ++j) + { + const QJsonObject objEntry(arrEntry.at(j).toObject()); + AudioVideoManagement::AvMenuEntry avMenuEntry; - avMenuEntry.id(-10000000 + objEntry[QStringLiteral("id")].toInt()); - avMenuEntry.isGroup(objEntry[QStringLiteral("isGroup")].toBool()); - avMenuEntry.mountingPointId(objEntry[QStringLiteral("mountingPointId")].toInt()); - if (objEntry.contains(QStringLiteral("name"))) - avMenuEntry.name().set(objEntry[QStringLiteral("name")].toString().toStdString()); - if (objEntry[QStringLiteral("isGroup")].toBool()) - avMenuEntry.parentId(0); - else - avMenuEntry.parentId(-10000000 + objEntry[QStringLiteral("parentId")].toInt()); - avMenuEntry.rowId(objEntry[QStringLiteral("rowId")].toInt()); + avMenuEntry.id(-10000000 + objEntry[QStringLiteral("id")].toInt()); + avMenuEntry.isGroup(objEntry[QStringLiteral("isGroup")].toBool()); + avMenuEntry.mountingPointId(objEntry[QStringLiteral("mountingPointId")].toInt()); + if (objEntry.contains(QStringLiteral("name"))) + avMenuEntry.name().set(objEntry[QStringLiteral("name")].toString().toStdString()); + if (objEntry[QStringLiteral("isGroup")].toBool()) + avMenuEntry.parentId(0); + else + avMenuEntry.parentId(-10000000 + objEntry[QStringLiteral("parentId")].toInt()); + avMenuEntry.rowId(objEntry[QStringLiteral("rowId")].toInt()); - menuStruct.menuEntries()[j] = avMenuEntry; - } - - result.append(menuStruct); + menuStruct.menuEntries()[j] = avMenuEntry; + } - return result; + result.append(menuStruct); + + return result; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.h old mode 100755 new mode 100644 index 4cb03b46a..08ab5dc14 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_menu_view_model.h @@ -1,35 +1,31 @@ - #pragma once #include #include - #include - namespace AudioVideoManagement { - - class MenuViewModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - explicit MenuViewModel(QObject *parent = nullptr); + Q_OBJECT + public: + explicit MenuViewModel(QObject* parent = nullptr); - bool initModel(const std::shared_ptr &dtc, bool isAudio); - QVariant data(const QModelIndex &, int) const override final; - QByteArray modelToJson(int row) const; - QVector jsonToMenuStructs(const QByteArray &content) const; -protected: -NGL::INGLLogger &m_logger; - bool isFiltered(const MenuStruct &data, DataModification modType) const override final; + bool initModel(const std::shared_ptr& dtc, bool isAudio); + QVariant data(const QModelIndex&, int) const override final; + QByteArray modelToJson(int row) const; + QVector jsonToMenuStructs(const QByteArray& content) const; -private: - bool m_isAudio; - std::shared_ptr m_dtc; + protected: + NGL::INGLLogger& m_logger; + bool isFiltered(const MenuStruct& data, DataModification modType) const override final; + + private: + bool m_isAudio; + std::shared_ptr m_dtc; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_new_menu_struct.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_new_menu_struct.h old mode 100755 new mode 100644 index 4cf964595..f47cc1ba2 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_new_menu_struct.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_new_menu_struct.h @@ -1,37 +1,35 @@ - #pragma once #include - #include namespace Ui { class NewMenuStruct; } + namespace AudioVideoManagement { class NewMenuStruct : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT + Q_OBJECT -public: - explicit NewMenuStruct(QWidget *parent = nullptr); - ~NewMenuStruct(); + public: + explicit NewMenuStruct(QWidget* parent = nullptr); + ~NewMenuStruct(); -private Q_SLOTS: - void onSetNewName(); + private Q_SLOTS: + void onSetNewName(); -Q_SIGNALS: - void newName(const QString &); + Q_SIGNALS: + void newName(const QString&); -private: - -NGL::INGLLogger &m_logger; - Ui::NewMenuStruct *m_ui; + private: + NGL::INGLLogger& m_logger; + Ui::NewMenuStruct* m_ui; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.cpp old mode 100755 new mode 100644 index a1db2e0c0..8bdf1c245 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.cpp @@ -1,1675 +1,1535 @@ - #include "avm_playback_menu.h" + #include "TopicEditor/avm_sequence_model.h" + #include #include #include #include #include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include #include +#include +#include #include #include #include #include #include -#include -#include - +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace { - bool isTimezoneValid(char tz) { - tz = toupper(tz); - return !(tz < 'A' || tz == 'J' || tz > 'Z'); + tz = toupper(tz); + return !(tz < 'A' || tz == 'J' || tz > 'Z'); } -int timezone2Hours(char tz, bool *bOk) +int timezone2Hours(char tz, bool* bOk) { - if (!isTimezoneValid(tz)) - { + if (!isTimezoneValid(tz)) + { + if (bOk) + *bOk = false; + return 0; + } if (bOk) - *bOk = false; + *bOk = true; + if (tz < 'J') + return tz - 'A' + 1; + if (tz < 'N') + return tz - 'A'; + if (tz < 'Z') + return 'Z' - tz - 13; + return 0; - } - if (bOk) - *bOk = true; - if (tz < 'J') - return tz - 'A' + 1; - if (tz < 'N') - return tz - 'A'; - if (tz < 'Z') - return 'Z' - tz - 13; - - return 0; } - -const QString &ALL_STREAMS() +const QString& ALL_STREAMS() { - static const QString ALL_STREAMS_ = QStringLiteral("*"); - return ALL_STREAMS_; + static const QString ALL_STREAMS_ = QStringLiteral("*"); + return ALL_STREAMS_; } -} - +} // namespace namespace AudioVideoManagement { - - - class AvmPlaybackMenu::TimelineBuilder : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit TimelineBuilder(AvaControl *avaCtrl) - : m_avaCtrl(avaCtrl) - { - Q_ASSERT(avaCtrl); - } - - - - void queryTimeline(const QVector &streams) - { - m_timeline.clear(); - m_ignoreTimelineCount += m_awaitedTimelineCount; - m_awaitedTimelineCount = streams.size(); - for (const auto &stream : streams) - m_avaCtrl->queryTimeline(stream.toString(), this, &TimelineBuilder::onTimelineReceived); - } - - const AvaTimeline &timeline() const - { - - - - return m_timeline; - } - - - - void reset() - { - m_ignoreTimelineCount = 0; - m_awaitedTimelineCount = 0; - } - -signals: - void timelineComplete(const AvaTimeline &timeline); - -private slots: - void onTimelineReceived(const AvaTimeline &timeline) - { - Q_ASSERT(m_awaitedTimelineCount > 0); - - if (m_ignoreTimelineCount > 0) + public: + explicit TimelineBuilder(AvaControl* avaCtrl) : m_avaCtrl(avaCtrl) { - --m_ignoreTimelineCount; - return; + Q_ASSERT(avaCtrl); } - m_timeline.merge(timeline); + void queryTimeline(const QVector& streams) + { + m_timeline.clear(); + m_ignoreTimelineCount += m_awaitedTimelineCount; + m_awaitedTimelineCount = streams.size(); + for (const auto& stream : streams) + m_avaCtrl->queryTimeline(stream.toString(), this, &TimelineBuilder::onTimelineReceived); + } - if (--m_awaitedTimelineCount > 0) - return; + const AvaTimeline& timeline() const + { - emit timelineComplete(m_timeline); - } + return m_timeline; + } -private: - AvaControl *m_avaCtrl; - AvaTimeline m_timeline; - int m_ignoreTimelineCount{0}; - int m_awaitedTimelineCount{0}; + void reset() + { + m_ignoreTimelineCount = 0; + m_awaitedTimelineCount = 0; + } + + signals: + void timelineComplete(const AvaTimeline& timeline); + + private slots: + + void onTimelineReceived(const AvaTimeline& timeline) + { + Q_ASSERT(m_awaitedTimelineCount > 0); + + if (m_ignoreTimelineCount > 0) + { + --m_ignoreTimelineCount; + return; + } + + m_timeline.merge(timeline); + + if (--m_awaitedTimelineCount > 0) + return; + + emit timelineComplete(m_timeline); + } + + private: + AvaControl* m_avaCtrl; + AvaTimeline m_timeline; + int m_ignoreTimelineCount{0}; + int m_awaitedTimelineCount{0}; }; - - - - class AvmPlaybackMenu::TimeControl : public QObject { - Q_OBJECT + Q_OBJECT -public: - TimeControl(LtsWidgets::LtsMSecDateTimeEdit *dt, QSlider *slider, QLabel *lblStart, QLabel *lblEnd) - : m_dt(dt) - , m_slider(slider) - , m_lblStart(lblStart) - , m_lblEnd(lblEnd) - { - Q_ASSERT(dt); - Q_ASSERT(slider); - Q_ASSERT(lblStart); - Q_ASSERT(lblEnd); - - connect(m_dt, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, this, &TimeControl::onDtChanged); - connect(m_slider, &QSlider::valueChanged, this, &TimeControl::onSliderChanged); - } - - - QString dateTimeToString(const QDateTime &dt) - { - return dt.toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")); - } - - - QString msecsSinceEpochToString(qint64 msecs) - { - return dateTimeToString(QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); - } - - - void setTimezoneHoursOffset(int timezoneHoursOffset) - { - m_timezoneHoursOffset = timezoneHoursOffset; - - if (!m_interval.is_initialized()) - return; - - - - m_lblStart->setText(msecsSinceEpochToString(toMSecSinceEpoch(m_interval->first))); - m_lblEnd->setText(msecsSinceEpochToString(toMSecSinceEpoch(m_interval->second))); - } - - - void setTime(AvaTimePoint t) - { - QSignalBlocker b1(m_dt); - - if (!m_interval.is_initialized()) + public: + TimeControl(LtsWidgets::LtsMSecDateTimeEdit* dt, QSlider* slider, QLabel* lblStart, QLabel* lblEnd) + : m_dt(dt), m_slider(slider), m_lblStart(lblStart), m_lblEnd(lblEnd) { - m_dt->setMsecsSinceEpoch(AudioVideoManagement::toMSecSinceEpoch(t)); - return; + Q_ASSERT(dt); + Q_ASSERT(slider); + Q_ASSERT(lblStart); + Q_ASSERT(lblEnd); + + connect(m_dt, &LtsWidgets::LtsMSecDateTimeEdit::dateTimeChanged, this, &TimeControl::onDtChanged); + connect(m_slider, &QSlider::valueChanged, this, &TimeControl::onSliderChanged); } - t = timePointInInterval(t); - m_dt->setMsecsSinceEpoch(AudioVideoManagement::toMSecSinceEpoch(t)); + QString dateTimeToString(const QDateTime& dt) + { + return dt.toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")); + } - - QSignalBlocker blocker(m_slider); - AvaDuration delta = t - m_interval->first; - std::chrono::seconds deltaS = std::chrono::duration_cast(delta + std::chrono::milliseconds(500)); - m_slider->setValue(deltaS.count()); - } + QString msecsSinceEpochToString(qint64 msecs) + { + return dateTimeToString( + QDateTime::fromMSecsSinceEpoch(msecs, Qt::TimeSpec::OffsetFromUTC, m_timezoneHoursOffset * 3600)); + } + void setTimezoneHoursOffset(int timezoneHoursOffset) + { + m_timezoneHoursOffset = timezoneHoursOffset; - void setInterval(AvaTimelinePart interval) - { - std::chrono::seconds intervalLength = std::chrono::duration_cast(interval.second - interval.first); + if (!m_interval.is_initialized()) + return; - QSignalBlocker b1(m_slider); - m_slider->setMinimum(0); - m_slider->setMaximum(intervalLength.count()); - m_lblStart->setText(msecsSinceEpochToString(toMSecSinceEpoch(interval.first))); - m_lblEnd->setText(msecsSinceEpochToString(toMSecSinceEpoch(interval.second))); + m_lblStart->setText(msecsSinceEpochToString(toMSecSinceEpoch(m_interval->first))); + m_lblEnd->setText(msecsSinceEpochToString(toMSecSinceEpoch(m_interval->second))); + } - m_interval = interval; - } + void setTime(AvaTimePoint t) + { + QSignalBlocker b1(m_dt); + if (!m_interval.is_initialized()) + { + m_dt->setMsecsSinceEpoch(AudioVideoManagement::toMSecSinceEpoch(t)); + return; + } - AvaTimePoint timePointInInterval(AvaTimePoint t) - { - Q_ASSERT(m_interval.is_initialized()); - if (!m_interval.is_initialized()) - return {}; + t = timePointInInterval(t); + m_dt->setMsecsSinceEpoch(AudioVideoManagement::toMSecSinceEpoch(t)); - if (t < m_interval->first) - return m_interval->first; + QSignalBlocker blocker(m_slider); + AvaDuration delta = t - m_interval->first; + std::chrono::seconds deltaS = + std::chrono::duration_cast(delta + std::chrono::milliseconds(500)); + m_slider->setValue(deltaS.count()); + } - if (t > m_interval->second) - return m_interval->second; + void setInterval(AvaTimelinePart interval) + { + std::chrono::seconds intervalLength = + std::chrono::duration_cast(interval.second - interval.first); - return t; - } + QSignalBlocker b1(m_slider); + m_slider->setMinimum(0); + m_slider->setMaximum(intervalLength.count()); + m_lblStart->setText(msecsSinceEpochToString(toMSecSinceEpoch(interval.first))); + m_lblEnd->setText(msecsSinceEpochToString(toMSecSinceEpoch(interval.second))); + m_interval = interval; + } - AvaTimePoint time() const { return toTimePoint(m_dt->msecsSinceEpoch()); } - qint64 timeMSec() const { return m_dt->msecsSinceEpoch(); } + AvaTimePoint timePointInInterval(AvaTimePoint t) + { + Q_ASSERT(m_interval.is_initialized()); + if (!m_interval.is_initialized()) + return {}; -signals: - void timeChanged(AvaTimePoint currentTime); + if (t < m_interval->first) + return m_interval->first; -private slots: - void onDtChanged() - { - emit timeChanged(toTimePoint(m_dt->msecsSinceEpoch())); - } + if (t > m_interval->second) + return m_interval->second; + return t; + } - void onSliderChanged(int seconds) - { - QSignalBlocker b1(m_dt); - AvaTimePoint t = m_interval->first + std::chrono::seconds(seconds); - m_dt->setMsecsSinceEpoch(toMSecSinceEpoch(t)); - emit timeChanged(toTimePoint(m_dt->msecsSinceEpoch())); - } + AvaTimePoint time() const + { + return toTimePoint(m_dt->msecsSinceEpoch()); + } -private: - LtsWidgets::LtsMSecDateTimeEdit *m_dt; - QSlider *m_slider; - QLabel *m_lblStart; - QLabel *m_lblEnd; - boost::optional m_interval; - int m_timezoneHoursOffset = 0; + qint64 timeMSec() const + { + return m_dt->msecsSinceEpoch(); + } + + signals: + void timeChanged(AvaTimePoint currentTime); + + private slots: + + void onDtChanged() + { + emit timeChanged(toTimePoint(m_dt->msecsSinceEpoch())); + } + + void onSliderChanged(int seconds) + { + QSignalBlocker b1(m_dt); + AvaTimePoint t = m_interval->first + std::chrono::seconds(seconds); + m_dt->setMsecsSinceEpoch(toMSecSinceEpoch(t)); + emit timeChanged(toTimePoint(m_dt->msecsSinceEpoch())); + } + + private: + LtsWidgets::LtsMSecDateTimeEdit* m_dt; + QSlider* m_slider; + QLabel* m_lblStart; + QLabel* m_lblEnd; + boost::optional m_interval; + int m_timezoneHoursOffset = 0; }; +QueryTimeline::QueryTimeline(const AvaStream& stream, const AvaTimePoint& start, const AvaTimePoint& end, + AvaControl* control) + : QObject(), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + connect(control, &AvaControl::queryTimelineResponse, this, &QueryTimeline::signalTimelineComplete); + connect(control, &AvaControl::queryTimelineResponse, this, &QObject::deleteLater); - -QueryTimeline::QueryTimeline(const AvaStream &stream, const AvaTimePoint &start, const AvaTimePoint &end, AvaControl *control) : QObject(), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - connect(control, &AvaControl::queryTimelineResponse, - this, &QueryTimeline::signalTimelineComplete); - connect(control, &AvaControl::queryTimelineResponse, - this, &QObject::deleteLater); - - control->queryTimeline(stream.toString(), start, end); + control->queryTimeline(stream.toString(), start, end); } - - -AvmPlaybackMenu::AvmPlaybackMenu(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::Playback) - , m_requestHelper(new LtsUtils::RequestHelper(this)) -{} - +AvmPlaybackMenu::AvmPlaybackMenu(QWidget* parent) + : QWidget(parent), m_ui(new Ui::Playback), m_requestHelper(new LtsUtils::RequestHelper(this)) +{ +} AvmPlaybackMenu::~AvmPlaybackMenu() { - if (m_selectedStreams) - m_avaCtrl->releaseStream(m_playbackApp.dialogId(), ALL_STREAMS()); - m_playbackApp.hide(true ); + if (m_selectedStreams) + m_avaCtrl->releaseStream(m_playbackApp.dialogId(), ALL_STREAMS()); + m_playbackApp.hide(true); } - -QueryTimeline *AvmPlaybackMenu::queryTimeline(const AvaTimePoint &start, const AvaTimePoint &end) +QueryTimeline* AvmPlaybackMenu::queryTimeline(const AvaTimePoint& start, const AvaTimePoint& end) { - if (!m_currentStream) - return nullptr; + if (!m_currentStream) + return nullptr; - if (m_queryTimelineActive) - return nullptr; + if (m_queryTimelineActive) + return nullptr; - QueryTimeline *qt = new QueryTimeline(m_currentStream.get(), start, end, m_avaCtrl); + QueryTimeline* qt = new QueryTimeline(m_currentStream.get(), start, end, m_avaCtrl); + m_queryTimelineActive = true; + emit signalSetOverlay(new QWidget()); + connect(qt, &QueryTimeline::signalTimelineComplete, this, [this]() { + emit signalUnsetOverlay(); + m_queryTimelineActive = false; + }); - - - - - m_queryTimelineActive = true; - emit signalSetOverlay(new QWidget()); - - connect(qt, &QueryTimeline::signalTimelineComplete, - this, [this]() - { - emit signalUnsetOverlay(); - m_queryTimelineActive = false; - }); - - return qt; + return qt; } - -void AvmPlaybackMenu::setPlaybackPreset(const QString &streamName, const AvaTimePoint &startTime, bool autostartPresetAfterInit) +void AvmPlaybackMenu::setPlaybackPreset(const QString& streamName, const AvaTimePoint& startTime, + bool autostartPresetAfterInit) { - m_presetStreamName = streamName; - m_presetStartTime = startTime; - m_autostartOnce = autostartPresetAfterInit; + m_presetStreamName = streamName; + m_presetStartTime = startTime; + m_autostartOnce = autostartPresetAfterInit; - if (m_timelineIsComplete) - { - onStopClicked(); - processPresets(); - } + if (m_timelineIsComplete) + { + onStopClicked(); + processPresets(); + } } - void AvmPlaybackMenu::setMarkerPreset(int markerId, bool autostartPresetAfterInit) { - m_markerIdPreset = markerId; - m_autostartOnce = autostartPresetAfterInit; + m_markerIdPreset = markerId; + m_autostartOnce = autostartPresetAfterInit; - m_mrkDataIfc->getDtc()->waitForHistoricalDataMarker(8000); + m_mrkDataIfc->getDtc()->waitForHistoricalDataMarker(8000); - m_ui->tabWidget->setCurrentIndex(1); + m_ui->tabWidget->setCurrentIndex(1); - auto idx = m_markerModel->findIndexForId(*m_markerIdPreset); - auto mappedIdx = m_markerProxy->mapFromSource(idx); - m_ui->tvMarker->selectRow(mappedIdx); - m_ui->tvMarker->scrollTo(mappedIdx); - selectMarker(markerId); + auto idx = m_markerModel->findIndexForId(*m_markerIdPreset); + auto mappedIdx = m_markerProxy->mapFromSource(idx); + m_ui->tvMarker->selectRow(mappedIdx); + m_ui->tvMarker->scrollTo(mappedIdx); + selectMarker(markerId); - qWarning() << m_ui->tvMarker->selectionModel()->selectedRows(); + qWarning() << m_ui->tvMarker->selectionModel()->selectedRows(); } - -bool AvmPlaybackMenu::init(LtsSession::LtsSession *session, AvaSession *avaSession, PlaybackAppHandle &&appHandle, - StreamNameMapping *streamNameMapping, bool isAudio, bool insideTopicEditor, - const boost::optional &streamName, const boost::optional &startTime, +bool AvmPlaybackMenu::init(LtsSession::LtsSession* session, AvaSession* avaSession, PlaybackAppHandle&& appHandle, + StreamNameMapping* streamNameMapping, bool isAudio, bool insideTopicEditor, + const boost::optional& streamName, const boost::optional& startTime, bool setInitialSearchContentMarkers) { - Q_ASSERT(avaSession); + Q_ASSERT(avaSession); - - - Q_ASSERT(appHandle); + Q_ASSERT(appHandle); - m_isAudio = isAudio; - m_streamNameMapping = streamNameMapping; + m_isAudio = isAudio; + m_streamNameMapping = streamNameMapping; - m_presetStreamName = streamName; + m_presetStreamName = streamName; - if (m_presetStreamName) - DEBUG_LOG(m_logger) << "init stream preset: " << m_presetStreamName.get(); + if (m_presetStreamName) + DEBUG_LOG(m_logger) << "init stream preset: " << m_presetStreamName.get(); - m_presetStartTime = startTime; + m_presetStartTime = startTime; - if (m_presetStartTime) - DEBUG_LOG(m_logger) << "init time preset: " << std::chrono::milliseconds(m_presetStartTime.get().time_since_epoch()).count(); + if (m_presetStartTime) + DEBUG_LOG(m_logger) << "init time preset: " + << std::chrono::milliseconds(m_presetStartTime.get().time_since_epoch()).count(); - m_session = session; - m_playbackApp = std::move(appHandle); - m_avaCtrl = avaSession->control(); - m_timelineBuilder.reset(new TimelineBuilder(avaSession->control())); + m_session = session; + m_playbackApp = std::move(appHandle); + m_avaCtrl = avaSession->control(); + m_timelineBuilder.reset(new TimelineBuilder(avaSession->control())); - m_ui->setupUi(this); + m_ui->setupUi(this); - m_ui->pbDebug->hide(); + m_ui->pbDebug->hide(); #ifndef LTS_DEBUG - m_ui->lbAvsConnectionStatus->hide(); - m_ui->lblAvsConnectionStatus->hide(); + m_ui->lbAvsConnectionStatus->hide(); + m_ui->lblAvsConnectionStatus->hide(); #endif - m_ui->tabWidget->setCurrentIndex(0); + m_ui->tabWidget->setCurrentIndex(0); - - if (!insideTopicEditor) - m_ui->topicEditorEssentialsWidget->hide(); - else - { - setContentsMargins(QMargins()); - m_ui->tabWidget->setTabText(0, m_isAudio ? tr("Audio clips") : tr("Video clips")); - m_ui->multiStreamWidget->hide(); - m_ui->pbAddStreamClip->hide(); - m_ui->pbAddStreamMarker->hide(); - - - - m_ui->tavIntervals->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->tavIntervals, &QTableView::customContextMenuRequested, - this, [this](const QPoint & pos) + if (!insideTopicEditor) + m_ui->topicEditorEssentialsWidget->hide(); + else { - QMenu *m = new QMenu(this); + setContentsMargins(QMargins()); + m_ui->tabWidget->setTabText(0, m_isAudio ? tr("Audio clips") : tr("Video clips")); + m_ui->multiStreamWidget->hide(); + m_ui->pbAddStreamClip->hide(); + m_ui->pbAddStreamMarker->hide(); - auto a1 = new QAction(tr("Set start and end time"), this); + m_ui->tavIntervals->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->tavIntervals, &QTableView::customContextMenuRequested, this, [this](const QPoint& pos) { + QMenu* m = new QMenu(this); - connect(a1, &QAction::triggered, - this, [this]() - { - auto idxs = m_ui->tavIntervals->selectionModel()->selectedRows(); + auto a1 = new QAction(tr("Set start and end time"), this); - if (idxs.isEmpty()) - return; + connect(a1, &QAction::triggered, this, [this]() { + auto idxs = m_ui->tavIntervals->selectionModel()->selectedRows(); - AvaTimelinePart interval = m_intervalModel.getRowData(idxs.at(0).row()); - emit signalSetStart(toMSecSinceEpoch(interval.first)); - emit signalSetEnd(toMSecSinceEpoch(interval.second)); - }); + if (idxs.isEmpty()) + return; - m->addAction(a1); + AvaTimelinePart interval = m_intervalModel.getRowData(idxs.at(0).row()); + emit signalSetStart(toMSecSinceEpoch(interval.first)); + emit signalSetEnd(toMSecSinceEpoch(interval.second)); + }); - m->popup(m_ui->tavIntervals->viewport()->mapToGlobal(pos)); - }); - } + m->addAction(a1); - m_timeControl.reset(new TimeControl(m_ui->dtCurrentTime, m_ui->slSequenceSlider, m_ui->lblStartSeq, m_ui->lblEndSeq)); + m->popup(m_ui->tavIntervals->viewport()->mapToGlobal(pos)); + }); + } - if (m_isAudio) - m_maxSelectedStreams = 8; + m_timeControl.reset( + new TimeControl(m_ui->dtCurrentTime, m_ui->slSequenceSlider, m_ui->lblStartSeq, m_ui->lblEndSeq)); - m_ui->tavIntervals->setModel(&m_intervalModel); - m_ui->tavIntervals->setSelectionMode(QAbstractItemView::SingleSelection); - m_ui->tavIntervals->setSelectionBehavior(QAbstractItemView::SelectRows); - m_ui->tavIntervals->resizeColumnsToContents(); + if (m_isAudio) + m_maxSelectedStreams = 8; - - if (m_session->getForeignDataInterface(m_mrkDataIfc)) - { - m_markerModel.reset(new MarkerManagement::MarkerManagementDialogModel(this)); - m_markerProxy.reset(new MarkerManagement::MarkerSortFilterProxyModel(this)); - m_markerProxy->setSourceModel(m_markerModel.get()); - std::shared_ptr opmDtc; - m_session->getDtc(opmDtc); - std::shared_ptr flmGui; - m_session->getForeignGuiInterface(flmGui); - m_markerModel->initModel(m_mrkDataIfc->getDtc(), opmDtc, flmGui, true ); - m_ui->tvMarker->setModel(m_markerProxy.get()); - m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColImage); - m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColFileId); - m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColOffset); + m_ui->tavIntervals->setModel(&m_intervalModel); + m_ui->tavIntervals->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->tavIntervals->setSelectionBehavior(QAbstractItemView::SelectRows); + m_ui->tavIntervals->resizeColumnsToContents(); + + if (m_session->getForeignDataInterface(m_mrkDataIfc)) + { + m_markerModel.reset(new MarkerManagement::MarkerManagementDialogModel(this)); + m_markerProxy.reset(new MarkerManagement::MarkerSortFilterProxyModel(this)); + m_markerProxy->setSourceModel(m_markerModel.get()); + std::shared_ptr opmDtc; + m_session->getDtc(opmDtc); + std::shared_ptr flmGui; + m_session->getForeignGuiInterface(flmGui); + m_markerModel->initModel(m_mrkDataIfc->getDtc(), opmDtc, flmGui, true); + m_ui->tvMarker->setModel(m_markerProxy.get()); + m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColImage); + m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColFileId); + m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColOffset); #ifndef LTS_DEBUG - m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColStreams); + m_ui->tvMarker->hideColumn(MarkerManagement::MarkerManagementDialogModel::ColStreams); #endif - if (setInitialSearchContentMarkers) - m_ui->tvMarker->setInitialSearchContent(MarkerManagement::MarkerManagementDialogModel::ColOperator, - LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + if (setInitialSearchContentMarkers) + m_ui->tvMarker->setInitialSearchContent(MarkerManagement::MarkerManagementDialogModel::ColOperator, + LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - connect(m_ui->tvMarker, &LtsDataView::LtsDataView::activated, this, &AvmPlaybackMenu::onMarkerClicked); - connect(m_ui->pbSetMarker, &QPushButton::clicked, this, &AvmPlaybackMenu::onSetMarkerClicked); - } - else - { - m_ui->tabWidget->setTabEnabled(1, false); - } + connect(m_ui->tvMarker, &LtsDataView::LtsDataView::activated, this, &AvmPlaybackMenu::onMarkerClicked); + connect(m_ui->pbSetMarker, &QPushButton::clicked, this, &AvmPlaybackMenu::onSetMarkerClicked); + } + else + { + m_ui->tabWidget->setTabEnabled(1, false); + } + QSignalBlocker blocker1(m_ui->slSpeed); + m_ui->slSpeed->setMinimum(0); + m_ui->slSpeed->setMaximum(AvaSpeed::allowedValues().size() - 1); + m_ui->slSpeed->setSingleStep(1); + m_ui->slSpeed->setPageStep(1); + m_ui->slSpeed->setValue(AvaSpeed::allowedValues().indexOf(AvaSpeed(100))); + m_ui->lbSpeedValue->setText(QString::number(100)); - QSignalBlocker blocker1(m_ui->slSpeed); - m_ui->slSpeed->setMinimum(0); - m_ui->slSpeed->setMaximum(AvaSpeed::allowedValues().size() - 1); - m_ui->slSpeed->setSingleStep(1); - m_ui->slSpeed->setPageStep(1); - m_ui->slSpeed->setValue(AvaSpeed::allowedValues().indexOf(AvaSpeed(100))); - m_ui->lbSpeedValue->setText(QString::number(100)); + m_ui->slSpeed->setVisible(!m_isAudio); + m_ui->lbSpeedValue->setVisible(!m_isAudio); + m_ui->lbSpeed->setVisible(!m_isAudio); + if (m_isAudio) + m_ui->spacerSpeedVolume->changeSize(0, 0); - - m_ui->slSpeed->setVisible(!m_isAudio); - m_ui->lbSpeedValue->setVisible(!m_isAudio); - m_ui->lbSpeed->setVisible(!m_isAudio); - if (m_isAudio) - m_ui->spacerSpeedVolume->changeSize(0, 0); + QSignalBlocker blocker2(m_ui->slVolume); + m_ui->slVolume->setMinimum(AvaVolume::min()); + m_ui->slVolume->setMaximum(AvaVolume::max()); + m_ui->slVolume->setSingleStep(1); + m_ui->slVolume->setPageStep(10); + m_ui->slVolume->setValue(0); + m_ui->lbVolumeValue->setText(QString::number(0)); + m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-nopause.svg"))); - QSignalBlocker blocker2(m_ui->slVolume); - m_ui->slVolume->setMinimum(AvaVolume::min()); - m_ui->slVolume->setMaximum(AvaVolume::max()); - m_ui->slVolume->setSingleStep(1); - m_ui->slVolume->setPageStep(10); - m_ui->slVolume->setValue(0); - m_ui->lbVolumeValue->setText(QString::number(0)); + connect(avaSession, &AvaSession::sessionEstablished, this, &AvmPlaybackMenu::onSessionEstablished); + connect(avaSession, &AvaSession::disconnected, this, &AvmPlaybackMenu::onDisconnected); - m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-nopause.svg"))); + connect(m_timelineBuilder.get(), &TimelineBuilder::timelineComplete, this, &AvmPlaybackMenu::onTimelineComplete); + connect(m_timeControl.get(), &TimeControl::timeChanged, this, &AvmPlaybackMenu::onUiTimeChanged); - connect(avaSession, &AvaSession::sessionEstablished, this, &AvmPlaybackMenu::onSessionEstablished); - connect(avaSession, &AvaSession::disconnected, this, &AvmPlaybackMenu::onDisconnected); + connect(m_avaCtrl->comm(), &AvaComm::streamPositionReceived, this, &AvmPlaybackMenu::onStreamPositionReceived); + connect(m_avaCtrl->comm(), &AvaComm::volumeReceived, this, &AvmPlaybackMenu::onVolumeReceived); + connect(m_avaCtrl, &AvaControl::commandQueueEmpty, this, &AvmPlaybackMenu::onCommandQueueEmpty); - connect(m_timelineBuilder.get(), &TimelineBuilder::timelineComplete, this, &AvmPlaybackMenu::onTimelineComplete); - connect(m_timeControl.get(), &TimeControl::timeChanged, this, &AvmPlaybackMenu::onUiTimeChanged); + connect(m_ui->cbStreams, &QComboBox::currentTextChanged, this, &AvmPlaybackMenu::onStreamSelected); + connect(m_ui->cbMarkerStreams, &QComboBox::currentTextChanged, this, &AvmPlaybackMenu::onMarkerStreamSelected); - connect(m_avaCtrl->comm(), &AvaComm::streamPositionReceived, this, &AvmPlaybackMenu::onStreamPositionReceived); - connect(m_avaCtrl->comm(), &AvaComm::volumeReceived, this, &AvmPlaybackMenu::onVolumeReceived); - connect(m_avaCtrl, &AvaControl::commandQueueEmpty, this, &AvmPlaybackMenu::onCommandQueueEmpty); + connect(&m_intervalModel, &IntervalModel::currentIntervalChanged, this, &AvmPlaybackMenu::onCurrentIntervalChanged); + connect(m_ui->pbStart, &QToolButton::clicked, this, &AvmPlaybackMenu::onStartClicked); + connect(m_ui->pbPause, &QToolButton::clicked, this, &AvmPlaybackMenu::onPauseClicked); + connect(m_ui->pbStop, &QToolButton::clicked, this, &AvmPlaybackMenu::onStopClicked); + connect(m_ui->pbIntervalBackward, &QToolButton::clicked, this, &AvmPlaybackMenu::onIntervalBackwardClicked); + connect(m_ui->pbIntervalForward, &QToolButton::clicked, this, &AvmPlaybackMenu::onIntervalForwardClicked); + connect(m_ui->slSpeed, &QSlider::valueChanged, this, &AvmPlaybackMenu::onSpeedChanged); + connect(m_ui->slVolume, &QSlider::valueChanged, this, &AvmPlaybackMenu::onVolumeChanged); + connect(m_ui->tavIntervals, &QTableView::activated, this, &AvmPlaybackMenu::onIntervalActivated); + connect(m_ui->pbSkipPause, &QToolButton::clicked, this, &AvmPlaybackMenu::onSkipPauseClicked); + connect(m_ui->pbAllStreams, &QPushButton::clicked, this, &AvmPlaybackMenu::onAllStreams); - connect(m_ui->cbStreams, &QComboBox::currentTextChanged, this, &AvmPlaybackMenu::onStreamSelected); - connect(m_ui->cbMarkerStreams, &QComboBox::currentTextChanged, this, &AvmPlaybackMenu::onMarkerStreamSelected); + connect(m_ui->tabWidget, &QTabWidget::currentChanged, this, &AvmPlaybackMenu::onTabChanged); + connect(m_streamNameMapping, &StreamNameMapping::changed, this, &AvmPlaybackMenu::onStreamNameMappingChanged); - connect(&m_intervalModel, &IntervalModel::currentIntervalChanged, this, &AvmPlaybackMenu::onCurrentIntervalChanged); - connect(m_ui->pbStart, &QToolButton::clicked, this, &AvmPlaybackMenu::onStartClicked); - connect(m_ui->pbPause, &QToolButton::clicked, this, &AvmPlaybackMenu::onPauseClicked); - connect(m_ui->pbStop, &QToolButton::clicked, this, &AvmPlaybackMenu::onStopClicked); - connect(m_ui->pbIntervalBackward, &QToolButton::clicked, this, &AvmPlaybackMenu::onIntervalBackwardClicked); - connect(m_ui->pbIntervalForward, &QToolButton::clicked, this, &AvmPlaybackMenu::onIntervalForwardClicked); - connect(m_ui->slSpeed, &QSlider::valueChanged, this, &AvmPlaybackMenu::onSpeedChanged); - connect(m_ui->slVolume, &QSlider::valueChanged, this, &AvmPlaybackMenu::onVolumeChanged); - connect(m_ui->tavIntervals, &QTableView::activated, this, &AvmPlaybackMenu::onIntervalActivated); - connect(m_ui->pbSkipPause, &QToolButton::clicked, this, &AvmPlaybackMenu::onSkipPauseClicked); - connect(m_ui->pbAllStreams, &QPushButton::clicked, this, &AvmPlaybackMenu::onAllStreams); + connect(m_ui->pbAddStreamClip, &QPushButton::clicked, this, &AvmPlaybackMenu::onAddStreamClip); + connect(m_ui->pbAddStreamMarker, &QPushButton::clicked, this, &AvmPlaybackMenu::onAddStreamMarker); + connect(m_ui->pbRemoveSelectedStream, &QPushButton::clicked, this, &AvmPlaybackMenu::onRemoveSelectedStreams); - connect(m_ui->tabWidget, &QTabWidget::currentChanged, this, &AvmPlaybackMenu::onTabChanged); - - connect(m_streamNameMapping, &StreamNameMapping::changed, - this, &AvmPlaybackMenu::onStreamNameMappingChanged); - - connect(m_ui->pbAddStreamClip, &QPushButton::clicked, this, &AvmPlaybackMenu::onAddStreamClip); - connect(m_ui->pbAddStreamMarker, &QPushButton::clicked, this, &AvmPlaybackMenu::onAddStreamMarker); - connect(m_ui->pbRemoveSelectedStream, &QPushButton::clicked, this, &AvmPlaybackMenu::onRemoveSelectedStreams); - - connect(m_ui->pbAsStart, &QPushButton::clicked, this, [this]() - { - emit signalSetStart(m_ui->dtCurrentTime->msecsSinceEpoch()); - }); - - connect(m_ui->pbAsEnd, &QPushButton::clicked, this, [this]() - { - emit signalSetEnd(m_ui->dtCurrentTime->msecsSinceEpoch()); - }); - - + connect(m_ui->pbAsStart, &QPushButton::clicked, this, + [this]() { emit signalSetStart(m_ui->dtCurrentTime->msecsSinceEpoch()); }); + connect(m_ui->pbAsEnd, &QPushButton::clicked, this, + [this]() { emit signalSetEnd(m_ui->dtCurrentTime->msecsSinceEpoch()); }); #ifndef LTS_DEBUG - if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("AVM.Debug")) == QVariant(true)) + if (LtsSessionData::LtsSessionData::getInstance()->debugFlagValue(QStringLiteral("AVM.Debug")) == QVariant(true)) #endif - { - m_ui->tavIntervals->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->tavIntervals, &QTableView::customContextMenuRequested, - this, [this](const QPoint & pos) { - QMenu *menu = new QMenu; - menu->setAttribute(Qt::WA_DeleteOnClose); + m_ui->tavIntervals->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->tavIntervals, &QTableView::customContextMenuRequested, this, [this](const QPoint& pos) { + QMenu* menu = new QMenu; + menu->setAttribute(Qt::WA_DeleteOnClose); - QAction *a = menu->addAction(QStringLiteral("[debug]")); - a->setEnabled(false); + QAction* a = menu->addAction(QStringLiteral("[debug]")); + a->setEnabled(false); - auto sim = [this]() - { - AvaTimelinePart interval = m_intervalModel.getRowData(m_ui->tavIntervals->selectionModel()->currentIndex().row()); - new LtsWidgets::LtsMessageDialogNew(this, QStringLiteral("start: %1 - end: %2 - duration: %3").arg(toMSecSinceEpoch(interval.first)).arg(toMSecSinceEpoch(interval.second)).arg(toMSecSinceEpoch(interval.second) - toMSecSinceEpoch(interval.first))); - }; + auto sim = [this]() { + AvaTimelinePart interval = + m_intervalModel.getRowData(m_ui->tavIntervals->selectionModel()->currentIndex().row()); + new LtsWidgets::LtsMessageDialogNew( + this, QStringLiteral("start: %1 - end: %2 - duration: %3") + .arg(toMSecSinceEpoch(interval.first)) + .arg(toMSecSinceEpoch(interval.second)) + .arg(toMSecSinceEpoch(interval.second) - toMSecSinceEpoch(interval.first))); + }; - menu->addAction(QStringLiteral("show in msecs"), sim); - menu->popup(m_ui->tavIntervals->mapToGlobal(pos)); - }); + menu->addAction(QStringLiteral("show in msecs"), sim); + menu->popup(m_ui->tavIntervals->mapToGlobal(pos)); + }); + QMenu* menu = new QMenu(this); + menu->addAction(QStringLiteral("add test stream entry"), this, [this]() { + qint64 sm = QDateTime::currentMSecsSinceEpoch(); + qint64 em = sm + 48163; + AvaTimePoint s(std::chrono::duration_cast(std::chrono::milliseconds(sm))); + AvaTimePoint e(std::chrono::duration_cast(std::chrono::milliseconds(em))); + m_intervalModel.insertRow({s, e}); + }); - QMenu *menu = new QMenu(this); + menu->addAction(QStringLiteral("enable view"), this, [this]() { m_ui->tavIntervals->setEnabled(true); }); - menu->addAction(QStringLiteral("add test stream entry"), this, [this]() - { - qint64 sm = QDateTime::currentMSecsSinceEpoch(); - qint64 em = sm + 48163; - AvaTimePoint s(std::chrono::duration_cast(std::chrono::milliseconds(sm))); - AvaTimePoint e(std::chrono::duration_cast(std::chrono::milliseconds(em))); - m_intervalModel.insertRow({s, e}); - }); + m_ui->pbDebug->setMenu(menu); + m_ui->pbDebug->show(); + } - menu->addAction(QStringLiteral("enable view"), this, [this]() - { - m_ui->tavIntervals->setEnabled(true); - }); + onDisconnected(); + if (avaSession->isEstablished()) + onSessionEstablished(); - m_ui->pbDebug->setMenu(menu); - m_ui->pbDebug->show(); - } + for (int tz = 'Y'; tz <= 'Z'; ++tz) + m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); + m_ui->cbTimeZone->addItem(tr("Exercise default (%1)").arg(QLatin1Char(DTG::timezoneExerciseDefault())), 0); + for (int tz = 'A'; tz <= 'F'; ++tz) + m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); + const QChar tz = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("TimeSettings"), QStringLiteral("TimeZone"), QChar(QLatin1Char('Z'))) + .toChar(); + int idx = m_ui->cbTimeZone->findData(tz.isNull() ? 0 : tz); - onDisconnected(); - if (avaSession->isEstablished()) - onSessionEstablished(); - - - - - for (int tz = 'Y'; tz <= 'Z'; ++tz) - m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); - m_ui->cbTimeZone->addItem(tr("Exercise default (%1)").arg(QLatin1Char(DTG::timezoneExerciseDefault())), 0); - for (int tz = 'A'; tz <= 'F'; ++tz) - m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); - - const QChar tz = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("TimeSettings"), QStringLiteral("TimeZone"), QChar(QLatin1Char('Z'))).toChar(); - int idx = m_ui->cbTimeZone->findData(tz.isNull() ? 0 : tz); - - if (idx >= 0) - m_ui->cbTimeZone->setCurrentIndex(idx); - else - m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData(0)); - - - - - - bool k = false; - m_ui->dtCurrentTime->setTimezoneHoursOffset(timezone2Hours(tz.toLatin1(), &k)); - - auto timezoneChanged = [this](int) - { - char tz = m_ui->cbTimeZone->currentData().toInt(); - - if (tz == 0) - tz = DTG::timezoneExerciseDefault(); + if (idx >= 0) + m_ui->cbTimeZone->setCurrentIndex(idx); + else + m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData(0)); bool k = false; - int tzh = timezone2Hours(tz, &k); + m_ui->dtCurrentTime->setTimezoneHoursOffset(timezone2Hours(tz.toLatin1(), &k)); - if (!k) - return; + auto timezoneChanged = [this](int) { + char tz = m_ui->cbTimeZone->currentData().toInt(); - m_currentOffset = tzh; + if (tz == 0) + tz = DTG::timezoneExerciseDefault(); - emit signalTimezoneChanged(tzh); + bool k = false; + int tzh = timezone2Hours(tz, &k); - QSignalBlocker b1(m_ui->dtCurrentTime); - m_ui->dtCurrentTime->setTimezoneHoursOffset(tzh); + if (!k) + return; - m_timeControl->setTimezoneHoursOffset(tzh); + m_currentOffset = tzh; - m_intervalModel.setTimezoneHoursOffset(tzh); - m_markerModel->setTimezoneHoursOffset(tzh); - }; + emit signalTimezoneChanged(tzh); + QSignalBlocker b1(m_ui->dtCurrentTime); + m_ui->dtCurrentTime->setTimezoneHoursOffset(tzh); + + m_timeControl->setTimezoneHoursOffset(tzh); + + m_intervalModel.setTimezoneHoursOffset(tzh); + m_markerModel->setTimezoneHoursOffset(tzh); + }; + + connect(m_ui->cbTimeZone, QOverload::of(&QComboBox::currentIndexChanged), this, + [timezoneChanged](int) { timezoneChanged(0); }); - connect(m_ui->cbTimeZone, QOverload::of(&QComboBox::currentIndexChanged), - this, [timezoneChanged](int) - { timezoneChanged(0); - }); + connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalVisible, this, [this]() { + m_videoScreenSelectionDone = true; - timezoneChanged(0); + if (!m_timelineIsComplete) + return; + if (!m_autostartOnce) + return; + m_autostartOnce = false; + startPlayback(); + }); + connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalPause, this, &AvmPlaybackMenu::onPauseFromPlaybackApp); + connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalResume, this, + &AvmPlaybackMenu::onResumeFromPlaybackApp); - - connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalVisible, - this, [this]() - { - m_videoScreenSelectionDone = true; - - if (!m_timelineIsComplete) - return; - - if (!m_autostartOnce) - return; - - m_autostartOnce = false; - startPlayback(); - }); - - connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalPause, - this, &AvmPlaybackMenu::onPauseFromPlaybackApp); - - connect(m_playbackApp.objectWrapper(), &ObjectWrapper::signalResume, - this, &AvmPlaybackMenu::onResumeFromPlaybackApp); - - return true; + return true; } void AvmPlaybackMenu::onTabChanged(int index) { - switch (index) - { - case 0: - { - onStreamSelected(); - break; - } + switch (index) + { + case 0: { + onStreamSelected(); + break; + } - case 1: - { - m_ui->pbIntervalBackward->setEnabled(false); - m_ui->pbIntervalForward->setEnabled(false); - onMarkerStreamSelected(); - break; - } + case 1: { + m_ui->pbIntervalBackward->setEnabled(false); + m_ui->pbIntervalForward->setEnabled(false); + onMarkerStreamSelected(); + break; + } - default: - { - Q_ASSERT(index > 1); - break; - } - } + default: { + Q_ASSERT(index > 1); + break; + } + } } void AvmPlaybackMenu::onPauseFromPlaybackApp() { - m_buttonStateBeforePlaybackAppPause = m_currentButtonState; - - switch (m_currentButtonState) - { - case ButtonStates::AllOff: - return; - case ButtonStates::Started: - onPauseClicked(); - Q_FALLTHROUGH(); - case ButtonStates::Paused: - Q_FALLTHROUGH(); - case ButtonStates::Stopped: - Q_FALLTHROUGH(); - default: - setButtonStates(ButtonStates::AllOff); - disableAll(); - emit setTopicButtonStates(false); - return; - } - + m_buttonStateBeforePlaybackAppPause = m_currentButtonState; + switch (m_currentButtonState) + { + case ButtonStates::AllOff: + return; + case ButtonStates::Started: + onPauseClicked(); + Q_FALLTHROUGH(); + case ButtonStates::Paused: + Q_FALLTHROUGH(); + case ButtonStates::Stopped: + Q_FALLTHROUGH(); + default: + setButtonStates(ButtonStates::AllOff); + disableAll(); + emit setTopicButtonStates(false); + return; + } } void AvmPlaybackMenu::onResumeFromPlaybackApp() { - qWarning() << "onResumeFromPlaybackApp"; + qWarning() << "onResumeFromPlaybackApp"; - switch (m_buttonStateBeforePlaybackAppPause) - { - case ButtonStates::AllOff: - return; - case ButtonStates::Started: - enableAll(); - onStartClicked(); - emit setTopicButtonStates(true); - return; - case ButtonStates::Paused: - Q_FALLTHROUGH(); - case ButtonStates::Stopped: - Q_FALLTHROUGH(); - default: - enableAll(); - setButtonStates(m_buttonStateBeforePlaybackAppPause); - emit setTopicButtonStates(true); - return; - } + switch (m_buttonStateBeforePlaybackAppPause) + { + case ButtonStates::AllOff: + return; + case ButtonStates::Started: + enableAll(); + onStartClicked(); + emit setTopicButtonStates(true); + return; + case ButtonStates::Paused: + Q_FALLTHROUGH(); + case ButtonStates::Stopped: + Q_FALLTHROUGH(); + default: + enableAll(); + setButtonStates(m_buttonStateBeforePlaybackAppPause); + emit setTopicButtonStates(true); + return; + } } -void AvmPlaybackMenu::addStream(QComboBox *cb) +void AvmPlaybackMenu::addStream(QComboBox* cb) { - const auto currentStream(cb->currentData().value()); + const auto currentStream(cb->currentData().value()); - if (currentStream.internalName.isEmpty()) - return; + if (currentStream.internalName.isEmpty()) + return; - const int streamCount = m_ui->lwStreams->count(); - if (streamCount >= m_maxSelectedStreams) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("Cannot add more than %1 streams").arg(m_maxSelectedStreams)); - return; - } + const int streamCount = m_ui->lwStreams->count(); + if (streamCount >= m_maxSelectedStreams) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("Cannot add more than %1 streams").arg(m_maxSelectedStreams)); + return; + } - for (int i = 0; i < m_ui->lwStreams->count(); i++) - { - const QListWidgetItem *item = m_ui->lwStreams->item(i); - if (item->data(Qt::UserRole).value() == currentStream) - return; - } + for (int i = 0; i < m_ui->lwStreams->count(); i++) + { + const QListWidgetItem* item = m_ui->lwStreams->item(i); + if (item->data(Qt::UserRole).value() == currentStream) + return; + } - auto item = new QListWidgetItem(currentStream.internalName); - item->setData(Qt::UserRole, QVariant::fromValue(currentStream)); + auto item = new QListWidgetItem(currentStream.internalName); + item->setData(Qt::UserRole, QVariant::fromValue(currentStream)); - m_ui->lwStreams->addItem(item); + m_ui->lwStreams->addItem(item); - trySelectedStreams(); + trySelectedStreams(); } void AvmPlaybackMenu::onAddStreamClip() { - addStream(m_ui->cbStreams); + addStream(m_ui->cbStreams); } void AvmPlaybackMenu::onAddStreamMarker() { - addStream(m_ui->cbMarkerStreams); + addStream(m_ui->cbMarkerStreams); } void AvmPlaybackMenu::onRemoveSelectedStreams() { - const QModelIndexList indexList = m_ui->lwStreams->selectionModel()->selectedRows(); + const QModelIndexList indexList = m_ui->lwStreams->selectionModel()->selectedRows(); - for (const QModelIndex &idx : indexList) - delete m_ui->lwStreams->item(idx.row()); + for (const QModelIndex& idx : indexList) + delete m_ui->lwStreams->item(idx.row()); } void AvmPlaybackMenu::onStreamNameMappingChanged() { - QSignalBlocker block1(m_ui->cbStreams); - for (int i = 0; i < m_ui->cbStreams->count(); i++) - m_ui->cbStreams->setItemText(i, m_streamNameMapping->displayName(m_ui->cbStreams->itemData(i).value().internalName)); + QSignalBlocker block1(m_ui->cbStreams); + for (int i = 0; i < m_ui->cbStreams->count(); i++) + m_ui->cbStreams->setItemText( + i, m_streamNameMapping->displayName(m_ui->cbStreams->itemData(i).value().internalName)); - QSignalBlocker block2(m_ui->cbMarkerStreams); - for (int i = 0; i < m_ui->cbMarkerStreams->count(); i++) - m_ui->cbMarkerStreams->setItemText(i, m_streamNameMapping->displayName(m_ui->cbMarkerStreams->itemData(i).value().internalName)); + QSignalBlocker block2(m_ui->cbMarkerStreams); + for (int i = 0; i < m_ui->cbMarkerStreams->count(); i++) + m_ui->cbMarkerStreams->setItemText( + i, m_streamNameMapping->displayName(m_ui->cbMarkerStreams->itemData(i).value().internalName)); - for (int i = 0; i < m_ui->lwStreams->count(); i++) - { - QListWidgetItem *item = m_ui->lwStreams->item(i); - item->setData(Qt::UserRole, m_streamNameMapping->displayName(item->data(Qt::UserRole).value().internalName)); - } + for (int i = 0; i < m_ui->lwStreams->count(); i++) + { + QListWidgetItem* item = m_ui->lwStreams->item(i); + item->setData(Qt::UserRole, + m_streamNameMapping->displayName(item->data(Qt::UserRole).value().internalName)); + } } bool AvmPlaybackMenu::trySelectedStreams() { - if (!m_ui->lwStreams->count()) - return false; + if (!m_ui->lwStreams->count()) + return false; - QVector vec; + QVector vec; - for (int i = 0; i < m_ui->lwStreams->count(); i++) - vec.append(m_ui->lwStreams->item(i)->data(Qt::UserRole).value()); + for (int i = 0; i < m_ui->lwStreams->count(); i++) + vec.append(m_ui->lwStreams->item(i)->data(Qt::UserRole).value()); - onStreamSelectionChanged(vec); + onStreamSelectionChanged(vec); - return true; + return true; } void AvmPlaybackMenu::onStreamSelected() { - if (trySelectedStreams()) - return; + if (trySelectedStreams()) + return; - if (m_ui->cbStreams->currentIndex() < 0) - return; + if (m_ui->cbStreams->currentIndex() < 0) + return; - QVector vec; - AvaStream stream = m_ui->cbStreams->currentData().value(); - vec.append(stream); - onStreamSelectionChanged(vec); + QVector vec; + AvaStream stream = m_ui->cbStreams->currentData().value(); + vec.append(stream); + onStreamSelectionChanged(vec); - m_currentStream = stream; - emit signalCurrentStreamChanged(m_streamNameMapping->displayName(stream.internalName)); + m_currentStream = stream; + emit signalCurrentStreamChanged(m_streamNameMapping->displayName(stream.internalName)); } void AvmPlaybackMenu::onMarkerStreamSelected() { - if (trySelectedStreams()) - return; + if (trySelectedStreams()) + return; - if (m_ui->cbMarkerStreams->currentIndex() < 0) - return; + if (m_ui->cbMarkerStreams->currentIndex() < 0) + return; - const QVariant data(m_ui->cbMarkerStreams->currentData()); - if (data.isValid() && data.canConvert()) - { - const AvaStream stream(data.value()); - onStreamSelectionChanged({stream}); - - m_currentStream = stream; - emit signalCurrentStreamChanged(m_streamNameMapping->displayName(stream.internalName)); - } - else - { - m_currentStream = boost::none; - emit signalCurrentStreamChanged({}); - } -} - -void AvmPlaybackMenu::setStreamByName(const QString &name) -{ - using AudioVideoManagement::AvaStream; - - for (int i = 0; i < m_ui->cbStreams->count(); ++i) - { - QVariant data = m_ui->cbStreams->itemData(i); - Q_ASSERT(data.canConvert()); - AvaStream stream = m_ui->cbStreams->itemData(i).value(); - if (stream.internalName == name) + const QVariant data(m_ui->cbMarkerStreams->currentData()); + if (data.isValid() && data.canConvert()) { - m_ui->cbStreams->setCurrentIndex(i); - return; - } - } + const AvaStream stream(data.value()); + onStreamSelectionChanged({stream}); - m_ui->cbStreams->setCurrentIndex(0); + m_currentStream = stream; + emit signalCurrentStreamChanged(m_streamNameMapping->displayName(stream.internalName)); + } + else + { + m_currentStream = boost::none; + emit signalCurrentStreamChanged({}); + } } -void AvmPlaybackMenu::onMarkerModifyReply(const Core::FunctionReplyObject &replyObject) +void AvmPlaybackMenu::setStreamByName(const QString& name) { - m_requestHelper->requestReply(replyObject); + using AudioVideoManagement::AvaStream; + + for (int i = 0; i < m_ui->cbStreams->count(); ++i) + { + QVariant data = m_ui->cbStreams->itemData(i); + Q_ASSERT(data.canConvert()); + AvaStream stream = m_ui->cbStreams->itemData(i).value(); + if (stream.internalName == name) + { + m_ui->cbStreams->setCurrentIndex(i); + return; + } + } + + m_ui->cbStreams->setCurrentIndex(0); +} + +void AvmPlaybackMenu::onMarkerModifyReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); } void AvmPlaybackMenu::retranslate() { - m_ui->retranslateUi(this); - m_ui->tabWidget->setTabText(0, m_isAudio ? tr("Audio clips") : tr("Video clips")); + m_ui->retranslateUi(this); + m_ui->tabWidget->setTabText(0, m_isAudio ? tr("Audio clips") : tr("Video clips")); } void AvmPlaybackMenu::setStreamTime(qint64 time) { - m_ui->dtCurrentTime->setMsecsSinceEpoch(time); + m_ui->dtCurrentTime->setMsecsSinceEpoch(time); } - - - - - - - void AvmPlaybackMenu::onSessionEstablished() { - m_ui->lblAvsConnectionStatus->setText(QStringLiteral("%1").arg(tr("established"))); + m_ui->lblAvsConnectionStatus->setText(QStringLiteral("%1").arg(tr("established"))); - enableAll(); + enableAll(); - if (!m_intervalModel.currentPosition()) - { - m_ui->pbIntervalBackward->setEnabled(false); - m_ui->pbIntervalForward->setEnabled(false); - } - else - { - bool forceSignal = true; - m_intervalModel.setCurrentPosition(*m_intervalModel.currentPosition(), forceSignal); - } + if (!m_intervalModel.currentPosition()) + { + m_ui->pbIntervalBackward->setEnabled(false); + m_ui->pbIntervalForward->setEnabled(false); + } + else + { + bool forceSignal = true; + m_intervalModel.setCurrentPosition(*m_intervalModel.currentPosition(), forceSignal); + } - m_avaCtrl->setVolume(m_ui->slVolume->value()); + m_avaCtrl->setVolume(m_ui->slVolume->value()); - if (!m_selectedStreams) - { - - - AvaStreamType type = AvaStreamType::Video; - if (m_isAudio) - type = AvaStreamType::Audio; - m_avaCtrl->getStreamList(type, AvaStreamSource::Server, this, &AvmPlaybackMenu::onStreamListReceived); - return; - } - else - { - - - onStreamSelectionChanged(*m_selectedStreams); - } + if (!m_selectedStreams) + { + + AvaStreamType type = AvaStreamType::Video; + if (m_isAudio) + type = AvaStreamType::Audio; + m_avaCtrl->getStreamList(type, AvaStreamSource::Server, this, &AvmPlaybackMenu::onStreamListReceived); + return; + } + else + { + + onStreamSelectionChanged(*m_selectedStreams); + } } void AvmPlaybackMenu::onDisconnected() { - m_ui->lblAvsConnectionStatus->setText(QStringLiteral("%1").arg(tr("connecting..."))); - setButtonStates(ButtonStates::AllOff); - emit setTopicButtonStates(false); - disableAll(); - m_timelineBuilder->reset(); + m_ui->lblAvsConnectionStatus->setText(QStringLiteral("%1").arg(tr("connecting..."))); + setButtonStates(ButtonStates::AllOff); + emit setTopicButtonStates(false); + disableAll(); + m_timelineBuilder->reset(); } - -void AvmPlaybackMenu::preselectStream(const QString &fallbackInternalStreamName) +void AvmPlaybackMenu::preselectStream(const QString& fallbackInternalStreamName) { - if (m_markerIdPreset) - { - m_ui->tabWidget->setCurrentIndex(1); - m_ui->tvMarker->selectRow(m_markerModel->findIndexForId(*m_markerIdPreset)); - selectMarker(*m_markerIdPreset); - m_markerIdPreset.reset(); - return; - } - - { - const QString currentStreamName(m_presetStreamName.is_initialized() ? *m_presetStreamName : QString()); - const QString currentInternalName(currentStreamName.isEmpty() ? fallbackInternalStreamName : QString()); - - DEBUG_LOG(m_logger) << "currentStreamName: " << currentStreamName; - DEBUG_LOG(m_logger) << "currentInternalName: " << currentInternalName; - - m_presetStreamName.reset(); - - if (!currentInternalName.isEmpty() || !currentStreamName.isEmpty()) - { - DEBUG_LOG(m_logger) << "stream preset set - searching for '" << currentStreamName << "'.."; - - bool found = false; - for (int i = 0; i < m_ui->cbStreams->count(); i++) + if (m_markerIdPreset) { - const AvaStream &curStream = m_ui->cbStreams->itemData(i).value(); - - DEBUG_LOG(m_logger) << "stream " << i << ": " << curStream.displayName << " (" << curStream.internalName << ")"; - - if ((!currentInternalName.isEmpty() && curStream.displayName == currentInternalName) || - (!currentStreamName.isEmpty() && curStream.internalName == currentStreamName)) - { - found = true; - DEBUG_LOG(m_logger) << "stream preset set, found & selected"; - m_ui->cbStreams->setCurrentIndex(i); - break; - } + m_ui->tabWidget->setCurrentIndex(1); + m_ui->tvMarker->selectRow(m_markerModel->findIndexForId(*m_markerIdPreset)); + selectMarker(*m_markerIdPreset); + m_markerIdPreset.reset(); + return; } - if (!found) - WARNING_LOG(m_logger) << "new stream list does not contain old selected stream (" << currentInternalName << ") !"; - } - else - DEBUG_LOG(m_logger) << "no stream preset set"; - } + { + const QString currentStreamName(m_presetStreamName.is_initialized() ? *m_presetStreamName : QString()); + const QString currentInternalName(currentStreamName.isEmpty() ? fallbackInternalStreamName : QString()); + DEBUG_LOG(m_logger) << "currentStreamName: " << currentStreamName; + DEBUG_LOG(m_logger) << "currentInternalName: " << currentInternalName; - onStreamSelected(); + m_presetStreamName.reset(); + + if (!currentInternalName.isEmpty() || !currentStreamName.isEmpty()) + { + DEBUG_LOG(m_logger) << "stream preset set - searching for '" << currentStreamName << "'.."; + + bool found = false; + for (int i = 0; i < m_ui->cbStreams->count(); i++) + { + const AvaStream& curStream = m_ui->cbStreams->itemData(i).value(); + + DEBUG_LOG(m_logger) << "stream " << i << ": " << curStream.displayName << " (" << curStream.internalName + << ")"; + + if ((!currentInternalName.isEmpty() && curStream.displayName == currentInternalName) || + (!currentStreamName.isEmpty() && curStream.internalName == currentStreamName)) + { + found = true; + DEBUG_LOG(m_logger) << "stream preset set, found & selected"; + m_ui->cbStreams->setCurrentIndex(i); + break; + } + } + + if (!found) + WARNING_LOG(m_logger) << "new stream list does not contain old selected stream (" << currentInternalName + << ") !"; + } + else + DEBUG_LOG(m_logger) << "no stream preset set"; + } + + onStreamSelected(); } - void AvmPlaybackMenu::processPresets() { - if (m_presetStartTime) - m_savedPos = *m_presetStartTime; + if (m_presetStartTime) + m_savedPos = *m_presetStartTime; - m_presetStartTime.reset(); + m_presetStartTime.reset(); - preselectStream(m_ui->cbStreams->currentData().value().internalName ); + preselectStream(m_ui->cbStreams->currentData().value().internalName); } - -void AvmPlaybackMenu::onStreamListReceived(const QVector &streams) +void AvmPlaybackMenu::onStreamListReceived(const QVector& streams) { - m_streams = streams; + m_streams = streams; - QSignalBlocker block1(m_ui->cbStreams); - m_ui->cbStreams->clear(); - for (const AvaStream &s : streams) - { - QString displayName = m_streamNameMapping->displayName(s.internalName); - m_ui->cbStreams->addItem(displayName, QVariant::fromValue(s)); - } + QSignalBlocker block1(m_ui->cbStreams); + m_ui->cbStreams->clear(); + for (const AvaStream& s : streams) + { + QString displayName = m_streamNameMapping->displayName(s.internalName); + m_ui->cbStreams->addItem(displayName, QVariant::fromValue(s)); + } - processPresets(); + processPresets(); } - void AvmPlaybackMenu::startPlayback(bool usePresets) { - Q_ASSERT(m_currentButtonState != ButtonStates::AllOff); + Q_ASSERT(m_currentButtonState != ButtonStates::AllOff); - if (m_currentButtonState == ButtonStates::Paused || m_currentButtonState == ButtonStates::Started) - onStopClicked(); + if (m_currentButtonState == ButtonStates::Paused || m_currentButtonState == ButtonStates::Started) + onStopClicked(); - if (usePresets && m_presetStartTime) - { - preselectStream(m_ui->cbStreams->currentData().value().internalName); - m_savedPos = m_presetStartTime.get(); - m_presetStartTime.reset(); - } - else - onStartClicked(); + if (usePresets && m_presetStartTime) + { + preselectStream(m_ui->cbStreams->currentData().value().internalName); + m_savedPos = m_presetStartTime.get(); + m_presetStartTime.reset(); + } + else + onStartClicked(); } - void AvmPlaybackMenu::setSavedPos(qint64 msecs) { - m_savedPos = AvaTimePoint(std::chrono::duration_cast(std::chrono::milliseconds(msecs))); + m_savedPos = AvaTimePoint(std::chrono::duration_cast(std::chrono::milliseconds(msecs))); } - -void AvmPlaybackMenu::onTimelineComplete(const AvaTimeline &timeline) +void AvmPlaybackMenu::onTimelineComplete(const AvaTimeline& timeline) { - DEBUG_LOG(m_logger) << "onTimelineComplete"; + DEBUG_LOG(m_logger) << "onTimelineComplete"; - m_intervalModel.setData(timeline.parts()); - m_ui->tavIntervals->resizeColumnsToContents(); - setButtonStates(ButtonStates::Stopped); - emit setTopicButtonStates(true); + m_intervalModel.setData(timeline.parts()); + m_ui->tavIntervals->resizeColumnsToContents(); + setButtonStates(ButtonStates::Stopped); + emit setTopicButtonStates(true); - if (timeline.isEmpty()) - return; + if (timeline.isEmpty()) + return; - AvaTimePoint newPos = timeline.startTime(); + AvaTimePoint newPos = timeline.startTime(); - if (m_savedPos) - { - newPos = *m_savedPos; - m_savedPos.reset(); - } - - DEBUG_LOG(m_logger) << "onTimelineComplete " << std::chrono::milliseconds(newPos.time_since_epoch()).count(); - m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), newPos); - - m_timelineIsComplete = true; - - if (m_autostartOnce) - { - - - if (m_isAudio || m_videoScreenSelectionDone) + if (m_savedPos) { - m_autostartOnce = false; - startPlayback(); + newPos = *m_savedPos; + m_savedPos.reset(); + } + + DEBUG_LOG(m_logger) << "onTimelineComplete " << std::chrono::milliseconds(newPos.time_since_epoch()).count(); + m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), newPos); + + m_timelineIsComplete = true; + + if (m_autostartOnce) + { + + if (m_isAudio || m_videoScreenSelectionDone) + { + m_autostartOnce = false; + startPlayback(); + } } - } } - - -void AvmPlaybackMenu::onStreamPositionReceived(const QString &dialogId, const QString &streamName, AvaTimePoint pos) +void AvmPlaybackMenu::onStreamPositionReceived(const QString& dialogId, const QString& streamName, AvaTimePoint pos) { - Q_UNUSED(streamName); + Q_UNUSED(streamName); - if (dialogId != m_playbackApp.dialogId()) - return; + if (dialogId != m_playbackApp.dialogId()) + return; - m_lastAvsPos = pos; - DEBUG_LOG(m_logger) << "onStreamPositionReceived: last avs pos now: " << std::chrono::milliseconds((*m_lastAvsPos).time_since_epoch()).count() << " - direct apply? " << m_avaCtrl->isEmpty(); + m_lastAvsPos = pos; + DEBUG_LOG(m_logger) << "onStreamPositionReceived: last avs pos now: " + << std::chrono::milliseconds((*m_lastAvsPos).time_since_epoch()).count() << " - direct apply? " + << m_avaCtrl->isEmpty(); - if (m_avaCtrl->isEmpty()) - applyAvsPos(); + if (m_avaCtrl->isEmpty()) + applyAvsPos(); } void AvmPlaybackMenu::onVolumeReceived(AvaVolume db) { - m_lastAvsVolume = db; - if (m_avaCtrl->isEmpty()) - applyAvsVolume(); + m_lastAvsVolume = db; + if (m_avaCtrl->isEmpty()) + applyAvsVolume(); } void AvmPlaybackMenu::onCommandQueueEmpty() { - - if (m_lastAvsPos) - applyAvsPos(); + if (m_lastAvsPos) + applyAvsPos(); - if (m_lastAvsVolume) - applyAvsVolume(); + if (m_lastAvsVolume) + applyAvsVolume(); } void AvmPlaybackMenu::applyAvsPos() { - Q_ASSERT(m_lastAvsPos); + Q_ASSERT(m_lastAvsPos); - - - - - - - - - - - m_intervalModel.setCurrentPosition(*m_lastAvsPos); - m_timeControl->setTime(*m_lastAvsPos); - m_lastAvsPos.reset(); + m_intervalModel.setCurrentPosition(*m_lastAvsPos); + m_timeControl->setTime(*m_lastAvsPos); + m_lastAvsPos.reset(); } void AvmPlaybackMenu::applyAvsVolume() { - Q_ASSERT(m_lastAvsVolume); - m_ui->slVolume->setValue(*m_lastAvsVolume); + Q_ASSERT(m_lastAvsVolume); + m_ui->slVolume->setValue(*m_lastAvsVolume); } - void AvmPlaybackMenu::onUiTimeChanged(AvaTimePoint t) { - if (m_currentButtonState != ButtonStates::Paused && - m_currentButtonState != ButtonStates::Stopped) - return; + if (m_currentButtonState != ButtonStates::Paused && m_currentButtonState != ButtonStates::Stopped) + return; - DEBUG_LOG(m_logger) << "onUiTimeChanged " << std::chrono::milliseconds(t.time_since_epoch()).count(); - m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), t); + DEBUG_LOG(m_logger) << "onUiTimeChanged " << std::chrono::milliseconds(t.time_since_epoch()).count(); + m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), t); } -void AvmPlaybackMenu::onStreamSelectionChanged(const QVector &selectedStreams) +void AvmPlaybackMenu::onStreamSelectionChanged(const QVector& selectedStreams) { - DEBUG_LOG(m_logger) << "onStreamSelectionChanged count = " << selectedStreams.count(); + DEBUG_LOG(m_logger) << "onStreamSelectionChanged count = " << selectedStreams.count(); - Q_ASSERT(!selectedStreams.isEmpty()); + Q_ASSERT(!selectedStreams.isEmpty()); - - if (!m_savedPos) - m_savedPos = m_intervalModel.currentPosition(); + if (!m_savedPos) + m_savedPos = m_intervalModel.currentPosition(); - m_selectedStreams = selectedStreams; + m_selectedStreams = selectedStreams; - onStopClicked(); + onStopClicked(); - m_intervalModel.reset(); - setButtonStates(ButtonStates::AllOff); - emit setTopicButtonStates(false); - m_timelineBuilder->queryTimeline(selectedStreams); + m_intervalModel.reset(); + setButtonStates(ButtonStates::AllOff); + emit setTopicButtonStates(false); + m_timelineBuilder->queryTimeline(selectedStreams); - - m_avaCtrl->chooseStreamOverview(m_playbackApp.dialogId(), AvaStream::toStringList(selectedStreams)); - m_avaCtrl->setPint(m_playbackApp.dialogId(), ALL_STREAMS(), m_skipEmpty); + m_avaCtrl->chooseStreamOverview(m_playbackApp.dialogId(), AvaStream::toStringList(selectedStreams)); + m_avaCtrl->setPint(m_playbackApp.dialogId(), ALL_STREAMS(), m_skipEmpty); } - - -void AvmPlaybackMenu::onIntervalActivated(const QModelIndex &index) +void AvmPlaybackMenu::onIntervalActivated(const QModelIndex& index) { - AvaTimelinePart interval = m_intervalModel.getRowData(index.row()); - DEBUG_LOG(m_logger) << "start = " << std::chrono::milliseconds(interval.first.time_since_epoch()).count(); - m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), interval.first); - + AvaTimelinePart interval = m_intervalModel.getRowData(index.row()); + DEBUG_LOG(m_logger) << "start = " << std::chrono::milliseconds(interval.first.time_since_epoch()).count(); + m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), interval.first); - - - m_ui->tvMarker->selectionModel()->clear(); - m_ui->tavIntervals->selectionModel()->clear(); - - - + m_ui->tvMarker->selectionModel()->clear(); + m_ui->tavIntervals->selectionModel()->clear(); } -void AvmPlaybackMenu::setStreamName(const QString &internalStreamName) +void AvmPlaybackMenu::setStreamName(const QString& internalStreamName) { - int idx = -1; + int idx = -1; - for (int i = 0; i < m_ui->cbStreams->count(); i++) - { - if (m_ui->cbStreams->itemData(i).value().internalName == internalStreamName) + for (int i = 0; i < m_ui->cbStreams->count(); i++) { - idx = i; - break; + if (m_ui->cbStreams->itemData(i).value().internalName == internalStreamName) + { + idx = i; + break; + } } - } - if (idx == -1) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("The sequence uses a stream that is not available anymore"), tr("Stream from sequence not found")); - m_ui->cbStreams->setCurrentText(QString()); - return; - } + if (idx == -1) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("The sequence uses a stream that is not available anymore"), + tr("Stream from sequence not found")); + m_ui->cbStreams->setCurrentText(QString()); + return; + } - - QVector vec; - AvaStream stream = m_ui->cbStreams->itemData(idx).value(); - vec.append(stream); - onStreamSelectionChanged(vec); + QVector vec; + AvaStream stream = m_ui->cbStreams->itemData(idx).value(); + vec.append(stream); + onStreamSelectionChanged(vec); - m_ui->cbStreams->setCurrentIndex(idx); + m_ui->cbStreams->setCurrentIndex(idx); } bool AvmPlaybackMenu::getSkipPause() const { - return m_skipEmpty; + return m_skipEmpty; } void AvmPlaybackMenu::setSkipPause(bool bSkip) { - if (m_skipEmpty == bSkip) - return; - m_skipEmpty = !bSkip; - onSkipPauseClicked(); + if (m_skipEmpty == bSkip) + return; + m_skipEmpty = !bSkip; + onSkipPauseClicked(); } QString AvmPlaybackMenu::getInternalStreamName() const { - if (m_currentStream) - return m_currentStream.get().internalName; - return {}; + if (m_currentStream) + return m_currentStream.get().internalName; + return {}; } -void AvmPlaybackMenu::selectMarker(const MarkerManagement::Marker &marker) +void AvmPlaybackMenu::selectMarker(const MarkerManagement::Marker& marker) { - if (marker.id() == 0) - return; + if (marker.id() == 0) + return; - QSignalBlocker blocker(m_ui->cbMarkerStreams); - (void)blocker; + QSignalBlocker blocker(m_ui->cbMarkerStreams); + (void)blocker; - const auto &rowData = marker; - DEBUG_LOG(m_logger) << "AvmPlaybackMenu::onMarkerClicked name = " << QString::fromStdString(rowData.name()) - << " note = " << QString::fromStdString(rowData.note()); + const auto& rowData = marker; + DEBUG_LOG(m_logger) << "AvmPlaybackMenu::onMarkerClicked name = " << QString::fromStdString(rowData.name()) + << " note = " << QString::fromStdString(rowData.note()); - bool selectMarkerStream = false; + bool selectMarkerStream = false; - for (const MarkerManagement::MarkerDescription &desc : rowData.descriptions()) - { - if ((desc.markerType() == MarkerManagement::MarkerType::Video && m_isAudio == false) || - (desc.markerType() == MarkerManagement::MarkerType::Audio && m_isAudio == true)) + for (const MarkerManagement::MarkerDescription& desc : rowData.descriptions()) { - m_ui->cbMarkerStreams->clear(); - break; - } - } - - for (const MarkerManagement::MarkerDescription &desc : rowData.descriptions()) - { - DEBUG_LOG(m_logger) << " description = " << QString::fromStdString(desc.content()) - << " desc.markerType()=" << desc.markerType(); - if ((desc.markerType() == MarkerManagement::MarkerType::Video && m_isAudio == false) || - (desc.markerType() == MarkerManagement::MarkerType::Audio && m_isAudio == true)) - { - AvaStream avaStream; - avaStream.type = m_isAudio ? AvaStreamType::Audio : AvaStreamType::Video; - avaStream.source = AvaStreamSource::Server; - - AvaStream selectedStream; - const QStringList streams(QString::fromStdString(desc.content()).split(QLatin1Char(','))); - - for (const QString &sr : streams) - { - bool bIsSelected = false; - avaStream.internalName = sr.simplified(); - - if (sr.endsWith(QLatin1Char('*'))) + if ((desc.markerType() == MarkerManagement::MarkerType::Video && m_isAudio == false) || + (desc.markerType() == MarkerManagement::MarkerType::Audio && m_isAudio == true)) { - QString &in = avaStream.internalName; - in = in.left(in.size() - 1); - bIsSelected = true; + m_ui->cbMarkerStreams->clear(); + break; } - - avaStream.displayName = m_streamNameMapping->displayName(avaStream.internalName); - m_ui->cbMarkerStreams->addItem(avaStream.displayName, QVariant::fromValue(avaStream)); - DEBUG_LOG(m_logger) << "streams[" << avaStream.internalName << "]" - << " internaName=" << avaStream.internalName - << " displayName=" << avaStream.displayName; - if (bIsSelected && selectedStream.internalName.isEmpty()) - selectedStream = avaStream; - } - - if (!selectedStream.displayName.isEmpty()) - { - const QVariant data(QVariant::fromValue(selectedStream)); - m_ui->cbMarkerStreams->setCurrentIndex(m_ui->cbMarkerStreams->findData(data)); - selectMarkerStream = true; - } } - } - qint64 time = rowData.timeStamp() - rowData.timeStampOffset(); + for (const MarkerManagement::MarkerDescription& desc : rowData.descriptions()) + { + DEBUG_LOG(m_logger) << " description = " << QString::fromStdString(desc.content()) + << " desc.markerType()=" << desc.markerType(); + if ((desc.markerType() == MarkerManagement::MarkerType::Video && m_isAudio == false) || + (desc.markerType() == MarkerManagement::MarkerType::Audio && m_isAudio == true)) + { + AvaStream avaStream; + avaStream.type = m_isAudio ? AvaStreamType::Audio : AvaStreamType::Video; + avaStream.source = AvaStreamSource::Server; - DEBUG_LOG(m_logger) << "marker time: " << time << " (" << QDateTime::fromMSecsSinceEpoch(time).toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")) << ")"; + AvaStream selectedStream; + const QStringList streams(QString::fromStdString(desc.content()).split(QLatin1Char(','))); - std::chrono::milliseconds t(time); - AvaTimePoint p(std::chrono::duration_cast(t)); + for (const QString& sr : streams) + { + bool bIsSelected = false; + avaStream.internalName = sr.simplified(); - - + if (sr.endsWith(QLatin1Char('*'))) + { + QString& in = avaStream.internalName; + in = in.left(in.size() - 1); + bIsSelected = true; + } - m_savedPos = p; + avaStream.displayName = m_streamNameMapping->displayName(avaStream.internalName); + m_ui->cbMarkerStreams->addItem(avaStream.displayName, QVariant::fromValue(avaStream)); + DEBUG_LOG(m_logger) << "streams[" << avaStream.internalName << "]" + << " internaName=" << avaStream.internalName + << " displayName=" << avaStream.displayName; + if (bIsSelected && selectedStream.internalName.isEmpty()) + selectedStream = avaStream; + } + if (!selectedStream.displayName.isEmpty()) + { + const QVariant data(QVariant::fromValue(selectedStream)); + m_ui->cbMarkerStreams->setCurrentIndex(m_ui->cbMarkerStreams->findData(data)); + selectMarkerStream = true; + } + } + } + qint64 time = rowData.timeStamp() - rowData.timeStampOffset(); + DEBUG_LOG(m_logger) << "marker time: " << time << " (" + << QDateTime::fromMSecsSinceEpoch(time).toString(QStringLiteral("dd.MM.yy HH:mm:ss.zzz")) + << ")"; - if (selectMarkerStream) - onMarkerStreamSelected(); + std::chrono::milliseconds t(time); + AvaTimePoint p(std::chrono::duration_cast(t)); - emit markerSelected(QString::fromStdString(rowData.note())); - + m_savedPos = p; - m_ui->tavIntervals->selectionModel()->clear(); + if (selectMarkerStream) + onMarkerStreamSelected(); + + emit markerSelected(QString::fromStdString(rowData.note())); + + m_ui->tavIntervals->selectionModel()->clear(); } void AvmPlaybackMenu::selectMarker(int markerId) { - selectMarker(m_mrkDataIfc->getDtc()->marker(markerId)); + selectMarker(m_mrkDataIfc->getDtc()->marker(markerId)); } -void AvmPlaybackMenu::onMarkerClicked(const QModelIndex &index) +void AvmPlaybackMenu::onMarkerClicked(const QModelIndex& index) { - if (!index.isValid()) - return; + if (!index.isValid()) + return; - selectMarker(m_markerModel->getRowData(index.row())); + selectMarker(m_markerModel->getRowData(index.row())); } void AvmPlaybackMenu::onSetMarkerClicked() { - if (!m_selectedStreams || m_selectedStreams.get().isEmpty()) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("No stream selected to create a marker from.")); - WARNING_LOG(m_logger) << "onSetMarkerClicked called, but no selected streams available"; - return; - } + if (!m_selectedStreams || m_selectedStreams.get().isEmpty()) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("No stream selected to create a marker from.")); + WARNING_LOG(m_logger) << "onSetMarkerClicked called, but no selected streams available"; + return; + } - bool ok = false; - QString note = QInputDialog::getText(this, tr("Enter Note"), - tr("Note:"), QLineEdit::Normal, QString(), &ok); + bool ok = false; + QString note = QInputDialog::getText(this, tr("Enter Note"), tr("Note:"), QLineEdit::Normal, QString(), &ok); - if (!ok) - return; + if (!ok) + return; - MarkerManagement::Marker mrk; - MarkerManagement::MarkerDescription ma; - ma.markerType(m_isAudio ? MarkerManagement::MarkerType::Audio : MarkerManagement::MarkerType::Video); - auto &descriptions = mrk.descriptions(); - QStringList streamList; - streamList.reserve(m_selectedStreams->size()); - const QLatin1Char star = QLatin1Char('*'); - const auto &x = *m_selectedStreams; - for (const AvaStream &stream : x) - { - streamList += stream.internalName; - streamList.last().append(star); - } - ma.content() = streamList.join(QStringLiteral(", ")).toStdString(); - descriptions.resize(descriptions.size() + 1, ma); - mrk.note(note.toStdString()); - mrk.timeStamp(m_timeControl->timeMSec()); - mrk.timeStampOffset(0); - mrk.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + MarkerManagement::Marker mrk; + MarkerManagement::MarkerDescription ma; + ma.markerType(m_isAudio ? MarkerManagement::MarkerType::Audio : MarkerManagement::MarkerType::Video); + auto& descriptions = mrk.descriptions(); + QStringList streamList; + streamList.reserve(m_selectedStreams->size()); + const QLatin1Char star = QLatin1Char('*'); + const auto& x = *m_selectedStreams; + for (const AvaStream& stream : x) + { + streamList += stream.internalName; + streamList.last().append(star); + } + ma.content() = streamList.join(QStringLiteral(", ")).toStdString(); + descriptions.resize(descriptions.size() + 1, ma); + mrk.note(note.toStdString()); + mrk.timeStamp(m_timeControl->timeMSec()); + mrk.timeStampOffset(0); + mrk.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - m_requestHelper->startSingleRequest([mrk, this]() - { - return m_mrkDataIfc->setMarker(mrk, this); - }); + m_requestHelper->startSingleRequest([mrk, this]() { return m_mrkDataIfc->setMarker(mrk, this); }); } void AvmPlaybackMenu::onStartClicked() { - - - DEBUG_LOG(m_logger) << "onStartClicked" - << " dialogId=" << m_playbackApp.dialogId() - << " currentSpeed=" << currentSpeed() - - - ; - if (!m_selectedStreams || m_selectedStreams.get().isEmpty()) - { - if (qobject_cast(sender()) != nullptr) + DEBUG_LOG(m_logger) << "onStartClicked" + << " dialogId=" << m_playbackApp.dialogId() << " currentSpeed=" << currentSpeed() + + ; + + if (!m_selectedStreams || m_selectedStreams.get().isEmpty()) { - new LtsWidgets::LtsMessageDialogNew(this, tr("No stream selected to start a replay from.")); - return; + if (qobject_cast(sender()) != nullptr) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("No stream selected to start a replay from.")); + return; + } + + WARNING_LOG(m_logger) << "onStartClicked called, but no selected streams available"; + return; } - WARNING_LOG(m_logger) << "onStartClicked called, but no selected streams available"; - return; - } - - m_avaCtrl->startStream(m_playbackApp.dialogId(), ALL_STREAMS(), currentSpeed()); - m_avaCtrl->positionUpdate(m_playbackApp.dialogId(), m_selectedStreams->first().toString(), std::chrono::seconds(1)); - setButtonStates(ButtonStates::Started); + m_avaCtrl->startStream(m_playbackApp.dialogId(), ALL_STREAMS(), currentSpeed()); + m_avaCtrl->positionUpdate(m_playbackApp.dialogId(), m_selectedStreams->first().toString(), std::chrono::seconds(1)); + setButtonStates(ButtonStates::Started); } void AvmPlaybackMenu::onPauseClicked() { - m_avaCtrl->pauseStream(m_playbackApp.dialogId(), ALL_STREAMS()); - setButtonStates(ButtonStates::Paused); + m_avaCtrl->pauseStream(m_playbackApp.dialogId(), ALL_STREAMS()); + setButtonStates(ButtonStates::Paused); } void AvmPlaybackMenu::onStopClicked() { - m_avaCtrl->stopStream(m_playbackApp.dialogId(), ALL_STREAMS()); - setButtonStates(ButtonStates::Stopped); + m_avaCtrl->stopStream(m_playbackApp.dialogId(), ALL_STREAMS()); + setButtonStates(ButtonStates::Stopped); } void AvmPlaybackMenu::onSkipPauseClicked() { - m_skipEmpty = !m_skipEmpty; - if (m_skipEmpty) - m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-nopause.svg"))); - else - m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-withpause.svg"))); - m_avaCtrl->setPint(m_playbackApp.dialogId(), ALL_STREAMS(), m_skipEmpty); + m_skipEmpty = !m_skipEmpty; + if (m_skipEmpty) + m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-nopause.svg"))); + else + m_ui->pbSkipPause->setIcon(QIcon(QStringLiteral("icon:media-vcr-withpause.svg"))); + m_avaCtrl->setPint(m_playbackApp.dialogId(), ALL_STREAMS(), m_skipEmpty); } void AvmPlaybackMenu::onAllStreams() { - QSignalBlocker block2(m_ui->cbMarkerStreams); - m_ui->cbMarkerStreams->clear(); - for (int i = 0; i < m_ui->cbStreams->count(); i++) - m_ui->cbMarkerStreams->addItem(m_ui->cbStreams->itemText(i), m_ui->cbStreams->itemData(i)); + QSignalBlocker block2(m_ui->cbMarkerStreams); + m_ui->cbMarkerStreams->clear(); + for (int i = 0; i < m_ui->cbStreams->count(); i++) + m_ui->cbMarkerStreams->addItem(m_ui->cbStreams->itemText(i), m_ui->cbStreams->itemData(i)); } void AvmPlaybackMenu::onIntervalBackwardClicked() { - const AvaTimelinePart &targetInterval = m_intervalModel.previousInterval(); - DEBUG_LOG(m_logger) << "onIntervalBackwardClicked " << std::chrono::milliseconds(targetInterval.first.time_since_epoch()).count(); - m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), targetInterval.first); + const AvaTimelinePart& targetInterval = m_intervalModel.previousInterval(); + DEBUG_LOG(m_logger) << "onIntervalBackwardClicked " + << std::chrono::milliseconds(targetInterval.first.time_since_epoch()).count(); + m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), targetInterval.first); } void AvmPlaybackMenu::onIntervalForwardClicked() { - const AvaTimelinePart &targetInterval = m_intervalModel.nextInterval(); - DEBUG_LOG(m_logger) << "onIntervalForwardClicked " << std::chrono::milliseconds(targetInterval.first.time_since_epoch()).count(); - m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), targetInterval.first); + const AvaTimelinePart& targetInterval = m_intervalModel.nextInterval(); + DEBUG_LOG(m_logger) << "onIntervalForwardClicked " + << std::chrono::milliseconds(targetInterval.first.time_since_epoch()).count(); + m_avaCtrl->setAbsPosition(m_playbackApp.dialogId(), ALL_STREAMS(), targetInterval.first); } - - void AvmPlaybackMenu::onSpeedChanged() { - m_ui->lbSpeedValue->setText(QString::number(currentSpeed())); - m_avaCtrl->setStreamSpeed(m_playbackApp.dialogId(), ALL_STREAMS(), currentSpeed()); - if ( m_currentButtonState == ButtonStates::Paused) - m_avaCtrl->pauseStream(m_playbackApp.dialogId(), ALL_STREAMS()); - else if ( m_currentButtonState == ButtonStates::Stopped) - m_avaCtrl->stopStream(m_playbackApp.dialogId(), ALL_STREAMS()); + m_ui->lbSpeedValue->setText(QString::number(currentSpeed())); + m_avaCtrl->setStreamSpeed(m_playbackApp.dialogId(), ALL_STREAMS(), currentSpeed()); + if (m_currentButtonState == ButtonStates::Paused) + m_avaCtrl->pauseStream(m_playbackApp.dialogId(), ALL_STREAMS()); + else if (m_currentButtonState == ButtonStates::Stopped) + m_avaCtrl->stopStream(m_playbackApp.dialogId(), ALL_STREAMS()); } void AvmPlaybackMenu::onVolumeChanged(int percent) { - m_ui->lbVolumeValue->setText(QString::number(percent)); - m_avaCtrl->setVolume(percent); + m_ui->lbVolumeValue->setText(QString::number(percent)); + m_avaCtrl->setVolume(percent); } - - -void AvmPlaybackMenu::onCurrentIntervalChanged(bool hasPreviousInterval, bool hasNextInterval, const QModelIndex &rowIndex) +void AvmPlaybackMenu::onCurrentIntervalChanged(bool hasPreviousInterval, bool hasNextInterval, + const QModelIndex& rowIndex) { - if (m_ui->tabWidget->currentIndex() == 0) - { - m_ui->pbIntervalBackward->setEnabled(hasPreviousInterval); - m_ui->pbIntervalForward->setEnabled(hasNextInterval); - } - else - { - m_ui->pbIntervalBackward->setEnabled(false); - m_ui->pbIntervalForward->setEnabled(false); - } + if (m_ui->tabWidget->currentIndex() == 0) + { + m_ui->pbIntervalBackward->setEnabled(hasPreviousInterval); + m_ui->pbIntervalForward->setEnabled(hasNextInterval); + } + else + { + m_ui->pbIntervalBackward->setEnabled(false); + m_ui->pbIntervalForward->setEnabled(false); + } - if (rowIndex.isValid()) - { - m_ui->tavIntervals->scrollTo(rowIndex); + if (rowIndex.isValid()) + { + m_ui->tavIntervals->scrollTo(rowIndex); - m_timeControl->setInterval(m_intervalModel.getRowData(rowIndex.row())); - return; - } + m_timeControl->setInterval(m_intervalModel.getRowData(rowIndex.row())); + return; + } - if (m_timelineBuilder->timeline().isEmpty()) - return; + if (m_timelineBuilder->timeline().isEmpty()) + return; - AvaTimelinePart interval{m_timelineBuilder->timeline().startTime(), m_timelineBuilder->timeline().endTime()}; - m_timeControl->setInterval(interval); + AvaTimelinePart interval{m_timelineBuilder->timeline().startTime(), m_timelineBuilder->timeline().endTime()}; + m_timeControl->setInterval(interval); } AvaSpeed AvmPlaybackMenu::currentSpeed() const { - int uiValue = m_ui->slSpeed->value(); - Q_ASSERT(uiValue < AvaSpeed::allowedValues().size()); - AvaSpeed speed = AvaSpeed::allowedValues().at(uiValue); - return speed; + int uiValue = m_ui->slSpeed->value(); + Q_ASSERT(uiValue < AvaSpeed::allowedValues().size()); + AvaSpeed speed = AvaSpeed::allowedValues().at(uiValue); + return speed; } - - void AvmPlaybackMenu::setButtonStates(ButtonStates s) { - switch (s) - { - case ButtonStates::AllOff: - m_ui->pbStart->setEnabled(false); - m_ui->pbStart->show(); - m_ui->pbPause->setEnabled(false); - m_ui->pbPause->hide(); - m_ui->pbStop->setEnabled(false); - m_ui->tvMarker->setEnabled(false); - m_ui->dtCurrentTime->setEnabled(false); - m_ui->slSequenceSlider->setEnabled(false); - m_ui->pbSetMarker->setEnabled(false); - break; + switch (s) + { + case ButtonStates::AllOff: + m_ui->pbStart->setEnabled(false); + m_ui->pbStart->show(); + m_ui->pbPause->setEnabled(false); + m_ui->pbPause->hide(); + m_ui->pbStop->setEnabled(false); + m_ui->tvMarker->setEnabled(false); + m_ui->dtCurrentTime->setEnabled(false); + m_ui->slSequenceSlider->setEnabled(false); + m_ui->pbSetMarker->setEnabled(false); + break; - case ButtonStates::Started: - m_ui->pbStart->setEnabled(false); - m_ui->pbStart->hide(); - m_ui->pbPause->setEnabled(true); - m_ui->pbPause->show(); - m_ui->pbStop->setEnabled(true); - m_ui->tvMarker->setEnabled(false); - m_ui->dtCurrentTime->setEnabled(false); - m_ui->slSequenceSlider->setEnabled(false); - m_ui->pbSetMarker->setEnabled(false); - break; + case ButtonStates::Started: + m_ui->pbStart->setEnabled(false); + m_ui->pbStart->hide(); + m_ui->pbPause->setEnabled(true); + m_ui->pbPause->show(); + m_ui->pbStop->setEnabled(true); + m_ui->tvMarker->setEnabled(false); + m_ui->dtCurrentTime->setEnabled(false); + m_ui->slSequenceSlider->setEnabled(false); + m_ui->pbSetMarker->setEnabled(false); + break; - case ButtonStates::Paused: - m_ui->pbStart->setEnabled(true); - m_ui->pbStart->show(); - m_ui->pbPause->setEnabled(false); - m_ui->pbPause->hide(); - m_ui->pbStop->setEnabled(true); - m_ui->tvMarker->setEnabled(true); - m_ui->dtCurrentTime->setEnabled(true); - m_ui->slSequenceSlider->setEnabled(true); - m_ui->pbSetMarker->setEnabled(true); - break; + case ButtonStates::Paused: + m_ui->pbStart->setEnabled(true); + m_ui->pbStart->show(); + m_ui->pbPause->setEnabled(false); + m_ui->pbPause->hide(); + m_ui->pbStop->setEnabled(true); + m_ui->tvMarker->setEnabled(true); + m_ui->dtCurrentTime->setEnabled(true); + m_ui->slSequenceSlider->setEnabled(true); + m_ui->pbSetMarker->setEnabled(true); + break; - case ButtonStates::Stopped: - m_ui->pbStart->setEnabled(true); - m_ui->pbStart->show(); - m_ui->pbPause->setEnabled(false); - m_ui->pbPause->hide(); - m_ui->pbStop->setEnabled(false); - m_ui->tvMarker->setEnabled(true); - m_ui->dtCurrentTime->setEnabled(true); - m_ui->slSequenceSlider->setEnabled(true); - m_ui->pbSetMarker->setEnabled(true); - break; - } - m_currentButtonState = s; + case ButtonStates::Stopped: + m_ui->pbStart->setEnabled(true); + m_ui->pbStart->show(); + m_ui->pbPause->setEnabled(false); + m_ui->pbPause->hide(); + m_ui->pbStop->setEnabled(false); + m_ui->tvMarker->setEnabled(true); + m_ui->dtCurrentTime->setEnabled(true); + m_ui->slSequenceSlider->setEnabled(true); + m_ui->pbSetMarker->setEnabled(true); + break; + } + m_currentButtonState = s; } void AvmPlaybackMenu::enableAll(bool enabled) { - m_ui->pbIntervalBackward->setEnabled(enabled); - m_ui->pbIntervalForward->setEnabled(enabled); - m_ui->pbSkipPause->setEnabled(enabled); - m_ui->slSpeed->setEnabled(enabled); - m_ui->slVolume->setEnabled(enabled); - m_ui->tavIntervals->setEnabled(enabled); - m_ui->tvMarker->setEnabled(enabled); - m_ui->cbStreams->setEnabled(enabled); + m_ui->pbIntervalBackward->setEnabled(enabled); + m_ui->pbIntervalForward->setEnabled(enabled); + m_ui->pbSkipPause->setEnabled(enabled); + m_ui->slSpeed->setEnabled(enabled); + m_ui->slVolume->setEnabled(enabled); + m_ui->tavIntervals->setEnabled(enabled); + m_ui->tvMarker->setEnabled(enabled); + m_ui->cbStreams->setEnabled(enabled); } void AvmPlaybackMenu::hideStreamSelection() { - - - m_ui->lblCbStreams->hide(); - m_ui->cbStreams->hide(); + + m_ui->lblCbStreams->hide(); + m_ui->cbStreams->hide(); } qint64 AvmPlaybackMenu::getCurrentTime() const { - return m_timeControl->timeMSec(); + return m_timeControl->timeMSec(); } AvaSpeed AvmPlaybackMenu::getSpeed() const { - return currentSpeed(); + return currentSpeed(); } void AvmPlaybackMenu::setSpeed(AvaSpeed newSpeed) { - m_ui->slSpeed->setValue(AvaSpeed::allowedValues().indexOf(newSpeed)); + m_ui->slSpeed->setValue(AvaSpeed::allowedValues().indexOf(newSpeed)); } - int AvmPlaybackMenu::getVolume() const { - return m_ui->slVolume->value(); + return m_ui->slVolume->value(); } void AvmPlaybackMenu::setVolume(int newVolume) { - m_ui->slVolume->setValue(newVolume); + m_ui->slVolume->setValue(newVolume); } -} +} // namespace AudioVideoManagement #include "avm_playback_menu.moc" - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.h old mode 100755 new mode 100644 index 700ab0d9a..d54dba320 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu.h @@ -1,33 +1,31 @@ - #pragma once -#include "ui_avm_playback_menu.h" #include "interval_model.h" -#include -#include +#include "ui_avm_playback_menu.h" + #include +#include #include +#include #include #include #include #include - namespace MarkerManagement { class MarkerManagementDialogModel; class MarkerSortFilterProxyModel; class ForeignDataInterface; -} +} // namespace MarkerManagement namespace LtsUtils { class RequestHelper; } - namespace AudioVideoManagement { @@ -37,180 +35,176 @@ class AvsSequence; class StreamNameMapping; class AvmPlaybackMenu; - class QueryTimeline : public QObject { - Q_OBJECT -private: -NGL::INGLLogger &m_logger; - friend class AvmPlaybackMenu; + Q_OBJECT + private: + NGL::INGLLogger& m_logger; + friend class AvmPlaybackMenu; - QueryTimeline(const AvaStream &stream, const AvaTimePoint &start, const AvaTimePoint &end, AvaControl *control); + QueryTimeline(const AvaStream& stream, const AvaTimePoint& start, const AvaTimePoint& end, AvaControl* control); - AvaControl *m_avaCtrl { nullptr }; + AvaControl* m_avaCtrl{nullptr}; -private slots: - + private slots: -signals: - void signalTimelineComplete(const AvaTimeline &timeline); + signals: + void signalTimelineComplete(const AvaTimeline& timeline); }; - -class AvmPlaybackMenu : public QWidget, - protected MarkerManagement::Interface::Ftc::MarkerModifyReplyHandler +class AvmPlaybackMenu : public QWidget, protected MarkerManagement::Interface::Ftc::MarkerModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit AvmPlaybackMenu(QWidget *parent = nullptr); - ~AvmPlaybackMenu(); + public: + explicit AvmPlaybackMenu(QWidget* parent = nullptr); + ~AvmPlaybackMenu(); - bool init(LtsSession::LtsSession *session, AvaSession *avaSession, PlaybackAppHandle &&appHandle, - StreamNameMapping* streamNameMapping, bool isAudio, bool insideTopicEditor, - const boost::optional &streamName = boost::none, - const boost::optional &startTime = boost::none, bool setInitialSearchContentMarkers = true); + bool init(LtsSession::LtsSession* session, AvaSession* avaSession, PlaybackAppHandle&& appHandle, + StreamNameMapping* streamNameMapping, bool isAudio, bool insideTopicEditor, + const boost::optional& streamName = boost::none, + const boost::optional& startTime = boost::none, bool setInitialSearchContentMarkers = true); - void setPlaybackPreset(const QString &streamName, const AvaTimePoint &startTime, bool autostartPresetAfterInit); - void setMarkerPreset(int markerId, bool autostartPresetAfterInit); + void setPlaybackPreset(const QString& streamName, const AvaTimePoint& startTime, bool autostartPresetAfterInit); + void setMarkerPreset(int markerId, bool autostartPresetAfterInit); - QueryTimeline *queryTimeline(const AvaTimePoint &start, const AvaTimePoint &end); + QueryTimeline* queryTimeline(const AvaTimePoint& start, const AvaTimePoint& end); - void onMarkerModifyReply(const Core::FunctionReplyObject &replyObject) override final; + void onMarkerModifyReply(const Core::FunctionReplyObject& replyObject) override final; - void retranslate(); + void retranslate(); - - void setStreamTime(qint64 time); - void hideStreamSelection(); - qint64 getCurrentTime() const; - AvaSpeed getSpeed() const; - void setSpeed(AvaSpeed newSpeed); - int getVolume() const; - void setVolume(int newVolume); - void setStreamByName(const QString &name); - - QString getInternalStreamName() const; - void setStreamName(const QString &internalStreamName); - bool getSkipPause() const; - void setSkipPause(bool bSkip); - void startPlayback(bool usePresets = false); - void setSavedPos(qint64 msecs); - int currentOffset() const { return m_currentOffset; } - void selectMarker(const MarkerManagement::Marker &marker); - void selectMarker(int markerId); + void setStreamTime(qint64 time); + void hideStreamSelection(); + qint64 getCurrentTime() const; + AvaSpeed getSpeed() const; + void setSpeed(AvaSpeed newSpeed); + int getVolume() const; + void setVolume(int newVolume); + void setStreamByName(const QString& name); -signals: - void signalSetOverlay(QWidget *widget); - void signalUnsetOverlay(); + QString getInternalStreamName() const; + void setStreamName(const QString& internalStreamName); + bool getSkipPause() const; + void setSkipPause(bool bSkip); + void startPlayback(bool usePresets = false); + void setSavedPos(qint64 msecs); - void setTopicButtonStates(bool enable); - void markerSelected(const QString &description); + int currentOffset() const + { + return m_currentOffset; + } - - void signalSetStart(qint64 start); - void signalSetEnd(qint64 end); - void signalCurrentStreamChanged(const QString &displayName); - void signalTimezoneChanged(int timezoneHoursOffset); + void selectMarker(const MarkerManagement::Marker& marker); + void selectMarker(int markerId); -public slots: - void onStreamSelectionChanged(const QVector &selectedStreams); + signals: + void signalSetOverlay(QWidget* widget); + void signalUnsetOverlay(); -private slots: - void onSessionEstablished(); - void onDisconnected(); + void setTopicButtonStates(bool enable); + void markerSelected(const QString& description); - void onStreamListReceived(const QVector &streams); - void onTimelineComplete(const AvaTimeline &timeline); - void onStreamPositionReceived(const QString &dialogId, const QString &streamName, AvaTimePoint); - void onVolumeReceived(AvaVolume db); - void onCommandQueueEmpty(); + void signalSetStart(qint64 start); + void signalSetEnd(qint64 end); + void signalCurrentStreamChanged(const QString& displayName); + void signalTimezoneChanged(int timezoneHoursOffset); - void onUiTimeChanged(AvaTimePoint t); - void onIntervalActivated(const QModelIndex &index); - void onMarkerClicked(const QModelIndex &index); - void onSetMarkerClicked(); - void onStartClicked(); - void onPauseClicked(); - void onStopClicked(); - void onSkipPauseClicked(); - void onAllStreams(); - void onIntervalBackwardClicked(); - void onIntervalForwardClicked(); - void onSpeedChanged(); - void onVolumeChanged(int percent); - void onCurrentIntervalChanged(bool hasPreviousInterval, bool hasNextInterval, const QModelIndex &rowIndex); - void onStreamSelected(); - void onMarkerStreamSelected(); - void onStreamNameMappingChanged(); - void onAddStreamClip(); - void onAddStreamMarker(); - void onRemoveSelectedStreams(); - void onTabChanged(int index); - void onPauseFromPlaybackApp(); - void onResumeFromPlaybackApp(); + public slots: + void onStreamSelectionChanged(const QVector& selectedStreams); + private slots: + void onSessionEstablished(); + void onDisconnected(); -private: - enum class ButtonStates - { - AllOff, - Started, - Paused, - Stopped - }; + void onStreamListReceived(const QVector& streams); + void onTimelineComplete(const AvaTimeline& timeline); + void onStreamPositionReceived(const QString& dialogId, const QString& streamName, AvaTimePoint); + void onVolumeReceived(AvaVolume db); + void onCommandQueueEmpty(); - void processPresets(); - void preselectStream(const QString &fallbackInternalStreamName); - AvaSpeed currentSpeed() const; - void setButtonStates(ButtonStates); - void enableAll(bool enabled = true); - void disableAll() { enableAll(false); } - bool trySelectedStreams(); - void addStream(QComboBox *cb); + void onUiTimeChanged(AvaTimePoint t); + void onIntervalActivated(const QModelIndex& index); + void onMarkerClicked(const QModelIndex& index); + void onSetMarkerClicked(); + void onStartClicked(); + void onPauseClicked(); + void onStopClicked(); + void onSkipPauseClicked(); + void onAllStreams(); + void onIntervalBackwardClicked(); + void onIntervalForwardClicked(); + void onSpeedChanged(); + void onVolumeChanged(int percent); + void onCurrentIntervalChanged(bool hasPreviousInterval, bool hasNextInterval, const QModelIndex& rowIndex); + void onStreamSelected(); + void onMarkerStreamSelected(); + void onStreamNameMappingChanged(); + void onAddStreamClip(); + void onAddStreamMarker(); + void onRemoveSelectedStreams(); + void onTabChanged(int index); + void onPauseFromPlaybackApp(); + void onResumeFromPlaybackApp(); - void applyAvsPos(); - void applyAvsVolume(); - + private: + enum class ButtonStates { AllOff, Started, Paused, Stopped }; - PlaybackAppHandle m_playbackApp; - bool m_isAudio = false; - StreamNameMapping *m_streamNameMapping = nullptr; - boost::optional m_presetStreamName; - boost::optional m_markerIdPreset; - boost::optional m_presetStartTime; + void processPresets(); + void preselectStream(const QString& fallbackInternalStreamName); + AvaSpeed currentSpeed() const; + void setButtonStates(ButtonStates); + void enableAll(bool enabled = true); - class TimelineBuilder; - std::unique_ptr m_timelineBuilder; + void disableAll() + { + enableAll(false); + } - std::unique_ptr m_ui; + bool trySelectedStreams(); + void addStream(QComboBox* cb); - class TimeControl; - std::unique_ptr m_timeControl; + void applyAvsPos(); + void applyAvsVolume(); - boost::optional> m_selectedStreams; - IntervalModel m_intervalModel; - boost::optional m_savedPos; - std::unique_ptr m_markerModel; - std::unique_ptr m_markerProxy; - AvaControl *m_avaCtrl = nullptr; - LtsSession::LtsSession *m_session = nullptr; - bool m_skipEmpty = true; - ButtonStates m_currentButtonState; - std::shared_ptr m_mrkDataIfc; - boost::optional m_lastAvsPos; - boost::optional m_lastAvsVolume; - std::unique_ptr m_requestHelper; - QVector m_streams; - boost::optional m_currentStream; - bool m_autostartOnce { false }; - int m_maxSelectedStreams = 12; - bool m_queryTimelineActive { false }; - int m_currentOffset = 0; + PlaybackAppHandle m_playbackApp; + bool m_isAudio = false; + StreamNameMapping* m_streamNameMapping = nullptr; + boost::optional m_presetStreamName; + boost::optional m_markerIdPreset; + boost::optional m_presetStartTime; - bool m_videoScreenSelectionDone { false }; - bool m_timelineIsComplete { false }; - ButtonStates m_buttonStateBeforePlaybackAppPause { ButtonStates::AllOff }; + class TimelineBuilder; + std::unique_ptr m_timelineBuilder; + + std::unique_ptr m_ui; + + class TimeControl; + std::unique_ptr m_timeControl; + + boost::optional> m_selectedStreams; + IntervalModel m_intervalModel; + boost::optional m_savedPos; + std::unique_ptr m_markerModel; + std::unique_ptr m_markerProxy; + AvaControl* m_avaCtrl = nullptr; + LtsSession::LtsSession* m_session = nullptr; + bool m_skipEmpty = true; + ButtonStates m_currentButtonState; + std::shared_ptr m_mrkDataIfc; + boost::optional m_lastAvsPos; + boost::optional m_lastAvsVolume; + std::unique_ptr m_requestHelper; + QVector m_streams; + boost::optional m_currentStream; + bool m_autostartOnce{false}; + int m_maxSelectedStreams = 12; + bool m_queryTimelineActive{false}; + int m_currentOffset = 0; + + bool m_videoScreenSelectionDone{false}; + bool m_timelineIsComplete{false}; + ButtonStates m_buttonStateBeforePlaybackAppPause{ButtonStates::AllOff}; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu_dialog.h old mode 100755 new mode 100644 index b89b3944e..cb6489236 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_playback_menu_dialog.h @@ -1,38 +1,38 @@ - #pragma once #include "ui_avm_playback_menu_dialog.h" -#include -#include -#include + #include +#include #include +#include +#include #include -namespace Ui { +namespace Ui +{ class AvmPlaybackMenuDialog; } + namespace AudioVideoManagement { class AvmPlaybackMenuDialog : public LtsWidgets::LtsDialog { - Q_OBJECT -public: - AvmPlaybackMenuDialog(bool isAudio, QWidget *parent); - AudioVideoManagement::AvmPlaybackMenu *avmPlaybackMenu(); + Q_OBJECT + public: + AvmPlaybackMenuDialog(bool isAudio, QWidget* parent); + AudioVideoManagement::AvmPlaybackMenu* avmPlaybackMenu(); - ~AvmPlaybackMenuDialog(); + ~AvmPlaybackMenuDialog(); - void retranslate() override; + void retranslate() override; -private: - -NGL::INGLLogger &m_logger; - bool m_isAudio; - Ui::AvmPlaybackMenuDialog *m_ui; - + private: + NGL::INGLLogger& m_logger; + bool m_isAudio; + Ui::AvmPlaybackMenuDialog* m_ui; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.cpp old mode 100755 new mode 100644 index a2800ebcf..db31b58d4 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.cpp @@ -1,676 +1,634 @@ - #include "avm_used_streams_model.h" -#include + #include "avm_available_streams_model.h" + #include -#include #include #include +#include +#include namespace AudioVideoManagement { const QString UsedStreamsModel::s_MimeTypeOI = QStringLiteral("UsedStreamsModel/OrderItem"); -UsedStreamsModel::UsedStreamsModel(const std::shared_ptr avmDtc, const std::shared_ptr ismDtc, - const MenuStruct &ms, - StreamNameMapping *streamNameMapping, - QObject *parent) - : NGLTreeModel(parent, nullptr, {tr("Streams")}) -, m_avmDtc(avmDtc) -, m_ismDtc(ismDtc) -, m_dummyId(-10000000) -, m_menuStruct(ms) -, m_streamNameMapping(streamNameMapping) +UsedStreamsModel::UsedStreamsModel(const std::shared_ptr avmDtc, + const std::shared_ptr ismDtc, + const MenuStruct& ms, StreamNameMapping* streamNameMapping, QObject* parent) + : NGLTreeModel(parent, nullptr, {tr("Streams")}), m_avmDtc(avmDtc), m_ismDtc(ismDtc), m_dummyId(-10000000), + m_menuStruct(ms), m_streamNameMapping(streamNameMapping) { - Q_ASSERT(streamNameMapping); - initModel(); + Q_ASSERT(streamNameMapping); + initModel(); } -QVariant UsedStreamsModel::data(const QModelIndex &index, int role) const +QVariant UsedStreamsModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) - return QVariant(); + if (!index.isValid()) + return QVariant(); - NGLTreeItem *item = privateData(index); - if (!item->data().canConvert()) - return QVariant(); + NGLTreeItem* item = privateData(index); + if (!item->data().canConvert()) + return QVariant(); - const StreamModelData availStream = item->data().value(); + const StreamModelData availStream = item->data().value(); - switch (role) - { - case Qt::DisplayRole: - case Qt::EditRole: - { - switch (index.column()) + switch (role) { - case 0: - return availStream.name; - default: - return QStringLiteral("??"); + case Qt::DisplayRole: + case Qt::EditRole: { + switch (index.column()) + { + case 0: + return availStream.name; + default: + return QStringLiteral("??"); + } + break; + } + case Qt::DecorationRole: { + switch (index.column()) + { + case 0: { + static const QIcon folder(QStringLiteral("icon:evaluation_folder.svg")); + static const QIcon camera(QStringLiteral("icon:camera_control.svg")); + return availStream.isGroup ? folder : camera; + } + default: + break; + } + break; + } + default: + break; } - break; - } - case Qt::DecorationRole: - { - switch (index.column()) - { - case 0: - { - static const QIcon folder(QStringLiteral("icon:evaluation_folder.svg")); - static const QIcon camera(QStringLiteral("icon:camera_control.svg")); - return availStream.isGroup ? folder : camera; - } - default: - break; - } - break; - } - default: - break; - } - return NGLTreeModel::data(index, role); + return NGLTreeModel::data(index, role); } -Qt::ItemFlags UsedStreamsModel::flags(const QModelIndex &index) const +Qt::ItemFlags UsedStreamsModel::flags(const QModelIndex& index) const { - Qt::ItemFlags defaultFlags = NGLTreeModel::flags(index); + Qt::ItemFlags defaultFlags = NGLTreeModel::flags(index); - if (index.isValid()) - { - defaultFlags ^= Qt::ItemIsDropEnabled; - NGLTreeItem *item = privateData(index); - if (item->data().canConvert()) + if (index.isValid()) { - StreamModelData menuEntry = item->data().value(); + defaultFlags ^= Qt::ItemIsDropEnabled; + NGLTreeItem* item = privateData(index); + if (item->data().canConvert()) + { + StreamModelData menuEntry = item->data().value(); + defaultFlags |= Qt::ItemIsDragEnabled; - defaultFlags |= Qt::ItemIsDragEnabled; - - if (menuEntry.isGroup) - { - defaultFlags |= Qt::ItemIsEditable; + if (menuEntry.isGroup) + { + defaultFlags |= Qt::ItemIsEditable; + defaultFlags |= Qt::ItemIsDropEnabled; + } + } + } + else defaultFlags |= Qt::ItemIsDropEnabled; - } - } - } - else - defaultFlags |= Qt::ItemIsDropEnabled; - return defaultFlags; + return defaultFlags; } - -QMimeData *UsedStreamsModel::mimeData(const QModelIndexList &indexes) const +QMimeData* UsedStreamsModel::mimeData(const QModelIndexList& indexes) const { - QString type = AvailableStreamsModel::s_MimeType; - for (const QModelIndex &mi : indexes) - { - if (mimeType(mi) == s_MimeTypeOI) + QString type = AvailableStreamsModel::s_MimeType; + for (const QModelIndex& mi : indexes) { - type = s_MimeTypeOI; - break; + if (mimeType(mi) == s_MimeTypeOI) + { + type = s_MimeTypeOI; + break; + } } - } - return getMimeData(indexes, type); + return getMimeData(indexes, type); } -bool UsedStreamsModel::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool UsedStreamsModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - Q_UNUSED(column); + Q_UNUSED(column); - if (action == Qt::IgnoreAction) - return true; + if (action == Qt::IgnoreAction) + return true; - if (!checkDrop(data, index(row, column), parent, action)) - return false; + if (!checkDrop(data, index(row, column), parent, action)) + return false; - INFO_LOG(m_logger) << "dropMimeData: action = " << action - << ", row = " << row - << ", parent: valid = " << parent.isValid(); + INFO_LOG(m_logger) << "dropMimeData: action = " << action << ", row = " << row + << ", parent: valid = " << parent.isValid(); - - - int beginRow; - QModelIndex parentR; - if (row != -1) - { - - parentR = parent; - beginRow = row; - } - else if (parent.isValid()) - { - - - parentR = parent; - - beginRow = rowCount(parentR); - } - else - { - - parentR = QModelIndex(); - beginRow = rowCount(parentR); - } + int beginRow; + QModelIndex parentR; + if (row != -1) + { - QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; - bool ret = insertMimeData(data, mimeType, parentR, beginRow); - if (ret) - { - - fixUpData(m_rootItem); - } - return ret; + parentR = parent; + beginRow = row; + } + else if (parent.isValid()) + { + + parentR = parent; + + beginRow = rowCount(parentR); + } + else + { + + parentR = QModelIndex(); + beginRow = rowCount(parentR); + } + + QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; + bool ret = insertMimeData(data, mimeType, parentR, beginRow); + if (ret) + { + + fixUpData(m_rootItem); + } + return ret; } -bool UsedStreamsModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) const +bool UsedStreamsModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const { - if (!NGLTreeModel::canDropMimeData(data, action, row, column, parent)) - return false; + if (!NGLTreeModel::canDropMimeData(data, action, row, column, parent)) + return false; - if (!data->hasFormat(AvailableStreamsModel::s_MimeType) && !data->hasFormat(s_MimeTypeOI)) - return false; + if (!data->hasFormat(AvailableStreamsModel::s_MimeType) && !data->hasFormat(s_MimeTypeOI)) + return false; - if ((action != Qt::MoveAction) && (action != Qt::CopyAction)) - return false; + if ((action != Qt::MoveAction) && (action != Qt::CopyAction)) + return false; - if (!checkDrop(data, parent, parent, action)) - return false; + if (!checkDrop(data, parent, parent, action)) + return false; + + if (!parent.isValid()) + return true; + NGLTreeItem* item = privateData(parent); + QVariant v = item->data(); + StreamModelData ms = v.value(); + if (!ms.isGroup) + return false; + + QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; + QByteArray encodedData = data->data(mimeType); + QDataStream stream(&encodedData, QIODevice::ReadOnly); + qint64 idParent, idItem, mountId; + bool group; + QVariant itemData; + + stream >> idParent >> idItem >> group >> itemData >> mountId; + ms = itemData.value(); + INFO_LOG(m_logger) << "Insert:" + << "\n ms.name=" << ms.name << "\n ms.isGroup=" << ms.isGroup << "\n ms.parentId=" << ms.parentId + << "\n ms.mountingPointId=" << ms.mountingPointId; + + if (ms.isGroup) + return false; - if (!parent.isValid()) return true; - NGLTreeItem *item = privateData(parent); - QVariant v = item->data(); - StreamModelData ms = v.value(); - if (!ms.isGroup) - return false; - - QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; - QByteArray encodedData = data->data(mimeType); - QDataStream stream(&encodedData, QIODevice::ReadOnly); - qint64 idParent, idItem, mountId; - bool group; - QVariant itemData; - - stream >> idParent >> idItem >> group >> itemData >> mountId; - ms = itemData.value(); - INFO_LOG(m_logger) << "Insert:" - << "\n ms.name=" << ms.name - << "\n ms.isGroup=" << ms.isGroup - << "\n ms.parentId=" << ms.parentId - << "\n ms.mountingPointId=" << ms.mountingPointId; - - if (ms.isGroup) - return false; - - return true; } - QStringList UsedStreamsModel::mimeTypes() const { - return { AvailableStreamsModel::s_MimeType, s_MimeTypeOI }; + return {AvailableStreamsModel::s_MimeType, s_MimeTypeOI}; } -QString UsedStreamsModel::mimeType(const QModelIndex &index) const +QString UsedStreamsModel::mimeType(const QModelIndex& index) const { - if (index.isValid()) - { - NGLTreeItem *item = privateData(index); - QVariant v = item->data(); - StreamModelData ms = v.value(); - if (ms.parentId == -1) - return s_MimeTypeOI; - - return AvailableStreamsModel::s_MimeType; - } - return s_MimeTypeOI; -} - - -static void getItems(const NGLTreeItem *item, - int rowId, - int parentId, - std::vector &contToAdd, - int &newId) -{ - if (item->data().canConvert()) - { - StreamModelData s = item->data().value(); - - AvMenuEntry me; - me.id(s.id ? s.id : newId++); - me.parentId(parentId); - me.isGroup(s.isGroup); - if (s.isGroup) - me.name().set(s.name.toStdString()); - else - me.mountingPointId(s.mountingPointId); - me.rowId(rowId); - - contToAdd.push_back(me); - - if (s.isGroup) + if (index.isValid()) { - for (int row = 0; row < item->childCount(); ++row) - getItems(item->child(row), row + 1, me.id(), contToAdd, newId); + NGLTreeItem* item = privateData(index); + QVariant v = item->data(); + StreamModelData ms = v.value(); + if (ms.parentId == -1) + return s_MimeTypeOI; + + return AvailableStreamsModel::s_MimeType; } - } + return s_MimeTypeOI; } +static void getItems(const NGLTreeItem* item, int rowId, int parentId, + std::vector& contToAdd, int& newId) +{ + if (item->data().canConvert()) + { + StreamModelData s = item->data().value(); + + AvMenuEntry me; + me.id(s.id ? s.id : newId++); + me.parentId(parentId); + me.isGroup(s.isGroup); + if (s.isGroup) + me.name().set(s.name.toStdString()); + else + me.mountingPointId(s.mountingPointId); + me.rowId(rowId); + + contToAdd.push_back(me); + + if (s.isGroup) + { + for (int row = 0; row < item->childCount(); ++row) + getItems(item->child(row), row + 1, me.id(), contToAdd, newId); + } + } +} MenuStruct UsedStreamsModel::getMenuStruct() const { - MenuStruct ms; - ms.id(m_menuStruct.id()); - ms.name(m_menuStruct.name()); + MenuStruct ms; + ms.id(m_menuStruct.id()); + ms.name(m_menuStruct.name()); - int newId = -10000000; - for (int row = 0; row < m_rootItem->childCount(); ++row) - getItems(m_rootItem->child(row), row + 1, ms.id(), ms.menuEntries(), newId); + int newId = -10000000; + for (int row = 0; row < m_rootItem->childCount(); ++row) + getItems(m_rootItem->child(row), row + 1, ms.id(), ms.menuEntries(), newId); - return ms; + return ms; } - -void UsedStreamsModel::insertChildren(NGLTreeItem *parent, int parentId, const std::vector &entries) +void UsedStreamsModel::insertChildren(NGLTreeItem* parent, int parentId, + const std::vector& entries) { - QVariant data; - QMap rowIds; - for (const AudioVideoManagement::AvMenuEntry &me : entries) - { - if (me.parentId() != parentId) - continue; - - data.setValue(StreamModelData::createFromServiceItem(me, m_streamNameMapping, m_avmDtc->videoTeams())); - - - NGLTreeItem *treeItem = new NGLTreeItem(data); - - - auto hierIt = rowIds.insert(me.rowId(), me.rowId()); - const int rowToInsert = std::distance(rowIds.begin(), hierIt); - - parent->insertChild(rowToInsert, treeItem); - - if (me.isGroup()) + QVariant data; + QMap rowIds; + for (const AudioVideoManagement::AvMenuEntry& me : entries) { - DEBUG_LOG(m_logger) << "insertChildren" - << me.mountingPointId() - << me.name(); - insertChildren(treeItem, me.id(), entries); - } - } -} + if (me.parentId() != parentId) + continue; -NGLTreeItem *UsedStreamsModel::getItemToCheck(const QModelIndex &index, const QModelIndex &parentIndex) const -{ + data.setValue(StreamModelData::createFromServiceItem(me, m_streamNameMapping, m_avmDtc->videoTeams())); - NGLTreeItem *item = privateData(index); - QVariant v = item->data(); - StreamModelData ms = v.value(); + NGLTreeItem* treeItem = new NGLTreeItem(data); - NGLTreeItem *itemParent = privateData(parentIndex); - const QVariant &variantParent = itemParent->data(); - NGLTreeItem *itemToCheck = itemParent; - const StreamModelData &msParent = variantParent.value(); + auto hierIt = rowIds.insert(me.rowId(), me.rowId()); + const int rowToInsert = std::distance(rowIds.begin(), hierIt); - if (!ms.isGroup && msParent.isGroup) - itemToCheck = itemParent; + parent->insertChild(rowToInsert, treeItem); - if (!ms.isGroup && !msParent.isGroup) - itemToCheck = m_rootItem; - - return itemToCheck; -} - -bool UsedStreamsModel::checkSingleItem(NGLTreeItem *target, StreamModelData &toCheck) const -{ - bool retValue = true; - if (!target) - { - ERROR_LOG(m_logger) << "Nullptr exception"; - return false; - } - else - { - - StreamModelData msTarget = target->data().value(); - if (msTarget.id == toCheck.parentId) - DEBUG_LOG(m_logger) << "Drag&drag in same folder."; - else if (msTarget.isGroup && toCheck.isGroup) - { - DEBUG_LOG(m_logger) << "Trying to drop folder into folder"; - retValue = false; - } - else - { - - const QVector &children = target->children(); - for (const NGLTreeItem *childData : children) - { - const QVariant &variantCheck = childData->data(); - const StreamModelData &msChild = variantCheck.value(); - if ((msChild.name == toCheck.name) && (msChild.id != toCheck.id)) + if (me.isGroup()) { - retValue = false; - break; + DEBUG_LOG(m_logger) << "insertChildren" << me.mountingPointId() << me.name(); + insertChildren(treeItem, me.id(), entries); } - } } - } - return retValue; } -bool UsedStreamsModel::checkDrop(const QMimeData *data, const QModelIndex &index, const QModelIndex &parentIndex, Qt::DropAction action) const +NGLTreeItem* UsedStreamsModel::getItemToCheck(const QModelIndex& index, const QModelIndex& parentIndex) const { - - + NGLTreeItem* item = privateData(index); + QVariant v = item->data(); + StreamModelData ms = v.value(); - NGLTreeItem *itemToCheck = getItemToCheck(index, parentIndex); + NGLTreeItem* itemParent = privateData(parentIndex); + const QVariant& variantParent = itemParent->data(); + NGLTreeItem* itemToCheck = itemParent; + const StreamModelData& msParent = variantParent.value(); - - - QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; - QByteArray encodedData = data->data(mimeType); - QList items; - QDataStream stream(&encodedData, QIODevice::ReadOnly); - qint64 idParent, idItem; - bool containsIcon; - QVariant itemData; - QIcon tmp; + if (!ms.isGroup && msParent.isGroup) + itemToCheck = itemParent; - stream >> containsIcon; - while (!stream.atEnd()) - { - stream >> idParent >> idItem >> itemData; - if (containsIcon) - stream >> tmp; - items.push_back(itemData.value()); - } + if (!ms.isGroup && !msParent.isGroup) + itemToCheck = m_rootItem; + return itemToCheck; +} - - int countDropped = 0; - int countAgainst = 0; - const QVector &children = itemToCheck->children(); - for (const auto &item : children) - { - const QVariant &variantCheck = item->data(); - const StreamModelData &msCheck = variantCheck.value(); - - if (msCheck.isGroup) - continue; - ++countAgainst; - } - - QList movedFolders; - bool onlyOneFolder = false; - for (StreamModelData &item : items) - { - - StreamModelData msToCheck = itemToCheck->data().value(); - if (movedFolders.size() == 0) +bool UsedStreamsModel::checkSingleItem(NGLTreeItem* target, StreamModelData& toCheck) const +{ + bool retValue = true; + if (!target) { - - movedFolders.push_back(item.parentId); - } - - if ((item.isGroup) && movedFolders.contains(item.parentId)) - movedFolders.push_back(item.id); - - else if ((movedFolders.at(0) != item.parentId) && (movedFolders.contains(item.parentId)) && (action == Qt::MoveAction)) - { - DEBUG_LOG(m_logger) << "Ignoring items in sub folder while moving."; - continue; - } - - else if (!movedFolders.contains(item.parentId) && (action == Qt::MoveAction)) - { - DEBUG_LOG(m_logger) << "Only allow items from same folder to be moved."; - return false; - } - if (!checkSingleItem(itemToCheck, item)) - { - DEBUG_LOG(m_logger) << "Not able to add item with name: " << item.name; - return false; - } - - if (item.isGroup) - { - if (!onlyOneFolder) - { - onlyOneFolder = true; - continue; - } - else - { - DEBUG_LOG(m_logger) << "More than one folder selected."; + ERROR_LOG(m_logger) << "Nullptr exception"; return false; - } } - if ((msToCheck.id == item.parentId) && (Qt::MoveAction == action)) - continue; - ++countDropped; - } - - if (countDropped + countAgainst > 12) - { - DEBUG_LOG(m_logger) << "Trying to add to many items to folder"; - return false; - } - return true; - -} - -QSet UsedStreamsModel::fillTakenCameras(NGLTreeItem *getItem) const -{ - QSet ret; - const QVector &children = getItem->children(); - for (const auto &item : std::as_const(children)) - { - if (item->childCount()) - ret += fillTakenCameras(item); else { - const QVariant &variantCheck = item->data(); - const StreamModelData &msCheck = variantCheck.value(); - if (msCheck.isGroup) - continue; - ret.insert(msCheck.mountingPointId); + StreamModelData msTarget = target->data().value(); + if (msTarget.id == toCheck.parentId) + DEBUG_LOG(m_logger) << "Drag&drag in same folder."; + else if (msTarget.isGroup && toCheck.isGroup) + { + DEBUG_LOG(m_logger) << "Trying to drop folder into folder"; + retValue = false; + } + else + { + + const QVector& children = target->children(); + for (const NGLTreeItem* childData : children) + { + const QVariant& variantCheck = childData->data(); + const StreamModelData& msChild = variantCheck.value(); + if ((msChild.name == toCheck.name) && (msChild.id != toCheck.id)) + { + retValue = false; + break; + } + } + } } - } - return ret; + return retValue; +} + +bool UsedStreamsModel::checkDrop(const QMimeData* data, const QModelIndex& index, const QModelIndex& parentIndex, + Qt::DropAction action) const +{ + + NGLTreeItem* itemToCheck = getItemToCheck(index, parentIndex); + + QString mimeType = data->hasFormat(s_MimeTypeOI) ? s_MimeTypeOI : AvailableStreamsModel::s_MimeType; + QByteArray encodedData = data->data(mimeType); + QList items; + QDataStream stream(&encodedData, QIODevice::ReadOnly); + qint64 idParent, idItem; + bool containsIcon; + QVariant itemData; + QIcon tmp; + + stream >> containsIcon; + while (!stream.atEnd()) + { + stream >> idParent >> idItem >> itemData; + if (containsIcon) + stream >> tmp; + items.push_back(itemData.value()); + } + + int countDropped = 0; + int countAgainst = 0; + const QVector& children = itemToCheck->children(); + for (const auto& item : children) + { + const QVariant& variantCheck = item->data(); + const StreamModelData& msCheck = variantCheck.value(); + + if (msCheck.isGroup) + continue; + ++countAgainst; + } + + QList movedFolders; + bool onlyOneFolder = false; + for (StreamModelData& item : items) + { + + StreamModelData msToCheck = itemToCheck->data().value(); + if (movedFolders.size() == 0) + { + + movedFolders.push_back(item.parentId); + } + + if ((item.isGroup) && movedFolders.contains(item.parentId)) + movedFolders.push_back(item.id); + + else if ((movedFolders.at(0) != item.parentId) && (movedFolders.contains(item.parentId)) && + (action == Qt::MoveAction)) + { + DEBUG_LOG(m_logger) << "Ignoring items in sub folder while moving."; + continue; + } + + else if (!movedFolders.contains(item.parentId) && (action == Qt::MoveAction)) + { + DEBUG_LOG(m_logger) << "Only allow items from same folder to be moved."; + return false; + } + if (!checkSingleItem(itemToCheck, item)) + { + DEBUG_LOG(m_logger) << "Not able to add item with name: " << item.name; + return false; + } + + if (item.isGroup) + { + if (!onlyOneFolder) + { + onlyOneFolder = true; + continue; + } + else + { + DEBUG_LOG(m_logger) << "More than one folder selected."; + return false; + } + } + if ((msToCheck.id == item.parentId) && (Qt::MoveAction == action)) + continue; + ++countDropped; + } + + if (countDropped + countAgainst > 12) + { + DEBUG_LOG(m_logger) << "Trying to add to many items to folder"; + return false; + } + return true; +} + +QSet UsedStreamsModel::fillTakenCameras(NGLTreeItem* getItem) const +{ + QSet ret; + const QVector& children = getItem->children(); + for (const auto& item : std::as_const(children)) + { + if (item->childCount()) + ret += fillTakenCameras(item); + else + { + const QVariant& variantCheck = item->data(); + const StreamModelData& msCheck = variantCheck.value(); + + if (msCheck.isGroup) + continue; + ret.insert(msCheck.mountingPointId); + } + } + return ret; } bool UsedStreamsModel::initModel() { - beginResetModel(); + beginResetModel(); - StreamModelData ms; - ms.parentId = -1; - ms.id = -2; + StreamModelData ms; + ms.parentId = -1; + ms.id = -2; - QVariant data; - data.setValue(ms); - setRootItem(new NGLTreeItem(data)); - - insertChildren(m_rootItem, m_menuStruct.id(), m_menuStruct.menuEntries()); - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, - this, &UsedStreamsModel::onDataChanged); - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, - this, &UsedStreamsModel::onDataChangedMvs); - - - connect(m_streamNameMapping, &StreamNameMapping::changed, - this, &UsedStreamsModel::onStreamNameDataChanged); - endResetModel(); - return true; -} - -NGLTreeItem *UsedStreamsModel::createItem(const QVariant &data, const QIcon &icon) const -{ - StreamModelData s = data.value(); - - s.id = 0; - s.parentId = 0; - QVariant newData; - newData.setValue(s); - return new NGLTreeItem(newData, icon); -} - - -bool UsedStreamsModel::setData(const QModelIndex &idx, const QVariant &value, int role) -{ - Q_UNUSED(role); - - if (idx.isValid()) - { QVariant data; - NGLTreeItem *ti = privateData(idx); - StreamModelData ms = ti->data().value(); - if (idx.column() == 0) - ms.name = value.toString(); data.setValue(ms); - ti->setData(data); - emit dataChanged(index(idx.row(), 0), index(idx.row(), columnCount(QModelIndex()) - 1)); + setRootItem(new NGLTreeItem(data)); + + insertChildren(m_rootItem, m_menuStruct.id(), m_menuStruct.menuEntries()); + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + &UsedStreamsModel::onDataChanged); + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, this, + &UsedStreamsModel::onDataChangedMvs); + + connect(m_streamNameMapping, &StreamNameMapping::changed, this, &UsedStreamsModel::onStreamNameDataChanged); + endResetModel(); return true; - } - return false; } -void UsedStreamsModel::onDataChanged(const InfrastructureManagement::MainStructureElement &data, +NGLTreeItem* UsedStreamsModel::createItem(const QVariant& data, const QIcon& icon) const +{ + StreamModelData s = data.value(); + + s.id = 0; + s.parentId = 0; + QVariant newData; + newData.setValue(s); + return new NGLTreeItem(newData, icon); +} + +bool UsedStreamsModel::setData(const QModelIndex& idx, const QVariant& value, int role) +{ + Q_UNUSED(role); + + if (idx.isValid()) + { + QVariant data; + NGLTreeItem* ti = privateData(idx); + StreamModelData ms = ti->data().value(); + if (idx.column() == 0) + ms.name = value.toString(); + data.setValue(ms); + ti->setData(data); + emit dataChanged(index(idx.row(), 0), index(idx.row(), columnCount(QModelIndex()) - 1)); + return true; + } + return false; +} + +void UsedStreamsModel::onDataChanged(const InfrastructureManagement::MainStructureElement& data, const DataModification modType) { - beginResetModel(); - INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount() - << " data.elements().size()=" << data.elements().size(); + beginResetModel(); + INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount() + << " data.elements().size()=" << data.elements().size(); - switch (modType) - { - case DataModification::eRemoved: - break; - case DataModification::eModified: - case DataModification::eAdded: - for (const InfrastructureManagement::StructureElement &se : data.elements()) + switch (modType) { - INFO_LOG(m_logger) << "se.id()" << se.id() - << " se.displayName()" << se.displayName() - << " m_rootItem->childCount()" << m_rootItem->childCount(); - const QString newName = QString::fromStdString(se.displayName()); - updateStreamNames(se.id(), newName, m_rootItem); + case DataModification::eRemoved: + break; + case DataModification::eModified: + case DataModification::eAdded: + for (const InfrastructureManagement::StructureElement& se : data.elements()) + { + INFO_LOG(m_logger) << "se.id()" << se.id() << " se.displayName()" << se.displayName() + << " m_rootItem->childCount()" << m_rootItem->childCount(); + const QString newName = QString::fromStdString(se.displayName()); + updateStreamNames(se.id(), newName, m_rootItem); + } } - } - endResetModel(); - emit modelDataChanged(); + endResetModel(); + emit modelDataChanged(); } -void UsedStreamsModel::onDataChangedMvs(const VideoTeam &data, const DataModification modType) +void UsedStreamsModel::onDataChangedMvs(const VideoTeam& data, const DataModification modType) { - beginResetModel(); - INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount(); + beginResetModel(); + INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount(); - switch (modType) - { - case DataModification::eRemoved: - break; - case DataModification::eModified: - case DataModification::eAdded: + switch (modType) + { + case DataModification::eRemoved: + break; + case DataModification::eModified: + case DataModification::eAdded: - INFO_LOG(m_logger) << "se.id()" << data.id() - << " se.displayName()" << data.streamName() + INFO_LOG(m_logger) << "se.id()" << data.id() << " se.displayName()" << data.streamName() + << " m_rootItem->childCount()" << m_rootItem->childCount(); + const QString newName = QString::fromStdString(data.streamName()); + updateStreamNames(-1 * data.id(), newName, m_rootItem); + } + endResetModel(); + emit modelDataChanged(); +} + +void UsedStreamsModel::onStreamNameDataChanged(int32_t mountingPointId, const QString& internalName, + const QString& displayName) +{ + Q_UNUSED(internalName) + + beginResetModel(); + INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount(); + INFO_LOG(m_logger) << "se.id()" << mountingPointId << " se.displayName()" << displayName << " m_rootItem->childCount()" << m_rootItem->childCount(); - const QString newName = QString::fromStdString(data.streamName()); - updateStreamNames(-1 * data.id(), newName, m_rootItem); + updateStreamNames(mountingPointId, displayName, m_rootItem); - } - endResetModel(); - emit modelDataChanged(); + endResetModel(); + emit modelDataChanged(); } -void UsedStreamsModel::onStreamNameDataChanged(int32_t mountingPointId, const QString &internalName, const QString &displayName) +void UsedStreamsModel::updateStreamNames(const int mountingPointId, const QString& newName, NGLTreeItem* item) { - Q_UNUSED(internalName) + INFO_LOG(m_logger) << "updateStreamNames mountingPointId=" << mountingPointId << " newName=" << newName; - beginResetModel(); - INFO_LOG(m_logger) << "onDataChanged m_rootItem->childCount()" << m_rootItem->childCount(); - INFO_LOG(m_logger) << "se.id()" << mountingPointId - << " se.displayName()" << displayName - << " m_rootItem->childCount()" << m_rootItem->childCount(); - updateStreamNames(mountingPointId, displayName, m_rootItem); - - endResetModel(); - emit modelDataChanged(); -} - -void UsedStreamsModel::updateStreamNames(const int mountingPointId, const QString &newName, NGLTreeItem *item) -{ - INFO_LOG(m_logger) << "updateStreamNames mountingPointId=" << mountingPointId - << " newName=" << newName; - - int childCount = item->childCount(); - for (int i = 0; i < childCount; ++i) - { - NGLTreeItem *child = item->child(i); - - if (!child->data().canConvert()) - ERROR_LOG(m_logger) << "Error convert item"; - - StreamModelData usedStream = child->data().value(); - INFO_LOG(m_logger) << "i=" << i - << " usedStream.mountingPointId=" << usedStream.mountingPointId - << " usedStream.name=" << usedStream.name - << " mountingPointId=" << mountingPointId - << " newName=" << newName; - if (mountingPointId == usedStream.mountingPointId) + int childCount = item->childCount(); + for (int i = 0; i < childCount; ++i) { - INFO_LOG(m_logger) << "Set new DisplayName id=" << usedStream.id - << " mountingPointId=" << usedStream.mountingPointId - << " name=" << usedStream.name - << " new Name =" << newName; + NGLTreeItem* child = item->child(i); - usedStream.name = newName; + if (!child->data().canConvert()) + ERROR_LOG(m_logger) << "Error convert item"; - QVariant dataVar; - dataVar.setValue(usedStream); - child->setData(dataVar); - break; + StreamModelData usedStream = child->data().value(); + INFO_LOG(m_logger) << "i=" << i << " usedStream.mountingPointId=" << usedStream.mountingPointId + << " usedStream.name=" << usedStream.name << " mountingPointId=" << mountingPointId + << " newName=" << newName; + if (mountingPointId == usedStream.mountingPointId) + { + INFO_LOG(m_logger) << "Set new DisplayName id=" << usedStream.id + << " mountingPointId=" << usedStream.mountingPointId << " name=" << usedStream.name + << " new Name =" << newName; + + usedStream.name = newName; + + QVariant dataVar; + dataVar.setValue(usedStream); + child->setData(dataVar); + break; + } + + updateStreamNames(mountingPointId, newName, item->child(i)); } - - - updateStreamNames(mountingPointId, newName, item->child(i)); - } } -void UsedStreamsModel::fixUpData(NGLTreeItem *item) +void UsedStreamsModel::fixUpData(NGLTreeItem* item) { - - const QVector &children = item->children(); - for (NGLTreeItem *child : children) - { - const StreamModelData parentStream = item->data().value(); - StreamModelData childStream = child->data().value(); - if (childStream.isGroup && childStream.id == 0) - childStream.id = m_dummyId++; - if (!childStream.isGroup && childStream.id == 0) - childStream.id = m_dummyId++; - childStream.parentId = parentStream.id; - QVariant data; - data.setValue(childStream); - child->setData(data); - if (child->childCount() > 0) - fixUpData(child); - } + const QVector& children = item->children(); + for (NGLTreeItem* child : children) + { + const StreamModelData parentStream = item->data().value(); + StreamModelData childStream = child->data().value(); + if (childStream.isGroup && childStream.id == 0) + childStream.id = m_dummyId++; + if (!childStream.isGroup && childStream.id == 0) + childStream.id = m_dummyId++; + childStream.parentId = parentStream.id; + + QVariant data; + data.setValue(childStream); + child->setData(data); + if (child->childCount() > 0) + fixUpData(child); + } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.h old mode 100755 new mode 100644 index 6eb45f42f..d3094d284 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/avm_used_streams_model.h @@ -2,12 +2,13 @@ #pragma once -#include +#include "avm_available_streams_model.h" + #include #include +#include #include #include -#include "avm_available_streams_model.h" namespace AudioVideoManagement { @@ -15,63 +16,61 @@ namespace AudioVideoManagement class MenuStruct; class StreamNameMapping; - - class UsedStreamsModel final : public NGLTreeModel { - Q_OBJECT -public: - UsedStreamsModel(const std::shared_ptr avmDtc, - const std::shared_ptr ismDtc, - const MenuStruct &ms, - StreamNameMapping *streamNameMapping, - QObject *parent); + Q_OBJECT + public: + UsedStreamsModel(const std::shared_ptr avmDtc, + const std::shared_ptr ismDtc, const MenuStruct& ms, + StreamNameMapping* streamNameMapping, QObject* parent); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - bool setData(const QModelIndex &idx, const QVariant &value, - int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QMimeData *mimeData(const QModelIndexList &indexes) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) override; - bool canDropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) const override; - QStringList mimeTypes() const override; - Qt::DropActions supportedDragActions() const override { return Qt::MoveAction; } + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + bool setData(const QModelIndex& idx, const QVariant& value, int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QMimeData* mimeData(const QModelIndexList& indexes) const override; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) override; + bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const override; + QStringList mimeTypes() const override; + Qt::DropActions supportedDragActions() const override + { + return Qt::MoveAction; + } - MenuStruct getMenuStruct() const; - bool initModel(); + MenuStruct getMenuStruct() const; + bool initModel(); -protected: + protected: + NGL::INGLLogger& m_logger; + NGLTreeItem* createItem(const QVariant& data, const QIcon& icon) const override; -NGL::INGLLogger &m_logger; - NGLTreeItem *createItem(const QVariant &data, const QIcon &icon) const override; + private slots: + void onDataChanged(const InfrastructureManagement::MainStructureElement& data, const DataModification modType); + void onDataChangedMvs(const AudioVideoManagement::VideoTeam& data, const DataModification modType); + void onStreamNameDataChanged(int32_t mountingPointId, const QString& internalName, const QString& displayName); -private slots: - void onDataChanged(const InfrastructureManagement::MainStructureElement &data, - const DataModification modType); - void onDataChangedMvs(const AudioVideoManagement::VideoTeam &data, - const DataModification modType); - void onStreamNameDataChanged(int32_t mountingPointId, const QString &internalName, const QString &displayName); -private: - void updateStreamNames(const int mountingPointId, const QString &newName, NGLTreeItem *item); + private: + void updateStreamNames(const int mountingPointId, const QString& newName, NGLTreeItem* item); - void fixUpData(NGLTreeItem *item); + void fixUpData(NGLTreeItem* item); - static const QString s_MimeTypeOI; - QString mimeType(const QModelIndex &index) const; - void insertNGLTreeItemChild(NGLTreeItem *item, NGLTreeItem *parent, bool asCopy); - void insertChildren(NGLTreeItem *parent, int parentId, const std::vector &entries); - const std::shared_ptr m_avmDtc; - const std::shared_ptr m_ismDtc; - NGLTreeItem *getItemToCheck(const QModelIndex &index, const QModelIndex &parentIndex) const; - bool checkSingleItem(NGLTreeItem * target, StreamModelData & toCheck) const; - bool checkDrop(const QMimeData *data, const QModelIndex &index, const QModelIndex &parentIndex, Qt::DropAction action) const; - QSet fillTakenCameras(NGLTreeItem *getItem) const; - int m_dummyId; - MenuStruct m_menuStruct; - StreamNameMapping *m_streamNameMapping; + static const QString s_MimeTypeOI; + QString mimeType(const QModelIndex& index) const; + void insertNGLTreeItemChild(NGLTreeItem* item, NGLTreeItem* parent, bool asCopy); + void insertChildren(NGLTreeItem* parent, int parentId, + const std::vector& entries); + const std::shared_ptr m_avmDtc; + const std::shared_ptr m_ismDtc; + NGLTreeItem* getItemToCheck(const QModelIndex& index, const QModelIndex& parentIndex) const; + bool checkSingleItem(NGLTreeItem* target, StreamModelData& toCheck) const; + bool checkDrop(const QMimeData* data, const QModelIndex& index, const QModelIndex& parentIndex, + Qt::DropAction action) const; + QSet fillTakenCameras(NGLTreeItem* getItem) const; + int m_dummyId; + MenuStruct m_menuStruct; + StreamNameMapping* m_streamNameMapping; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/topic_replay.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/topic_replay.cpp old mode 100755 new mode 100644 index 8fd3f393c..8f774e3be --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/topic_replay.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/AVMenuEdit/topic_replay.cpp @@ -1,464 +1,441 @@ - #include "topic_replay.h" -#include -#include + #include #include +#include +#include #include #include -#include #include -#include -#include +#include +#include #include #include -#include -#include #include -#include -#include +#include +#include +#include #include - +#include +#include namespace AudioVideoManagement { class TopicReplay::ExportScript : public QObject { - Q_OBJECT + Q_OBJECT -public: - ExportScript(const QString &topLevelExportDir, TopicEditorBase::ExportNotifier *exportStep); + public: + ExportScript(const QString& topLevelExportDir, TopicEditorBase::ExportNotifier* exportStep); -public slots: - void avScriptFinished(const QString &exportDir, AvaStreamType streamType, bool success); + public slots: + void avScriptFinished(const QString& exportDir, AvaStreamType streamType, bool success); -private: - QString audioVideoPlaylistErstellen(const QString &dir, AvaStreamType streamType); - bool writeFile(const QByteArray &data, const QString &fileName); + private: + QString audioVideoPlaylistErstellen(const QString& dir, AvaStreamType streamType); + bool writeFile(const QByteArray& data, const QString& fileName); - QString m_topLevelExportDir; - TopicEditorBase::ExportNotifier *m_exportStep; + QString m_topLevelExportDir; + TopicEditorBase::ExportNotifier* m_exportStep; }; - - - - -TopicReplay::TopicReplay(DataInterface *dataIfc, bool isAudio) - : m_isAudio(isAudio) - , m_dataIfc(dataIfc) +TopicReplay::TopicReplay(DataInterface* dataIfc, bool isAudio) : m_isAudio(isAudio), m_dataIfc(dataIfc) { - DEBUG_LOG(m_logger) << "TopicReplay::TopicReplay()"; - Q_ASSERT(dataIfc); + DEBUG_LOG(m_logger) << "TopicReplay::TopicReplay()"; + Q_ASSERT(dataIfc); } TopicReplay::~TopicReplay() { - DEBUG_LOG(m_logger) << "TopicReplay::~TopicReplay()"; + DEBUG_LOG(m_logger) << "TopicReplay::~TopicReplay()"; - if (m_isPlaying) - playbackStop(); + if (m_isPlaying) + playbackStop(); } -QWidget *TopicReplay::createWidget() +QWidget* TopicReplay::createWidget() { - DEBUG_LOG(m_logger) << "TopicReplay::createWidget()"; - Q_ASSERT(!m_screenPlacementHelper); + DEBUG_LOG(m_logger) << "TopicReplay::createWidget()"; + Q_ASSERT(!m_screenPlacementHelper); - if (m_isAudio) - return nullptr; + if (m_isAudio) + return nullptr; - m_screenPlacementHelper.reset(new ScreenPlacementHelper()); - connect(m_screenPlacementHelper.data(), &ScreenPlacementHelper::widgetPlaced, this, &TopicReplay::onWidgetPlaced); - return m_screenPlacementHelper.data(); + m_screenPlacementHelper.reset(new ScreenPlacementHelper()); + connect(m_screenPlacementHelper.data(), &ScreenPlacementHelper::widgetPlaced, this, &TopicReplay::onWidgetPlaced); + return m_screenPlacementHelper.data(); } - -void TopicReplay::slotSetScriptResponse(const AudioVideoManagement::AvaStreamInfo &streamInfo, AudioVideoManagement::AvaStreamState streamState) +void TopicReplay::slotSetScriptResponse(const AudioVideoManagement::AvaStreamInfo& streamInfo, + AudioVideoManagement::AvaStreamState streamState) { - if (streamState == AudioVideoManagement::AvaStreamState::NotPossible) - ERROR_LOG(m_logger) << "Script could not be set"; - else - ERROR_LOG(m_logger) << "Script set!"; + if (streamState == AudioVideoManagement::AvaStreamState::NotPossible) + ERROR_LOG(m_logger) << "Script could not be set"; + else + ERROR_LOG(m_logger) << "Script set!"; - ERROR_LOG(m_logger) << "streamInfo: start" << streamInfo.duration.count(); - ERROR_LOG(m_logger) << "streamState: " << static_cast(streamState); + ERROR_LOG(m_logger) << "streamInfo: start" << streamInfo.duration.count(); + ERROR_LOG(m_logger) << "streamState: " << static_cast(streamState); } - -bool TopicReplay::playbackInit(const QJsonObject &attributes) +bool TopicReplay::playbackInit(const QJsonObject& attributes) { - DEBUG_LOG(m_logger) << "TopicReplay::playbackInit()"; - DEBUG_LOG(m_logger) << QJsonDocument(attributes).toJson(); + DEBUG_LOG(m_logger) << "TopicReplay::playbackInit()"; + DEBUG_LOG(m_logger) << QJsonDocument(attributes).toJson(); - if (m_screenPlacementHelper && !m_isAudio) - m_screenPlacementHelper->show(); + if (m_screenPlacementHelper && !m_isAudio) + m_screenPlacementHelper->show(); - m_playbackAttributes = attributes; + m_playbackAttributes = attributes; - - AvaControl *ctrl = getAvaControl(); - if (ctrl == nullptr) - { - ERROR_LOG(m_logger) << "no ava control!"; - return false; - } + AvaControl* ctrl = getAvaControl(); + if (ctrl == nullptr) + { + ERROR_LOG(m_logger) << "no ava control!"; + return false; + } - AvaTopicData topicData(m_playbackAttributes); + AvaTopicData topicData(m_playbackAttributes); - if (!topicData.isValid) - { - ERROR_LOG(m_logger) << "topicData is invalid"; - return false; - } + if (!topicData.isValid) + { + ERROR_LOG(m_logger) << "topicData is invalid"; + return false; + } - m_scriptName = topicData.scriptName(); + m_scriptName = topicData.scriptName(); - Q_ASSERT(topicData.isAudio() == m_isAudio); + Q_ASSERT(topicData.isAudio() == m_isAudio); - PlaybackApp *app = m_isAudio ? m_dataIfc->audioPresentationApp() : m_dataIfc->videoPresentationApp(); - if (app == nullptr || app->inUse()) - { - ERROR_LOG(m_logger) << "app invalid or in use!"; - return false; - } + PlaybackApp* app = m_isAudio ? m_dataIfc->audioPresentationApp() : m_dataIfc->videoPresentationApp(); + if (app == nullptr || app->inUse()) + { + ERROR_LOG(m_logger) << "app invalid or in use!"; + return false; + } - - - - - if (!m_dialogGeometry) - { - if (m_isAudio) - m_appHandle = PlaybackAppHandle(app); + if (!m_dialogGeometry) + { + if (m_isAudio) + m_appHandle = PlaybackAppHandle(app); + else + m_appHandle = PlaybackAppHandle(app, QRect(0, 0, 0, 0)); + } else - m_appHandle = PlaybackAppHandle(app, QRect(0, 0, 0, 0)); - } - else - m_appHandle = PlaybackAppHandle(app, *m_dialogGeometry); + m_appHandle = PlaybackAppHandle(app, *m_dialogGeometry); - if (!m_appHandle) - { - ERROR_LOG(m_logger) << "appHandle: missing app after creating appHandle!"; - return false; - } + if (!m_appHandle) + { + ERROR_LOG(m_logger) << "appHandle: missing app after creating appHandle!"; + return false; + } + NGL::Settings s({}); + bool isLocal = s.isDatabaseConnectionLocal(); - NGL::Settings s({}); - bool isLocal = s.isDatabaseConnectionLocal(); + DEBUG_LOG(m_logger) << "isLocal? " << isLocal; - DEBUG_LOG(m_logger) << "isLocal? " << isLocal; - - AvaScriptSource source; - if (isLocal) - { - if (m_isAudio) - source = AvaScriptSource::LocalAudio; + AvaScriptSource source; + if (isLocal) + { + if (m_isAudio) + source = AvaScriptSource::LocalAudio; + else + source = AvaScriptSource::LocalVideo; + } else - source = AvaScriptSource::LocalVideo; - } - else - { - if (m_isAudio) - source = AvaScriptSource::ServerAudio; - else - source = AvaScriptSource::ServerVideo; - } + { + if (m_isAudio) + source = AvaScriptSource::ServerAudio; + else + source = AvaScriptSource::ServerVideo; + } - DEBUG_LOG(m_logger) << "source: " << static_cast(source); + DEBUG_LOG(m_logger) << "source: " << static_cast(source); - ctrl->setScript(m_appHandle.dialogId(), m_scriptName, - source, topicData.streamList(), - LtsUtils::createConnection(ctrl, &AudioVideoManagement::AvaControl::setScriptResponse, - this, &TopicReplay::slotSetScriptResponse)); + ctrl->setScript(m_appHandle.dialogId(), m_scriptName, source, topicData.streamList(), + LtsUtils::createConnection(ctrl, &AudioVideoManagement::AvaControl::setScriptResponse, this, + &TopicReplay::slotSetScriptResponse)); - return true; + return true; } bool TopicReplay::playbackStart(int secondsOffset) { - DEBUG_LOG(m_logger) << "TopicReplay::playbackStart()"; + DEBUG_LOG(m_logger) << "TopicReplay::playbackStart()"; - if (m_screenPlacementHelper && !m_isAudio) - m_screenPlacementHelper->show(); + if (m_screenPlacementHelper && !m_isAudio) + m_screenPlacementHelper->show(); - AvaControl *ctrl = getAvaControl(); - if (ctrl == nullptr) - { - ERROR_LOG(m_logger) << "ctrl == nullptr"; - return false; - } + AvaControl* ctrl = getAvaControl(); + if (ctrl == nullptr) + { + ERROR_LOG(m_logger) << "ctrl == nullptr"; + return false; + } - AvaTimePoint p{AvaDuration{std::chrono::seconds(secondsOffset)}}; + AvaTimePoint p{AvaDuration{std::chrono::seconds(secondsOffset)}}; - if (!m_appHandle) - { - ERROR_LOG(m_logger) << "appHandle: missing app!"; - return false; - } + if (!m_appHandle) + { + ERROR_LOG(m_logger) << "appHandle: missing app!"; + return false; + } - ctrl->setAbsPositionScript(m_appHandle.dialogId(), m_scriptName, p); - ctrl->startScript(m_appHandle.dialogId(), m_scriptName); + ctrl->setAbsPositionScript(m_appHandle.dialogId(), m_scriptName, p); + ctrl->startScript(m_appHandle.dialogId(), m_scriptName); - m_isPlaying = true; - DEBUG_LOG(m_logger) << "m_isPlaying = true"; - return true; + m_isPlaying = true; + DEBUG_LOG(m_logger) << "m_isPlaying = true"; + return true; } bool TopicReplay::playbackPause() { - DEBUG_LOG(m_logger) << "TopicReplay::playbackPause()"; + DEBUG_LOG(m_logger) << "TopicReplay::playbackPause()"; - if (m_screenPlacementHelper) - m_screenPlacementHelper->hide(); + if (m_screenPlacementHelper) + m_screenPlacementHelper->hide(); - if (!m_isPlaying) + if (!m_isPlaying) + return true; + + AvaControl* ctrl = getAvaControl(); + if (ctrl == nullptr) + { + ERROR_LOG(m_logger) << "no ctrl!"; + return false; + } + + if (!m_appHandle) + { + ERROR_LOG(m_logger) << "appHandle: missing app!"; + return false; + } + + ctrl->pauseScript(m_appHandle.dialogId(), m_scriptName); return true; - - AvaControl *ctrl = getAvaControl(); - if (ctrl == nullptr) - { - ERROR_LOG(m_logger) << "no ctrl!"; - return false; - } - - if (!m_appHandle) - { - ERROR_LOG(m_logger) << "appHandle: missing app!"; - return false; - } - - ctrl->pauseScript(m_appHandle.dialogId(), m_scriptName); - return true; } bool TopicReplay::playbackStop() { - DEBUG_LOG(m_logger) << "TopicReplay::playbackStop()"; + DEBUG_LOG(m_logger) << "TopicReplay::playbackStop()"; - if (m_screenPlacementHelper) - m_screenPlacementHelper->hide(); + if (m_screenPlacementHelper) + m_screenPlacementHelper->hide(); - if (!m_isPlaying) + if (!m_isPlaying) + return true; + + AvaControl* ctrl = getAvaControl(); + if (ctrl == nullptr) + { + ERROR_LOG(m_logger) << "no ctrl!"; + return false; + } + + if (!m_appHandle) + { + ERROR_LOG(m_logger) << "appHandle: missing app!"; + return false; + } + + ctrl->stopScript(m_appHandle.dialogId(), m_scriptName); + ctrl->releaseScript(m_appHandle.dialogId(), m_scriptName); + + m_isPlaying = false; return true; - - AvaControl *ctrl = getAvaControl(); - if (ctrl == nullptr) - { - ERROR_LOG(m_logger) << "no ctrl!"; - return false; - } - - if (!m_appHandle) - { - ERROR_LOG(m_logger) << "appHandle: missing app!"; - return false; - } - - ctrl->stopScript(m_appHandle.dialogId(), m_scriptName); - ctrl->releaseScript(m_appHandle.dialogId(), m_scriptName); - - m_isPlaying = false; - return true; } -bool TopicReplay::exportTopic(const QJsonObject &attributes, - const QString &folderPath, - TopicEditorBase::ExportNotifier *exportNotifier) +bool TopicReplay::exportTopic(const QJsonObject& attributes, const QString& folderPath, + TopicEditorBase::ExportNotifier* exportNotifier) { - Q_ASSERT(!m_exportScript); + Q_ASSERT(!m_exportScript); - VdControl *ctrl = getVdControl(); - if (ctrl == nullptr) - { - ERROR_LOG(m_logger) << "ctrl missing!"; - exportNotifier->setExportFailed(); - return false; - } - - m_exportScript.reset(new ExportScript(folderPath, exportNotifier)); - - AvaTopicData topicData(attributes); - m_scriptName = topicData.scriptName(); - - if (!topicData.isValid) - { - ERROR_LOG(m_logger) << "topicData is invalid"; - exportNotifier->setExportFailed(); - return false; - } - - QFileInfo fileInfo(QDir(folderPath).filePath(topicData.scriptName())); - - Q_ASSERT(topicData.isAudio() == m_isAudio); - - ctrl->vdSetScript(m_scriptName, - m_isAudio ? AvaStreamType::Audio : AvaStreamType::Video, - 0, topicData.streamList(), fileInfo.baseName(), fileInfo.absolutePath(), - this, &TopicReplay::avScriptFinished); - return true; -} - -void TopicReplay::onWidgetPlaced(const QRect &geometry) -{ - WARNING_LOG(m_logger) << "TopicReplay::onWidgetPlaced() - geo: " << geometry.x() << "/" << geometry.y() - << " m_isAudio=" << m_isAudio; - - m_dialogGeometry = geometry; - - if (m_isAudio) - return; - - PlaybackApp *app = m_isAudio ? m_dataIfc->audioPresentationApp() : m_dataIfc->videoPresentationApp(); - if (app == nullptr) - { - ERROR_LOG(m_logger) << "app missing!"; - return; - } - - if (!app->inUse()) - { - ERROR_LOG(m_logger) << "app not in use - waiting for playbackInit to aquire it"; - return; - } - - DEBUG_LOG(m_logger) << "setGeometry"; - app->setGeometry(*m_dialogGeometry); -} - -AvaControl *TopicReplay::getAvaControl() -{ - if (!m_dataIfc->hasAvsSession()) - return nullptr; - - AvaSession *avaSession = m_dataIfc->avaSession(); - if (!avaSession->isEstablished()) - return nullptr; - - return avaSession->control(); -} - -VdControl *TopicReplay::getVdControl() -{ - if (!m_dataIfc->hasAvsSession()) - return nullptr; - - VdSession *vdSession = m_dataIfc->vdSession(); - if (!vdSession->isEstablished()) - return nullptr; - - return vdSession->control(); -} - -void TopicReplay::avScriptFinished(const QString &exportDir, AvaStreamType streamType, bool success) -{ - VdControl *ctrl = getVdControl(); - ctrl->vdReleaseScript(m_scriptName); - m_exportScript->avScriptFinished(exportDir, streamType, success); -} - - - - -TopicReplay::ExportScript::ExportScript(const QString &topLevelExportDir, TopicEditorBase::ExportNotifier *exportStep) - : m_topLevelExportDir(topLevelExportDir) - , m_exportStep(exportStep) -{ - connect(exportStep, &QObject::destroyed, this, [this]() - { - if (static_cast(sender()) != m_exportStep) - return; - m_exportStep = nullptr; - }); - Q_ASSERT(exportStep); -} - -void TopicReplay::ExportScript::avScriptFinished(const QString &exportDir, AvaStreamType streamType, bool success) -{ - QString absPathToPlaylist = audioVideoPlaylistErstellen(exportDir, streamType); - - QDir toplevelExportDir(m_topLevelExportDir); - QString relativePathToPlaylist = toplevelExportDir.relativeFilePath(absPathToPlaylist); - - if (m_exportStep == nullptr) - return; - - if (success) - m_exportStep->setExportSuccessful(relativePathToPlaylist); - else - m_exportStep->setExportFailed(); -} - -QString TopicReplay::ExportScript::audioVideoPlaylistErstellen(const QString &dir, AvaStreamType streamType) -{ - QDir avDir(dir); - const QFileInfoList dateienList = avDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); - - QByteArray dataForFile; - QString data; - dataForFile.append("[playlist]\n"); - - int numberOfEntries = 0; - int i = 1; - const QString tmpl1(QStringLiteral("File %1=%2\n")); - const QString tmpl2(QStringLiteral("# File %1=%2\n")); - for (const QFileInfo &fileInfo : dateienList) - { - if (streamType == AvaStreamType::Video && fileInfo.suffix() == QLatin1String(".wav")) + VdControl* ctrl = getVdControl(); + if (ctrl == nullptr) { - data += tmpl2.arg(QString::number(i), fileInfo.fileName()); - i--; + ERROR_LOG(m_logger) << "ctrl missing!"; + exportNotifier->setExportFailed(); + return false; } + + m_exportScript.reset(new ExportScript(folderPath, exportNotifier)); + + AvaTopicData topicData(attributes); + m_scriptName = topicData.scriptName(); + + if (!topicData.isValid) + { + ERROR_LOG(m_logger) << "topicData is invalid"; + exportNotifier->setExportFailed(); + return false; + } + + QFileInfo fileInfo(QDir(folderPath).filePath(topicData.scriptName())); + + Q_ASSERT(topicData.isAudio() == m_isAudio); + + ctrl->vdSetScript(m_scriptName, m_isAudio ? AvaStreamType::Audio : AvaStreamType::Video, 0, topicData.streamList(), + fileInfo.baseName(), fileInfo.absolutePath(), this, &TopicReplay::avScriptFinished); + return true; +} + +void TopicReplay::onWidgetPlaced(const QRect& geometry) +{ + WARNING_LOG(m_logger) << "TopicReplay::onWidgetPlaced() - geo: " << geometry.x() << "/" << geometry.y() + << " m_isAudio=" << m_isAudio; + + m_dialogGeometry = geometry; + + if (m_isAudio) + return; + + PlaybackApp* app = m_isAudio ? m_dataIfc->audioPresentationApp() : m_dataIfc->videoPresentationApp(); + if (app == nullptr) + { + ERROR_LOG(m_logger) << "app missing!"; + return; + } + + if (!app->inUse()) + { + ERROR_LOG(m_logger) << "app not in use - waiting for playbackInit to aquire it"; + return; + } + + DEBUG_LOG(m_logger) << "setGeometry"; + app->setGeometry(*m_dialogGeometry); +} + +AvaControl* TopicReplay::getAvaControl() +{ + if (!m_dataIfc->hasAvsSession()) + return nullptr; + + AvaSession* avaSession = m_dataIfc->avaSession(); + if (!avaSession->isEstablished()) + return nullptr; + + return avaSession->control(); +} + +VdControl* TopicReplay::getVdControl() +{ + if (!m_dataIfc->hasAvsSession()) + return nullptr; + + VdSession* vdSession = m_dataIfc->vdSession(); + if (!vdSession->isEstablished()) + return nullptr; + + return vdSession->control(); +} + +void TopicReplay::avScriptFinished(const QString& exportDir, AvaStreamType streamType, bool success) +{ + VdControl* ctrl = getVdControl(); + ctrl->vdReleaseScript(m_scriptName); + m_exportScript->avScriptFinished(exportDir, streamType, success); +} + +TopicReplay::ExportScript::ExportScript(const QString& topLevelExportDir, TopicEditorBase::ExportNotifier* exportStep) + : m_topLevelExportDir(topLevelExportDir), m_exportStep(exportStep) +{ + connect(exportStep, &QObject::destroyed, this, [this]() { + if (static_cast(sender()) != m_exportStep) + return; + m_exportStep = nullptr; + }); + Q_ASSERT(exportStep); +} + +void TopicReplay::ExportScript::avScriptFinished(const QString& exportDir, AvaStreamType streamType, bool success) +{ + QString absPathToPlaylist = audioVideoPlaylistErstellen(exportDir, streamType); + + QDir toplevelExportDir(m_topLevelExportDir); + QString relativePathToPlaylist = toplevelExportDir.relativeFilePath(absPathToPlaylist); + + if (m_exportStep == nullptr) + return; + + if (success) + m_exportStep->setExportSuccessful(relativePathToPlaylist); else - { - data += tmpl1.arg(QString::number(i), fileInfo.fileName()); - numberOfEntries++; - } - i++; - } - - QString numberOfEntriesString = QStringLiteral("NumberOfEntries=") + QString::number(numberOfEntries) + QStringLiteral("\n"); - dataForFile.append(numberOfEntriesString.toUtf8()); - dataForFile.append(data.toUtf8()); - - QString fileName; - switch (streamType) - { - case AvaStreamType::Audio: - fileName = avDir.filePath(QStringLiteral("audio.pls")); - break; - - case AvaStreamType::Video: - fileName = avDir.filePath(QStringLiteral("video.pls")); - break; - } - - writeFile(dataForFile, fileName); - return fileName; + m_exportStep->setExportFailed(); } -bool TopicReplay::ExportScript::writeFile(const QByteArray &data, const QString &fileName) +QString TopicReplay::ExportScript::audioVideoPlaylistErstellen(const QString& dir, AvaStreamType streamType) { - QFile file(fileName); + QDir avDir(dir); + const QFileInfoList dateienList = avDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name); - if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) - return false; + QByteArray dataForFile; + QString data; + dataForFile.append("[playlist]\n"); - if (file.write(data) == -1) - { - file.close(); - return false; - } + int numberOfEntries = 0; + int i = 1; + const QString tmpl1(QStringLiteral("File %1=%2\n")); + const QString tmpl2(QStringLiteral("# File %1=%2\n")); + for (const QFileInfo& fileInfo : dateienList) + { + if (streamType == AvaStreamType::Video && fileInfo.suffix() == QLatin1String(".wav")) + { + data += tmpl2.arg(QString::number(i), fileInfo.fileName()); + i--; + } + else + { + data += tmpl1.arg(QString::number(i), fileInfo.fileName()); + numberOfEntries++; + } + i++; + } - file.close(); + QString numberOfEntriesString = + QStringLiteral("NumberOfEntries=") + QString::number(numberOfEntries) + QStringLiteral("\n"); + dataForFile.append(numberOfEntriesString.toUtf8()); + dataForFile.append(data.toUtf8()); - return true; + QString fileName; + switch (streamType) + { + case AvaStreamType::Audio: + fileName = avDir.filePath(QStringLiteral("audio.pls")); + break; + + case AvaStreamType::Video: + fileName = avDir.filePath(QStringLiteral("video.pls")); + break; + } + + writeFile(dataForFile, fileName); + return fileName; } -} +bool TopicReplay::ExportScript::writeFile(const QByteArray& data, const QString& fileName) +{ + QFile file(fileName); + if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) + return false; + + if (file.write(data) == -1) + { + file.close(); + return false; + } + + file.close(); + + return true; +} + +} // namespace AudioVideoManagement #include "topic_replay.moc" diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.cpp old mode 100755 new mode 100644 index 4356e066a..20cb36f0c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.cpp @@ -1,252 +1,227 @@ - #include "avm_combat_net_radio_dialog.h" -#include "ui_avm_combat_net_radio_dialog.h" + +#include "avm_cnr_json_helper.h" #include "avm_combat_net_radio_dialog_model.h" #include "avm_edit_combat_net_radio_dialog.h" -#include "avm_cnr_json_helper.h" #include "avm_load_combat_net_radio_dialog.h" +#include "ui_avm_combat_net_radio_dialog.h" -#include -#include - -#include -#include - -#include #include +#include +#include +#include +#include +#include namespace AudioVideoManagement { -CombatNetRadioDialog::CombatNetRadioDialog(LtsSession::LtsSession *session, const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_session(session) - , m_ui(new Ui::CombatNetRadioDialog) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +CombatNetRadioDialog::CombatNetRadioDialog(LtsSession::LtsSession* session, const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_session(session), + m_ui(new Ui::CombatNetRadioDialog), m_menuGroup(menuGroup), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - setUnchangeable(true); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CombatNetRadioDialog::onPrint); + m_ui->setupUi(this); + setUnchangeable(true); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CombatNetRadioDialog::onPrint); - setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); + setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); } CombatNetRadioDialog::~CombatNetRadioDialog() = default; void CombatNetRadioDialog::retranslate() { - translate(m_ui.get(), tr("Configure Combat Net Radio")); + translate(m_ui.get(), tr("Configure Combat Net Radio")); } void CombatNetRadioDialog::tableColumnOrganiserSetting() { - - m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); } -bool CombatNetRadioDialog::init(const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - const std::shared_ptr &ppmDtc, - ExerciseManagement::Interface::Dtc *exmDtc) +bool CombatNetRadioDialog::init(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + const std::shared_ptr& ppmDtc, + ExerciseManagement::Interface::Dtc* exmDtc) { - if (!(avmDtc->enableCnrChannel() && - avmDtc->enableCnrConfig() && - ppmDtc->enableParty() && - ppmDtc->enableParticipant() && - ppmDtc->enableType() && - avmFtc->enableModifyCnrConfig() && - avmFtc->enableRemoveCnrConfig())) - { - ERROR_LOG(m_logger) << "Could not enable topics"; - return false; - } + if (!(avmDtc->enableCnrChannel() && avmDtc->enableCnrConfig() && ppmDtc->enableParty() && + ppmDtc->enableParticipant() && ppmDtc->enableType() && avmFtc->enableModifyCnrConfig() && + avmFtc->enableRemoveCnrConfig())) + { + ERROR_LOG(m_logger) << "Could not enable topics"; + return false; + } - m_model.reset(new CombatNetRadioDialogModel(m_session->exerciseId(), this)); - m_filter.reset(new CombatNetRadioDialogFilter(m_session->exerciseId(), m_model.get())); + m_model.reset(new CombatNetRadioDialogModel(m_session->exerciseId(), this)); + m_filter.reset(new CombatNetRadioDialogFilter(m_session->exerciseId(), m_model.get())); - m_avmDtc = avmDtc; - m_avmFtc = avmFtc; - m_ppmDtc = ppmDtc; - m_exmDtc = exmDtc; + m_avmDtc = avmDtc; + m_avmFtc = avmFtc; + m_ppmDtc = ppmDtc; + m_exmDtc = exmDtc; - m_avmDtc->waitForHistoricalDataCnrChannel(3000); - m_ppmDtc->waitForHistoricalDataParty(3000); + m_avmDtc->waitForHistoricalDataCnrChannel(3000); + m_ppmDtc->waitForHistoricalDataParty(3000); - if (!m_model->init(avmDtc, ppmDtc)) - { - m_filter.reset(); - m_model.reset(); - ERROR_LOG(m_logger) << "Could not init model"; - return false; - } + if (!m_model->init(avmDtc, ppmDtc)) + { + m_filter.reset(); + m_model.reset(); + ERROR_LOG(m_logger) << "Could not init model"; + return false; + } - m_ui->dataView->setModel(m_filter.get()); + m_ui->dataView->setModel(m_filter.get()); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &CombatNetRadioDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &CombatNetRadioDialog::onEditClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &CombatNetRadioDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &CombatNetRadioDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &CombatNetRadioDialog::onEditClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &CombatNetRadioDialog::onRemoveClicked); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &CombatNetRadioDialog::onSelectionChanged); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &CombatNetRadioDialog::onSelectionChanged); - onSelectionChanged(); + onSelectionChanged(); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &CombatNetRadioDialog::onEditClicked); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, this, &CombatNetRadioDialog::onEditClicked); - - m_buttonBox->connectLibraryButton(this, - &CombatNetRadioDialog::onImportButtonClicked, - &CombatNetRadioDialog::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &CombatNetRadioDialog::onImportButtonClicked, + &CombatNetRadioDialog::onExportButtonClicked); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - return true; + return true; } -void CombatNetRadioDialog::onRemoveCnrConfigReply(const Core::FunctionReplyObject &replyObject) +void CombatNetRadioDialog::onRemoveCnrConfigReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -void CombatNetRadioDialog::onModifyCnrConfigReply(const Core::FunctionReplyObject &replyObject) +void CombatNetRadioDialog::onModifyCnrConfigReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } void CombatNetRadioDialog::onAddClicked() { - EditCombatNetRadioDialog *dialog = new EditCombatNetRadioDialog(m_session->exerciseId(), m_session, m_ppmDtc, m_avmDtc, m_avmFtc, m_exmDtc, this); - addDialog(dialog, m_menuGroup, QStringLiteral("NewCNRConfig"), LtsWidgets::LayoutArea::eDialogTab); + EditCombatNetRadioDialog* dialog = + new EditCombatNetRadioDialog(m_session->exerciseId(), m_session, m_ppmDtc, m_avmDtc, m_avmFtc, m_exmDtc, this); + addDialog(dialog, m_menuGroup, QStringLiteral("NewCNRConfig"), LtsWidgets::LayoutArea::eDialogTab); } void CombatNetRadioDialog::onEditClicked() { - - if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) - return; - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) + return; - if (!currentIndex.isValid()) - return; + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - CnrConfig config = m_model->data(currentIndex, Qt::UserRole).value(); + if (!currentIndex.isValid()) + return; - EditCombatNetRadioDialog *dialog = new EditCombatNetRadioDialog(config, - m_session->exerciseId(), - m_session, - m_ppmDtc, - m_avmDtc, - m_avmFtc, - m_exmDtc, - this); + CnrConfig config = m_model->data(currentIndex, Qt::UserRole).value(); - addDialog(dialog, m_menuGroup, QStringLiteral("EditCNRConfig%1").arg(config.id()), LtsWidgets::LayoutArea::eDialogTab); + EditCombatNetRadioDialog* dialog = new EditCombatNetRadioDialog(config, m_session->exerciseId(), m_session, + m_ppmDtc, m_avmDtc, m_avmFtc, m_exmDtc, this); + + addDialog(dialog, m_menuGroup, QStringLiteral("EditCNRConfig%1").arg(config.id()), + LtsWidgets::LayoutArea::eDialogTab); } void CombatNetRadioDialog::onRemoveClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - Core::RemoveElementRequest request(m_model->data(currentIndex, Qt::UserRole).value().id()); + Core::RemoveElementRequest request(m_model->data(currentIndex, Qt::UserRole).value().id()); - m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->removeCnrConfigRequest(request, this); - }); + m_requestHelper->startSingleRequest([this, request]() { return m_avmFtc->removeCnrConfigRequest(request, this); }); } void CombatNetRadioDialog::onSelectionChanged() { - bool rowSelected = m_ui->dataView->selectionModel()->selectedRows().size() > 0; - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, rowSelected); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, rowSelected); + bool rowSelected = m_ui->dataView->selectionModel()->selectedRows().size() > 0; + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, rowSelected); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, rowSelected); - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - CnrConfig config = m_model->data(currentIndex, Qt::UserRole).value(); - bool enabled = rowSelected && (config.exerciseId().is_set() || m_session->partitionType() == IDL::PartitionType::Global); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, enabled); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, enabled); + CnrConfig config = m_model->data(currentIndex, Qt::UserRole).value(); + bool enabled = + rowSelected && (config.exerciseId().is_set() || m_session->partitionType() == IDL::PartitionType::Global); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, enabled); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, enabled); } void CombatNetRadioDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); + LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); } void CombatNetRadioDialog::onExportButtonClicked() { - QByteArray byteArray = m_filter->modelToJson(); + QByteArray byteArray = m_filter->modelToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void CombatNetRadioDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMCombatNetRadio)); + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMCombatNetRadio)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMCombatNetRadio))) + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - LoadCombatNetRadioDialog loadingDialog(content, m_session) ; - loadingDialog.exec(); - - if (loadingDialog.isApplied()) - { - const QVector removeRequests = loadingDialog.removeRequests(); - - for (const auto &removeRequest : removeRequests) + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMCombatNetRadio))) { - m_requestHelper->addRequest([this, removeRequest]() - { - return m_avmFtc->removeCnrConfigRequest(removeRequest, this); - }); + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); } - - const QVector modifyRequests = loadingDialog.modifyRequests(); - - for (const auto &modifyRequest : modifyRequests) + else { - m_requestHelper->addRequest([this, modifyRequest]() - { - return m_avmFtc->modifyCnrConfigRequest(modifyRequest, this); - }); - } + LoadCombatNetRadioDialog loadingDialog(content, m_session); + loadingDialog.exec(); - if (modifyRequests.size() || removeRequests.size()) - (void) m_requestHelper->startRequests(); - } + if (loadingDialog.isApplied()) + { + const QVector removeRequests = loadingDialog.removeRequests(); + + for (const auto& removeRequest : removeRequests) + { + m_requestHelper->addRequest( + [this, removeRequest]() { return m_avmFtc->removeCnrConfigRequest(removeRequest, this); }); + } + + const QVector modifyRequests = loadingDialog.modifyRequests(); + + for (const auto& modifyRequest : modifyRequests) + { + m_requestHelper->addRequest( + [this, modifyRequest]() { return m_avmFtc->modifyCnrConfigRequest(modifyRequest, this); }); + } + + if (modifyRequests.size() || removeRequests.size()) + (void)m_requestHelper->startRequests(); + } + } } - } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.h old mode 100755 new mode 100644 index 2cc2322e1..debf14a6c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog.h @@ -1,14 +1,11 @@ - #pragma once -#include - -#include #include +#include +#include #include - #include namespace Ui @@ -27,7 +24,7 @@ namespace Interface { class Dtc; } -} +} // namespace AudioVideoManagement namespace ParticipantManagement { @@ -35,7 +32,7 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace ExerciseManagement { @@ -43,58 +40,59 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace LtsSession { class LtsSession; } + namespace AudioVideoManagement { class CombatNetRadioDialogModel; class CombatNetRadioDialogFilter; -class CombatNetRadioDialog - : public LtsWidgets::LtsDialog - , protected Interface::Ftc::RemoveCnrConfigReplyHandler - , protected Interface::Ftc::ModifyCnrConfigReplyHandler +class CombatNetRadioDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::RemoveCnrConfigReplyHandler, + protected Interface::Ftc::ModifyCnrConfigReplyHandler { - Q_OBJECT -public: - explicit CombatNetRadioDialog(LtsSession::LtsSession *session, const QString &menuGroup, QWidget *parent = nullptr); - ~CombatNetRadioDialog(); + Q_OBJECT + public: + explicit CombatNetRadioDialog(LtsSession::LtsSession* session, const QString& menuGroup, QWidget* parent = nullptr); + ~CombatNetRadioDialog(); - bool init(const std::shared_ptr &avmDtc, const std::shared_ptr &avmFtc, const std::shared_ptr &ppmDtc, ExerciseManagement::Interface::Dtc *exmDtc); + bool init(const std::shared_ptr& avmDtc, const std::shared_ptr& avmFtc, + const std::shared_ptr& ppmDtc, + ExerciseManagement::Interface::Dtc* exmDtc); - void onRemoveCnrConfigReply(const Core::FunctionReplyObject &replyObject) override final; - void onModifyCnrConfigReply(const Core::FunctionReplyObject &replyObject) override final; + void onRemoveCnrConfigReply(const Core::FunctionReplyObject& replyObject) override final; + void onModifyCnrConfigReply(const Core::FunctionReplyObject& replyObject) override final; -private Q_SLOTS: - void onAddClicked(); - void onEditClicked(); - void onRemoveClicked(); - void onSelectionChanged(); - void onPrint(); - void onExportButtonClicked(); - void onImportButtonClicked(); + private Q_SLOTS: + void onAddClicked(); + void onEditClicked(); + void onRemoveClicked(); + void onSelectionChanged(); + void onPrint(); + void onExportButtonClicked(); + void onImportButtonClicked(); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void tableColumnOrganiserSetting() override; - -private: - LtsSession::LtsSession *m_session; - std::unique_ptr m_model; - std::unique_ptr m_filter; - std::unique_ptr m_ui; - QString m_menuGroup; - std::unique_ptr m_requestHelper; - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - std::shared_ptr m_ppmDtc; - ExerciseManagement::Interface::Dtc *m_exmDtc{nullptr}; - std::shared_ptr m_flmGui; -}; -} + private: + LtsSession::LtsSession* m_session; + std::unique_ptr m_model; + std::unique_ptr m_filter; + std::unique_ptr m_ui; + QString m_menuGroup; + std::unique_ptr m_requestHelper; + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + std::shared_ptr m_ppmDtc; + ExerciseManagement::Interface::Dtc* m_exmDtc{nullptr}; + std::shared_ptr m_flmGui; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.cpp old mode 100755 new mode 100644 index dcfe486a7..336db5be5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.cpp @@ -1,153 +1,145 @@ - #include "avm_combat_net_radio_dialog_model.h" -#include -#include -#include -#include + #include "avm_cnr_json_helper.h" +#include +#include +#include #include -#include #include +#include +#include namespace AudioVideoManagement { -CombatNetRadioDialogModel::CombatNetRadioDialogModel(int32_t exerciseId, QObject *parent) - : LtsAbstractTableModel( -{ - tr("Channel Number"), - tr("Radio Circuit"), - tr("Code Word"), - tr("Party"), - tr("Unit"), - tr("Global") -}, parent) -, m_exerciseId(exerciseId) +CombatNetRadioDialogModel::CombatNetRadioDialogModel(int32_t exerciseId, QObject* parent) + : LtsAbstractTableModel( + {tr("Channel Number"), tr("Radio Circuit"), tr("Code Word"), tr("Party"), tr("Unit"), tr("Global")}, parent), + m_exerciseId(exerciseId) { } -QVariant CombatNetRadioDialogModel::data(const QModelIndex &index, int role) const +QVariant CombatNetRadioDialogModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::BackgroundRole &&role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) + if ((role != Qt::BackgroundRole && role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) + return {}; + + const CnrConfig& config = m_vecData.at(index.row()); + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case CHANNEL: + INFO_LOG(m_logger) << "CombatNetRadioDialogModel::data role =" << role << " row = " << index.row(); + return QString::fromStdString(m_cnrChannels.value(config.cnrChannelId()).name()); + case RADIO_CIRCUIT: + return QString::fromStdString(config.radioCircuit()); + case CALL_SIGN: + return QString::fromStdString(config.callSign()); + case PARTY: + if (config.exerciseId().is_set() || config.partyId() > 0) + return ParticipantManagement::trPartyName(m_parties.value(config.partyId()).name()); + else + return QStringLiteral("-"); + case UNIT: { + if (!config.unitId().is_set()) + return {}; + const int unitId = config.unitId().get(); + const auto unit = m_units.value(config.unitId().get()); + if (unit.id() != unitId) + return {}; + + INFO_LOG(m_logger) << " config.unitId()=" << unitId << " Str=" << unit.name(); + + QString unitStr; + if (unit.designator().size() > 0) + unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); + unitStr.append(QString::fromStdString(unit.tacticalIdentifier())); + INFO_LOG(m_logger) << "unitStr = " << unitStr; + + return unitStr; + } + case GLOBAL: + return config.exerciseId().is_set() ? tr("No") : tr("Yes"); + } + } + else if (role == Qt::BackgroundRole) + { + if (config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) + return {}; + if (!config.exerciseId().is_set() && m_exerciseId <= 0) + return {}; + return QColor(Qt::gray); + } + else if (role == Qt::UserRole) + return QVariant::fromValue(config); + return {}; - - const CnrConfig &config = m_vecData.at(index.row()); - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case CHANNEL: - INFO_LOG(m_logger)<<"CombatNetRadioDialogModel::data role =" << role - << " row = " << index.row(); - return QString::fromStdString(m_cnrChannels.value(config.cnrChannelId()).name()); - case RADIO_CIRCUIT: - return QString::fromStdString(config.radioCircuit()); - case CALL_SIGN: - return QString::fromStdString(config.callSign()); - case PARTY: - if(config.exerciseId().is_set() || config.partyId() > 0) - return ParticipantManagement::trPartyName(m_parties.value(config.partyId()).name()); - else - return QStringLiteral("-"); - case UNIT: - { - if (!config.unitId().is_set()) - return {}; - const int unitId = config.unitId().get(); - const auto unit = m_units.value(config.unitId().get()); - if (unit.id() != unitId) - return {}; - - INFO_LOG(m_logger) << " config.unitId()=" << unitId - << " Str=" << unit.name(); - - QString unitStr; - if (unit.designator().size() > 0) - unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); - unitStr.append(QString::fromStdString(unit.tacticalIdentifier())); - INFO_LOG(m_logger) << "unitStr = " << unitStr; - - return unitStr; - } - case GLOBAL: - return config.exerciseId().is_set() ? tr("No") : tr("Yes"); - } - } - else if (role == Qt::BackgroundRole) - { - if (config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) - return {}; - if (!config.exerciseId().is_set() && m_exerciseId <= 0) - return {}; - return QColor(Qt::gray); - } - else if (role == Qt::UserRole) - return QVariant::fromValue(config); - - return {}; } -bool CombatNetRadioDialogModel::init(const std::shared_ptr &avmDtc, const std::shared_ptr &ppmDtc) +bool CombatNetRadioDialogModel::init(const std::shared_ptr& avmDtc, + const std::shared_ptr& ppmDtc) { - m_avmDtc = avmDtc; + m_avmDtc = avmDtc; - m_cnrChannels = avmDtc->cnrChannels(); + m_cnrChannels = avmDtc->cnrChannels(); - if (!ppmDtc->visibleParties(m_parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_exerciseId))) - { - ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; - return false; - } - m_units = ppmDtc->units(); + if (!ppmDtc->visibleParties(m_parties, + LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_exerciseId))) + { + ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; + return false; + } + m_units = ppmDtc->units(); - connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, &CombatNetRadioDialogModel::onDataChanged); - m_avmDtc->cnrConfigs([this](const CnrConfig &c) { insertRow(c); }); + connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, &CombatNetRadioDialogModel::onDataChanged); + m_avmDtc->cnrConfigs([this](const CnrConfig& c) { insertRow(c); }); - return true; + return true; } + bool CombatNetRadioDialogModel::onlyGlobals() { - for(const CnrConfig &config : std::as_const(m_vecData)) - { - if(config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) - return false; - } - return true; + for (const CnrConfig& config : std::as_const(m_vecData)) + { + if (config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) + return false; + } + return true; } QByteArray CombatNetRadioDialogFilter::modelToJson() const { - QVector configs; - configs.reserve(rowCount()); + QVector configs; + configs.reserve(rowCount()); - for (int row = 0; row < rowCount(); ++row) - { - int sourceRow = mapToSource(index(row, 0)).row(); - configs.append(m_sourceModel->getRowData(sourceRow)); - } + for (int row = 0; row < rowCount(); ++row) + { + int sourceRow = mapToSource(index(row, 0)).row(); + configs.append(m_sourceModel->getRowData(sourceRow)); + } - return cnrConfigVectorToJson(configs, m_exerciseId); + return cnrConfigVectorToJson(configs, m_exerciseId); } -CombatNetRadioDialogFilter::CombatNetRadioDialogFilter(int32_t exerciseId, CombatNetRadioDialogModel *sourceModel) - : m_exerciseId(exerciseId) - , m_sourceModel(sourceModel) +CombatNetRadioDialogFilter::CombatNetRadioDialogFilter(int32_t exerciseId, CombatNetRadioDialogModel* sourceModel) + : m_exerciseId(exerciseId), m_sourceModel(sourceModel) { - Q_ASSERT(sourceModel); - setSourceModel(sourceModel); + Q_ASSERT(sourceModel); + setSourceModel(sourceModel); } -bool CombatNetRadioDialogFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool CombatNetRadioDialogFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { - CnrConfig cnrConfig = m_sourceModel->getRowData(sourceRow); + CnrConfig cnrConfig = m_sourceModel->getRowData(sourceRow); - if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId().get() != m_exerciseId) - return false; + if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId().get() != m_exerciseId) + return false; - return LtsColumnFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); + return LtsColumnFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.h old mode 100755 new mode 100644 index ab240a8b2..f8e14c5fe --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_combat_net_radio_dialog_model.h @@ -1,77 +1,60 @@ - #pragma once - -#include +#include +#include #include #include - -#include -#include #include - -#include +#include #include +#include namespace AudioVideoManagement { -class CombatNetRadioDialogModel final - : public LtsWidgets::LtsAbstractTableModel +class CombatNetRadioDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - CHANNEL, - RADIO_CIRCUIT, - CALL_SIGN, - PARTY, - UNIT, - GLOBAL - }; + public: + enum Columns { CHANNEL, RADIO_CIRCUIT, CALL_SIGN, PARTY, UNIT, GLOBAL }; - explicit CombatNetRadioDialogModel(int32_t exerciseId, QObject *parent = nullptr); + explicit CombatNetRadioDialogModel(int32_t exerciseId, QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role) const override; - bool init(const std::shared_ptr &avmDtc, const std::shared_ptr &ppmDtc); - bool onlyGlobals(); + QVariant data(const QModelIndex& index, int role) const override; + bool init(const std::shared_ptr& avmDtc, + const std::shared_ptr& ppmDtc); + bool onlyGlobals(); -private: - -NGL::INGLLogger &m_logger; - std::shared_ptr m_avmDtc; - int32_t m_exerciseId; - QMap m_cnrChannels; - QMap m_parties; - QMap m_units; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_avmDtc; + int32_t m_exerciseId; + QMap m_cnrChannels; + QMap m_parties; + QMap m_units; }; - - - class CombatNetRadioDialogFilter : public LtsWidgets::LtsColumnFilterProxyModel { -public: - explicit CombatNetRadioDialogFilter(int32_t exerciseId, CombatNetRadioDialogModel *sourceModel); + public: + explicit CombatNetRadioDialogFilter(int32_t exerciseId, CombatNetRadioDialogModel* sourceModel); - QByteArray modelToJson() const; + QByteArray modelToJson() const; -protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; + protected: + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; -private: - - using LtsWidgets::LtsColumnFilterProxyModel::setSourceModel; + private: + using LtsWidgets::LtsColumnFilterProxyModel::setSourceModel; - int32_t m_exerciseId; - CombatNetRadioDialogModel *m_sourceModel; + int32_t m_exerciseId; + CombatNetRadioDialogModel* m_sourceModel; }; -} +} // namespace AudioVideoManagement Q_DECLARE_METATYPE(AudioVideoManagement::CnrConfig) Q_DECLARE_METATYPE(AudioVideoManagement::FrequencyPlanningData) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.cpp old mode 100755 new mode 100644 index 13c7f6426..4f3363409 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.cpp @@ -1,22 +1,21 @@ - #include "avm_edit_combat_net_radio_dialog.h" -#include -#include "ui_avm_edit_combat_net_radio_dialog.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include "ui_avm_edit_combat_net_radio_dialog.h" + +#include +#include +#include +#include +#include +#include +#include #include +#include #include #include - +#include namespace AudioVideoManagement { @@ -24,575 +23,558 @@ namespace AudioVideoManagement namespace { -CnrConfig toConfig(const ModifyCnrConfigRequest &modifyRequest) +CnrConfig toConfig(const ModifyCnrConfigRequest& modifyRequest) { - return {modifyRequest.id(), modifyRequest.cnrChannelId(), modifyRequest.exerciseId(), modifyRequest.radioCircuit(), - modifyRequest.partyId(), modifyRequest.unitId(), modifyRequest.recording(), modifyRequest.callSign(), false}; + return {modifyRequest.id(), modifyRequest.cnrChannelId(), modifyRequest.exerciseId(), + modifyRequest.radioCircuit(), modifyRequest.partyId(), modifyRequest.unitId(), + modifyRequest.recording(), modifyRequest.callSign(), false}; } -const QString &NO_CHANNEL() +const QString& NO_CHANNEL() { - static const QString noChannel = QStringLiteral("---"); - return noChannel; + static const QString noChannel = QStringLiteral("---"); + return noChannel; } -} +} // namespace - -EditCombatNetRadioDialog::EditCombatNetRadioDialog(int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent) - : EditCombatNetRadioDialog(boost::none, exerciseId, session, ppmDtc, avmDtc, avmFtc, exmDtc, parent) +EditCombatNetRadioDialog::EditCombatNetRadioDialog(int32_t exerciseId, LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, QWidget* parent) + : EditCombatNetRadioDialog(boost::none, exerciseId, session, ppmDtc, avmDtc, avmFtc, exmDtc, parent) { - m_ui->chkRecording->setChecked(true); - m_isGlobal = session->partitionType() == IDL::PartitionType::Global; - - if(m_isGlobal) - setUiValuesForGlobal(); - - initCbChannelsForCreate(); - setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); -} - -EditCombatNetRadioDialog::EditCombatNetRadioDialog(const CnrConfig &cnrConfig, - int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent) - : EditCombatNetRadioDialog(cnrConfig.id(), exerciseId, session, ppmDtc, avmDtc, avmFtc, exmDtc, parent) -{ - m_channelId = cnrConfig.cnrChannelId(); - m_isGlobal = session->partitionType() == IDL::PartitionType::Global; - setUiValues(cnrConfig); - - setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); -} - -EditCombatNetRadioDialog::EditCombatNetRadioDialog(const boost::optional &id, - int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::EditCombatNetRadioDialog) - , m_id(id) - , m_exerciseId(exerciseId) - , m_ppmDtc(ppmDtc) - , m_avmDtc(avmDtc) - , m_avmFtc(avmFtc) - , m_exmDtc(exmDtc) - , m_requestHelper(new LtsUtils::RequestHelper(this)) -{ - Q_ASSERT(ppmDtc); - Q_ASSERT(avmDtc); - Q_ASSERT(avmFtc); - Q_ASSERT(exmDtc); - - m_ui->setupUi(this); - if (ProjectSettings::isAlwaysRecording()) - { m_ui->chkRecording->setChecked(true); - m_ui->chkRecording->setEnabled(false); - m_ui->chkRecording->hide(); - m_ui->lbRecording->hide(); - } - init(session); + m_isGlobal = session->partitionType() == IDL::PartitionType::Global; + + if (m_isGlobal) + setUiValuesForGlobal(); + + initCbChannelsForCreate(); + setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); +} + +EditCombatNetRadioDialog::EditCombatNetRadioDialog(const CnrConfig& cnrConfig, int32_t exerciseId, + LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, QWidget* parent) + : EditCombatNetRadioDialog(cnrConfig.id(), exerciseId, session, ppmDtc, avmDtc, avmFtc, exmDtc, parent) +{ + m_channelId = cnrConfig.cnrChannelId(); + m_isGlobal = session->partitionType() == IDL::PartitionType::Global; + setUiValues(cnrConfig); + + setOnlineHelpFilename(QStringLiteral("Situation-Combat_Net_Radio_Configuration")); +} + +EditCombatNetRadioDialog::EditCombatNetRadioDialog(const boost::optional& id, int32_t exerciseId, + LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::EditCombatNetRadioDialog), m_id(id), m_exerciseId(exerciseId), m_ppmDtc(ppmDtc), m_avmDtc(avmDtc), + m_avmFtc(avmFtc), m_exmDtc(exmDtc), m_requestHelper(new LtsUtils::RequestHelper(this)) +{ + Q_ASSERT(ppmDtc); + Q_ASSERT(avmDtc); + Q_ASSERT(avmFtc); + Q_ASSERT(exmDtc); + + m_ui->setupUi(this); + if (ProjectSettings::isAlwaysRecording()) + { + m_ui->chkRecording->setChecked(true); + m_ui->chkRecording->setEnabled(false); + m_ui->chkRecording->hide(); + m_ui->lbRecording->hide(); + } + init(session); } EditCombatNetRadioDialog::~EditCombatNetRadioDialog() = default; void EditCombatNetRadioDialog::retranslate() { - translate(m_ui.get(), QString(), !m_id.is_initialized(), tr("Combat Net Radio")); + translate(m_ui.get(), QString(), !m_id.is_initialized(), tr("Combat Net Radio")); } -void EditCombatNetRadioDialog::setUiValues(const CnrConfig &cnrConfig) +void EditCombatNetRadioDialog::setUiValues(const CnrConfig& cnrConfig) { - if(m_isGlobal) - setUiValuesForGlobal(); - - m_ui->chkGlobal->setChecked(m_isGlobal); - initCbChannels(cnrConfig.cnrChannelId()); - bool disableParty = (m_avmDtc->cnrChannel(cnrConfig.cnrChannelId()).frequencyBand() == FrequencyBand_def::REL) || m_isGlobal; - if (!disableParty) - { - m_ui->cbParty->setCurrentIndex(m_ui->cbParty->findData(cnrConfig.partyId())); - int unitId = cnrConfig.unitId().is_set() ? cnrConfig.unitId().get() : 0; - m_ui->cbUnit->setCurrentIndex(m_ui->cbUnit->findData(unitId)); - } - m_ui->leCallSign->setText(QString::fromStdString(cnrConfig.callSign())); - m_ui->chkRecording->setChecked(cnrConfig.recording()); - m_ui->leRadioCircuit->setText(QString::fromStdString(cnrConfig.radioCircuit())); - onPartyIndexChanged(cnrConfig.partyId()); + if (m_isGlobal) + setUiValuesForGlobal(); + m_ui->chkGlobal->setChecked(m_isGlobal); + initCbChannels(cnrConfig.cnrChannelId()); + bool disableParty = + (m_avmDtc->cnrChannel(cnrConfig.cnrChannelId()).frequencyBand() == FrequencyBand_def::REL) || m_isGlobal; + if (!disableParty) + { + m_ui->cbParty->setCurrentIndex(m_ui->cbParty->findData(cnrConfig.partyId())); + int unitId = cnrConfig.unitId().is_set() ? cnrConfig.unitId().get() : 0; + m_ui->cbUnit->setCurrentIndex(m_ui->cbUnit->findData(unitId)); + } + m_ui->leCallSign->setText(QString::fromStdString(cnrConfig.callSign())); + m_ui->chkRecording->setChecked(cnrConfig.recording()); + m_ui->leRadioCircuit->setText(QString::fromStdString(cnrConfig.radioCircuit())); + onPartyIndexChanged(cnrConfig.partyId()); } void EditCombatNetRadioDialog::setUiValuesForGlobal() { - m_ui->chkGlobal->setChecked(true); - m_ui->cbUnit->setEnabled(false); - m_ui->lbUnit->setEnabled(false); + m_ui->chkGlobal->setChecked(true); + m_ui->cbUnit->setEnabled(false); + m_ui->lbUnit->setEnabled(false); - - m_ui->cbParty->setCurrentIndex(m_ui->cbParty->findData(1)); - m_ui->cbParty->setEnabled(false); - m_ui->lbParty->setEnabled(false); + m_ui->cbParty->setCurrentIndex(m_ui->cbParty->findData(1)); + m_ui->cbParty->setEnabled(false); + m_ui->lbParty->setEnabled(false); } ModifyCnrConfigRequest EditCombatNetRadioDialog::createRequest() { - ModifyCnrConfigRequest request; + ModifyCnrConfigRequest request; - request.id(m_id.get_value_or(0)); - request.callSign(m_ui->leCallSign->text().toStdString()); - request.cnrChannelId(m_ui->cbChannel->currentData().toInt()); - request.radioCircuit(m_ui->leRadioCircuit->text().toStdString()); - request.recording(m_ui->chkRecording->isChecked()); - request.partyId(m_ui->cbParty->currentData().toInt()); - if (!m_isGlobal) - request.exerciseId(m_exerciseId); - if (m_ui->cbUnit->currentIndex() > 0) - request.unitId().set(m_ui->cbUnit->currentIndex()); - return request; + request.id(m_id.get_value_or(0)); + request.callSign(m_ui->leCallSign->text().toStdString()); + request.cnrChannelId(m_ui->cbChannel->currentData().toInt()); + request.radioCircuit(m_ui->leRadioCircuit->text().toStdString()); + request.recording(m_ui->chkRecording->isChecked()); + request.partyId(m_ui->cbParty->currentData().toInt()); + if (!m_isGlobal) + request.exerciseId(m_exerciseId); + if (m_ui->cbUnit->currentIndex() > 0) + request.unitId().set(m_ui->cbUnit->currentIndex()); + return request; } bool EditCombatNetRadioDialog::apply() { - ModifyCnrConfigRequest request = createRequest(); + ModifyCnrConfigRequest request = createRequest(); - if (m_ui->cbUnit->currentIndex() > 0) - { - request.unitId().set(m_ui->cbUnit->currentData().toInt()); - INFO_LOG(m_logger)<< "currentIndex="<cbUnit->currentIndex() - << " unitId ="<cbUnit->currentIndex() > 0) + { + request.unitId().set(m_ui->cbUnit->currentData().toInt()); + INFO_LOG(m_logger) << "currentIndex=" << m_ui->cbUnit->currentIndex() << " unitId =" << request.unitId().get(); + } - return m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->modifyCnrConfigRequest(request, this); - }); + return m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->modifyCnrConfigRequest(request, this); }); } -void EditCombatNetRadioDialog::init(LtsSession::LtsSession *session) +void EditCombatNetRadioDialog::init(LtsSession::LtsSession* session) { - m_units = m_ppmDtc->units(); + m_units = m_ppmDtc->units(); - QMap parties; - if (!m_ppmDtc->visibleParties(parties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_exerciseId))) - ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; + QMap parties; + if (!m_ppmDtc->visibleParties(parties, + LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_exerciseId))) + ERROR_LOG(m_logger) << "Could not retrieve visible Parties!"; - for (const ParticipantManagement::Party &party : std::as_const(parties)) - m_ui->cbParty->addItem(ParticipantManagement::trPartyName(party.name()), party.id()); + for (const ParticipantManagement::Party& party : std::as_const(parties)) + m_ui->cbParty->addItem(ParticipantManagement::trPartyName(party.name()), party.id()); - connect(m_ui->cbParty, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, &EditCombatNetRadioDialog::onPartyIndexChanged); - connect(m_ui->cbChannel, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, &EditCombatNetRadioDialog::onChannelChanged); - connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, &EditCombatNetRadioDialog::updateFreeChannelsAndTakenNames); - connect(m_exmDtc, &ExerciseManagement::Interface::Dtc::exerciseChanged, this, &EditCombatNetRadioDialog::updateFreeChannelsAndTakenNames); + connect(m_ui->cbParty, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &EditCombatNetRadioDialog::onPartyIndexChanged); + connect(m_ui->cbChannel, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &EditCombatNetRadioDialog::onChannelChanged); + connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, + &EditCombatNetRadioDialog::updateFreeChannelsAndTakenNames); + connect(m_exmDtc, &ExerciseManagement::Interface::Dtc::exerciseChanged, this, + &EditCombatNetRadioDialog::updateFreeChannelsAndTakenNames); - onPartyIndexChanged(m_ui->cbParty->currentIndex()); + onPartyIndexChanged(m_ui->cbParty->currentIndex()); - - m_buttonBox->connectLibraryButton(this, - &EditCombatNetRadioDialog::onImportButtonClicked, - &EditCombatNetRadioDialog::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &EditCombatNetRadioDialog::onImportButtonClicked, + &EditCombatNetRadioDialog::onExportButtonClicked); - if (!session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - - m_uiRequirements->addRequirement({m_ui->lbRadioCircuit, [this] () { return isNameValid(m_ui->leRadioCircuit->text()); }, tr("name invalid")}); - m_uiRequirements->addRequirement({m_ui->lbChannel, [this] () { return m_ui->cbChannel->currentData().toInt() > 0; }, tr("channel invalid")}); + m_uiRequirements->addRequirement( + {m_ui->lbRadioCircuit, [this]() { return isNameValid(m_ui->leRadioCircuit->text()); }, tr("name invalid")}); + m_uiRequirements->addRequirement( + {m_ui->lbChannel, [this]() { return m_ui->cbChannel->currentData().toInt() > 0; }, tr("channel invalid")}); } void EditCombatNetRadioDialog::initCbChannelsForCreate() { - Q_ASSERT(!m_id.is_initialized()); - Q_ASSERT(m_ui->cbChannel->count() == 0); - updateFreeChannelsAndTakenNames(); - if (m_ui->cbChannel->count()) - m_ui->cbChannel->setCurrentIndex(0); - else - m_ui->cbChannel->addItem(NO_CHANNEL(), -1); + Q_ASSERT(!m_id.is_initialized()); + Q_ASSERT(m_ui->cbChannel->count() == 0); + updateFreeChannelsAndTakenNames(); + if (m_ui->cbChannel->count()) + m_ui->cbChannel->setCurrentIndex(0); + else + m_ui->cbChannel->addItem(NO_CHANNEL(), -1); } void EditCombatNetRadioDialog::initCbChannels(int channelId) { - m_ui->cbChannel->clear(); - updateFreeChannelsAndTakenNames(); - m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(channelId)); + m_ui->cbChannel->clear(); + updateFreeChannelsAndTakenNames(); + m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(channelId)); } - - void EditCombatNetRadioDialog::updateFreeChannelsAndTakenNames() { - const auto exercisesConsider = exercisesToConsider(); - const auto exercisesIgnore = exercisesToIgnore(); + const auto exercisesConsider = exercisesToConsider(); + const auto exercisesIgnore = exercisesToIgnore(); - m_takenNames.clear(); + m_takenNames.clear(); - QVector freeChannels = m_avmDtc->cnrChannels().keys().toVector(); - QMap channelsToDisable; - QMap exerciseNameCache; - const auto allCnrConfigs = m_avmDtc->cnrConfigs(); - const ExerciseManagement::Exercise ownExercise = m_exmDtc->exercise(m_exerciseId); - ExerciseManagement::ExerciseState ownState = m_exmDtc->exercise(m_exerciseId).state(); + QVector freeChannels = m_avmDtc->cnrChannels().keys().toVector(); + QMap channelsToDisable; + QMap exerciseNameCache; + const auto allCnrConfigs = m_avmDtc->cnrConfigs(); + const ExerciseManagement::Exercise ownExercise = m_exmDtc->exercise(m_exerciseId); + ExerciseManagement::ExerciseState ownState = m_exmDtc->exercise(m_exerciseId).state(); - for (const AudioVideoManagement::CnrConfig &cnrConfig : allCnrConfigs) - { - if (m_id.is_initialized() && *m_id == cnrConfig.id()) - continue; - - if (ownExercise.state() == ExerciseManagement::ExerciseState::Created && cnrConfig.exerciseId() != m_exerciseId) + for (const AudioVideoManagement::CnrConfig& cnrConfig : allCnrConfigs) { - if (ownExercise.linkedExerciseId() < 1 || cnrConfig.exerciseId() != ownExercise.linkedExerciseId()) - continue; + if (m_id.is_initialized() && *m_id == cnrConfig.id()) + continue; - if (!exerciseNameCache.contains(ownExercise.linkedExerciseId())) - exerciseNameCache.insert(ownExercise.linkedExerciseId(), QString::fromStdString(m_exmDtc->exercise(ownExercise.linkedExerciseId()).name())); - - channelsToDisable.insert(cnrConfig.cnrChannelId(), tr("(already taken in %1)").arg(exerciseNameCache.value(ownExercise.linkedExerciseId()))); - - continue; - } - - if (ownExercise.state() == ExerciseManagement::ExerciseState::Started || ownExercise.state() == ExerciseManagement::ExerciseState::Paused) - { - if (cnrConfig.exerciseId().is_set()) - { - int cnrExerciseId = cnrConfig.exerciseId().get(); - - if (exercisesConsider.contains(cnrExerciseId) && cnrExerciseId != m_exerciseId) + if (ownExercise.state() == ExerciseManagement::ExerciseState::Created && cnrConfig.exerciseId() != m_exerciseId) { - if (!exerciseNameCache.contains(cnrExerciseId)) - exerciseNameCache.insert(cnrExerciseId, QString::fromStdString(m_exmDtc->exercise(cnrExerciseId).name())); + if (ownExercise.linkedExerciseId() < 1 || cnrConfig.exerciseId() != ownExercise.linkedExerciseId()) + continue; - channelsToDisable.insert(cnrConfig.cnrChannelId(), tr("(already taken in %1)").arg(exerciseNameCache.value(cnrExerciseId))); + if (!exerciseNameCache.contains(ownExercise.linkedExerciseId())) + exerciseNameCache.insert( + ownExercise.linkedExerciseId(), + QString::fromStdString(m_exmDtc->exercise(ownExercise.linkedExerciseId()).name())); - continue; + channelsToDisable.insert( + cnrConfig.cnrChannelId(), + tr("(already taken in %1)").arg(exerciseNameCache.value(ownExercise.linkedExerciseId()))); + + continue; } - } + + if (ownExercise.state() == ExerciseManagement::ExerciseState::Started || + ownExercise.state() == ExerciseManagement::ExerciseState::Paused) + { + if (cnrConfig.exerciseId().is_set()) + { + int cnrExerciseId = cnrConfig.exerciseId().get(); + + if (exercisesConsider.contains(cnrExerciseId) && cnrExerciseId != m_exerciseId) + { + if (!exerciseNameCache.contains(cnrExerciseId)) + exerciseNameCache.insert(cnrExerciseId, + QString::fromStdString(m_exmDtc->exercise(cnrExerciseId).name())); + + channelsToDisable.insert(cnrConfig.cnrChannelId(), + tr("(already taken in %1)").arg(exerciseNameCache.value(cnrExerciseId))); + + continue; + } + } + } + + if (!m_isGlobal) + { + if (cnrConfig.exerciseId().is_set() && !exercisesConsider.contains(cnrConfig.exerciseId().get())) + continue; + + if (!cnrConfig.exerciseId().is_set() && ownState != ExerciseManagement::ExerciseState::Created) + { + channelsToDisable.insert(cnrConfig.cnrChannelId(), tr("(already taken in global exercise)")); + + continue; + } + } + + if (m_isGlobal && cnrConfig.exerciseId().is_set() && exercisesConsider.contains(cnrConfig.exerciseId().get())) + { + int exerciseId = cnrConfig.exerciseId().get(); + + if (!exerciseNameCache.contains(exerciseId)) + exerciseNameCache.insert(exerciseId, QString::fromStdString(m_exmDtc->exercise(exerciseId).name())); + + channelsToDisable.insert(cnrConfig.cnrChannelId(), + tr("(already taken in %1)").arg(exerciseNameCache.value(exerciseId))); + + continue; + } + + if (cnrConfig.exerciseId().is_set() && exercisesIgnore.contains(cnrConfig.exerciseId().get())) + continue; + + m_takenNames.push_back(QString::fromStdString(cnrConfig.radioCircuit())); + + freeChannels.removeOne(cnrConfig.cnrChannelId()); } - if (!m_isGlobal) + if (m_id.is_initialized()) { - if (cnrConfig.exerciseId().is_set() && !exercisesConsider.contains(cnrConfig.exerciseId().get())) - continue; - - if (!cnrConfig.exerciseId().is_set() && ownState != ExerciseManagement::ExerciseState::Created) - { - channelsToDisable.insert(cnrConfig.cnrChannelId(), tr("(already taken in global exercise)")); - - continue; - } + if (freeChannels.contains(*m_channelId)) + updateCbChannels({*m_channelId}, {}); + else + updateCbChannels({}, {}); } - - if (m_isGlobal && cnrConfig.exerciseId().is_set() && exercisesConsider.contains(cnrConfig.exerciseId().get())) - { - int exerciseId = cnrConfig.exerciseId().get(); - - if (!exerciseNameCache.contains(exerciseId)) - exerciseNameCache.insert(exerciseId, QString::fromStdString(m_exmDtc->exercise(exerciseId).name())); - - channelsToDisable.insert(cnrConfig.cnrChannelId(), tr("(already taken in %1)").arg(exerciseNameCache.value(exerciseId))); - - continue; - } - - if (cnrConfig.exerciseId().is_set() && exercisesIgnore.contains(cnrConfig.exerciseId().get())) - continue; - - m_takenNames.push_back(QString::fromStdString(cnrConfig.radioCircuit())); - - freeChannels.removeOne(cnrConfig.cnrChannelId()); - } - - if (m_id.is_initialized()) - { - if (freeChannels.contains(*m_channelId)) - updateCbChannels({*m_channelId}, {}); else - updateCbChannels({},{}); - } - else - updateCbChannels(std::move(freeChannels), std::move(channelsToDisable)); + updateCbChannels(std::move(freeChannels), std::move(channelsToDisable)); } - - -void EditCombatNetRadioDialog::updateCbChannels(QVector &&freeChannels, QMap &&channelsToDisable) +void EditCombatNetRadioDialog::updateCbChannels(QVector&& freeChannels, QMap&& channelsToDisable) { - const auto allChannels = m_avmDtc->cnrChannels(); + const auto allChannels = m_avmDtc->cnrChannels(); - const auto byName = [&allChannels] (int leftChannelId, int rightChannelId) { return QLatin1String(allChannels[leftChannelId].name().c_str()) < QLatin1String(allChannels[rightChannelId].name().c_str()); }; - std::sort(freeChannels.begin(), freeChannels.end(), byName); + const auto byName = [&allChannels](int leftChannelId, int rightChannelId) { + return QLatin1String(allChannels[leftChannelId].name().c_str()) < + QLatin1String(allChannels[rightChannelId].name().c_str()); + }; + std::sort(freeChannels.begin(), freeChannels.end(), byName); - bool bOk; - int currentlySelectedChannelId = m_ui->cbChannel->currentData().toInt(&bOk); + bool bOk; + int currentlySelectedChannelId = m_ui->cbChannel->currentData().toInt(&bOk); - if (!bOk) - { - currentlySelectedChannelId = -1; - - if (freeChannels.count() && channelsToDisable.contains(freeChannels.at(0))) + if (!bOk) { - currentlySelectedChannelId = freeChannels.at(0); + currentlySelectedChannelId = -1; - while (channelsToDisable.contains(currentlySelectedChannelId)) - { - int channelIndex = freeChannels.indexOf(currentlySelectedChannelId); - - if (channelIndex == freeChannels.size() - 1) + if (freeChannels.count() && channelsToDisable.contains(freeChannels.at(0))) { - currentlySelectedChannelId = -1; - break; + currentlySelectedChannelId = freeChannels.at(0); + + while (channelsToDisable.contains(currentlySelectedChannelId)) + { + int channelIndex = freeChannels.indexOf(currentlySelectedChannelId); + + if (channelIndex == freeChannels.size() - 1) + { + currentlySelectedChannelId = -1; + break; + } + + currentlySelectedChannelId = freeChannels.at(channelIndex + 1); + } + } + } + + m_ui->cbChannel->clear(); + for (const auto& channelId : freeChannels) + { + QString channelName = QString::fromStdString(allChannels[channelId].name()); + + if (channelsToDisable.contains(channelId)) + { + QString text = QLatin1String("%1 %2").arg(channelName).arg(channelsToDisable.value(channelId)); + m_ui->cbChannel->addItem(text, channelId); + + auto* model = qobject_cast(m_ui->cbChannel->model()); + + if (!model) + continue; + + auto* item = model->item(m_ui->cbChannel->count() - 1); + + if (!item) + continue; + + item->setEnabled(false); + + continue; } - currentlySelectedChannelId = freeChannels.at(channelIndex + 1); - } - } - } - - m_ui->cbChannel->clear(); - for (const auto &channelId : freeChannels) - { - QString channelName = QString::fromStdString(allChannels[channelId].name()); - - if (channelsToDisable.contains(channelId)) - { - QString text = QLatin1String("%1 %2").arg(channelName).arg(channelsToDisable.value(channelId)); - m_ui->cbChannel->addItem(text, channelId); - - auto * model = qobject_cast(m_ui->cbChannel->model()); - - if(!model) - continue; - - auto * item = model->item(m_ui->cbChannel->count() - 1); - - if(!item) - continue; - - item->setEnabled(false); - - continue; + m_ui->cbChannel->addItem(channelName, channelId); } - m_ui->cbChannel->addItem(channelName, channelId); - } - - if (!m_ui->cbChannel->count()) - m_ui->cbChannel->addItem(NO_CHANNEL(), -1); - else if (freeChannels.size() == 1) - m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(currentlySelectedChannelId)); - else if (currentlySelectedChannelId != -1) - QTimer::singleShot(100, this, [this, currentlySelectedChannelId] () { m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(currentlySelectedChannelId)); }); + if (!m_ui->cbChannel->count()) + m_ui->cbChannel->addItem(NO_CHANNEL(), -1); + else if (freeChannels.size() == 1) + m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(currentlySelectedChannelId)); + else if (currentlySelectedChannelId != -1) + QTimer::singleShot(100, this, [this, currentlySelectedChannelId]() { + m_ui->cbChannel->setCurrentIndex(m_ui->cbChannel->findData(currentlySelectedChannelId)); + }); } - - QVector EditCombatNetRadioDialog::exercisesToConsider() const { - auto isActive = [](ExerciseManagement::ExerciseState state) -> bool - { - return (state == ExerciseManagement::ExerciseState::Started || - state == ExerciseManagement::ExerciseState::Paused); - }; + auto isActive = [](ExerciseManagement::ExerciseState state) -> bool { + return (state == ExerciseManagement::ExerciseState::Started || + state == ExerciseManagement::ExerciseState::Paused); + }; - const auto allExercises = m_exmDtc->exercises(); - const ExerciseManagement::Exercise ¤tExercise = allExercises.value(m_exerciseId); - QVector toBeConsidered; - toBeConsidered.reserve(allExercises.size()); + const auto allExercises = m_exmDtc->exercises(); + const ExerciseManagement::Exercise& currentExercise = allExercises.value(m_exerciseId); + QVector toBeConsidered; + toBeConsidered.reserve(allExercises.size()); - if (!m_isGlobal && currentExercise.state() == ExerciseManagement::ExerciseState::Created) - { - toBeConsidered.append(currentExercise.id()); + if (!m_isGlobal && currentExercise.state() == ExerciseManagement::ExerciseState::Created) + { + toBeConsidered.append(currentExercise.id()); - if (currentExercise.linkedExerciseId() > 0) - toBeConsidered.append(currentExercise.linkedExerciseId()); + if (currentExercise.linkedExerciseId() > 0) + toBeConsidered.append(currentExercise.linkedExerciseId()); + + return toBeConsidered; + } + + if (!m_isGlobal && !isActive(allExercises[m_exerciseId].state())) + return {m_exerciseId}; + + for (const auto& exercise : allExercises) + { + if (isActive(exercise.state())) + toBeConsidered.append(exercise.id()); + } return toBeConsidered; - } - - if (!m_isGlobal && !isActive(allExercises[m_exerciseId].state())) - return {m_exerciseId}; - - for (const auto &exercise : allExercises) - { - if (isActive(exercise.state())) - toBeConsidered.append(exercise.id()); - } - - return toBeConsidered; } QVector EditCombatNetRadioDialog::exercisesToIgnore() const { - const auto allExercises = m_exmDtc->exercises(); + const auto allExercises = m_exmDtc->exercises(); - auto canBeIgnored = [this] (const ExerciseManagement::Exercise &ex) -> bool - { - if (m_isGlobal) + auto canBeIgnored = [this](const ExerciseManagement::Exercise& ex) -> bool { + if (m_isGlobal) + { + return (ex.state() == ExerciseManagement::ExerciseState::Created || + ex.state() == ExerciseManagement::ExerciseState::Stopped || + ex.state() == ExerciseManagement::ExerciseState::Terminated || ex.isDeleted()); + } + return (ex.state() == ExerciseManagement::ExerciseState::Stopped || + ex.state() == ExerciseManagement::ExerciseState::Terminated || ex.isDeleted()); + }; + + QVector exercisesToIgnore; + for (const auto& ex : allExercises) { - return (ex.state() == ExerciseManagement::ExerciseState::Created || - ex.state() == ExerciseManagement::ExerciseState::Stopped || - ex.state() == ExerciseManagement::ExerciseState::Terminated || - ex.isDeleted()); + if (canBeIgnored(ex)) + exercisesToIgnore += ex.id(); } - return (ex.state() == ExerciseManagement::ExerciseState::Stopped || - ex.state() == ExerciseManagement::ExerciseState::Terminated || - ex.isDeleted()); - }; - - QVector exercisesToIgnore; - for (const auto &ex : allExercises) - { - if (canBeIgnored(ex)) - exercisesToIgnore += ex.id(); - } - return exercisesToIgnore; + return exercisesToIgnore; } - -bool EditCombatNetRadioDialog::isNameValid(const QString &name) const +bool EditCombatNetRadioDialog::isNameValid(const QString& name) const { - if (!isStreamNameValid(name)) - return false; - if (m_takenNames.contains(name)) - return false; - return true; + if (!isStreamNameValid(name)) + return false; + if (m_takenNames.contains(name)) + return false; + return true; } void EditCombatNetRadioDialog::onPartyIndexChanged(int index) { - m_ui->cbUnit->clear(); + m_ui->cbUnit->clear(); - m_ui->cbUnit->addItem(QLatin1String("-"), QVariant::fromValue(0)); + m_ui->cbUnit->addItem(QLatin1String("-"), QVariant::fromValue(0)); - int32_t partyId = m_ui->cbParty->itemData(index).toInt(); + int32_t partyId = m_ui->cbParty->itemData(index).toInt(); - for (const ParticipantManagement::Participant &unit : std::as_const(m_units)) - { - QString unitStr; - if (unit.partyId() == partyId) + for (const ParticipantManagement::Participant& unit : std::as_const(m_units)) { - if (unit.designator().size() > 0) - { - unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); - INFO_LOG(m_logger)<<"Designator != leer: unitStr = " << unitStr; - } - unitStr += QString::fromStdString(unit.tacticalIdentifier()); - INFO_LOG(m_logger) << "unitStr =" << unitStr - << " id =" << unit.id(); + QString unitStr; + if (unit.partyId() == partyId) + { + if (unit.designator().size() > 0) + { + unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); + INFO_LOG(m_logger) << "Designator != leer: unitStr = " << unitStr; + } + unitStr += QString::fromStdString(unit.tacticalIdentifier()); + INFO_LOG(m_logger) << "unitStr =" << unitStr << " id =" << unit.id(); - m_ui->cbUnit->addItem(unitStr, unit.id()); + m_ui->cbUnit->addItem(unitStr, unit.id()); + } } - } } void EditCombatNetRadioDialog::onChannelChanged(int index) { - int channelId = m_ui->cbChannel->itemData(index).toInt(); - - bool disableParty = (m_avmDtc->cnrChannel(channelId).frequencyBand() == FrequencyBand_def::REL) || m_isGlobal; - m_ui->cbUnit->setDisabled(disableParty); - m_ui->lbUnit->setDisabled(disableParty); - m_ui->cbParty->setDisabled(disableParty); - m_ui->lbParty->setDisabled(disableParty); - if(disableParty && !m_isGlobal) - { - m_ui->cbParty->addItem(QStringLiteral("-")); - m_ui->cbParty->setCurrentText(QStringLiteral("-")); - } + int channelId = m_ui->cbChannel->itemData(index).toInt(); + bool disableParty = (m_avmDtc->cnrChannel(channelId).frequencyBand() == FrequencyBand_def::REL) || m_isGlobal; + m_ui->cbUnit->setDisabled(disableParty); + m_ui->lbUnit->setDisabled(disableParty); + m_ui->cbParty->setDisabled(disableParty); + m_ui->lbParty->setDisabled(disableParty); + if (disableParty && !m_isGlobal) + { + m_ui->cbParty->addItem(QStringLiteral("-")); + m_ui->cbParty->setCurrentText(QStringLiteral("-")); + } } QByteArray EditCombatNetRadioDialog::cnrConfigRequestToJson() { - ModifyCnrConfigRequest req = createRequest(); + ModifyCnrConfigRequest req = createRequest(); - QJsonObject obj; - obj[QStringLiteral("id")] = req.id(); - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio); - obj[QStringLiteral("callSign")] = QString::fromStdString(req.callSign()); - obj[QStringLiteral("cnrChannelId")] = req.cnrChannelId(); - obj[QStringLiteral("radioCircuit")] = QString::fromStdString(req.radioCircuit()); - obj[QStringLiteral("recording")] = req.recording(); - obj[QStringLiteral("partyId")] = req.partyId(); - obj[QStringLiteral("isGlobal")] = !req.exerciseId().is_set(); - if (req.unitId().is_set()) - obj[QStringLiteral("unitId")] = req.unitId().get(); - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + QJsonObject obj; + obj[QStringLiteral("id")] = req.id(); + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio); + obj[QStringLiteral("callSign")] = QString::fromStdString(req.callSign()); + obj[QStringLiteral("cnrChannelId")] = req.cnrChannelId(); + obj[QStringLiteral("radioCircuit")] = QString::fromStdString(req.radioCircuit()); + obj[QStringLiteral("recording")] = req.recording(); + obj[QStringLiteral("partyId")] = req.partyId(); + obj[QStringLiteral("isGlobal")] = !req.exerciseId().is_set(); + if (req.unitId().is_set()) + obj[QStringLiteral("unitId")] = req.unitId().get(); + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -ModifyCnrConfigRequest EditCombatNetRadioDialog::jsonToModifyCnrConfig(const QByteArray &content) +ModifyCnrConfigRequest EditCombatNetRadioDialog::jsonToModifyCnrConfig(const QByteArray& content) { - ModifyCnrConfigRequest result; - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); + ModifyCnrConfigRequest result; + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); - result.id(obj[QStringLiteral("id")].toInt()); - result.callSign(obj[QStringLiteral("callSign")].toString().toStdString()); - result.cnrChannelId(obj[QStringLiteral("cnrChannelId")].toInt()); - result.radioCircuit(obj[QStringLiteral("radioCircuit")].toString().toStdString()); - result.recording(obj[QStringLiteral("recording")].toInt()); - result.partyId(obj[QStringLiteral("partyId")].toInt()); - if (!obj.contains(QLatin1String("isGlobal")) || !obj[QLatin1String("isGlobal")].toBool()) - result.exerciseId(m_exerciseId); - if (obj.contains(QStringLiteral("unitId"))) - result.unitId(obj[QStringLiteral("unitId")].toInt()); + result.id(obj[QStringLiteral("id")].toInt()); + result.callSign(obj[QStringLiteral("callSign")].toString().toStdString()); + result.cnrChannelId(obj[QStringLiteral("cnrChannelId")].toInt()); + result.radioCircuit(obj[QStringLiteral("radioCircuit")].toString().toStdString()); + result.recording(obj[QStringLiteral("recording")].toInt()); + result.partyId(obj[QStringLiteral("partyId")].toInt()); + if (!obj.contains(QLatin1String("isGlobal")) || !obj[QLatin1String("isGlobal")].toBool()) + result.exerciseId(m_exerciseId); + if (obj.contains(QStringLiteral("unitId"))) + result.unitId(obj[QStringLiteral("unitId")].toInt()); - return result; + return result; } void EditCombatNetRadioDialog::onExportButtonClicked() { - QByteArray byteArray = cnrConfigRequestToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_exerciseId, byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + QByteArray byteArray = cnrConfigRequestToJson(); + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_exerciseId, byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void EditCombatNetRadioDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_exerciseId, FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_exerciseId, + FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMEditCombatNetRadio))) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + ModifyCnrConfigRequest req = jsonToModifyCnrConfig(content); + setUiValues(toConfig(req)); + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + } } - else - { - ModifyCnrConfigRequest req = jsonToModifyCnrConfig(content); - setUiValues(toConfig(req)); - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; - } - } } - - -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.h old mode 100755 new mode 100644 index e9023209c..1e62f277b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_edit_combat_net_radio_dialog.h @@ -1,19 +1,17 @@ - #pragma once -#include - -#include -#include #include #include -#include +#include #include +#include +#include +#include #include -#include #include +#include #include #include @@ -25,7 +23,7 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace Ui { @@ -34,90 +32,78 @@ class EditCombatNetRadioDialog; namespace AudioVideoManagement { -class EditCombatNetRadioDialog - : public LtsWidgets::LtsDialog - , protected Interface::Ftc::ModifyCnrConfigReplyHandler +class EditCombatNetRadioDialog : public LtsWidgets::LtsDialog, protected Interface::Ftc::ModifyCnrConfigReplyHandler { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit EditCombatNetRadioDialog(int32_t exerciseId, LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, QWidget* parent); - explicit EditCombatNetRadioDialog(int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent); + explicit EditCombatNetRadioDialog(const CnrConfig& cnrConfig, int32_t exerciseId, LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, QWidget* parent); - + ~EditCombatNetRadioDialog(); - explicit EditCombatNetRadioDialog(const CnrConfig &cnrConfig, - int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent); + void retranslate() override; - ~EditCombatNetRadioDialog(); + void onModifyCnrConfigReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - void retranslate() override; + protected: + NGL::INGLLogger& m_logger; + bool apply() override; - void onModifyCnrConfigReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + private: + EditCombatNetRadioDialog(const boost::optional& id, int32_t exerciseId, LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, ExerciseManagement::Interface::Dtc* exmDtc, + QWidget* parent); -protected: + void init(LtsSession::LtsSession* session); -NGL::INGLLogger &m_logger; - bool apply() override; + void initCbChannelsForCreate(); + void initCbChannels(int channelId); + void updateFreeChannelsAndTakenNames(); + void updateCbChannels(QVector&& freeChannels, QMap&& channelsToDisable); + QVector exercisesToConsider() const; + QVector exercisesToIgnore() const; + bool isNameValid(const QString& name) const; -private: - EditCombatNetRadioDialog(const boost::optional &id, - int32_t exerciseId, - LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent); + QByteArray cnrConfigRequestToJson(); + ModifyCnrConfigRequest createRequest(); + ModifyCnrConfigRequest jsonToModifyCnrConfig(const QByteArray& content); + void setUiValues(const CnrConfig& cnrConfig); + void setUiValuesForGlobal(); - void init(LtsSession::LtsSession *session); + private Q_SLOTS: + void onPartyIndexChanged(int index); + void onExportButtonClicked(); + void onImportButtonClicked(); + void onChannelChanged(int index); - void initCbChannelsForCreate(); - void initCbChannels(int channelId); - void updateFreeChannelsAndTakenNames(); - void updateCbChannels(QVector &&freeChannels, QMap &&channelsToDisable); - QVector exercisesToConsider() const; - QVector exercisesToIgnore() const; - bool isNameValid(const QString &name) const; - - QByteArray cnrConfigRequestToJson(); - ModifyCnrConfigRequest createRequest(); - ModifyCnrConfigRequest jsonToModifyCnrConfig(const QByteArray &content); - void setUiValues(const CnrConfig &cnrConfig); - void setUiValuesForGlobal(); - -private Q_SLOTS: - void onPartyIndexChanged(int index); - void onExportButtonClicked(); - void onImportButtonClicked(); - void onChannelChanged(int index); - -private: - std::unique_ptr m_ui; - boost::optional m_id; - int32_t m_exerciseId; - boost::optional m_channelId; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - ExerciseManagement::Interface::Dtc *m_exmDtc; - std::shared_ptr m_flmGui; - QMap m_units; - QVector m_takenNames; - std::unique_ptr m_requestHelper; - bool m_isGlobal; -}; -} + private: + std::unique_ptr m_ui; + boost::optional m_id; + int32_t m_exerciseId; + boost::optional m_channelId; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + ExerciseManagement::Interface::Dtc* m_exmDtc; + std::shared_ptr m_flmGui; + QMap m_units; + QVector m_takenNames; + std::unique_ptr m_requestHelper; + bool m_isGlobal; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog.h old mode 100755 new mode 100644 index 5aafb6983..cf59e5724 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog.h @@ -1,11 +1,10 @@ - #pragma once -#include #include #include +#include namespace Ui { @@ -23,7 +22,7 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace ExerciseManagement { @@ -31,36 +30,33 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace AudioVideoManagement { class LoadCombatNetRadioDialogModel; -class LoadCombatNetRadioDialog - : public LtsWidgets::LtsFramelessDialog +class LoadCombatNetRadioDialog : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT -public: - explicit LoadCombatNetRadioDialog(const QByteArray &data, - LtsSession::LtsSession *session, - QWidget *parent = nullptr); + Q_OBJECT + public: + explicit LoadCombatNetRadioDialog(const QByteArray& data, LtsSession::LtsSession* session, + QWidget* parent = nullptr); - ~LoadCombatNetRadioDialog(); + ~LoadCombatNetRadioDialog(); - QVector removeRequests() const; - QVector modifyRequests() const; + QVector removeRequests() const; + QVector modifyRequests() const; - bool isApplied() const; + bool isApplied() const; -private Q_SLOTS: - void onOk(); + private Q_SLOTS: + void onOk(); -private: - -NGL::INGLLogger &m_logger; - std::unique_ptr m_ui; - LoadCombatNetRadioDialogModel *m_model; - bool m_isApplied = false; -}; -} + private: + NGL::INGLLogger& m_logger; + std::unique_ptr m_ui; + LoadCombatNetRadioDialogModel* m_model; + bool m_isApplied = false; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.cpp old mode 100755 new mode 100644 index 0626551a3..6df9f8e9f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.cpp @@ -1,427 +1,412 @@ - #include "avm_load_combat_net_radio_dialog_model.h" -#include -#include -#include -#include -#include - -#include -#include -#include #include "avm_cnr_json_helper.h" -#include - -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace AudioVideoManagement { -LoadCombatNetRadioDialogModel::LoadCombatNetRadioDialogModel(const QByteArray &data, - LtsSession::LtsSession *session, - QObject *parent) - : LtsAbstractTableModel( +LoadCombatNetRadioDialogModel::LoadCombatNetRadioDialogModel(const QByteArray& data, LtsSession::LtsSession* session, + QObject* parent) + : LtsAbstractTableModel( + {tr("Include"), tr("Channel"), tr("Radio Circuit"), tr("Code Word"), tr("Conflict(s)")}, parent), + m_exerciseId(session == nullptr ? 0 : session->exerciseId()) { - tr("Include"), - tr("Channel"), - tr("Radio Circuit"), - tr("Code Word"), - tr("Conflict(s)") -}, parent) - , m_exerciseId(session == nullptr ? 0 : session->exerciseId()) -{ - DEBUG_LOG(m_logger) << "Own exercise id: " << m_exerciseId; + DEBUG_LOG(m_logger) << "Own exercise id: " << m_exerciseId; - if (session != nullptr) - { - std::shared_ptr avmDtc; - - if (!session->getDtc(avmDtc) - || !avmDtc->enableCnrChannel() - || !avmDtc->enableCnrConfig()) - ERROR_LOG(m_logger) << "Could not get AVM data"; - else + if (session != nullptr) { - m_cnrChannels = avmDtc->cnrChannels(); - m_cnrConfigs = avmDtc->cnrConfigs(); + std::shared_ptr avmDtc; + + if (!session->getDtc(avmDtc) || !avmDtc->enableCnrChannel() || + !avmDtc->enableCnrConfig()) + ERROR_LOG(m_logger) << "Could not get AVM data"; + else + { + m_cnrChannels = avmDtc->cnrChannels(); + m_cnrConfigs = avmDtc->cnrConfigs(); + } + + DEBUG_LOG(m_logger) << "cnrconfigs: " << m_cnrConfigs.size(); + DEBUG_LOG(m_logger) << "ownExerciseId: " << m_exerciseId; + + std::shared_ptr exmDtc; + + if (!session->getDtc(exmDtc) || !exmDtc->enableExercise()) + ERROR_LOG(m_logger) << "Could not get EXM data"; + else + m_exercises = exmDtc->exercises(); + + DEBUG_LOG(m_logger) << "exercises: " << m_exercises.size(); + } + else + ERROR_LOG(m_logger) << "Got invalid session."; + + m_vecData = jsonToCnrConfigVector(data); + + m_includeStates.reserve(m_vecData.size()); + m_conflicts.reserve(m_vecData.size()); + + for (int32_t idxCounter = 0; idxCounter < m_vecData.size(); ++idxCounter) + { + Conflicts conflicts = getConflicts(idxCounter, m_vecData.at(idxCounter)); + + m_conflicts.append(conflicts); + m_includeStates.append(conflicts == NO_CONFLICT ? Qt::Checked : Qt::Unchecked); + + if (conflicts & CHANNEL_TAKEN_IN_GLOBAL || conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) + m_disabledRows.append(idxCounter); + } +} + +Qt::ItemFlags LoadCombatNetRadioDialogModel::flags(const QModelIndex& index) const +{ + if (indexIsValid(index) && m_disabledRows.contains(index.row())) + return Qt::NoItemFlags; + + if (index.column() > 0) + return LtsAbstractTableModel::flags(index); + + return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | LtsAbstractTableModel::flags(index); +} + +bool LoadCombatNetRadioDialogModel::setData(const QModelIndex& index, const QVariant& value, int role) +{ + if (indexIsValid(index) && role == Qt::CheckStateRole && index.column() == 0 && value.canConvert()) + { + m_includeStates[index.row()] = value.value(); + + emit dataChanged(index, index, {role}); + + return true; } - DEBUG_LOG(m_logger) << "cnrconfigs: " << m_cnrConfigs.size(); - DEBUG_LOG(m_logger) << "ownExerciseId: " << m_exerciseId; - - std::shared_ptr exmDtc; - - if (!session->getDtc(exmDtc) - || !exmDtc->enableExercise()) - ERROR_LOG(m_logger) << "Could not get EXM data"; - else - m_exercises = exmDtc->exercises(); - - DEBUG_LOG(m_logger) << "exercises: " << m_exercises.size(); - } - else - ERROR_LOG(m_logger) << "Got invalid session."; - - m_vecData = jsonToCnrConfigVector(data); - - m_includeStates.reserve(m_vecData.size()); - m_conflicts.reserve(m_vecData.size()); - - for (int32_t idxCounter = 0; idxCounter < m_vecData.size(); ++idxCounter) - { - Conflicts conflicts = getConflicts(idxCounter, m_vecData.at(idxCounter)); - - m_conflicts.append(conflicts); - m_includeStates.append(conflicts == NO_CONFLICT ? Qt::Checked : Qt::Unchecked); - - if (conflicts & CHANNEL_TAKEN_IN_GLOBAL || conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) - m_disabledRows.append(idxCounter); - } + return QAbstractTableModel::setData(index, value, role); } -Qt::ItemFlags LoadCombatNetRadioDialogModel::flags(const QModelIndex &index) const +QVariant LoadCombatNetRadioDialogModel::data(const QModelIndex& index, int role) const { - if (indexIsValid(index) && m_disabledRows.contains(index.row())) - return Qt::NoItemFlags; + if (!indexIsValid(index)) + return QVariant(); - if (index.column() > 0) - return LtsAbstractTableModel::flags(index); - - return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | LtsAbstractTableModel::flags(index); -} - -bool LoadCombatNetRadioDialogModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (indexIsValid(index) - && role == Qt::CheckStateRole - && index.column() == 0 - && value.canConvert()) - { - m_includeStates[index.row()] = value.value(); - - emit dataChanged(index, index, {role}); - - return true; - } - - return QAbstractTableModel::setData(index, value, role); -} - -QVariant LoadCombatNetRadioDialogModel::data(const QModelIndex &index, int role) const -{ - if (!indexIsValid(index)) - return QVariant(); - - switch (role) - { - case Qt::DisplayRole: - { - const CnrConfig &config = m_vecData.at(index.row()); - switch (index.column()) + switch (role) { - case CHANNEL: - return QString::fromStdString(m_cnrChannels.value(config.cnrChannelId()).name()); - case RADIO_CIRCUIT: - return QString::fromStdString(config.radioCircuit()); - case CALL_SIGN: - return QString::fromStdString(config.callSign()); - case CONFLICTS: - return conflictsText(m_conflicts.at(index.row())); - default: - return QVariant(); + case Qt::DisplayRole: { + const CnrConfig& config = m_vecData.at(index.row()); + switch (index.column()) + { + case CHANNEL: + return QString::fromStdString(m_cnrChannels.value(config.cnrChannelId()).name()); + case RADIO_CIRCUIT: + return QString::fromStdString(config.radioCircuit()); + case CALL_SIGN: + return QString::fromStdString(config.callSign()); + case CONFLICTS: + return conflictsText(m_conflicts.at(index.row())); + default: + return QVariant(); + } + } + case Qt::CheckStateRole: + if (index.column() != 0) + return QVariant(); + return m_includeStates.at(index.row()); + case Qt::BackgroundRole: + return getConflictsRowColor(m_conflicts.at(index.row())); + default: + return QVariant(); } - } - case Qt::CheckStateRole: - if (index.column() != 0) - return QVariant(); - return m_includeStates.at(index.row()); - case Qt::BackgroundRole: - return getConflictsRowColor(m_conflicts.at(index.row())); - default: - return QVariant(); - } } bool LoadCombatNetRadioDialogModel::allChecked() const { - for (int32_t row = 0; row < m_includeStates.size(); ++row) - { - if (m_disabledRows.contains(row)) - continue; + for (int32_t row = 0; row < m_includeStates.size(); ++row) + { + if (m_disabledRows.contains(row)) + continue; - if (m_includeStates.at(row) == Qt::Unchecked) - return false; - } + if (m_includeStates.at(row) == Qt::Unchecked) + return false; + } - return true; + return true; } void LoadCombatNetRadioDialogModel::setCheckState(bool isChecked) { - const QVariant data = QVariant(isChecked ? Qt::Checked : Qt::Unchecked); - const int role = Qt::CheckStateRole; + const QVariant data = QVariant(isChecked ? Qt::Checked : Qt::Unchecked); + const int role = Qt::CheckStateRole; - for (int32_t row = 0; row < rowCount(); ++row) - { - if (m_disabledRows.contains(row)) - continue; + for (int32_t row = 0; row < rowCount(); ++row) + { + if (m_disabledRows.contains(row)) + continue; - setData(createIndex(row, 0), data, role); - } + setData(createIndex(row, 0), data, role); + } } -LoadCombatNetRadioDialogModel::Conflicts LoadCombatNetRadioDialogModel::getConflicts(int32_t row, const CnrConfig &config) +LoadCombatNetRadioDialogModel::Conflicts LoadCombatNetRadioDialogModel::getConflicts(int32_t row, + const CnrConfig& config) { - Conflicts conflicts = NO_CONFLICT; + Conflicts conflicts = NO_CONFLICT; - for (auto it = m_cnrConfigs.constBegin(); it != m_cnrConfigs.constEnd(); ++it) - { - if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG) && isRadioCircuitTakenInOwnConfig(config, it.value())) + for (auto it = m_cnrConfigs.constBegin(); it != m_cnrConfigs.constEnd(); ++it) { - conflicts |= RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG; - addConflictedCnr(row, it.value().id()); + if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG) && isRadioCircuitTakenInOwnConfig(config, it.value())) + { + conflicts |= RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE) && + isRadioCircuitTakenInAnotherExercise(config, it.value())) + { + conflicts |= RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & CHANNEL_TAKEN_IN_ACTIVE_EXERCISE) && isChannelTakenInActiveExercise(config, it.value())) + { + conflicts |= CHANNEL_TAKEN_IN_ACTIVE_EXERCISE; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & CHANNEL_TAKEN_IN_LINKED_EXERCISE) && isChannelTakenInLinkedExercise(config, it.value())) + { + conflicts |= CHANNEL_TAKEN_IN_LINKED_EXERCISE; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & CHANNEL_TAKEN_IN_OWN_CONFIG) && isChannelTakenInOwnConfig(config, it.value())) + { + conflicts |= CHANNEL_TAKEN_IN_OWN_CONFIG; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & CHANNEL_TAKEN_IN_GLOBAL) && isChannelTakenInGlobal(config, it.value())) + { + conflicts |= CHANNEL_TAKEN_IN_GLOBAL; + addConflictedCnr(row, it.value().id()); + } + + if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) && isRadioCircuitTakenInGlobal(config, it.value())) + { + conflicts |= RADIO_CIRCUIT_TAKEN_IN_GLOBAL; + addConflictedCnr(row, it.value().id()); + } } - if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE) && isRadioCircuitTakenInAnotherExercise(config, it.value())) - { - conflicts |= RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE; - addConflictedCnr(row, it.value().id()); - } - - if (!(conflicts & CHANNEL_TAKEN_IN_ACTIVE_EXERCISE) && isChannelTakenInActiveExercise(config, it.value())) - { - conflicts |= CHANNEL_TAKEN_IN_ACTIVE_EXERCISE; - addConflictedCnr(row, it.value().id()); - } - - if (!(conflicts & CHANNEL_TAKEN_IN_LINKED_EXERCISE) && isChannelTakenInLinkedExercise(config, it.value())) - { - conflicts |= CHANNEL_TAKEN_IN_LINKED_EXERCISE; - addConflictedCnr(row, it.value().id()); - } - - if (!(conflicts & CHANNEL_TAKEN_IN_OWN_CONFIG) && isChannelTakenInOwnConfig(config, it.value())) - { - conflicts |= CHANNEL_TAKEN_IN_OWN_CONFIG; - addConflictedCnr(row, it.value().id()); - } - - if (!(conflicts & CHANNEL_TAKEN_IN_GLOBAL) && isChannelTakenInGlobal(config, it.value())) - { - conflicts |= CHANNEL_TAKEN_IN_GLOBAL; - addConflictedCnr(row, it.value().id()); - } - - if (!(conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) && isRadioCircuitTakenInGlobal(config, it.value())) - { - conflicts |= RADIO_CIRCUIT_TAKEN_IN_GLOBAL; - addConflictedCnr(row, it.value().id()); - } - } - - return conflicts; + return conflicts; } QString LoadCombatNetRadioDialogModel::conflictsText(Conflicts conflicts) const { - QStringList conflictTexts; + QStringList conflictTexts; - if (conflicts & RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG) - conflictTexts.append(tr("Radio Circuit is already taken in own config.")); + if (conflicts & RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG) + conflictTexts.append(tr("Radio Circuit is already taken in own config.")); - if (conflicts & RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE) - conflictTexts.append(tr("Radio Circuit is already taken in another exercise.")); + if (conflicts & RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE) + conflictTexts.append(tr("Radio Circuit is already taken in another exercise.")); - if (conflicts & CHANNEL_TAKEN_IN_ACTIVE_EXERCISE) - conflictTexts.append(tr("Channel already taken in active exercise.")); + if (conflicts & CHANNEL_TAKEN_IN_ACTIVE_EXERCISE) + conflictTexts.append(tr("Channel already taken in active exercise.")); - if (conflicts & CHANNEL_TAKEN_IN_LINKED_EXERCISE) - conflictTexts.append(tr("Channel already taken in linked exercise.")); + if (conflicts & CHANNEL_TAKEN_IN_LINKED_EXERCISE) + conflictTexts.append(tr("Channel already taken in linked exercise.")); - if (conflicts & CHANNEL_TAKEN_IN_OWN_CONFIG) - conflictTexts.append(tr("Channel is already taken in own Cnr Config.")); + if (conflicts & CHANNEL_TAKEN_IN_OWN_CONFIG) + conflictTexts.append(tr("Channel is already taken in own Cnr Config.")); - if (conflicts & CHANNEL_TAKEN_IN_GLOBAL) - conflictTexts.append(tr("Channel already taken in global Cnr Config.")); + if (conflicts & CHANNEL_TAKEN_IN_GLOBAL) + conflictTexts.append(tr("Channel already taken in global Cnr Config.")); - if (conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) - conflictTexts.append(tr("Radio Circuit already taken in global Cnr Config.")); + if (conflicts & RADIO_CIRCUIT_TAKEN_IN_GLOBAL) + conflictTexts.append(tr("Radio Circuit already taken in global Cnr Config.")); - return conflictTexts.isEmpty() ? QLatin1String("-") : conflictTexts.join(QLatin1Char('\n')); + return conflictTexts.isEmpty() ? QLatin1String("-") : conflictTexts.join(QLatin1Char('\n')); } void LoadCombatNetRadioDialogModel::addConflictedCnr(int32_t row, int32_t cnrConfigId) { - m_conflictedCnrIds[row].append(cnrConfigId); + m_conflictedCnrIds[row].append(cnrConfigId); } bool LoadCombatNetRadioDialogModel::isActiveExercise(int32_t exerciseId) const { - if (exerciseId == 0) - return true; + if (exerciseId == 0) + return true; - using namespace ExerciseManagement; + using namespace ExerciseManagement; - ExerciseState exerciseState = m_exercises.value(exerciseId).state(); + ExerciseState exerciseState = m_exercises.value(exerciseId).state(); - return exerciseState == ExerciseState::Started || exerciseState == ExerciseState::Paused; + return exerciseState == ExerciseState::Started || exerciseState == ExerciseState::Paused; } QColor LoadCombatNetRadioDialogModel::getConflictsRowColor(Conflicts conflicts) const { - if (conflicts >= CHANNEL_TAKEN_IN_GLOBAL) - return QColor(Qt::red).lighter(); + if (conflicts >= CHANNEL_TAKEN_IN_GLOBAL) + return QColor(Qt::red).lighter(); - if (conflicts > NO_CONFLICT) - return QColor(Qt::yellow).lighter(); + if (conflicts > NO_CONFLICT) + return QColor(Qt::yellow).lighter(); - return QColor(Qt::green).lighter(); + return QColor(Qt::green).lighter(); } -bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInOwnConfig(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInOwnConfig(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - if (m_exerciseId == 0) - return !existingConfig.exerciseId().is_set() && existingConfig.radioCircuit() == loadConfig.radioCircuit(); + if (m_exerciseId == 0) + return !existingConfig.exerciseId().is_set() && existingConfig.radioCircuit() == loadConfig.radioCircuit(); - if (!existingConfig.exerciseId().is_set() - || existingConfig.exerciseId().get() != m_exerciseId - || existingConfig.radioCircuit() != loadConfig.radioCircuit()) - return false; + if (!existingConfig.exerciseId().is_set() || existingConfig.exerciseId().get() != m_exerciseId || + existingConfig.radioCircuit() != loadConfig.radioCircuit()) + return false; - return true; + return true; } -bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInAnotherExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInAnotherExercise(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - if (!isActiveExercise(m_exerciseId) - || !existingConfig.exerciseId().is_set() - || !isActiveExercise(existingConfig.exerciseId().get()) - || existingConfig.exerciseId().get() == m_exerciseId - || existingConfig.radioCircuit() != loadConfig.radioCircuit()) - return false; + if (!isActiveExercise(m_exerciseId) || !existingConfig.exerciseId().is_set() || + !isActiveExercise(existingConfig.exerciseId().get()) || existingConfig.exerciseId().get() == m_exerciseId || + existingConfig.radioCircuit() != loadConfig.radioCircuit()) + return false; - return true; + return true; } -bool LoadCombatNetRadioDialogModel::isChannelTakenInActiveExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isChannelTakenInActiveExercise(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; + int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; - if (!isActiveExercise(m_exerciseId) - || exerciseId == 0 - || exerciseId == m_exerciseId - || !isActiveExercise(exerciseId) - || existingConfig.cnrChannelId() != loadConfig.cnrChannelId() - || !isActiveExercise(exerciseId)) - return false; + if (!isActiveExercise(m_exerciseId) || exerciseId == 0 || exerciseId == m_exerciseId || + !isActiveExercise(exerciseId) || existingConfig.cnrChannelId() != loadConfig.cnrChannelId() || + !isActiveExercise(exerciseId)) + return false; - return true; + return true; } -bool LoadCombatNetRadioDialogModel::isChannelTakenInLinkedExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isChannelTakenInLinkedExercise(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - if (m_exerciseId == 0 || m_exercises.value(m_exerciseId).linkedExerciseId() == 0) - return false; + if (m_exerciseId == 0 || m_exercises.value(m_exerciseId).linkedExerciseId() == 0) + return false; - int32_t linkedExerciseId = m_exercises.value(m_exerciseId).linkedExerciseId(); + int32_t linkedExerciseId = m_exercises.value(m_exerciseId).linkedExerciseId(); - int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; + int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; - if (exerciseId != linkedExerciseId || existingConfig.cnrChannelId() != loadConfig.cnrChannelId()) - return false; + if (exerciseId != linkedExerciseId || existingConfig.cnrChannelId() != loadConfig.cnrChannelId()) + return false; - return true; + return true; } -bool LoadCombatNetRadioDialogModel::isChannelTakenInOwnConfig(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isChannelTakenInOwnConfig(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; + int32_t exerciseId = existingConfig.exerciseId().is_set() ? existingConfig.exerciseId().get() : 0; - return existingConfig.cnrChannelId() == loadConfig.cnrChannelId() && exerciseId == m_exerciseId; + return existingConfig.cnrChannelId() == loadConfig.cnrChannelId() && exerciseId == m_exerciseId; } -bool LoadCombatNetRadioDialogModel::isChannelTakenInGlobal(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isChannelTakenInGlobal(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - if (!isActiveExercise(m_exerciseId) - || m_exerciseId == 0 - || existingConfig.exerciseId().is_set() - || existingConfig.cnrChannelId() != loadConfig.cnrChannelId()) - return false; + if (!isActiveExercise(m_exerciseId) || m_exerciseId == 0 || existingConfig.exerciseId().is_set() || + existingConfig.cnrChannelId() != loadConfig.cnrChannelId()) + return false; - return true; + return true; } -bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInGlobal(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const +bool LoadCombatNetRadioDialogModel::isRadioCircuitTakenInGlobal(const CnrConfig& loadConfig, + const CnrConfig& existingConfig) const { - if (!isActiveExercise(m_exerciseId) - || m_exerciseId == 0 - || existingConfig.exerciseId().is_set() - || existingConfig.radioCircuit() != loadConfig.radioCircuit()) - return false; + if (!isActiveExercise(m_exerciseId) || m_exerciseId == 0 || existingConfig.exerciseId().is_set() || + existingConfig.radioCircuit() != loadConfig.radioCircuit()) + return false; - return true; + return true; } QVector LoadCombatNetRadioDialogModel::removeRequests() const { - QVector removeRequestsVec; + QVector removeRequestsVec; - for (int32_t idxCounter = 0; idxCounter < m_includeStates.size(); ++idxCounter) - { - if (m_includeStates.at(idxCounter) == Qt::Checked && m_conflicts.at(idxCounter) != NO_CONFLICT) + for (int32_t idxCounter = 0; idxCounter < m_includeStates.size(); ++idxCounter) { - if (!m_conflictedCnrIds.contains(idxCounter)) - { - WARNING_LOG(m_logger) << "Tried to get remove request for row " << idxCounter << " but it is not present."; - continue; - } + if (m_includeStates.at(idxCounter) == Qt::Checked && m_conflicts.at(idxCounter) != NO_CONFLICT) + { + if (!m_conflictedCnrIds.contains(idxCounter)) + { + WARNING_LOG(m_logger) << "Tried to get remove request for row " << idxCounter + << " but it is not present."; + continue; + } - const QVector cnrConfigIds = m_conflictedCnrIds.value(idxCounter); + const QVector cnrConfigIds = m_conflictedCnrIds.value(idxCounter); - for (int32_t cnrConfigId : cnrConfigIds) - { - Core::RemoveElementRequest removeRequest(cnrConfigId); + for (int32_t cnrConfigId : cnrConfigIds) + { + Core::RemoveElementRequest removeRequest(cnrConfigId); - if (!removeRequestsVec.contains(removeRequest)) - removeRequestsVec.append(removeRequest); - } + if (!removeRequestsVec.contains(removeRequest)) + removeRequestsVec.append(removeRequest); + } + } } - } - return removeRequestsVec; + return removeRequestsVec; } QVector LoadCombatNetRadioDialogModel::modifyRequests() const { - const dds::core::optional exerciseId = m_exerciseId == 0 ? dds::core::optional() : dds::core::optional(m_exerciseId); - const int32_t partyId = m_exerciseId == 0 ? 1 : 0; - QVector modifyRequestsVec; + const dds::core::optional exerciseId = + m_exerciseId == 0 ? dds::core::optional() : dds::core::optional(m_exerciseId); + const int32_t partyId = m_exerciseId == 0 ? 1 : 0; + QVector modifyRequestsVec; - modifyRequestsVec.reserve(m_includeStates.size()); + modifyRequestsVec.reserve(m_includeStates.size()); - for (int32_t row = 0; row < m_includeStates.size(); ++row) - { - if (m_includeStates.at(row) != Qt::Checked) - continue; + for (int32_t row = 0; row < m_includeStates.size(); ++row) + { + if (m_includeStates.at(row) != Qt::Checked) + continue; - const CnrConfig &cnrConfig = m_vecData.at(row); + const CnrConfig& cnrConfig = m_vecData.at(row); - modifyRequestsVec.append({0, - cnrConfig.cnrChannelId(), - exerciseId, - cnrConfig.radioCircuit(), - cnrConfig.recording(), - {}, - partyId, - cnrConfig.callSign()}); - } + modifyRequestsVec.append({0, + cnrConfig.cnrChannelId(), + exerciseId, + cnrConfig.radioCircuit(), + cnrConfig.recording(), + {}, + partyId, + cnrConfig.callSign()}); + } - return modifyRequestsVec; + return modifyRequestsVec; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.h old mode 100755 new mode 100644 index de77997f8..8c45fc6b7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/CombatNetRadioConfiguration/avm_load_combat_net_radio_dialog_model.h @@ -1,14 +1,13 @@ - #pragma once -#include +#include +#include +#include #include #include -#include -#include -#include +#include namespace Core { @@ -21,7 +20,7 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace LtsSession { @@ -31,83 +30,70 @@ class LtsSession; namespace AudioVideoManagement { -class LoadCombatNetRadioDialogModel final - : public LtsWidgets::LtsAbstractTableModel +class LoadCombatNetRadioDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - INCLUDE, - CHANNEL, - RADIO_CIRCUIT, - CALL_SIGN, - CONFLICTS - }; + public: + enum Columns { INCLUDE, CHANNEL, RADIO_CIRCUIT, CALL_SIGN, CONFLICTS }; - enum Conflict - { - NO_CONFLICT = 0, - RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG = 0b00000001, - RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE = 0b00000010, - CHANNEL_TAKEN_IN_ACTIVE_EXERCISE = 0b00000100, - CHANNEL_TAKEN_IN_LINKED_EXERCISE = 0b00001000, - CHANNEL_TAKEN_IN_OWN_CONFIG = 0b00010000, + enum Conflict { + NO_CONFLICT = 0, + RADIO_CIRCUIT_TAKEN_IN_OWN_CONFIG = 0b00000001, + RADIO_CIRCUIT_TAKEN_IN_ANOTHER_EXERCISE = 0b00000010, + CHANNEL_TAKEN_IN_ACTIVE_EXERCISE = 0b00000100, + CHANNEL_TAKEN_IN_LINKED_EXERCISE = 0b00001000, + CHANNEL_TAKEN_IN_OWN_CONFIG = 0b00010000, - - CHANNEL_TAKEN_IN_GLOBAL = 0b00100000, - RADIO_CIRCUIT_TAKEN_IN_GLOBAL = 0b01000000, - }; - Q_DECLARE_FLAGS(Conflicts, Conflict) + CHANNEL_TAKEN_IN_GLOBAL = 0b00100000, + RADIO_CIRCUIT_TAKEN_IN_GLOBAL = 0b01000000, + }; + Q_DECLARE_FLAGS(Conflicts, Conflict) - explicit LoadCombatNetRadioDialogModel(const QByteArray &data, - LtsSession::LtsSession *session, - QObject *parent = nullptr); + explicit LoadCombatNetRadioDialogModel(const QByteArray& data, LtsSession::LtsSession* session, + QObject* parent = nullptr); - Qt::ItemFlags flags(const QModelIndex &index) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; - QVariant data(const QModelIndex &index, int role) const override; + QVariant data(const QModelIndex& index, int role) const override; - bool allChecked() const; + bool allChecked() const; - QVector removeRequests() const; - QVector modifyRequests() const; + QVector removeRequests() const; + QVector modifyRequests() const; -public Q_SLOTS: - void setCheckState(bool isChecked); + public Q_SLOTS: + void setCheckState(bool isChecked); -private: + private: + NGL::INGLLogger& m_logger; + LoadCombatNetRadioDialogModel::Conflicts getConflicts(int32_t row, const CnrConfig& config); + QString conflictsText(Conflicts conflicts) const; + bool isRadioCircuitTakenInOwnConfig(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isRadioCircuitTakenInAnotherExercise(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isChannelTakenInActiveExercise(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isChannelTakenInLinkedExercise(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isChannelTakenInOwnConfig(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isChannelTakenInGlobal(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; + bool isRadioCircuitTakenInGlobal(const CnrConfig& loadConfig, const CnrConfig& existingConfig) const; -NGL::INGLLogger &m_logger; - LoadCombatNetRadioDialogModel::Conflicts getConflicts(int32_t row, const CnrConfig &config); - QString conflictsText(Conflicts conflicts) const; + void addConflictedCnr(int32_t row, int32_t cnrConfigId); - bool isRadioCircuitTakenInOwnConfig(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isRadioCircuitTakenInAnotherExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isChannelTakenInActiveExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isChannelTakenInLinkedExercise(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isChannelTakenInOwnConfig(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isChannelTakenInGlobal(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; - bool isRadioCircuitTakenInGlobal(const CnrConfig &loadConfig, const CnrConfig &existingConfig) const; + bool isActiveExercise(int32_t exerciseId) const; - void addConflictedCnr(int32_t row, int32_t cnrConfigId); + QColor getConflictsRowColor(Conflicts conflicts) const; - bool isActiveExercise(int32_t exerciseId) const; - - QColor getConflictsRowColor(Conflicts conflicts) const; - -private: - int32_t m_exerciseId; - QMap m_cnrChannels; - QMap m_cnrConfigs; - QMap m_exercises; - QMap > m_conflictedCnrIds; - QVector m_includeStates; - QVector m_disabledRows; - QVector m_conflicts; + private: + int32_t m_exerciseId; + QMap m_cnrChannels; + QMap m_cnrConfigs; + QMap m_exercises; + QMap> m_conflictedCnrIds; + QVector m_includeStates; + QVector m_disabledRows; + QVector m_conflicts; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_dialog.cpp old mode 100755 new mode 100644 index 2cb74ee22..495b88eda --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_dialog.cpp @@ -1,422 +1,382 @@ - #include "avm_edit_frequency_planning_dialog.h" -#include -#include "ui_avm_edit_frequency_planning_dialog.h" + #include "avm_edit_frequency_planning_frequency_data_model.h" +#include "avm_load_frequency_planning_dialog.h" +#include "ui_avm_edit_frequency_planning_dialog.h" - +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include -#include -#include -#include -#include -#include -#include #include -#include -#include "avm_load_frequency_planning_dialog.h" - -#include -#include #include +#include +#include namespace { bool isActive(ExerciseManagement::ExerciseState state) { - return (state == ExerciseManagement::ExerciseState::Started || - state == ExerciseManagement::ExerciseState::Paused); + return (state == ExerciseManagement::ExerciseState::Started || state == ExerciseManagement::ExerciseState::Paused); } -} - +} // namespace namespace AudioVideoManagement { -EditFrequencyPlanningDialog::EditFrequencyPlanningDialog(LtsSession::LtsSession *session, - const QString &menuGroup, - const QString &freqPlanningDialogIdentifier, - const FrequencyPlanning &planning, - const bool copy, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &ismDtc, - ExerciseManagement::Interface::Dtc *exmDtc, - QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_session(session) - , m_menuGroup(menuGroup) - , m_freqPlanningDialogIdentifier(freqPlanningDialogIdentifier) - , m_ui(new Ui::EditFrequencyPlanningDialog) - , m_planning(planning) - , m_avmDtc(avmDtc) - , m_avmFtc(avmFtc) - , m_ppmDtc(ppmDtc) - , m_ismDtc(ismDtc) - , m_exmDtc(exmDtc) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_frequencyDataModel(new EditFrequencyPlanningFrequencyDataModel(planning, m_session->exerciseId(), avmDtc, ismDtc, ppmDtc, this)) - , m_frequencyPlanningId(copy ? 0 : planning.id()) - , m_exerciseId(session->exerciseId()) - , m_isEdit(EditFrequencyPlanningSetResourceDialog::DialogMode::Assign) - , m_activeFrequencyPlanningStatus(0) +EditFrequencyPlanningDialog::EditFrequencyPlanningDialog( + LtsSession::LtsSession* session, const QString& menuGroup, const QString& freqPlanningDialogIdentifier, + const FrequencyPlanning& planning, const bool copy, const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, const std::shared_ptr& ppmDtc, + const std::shared_ptr& ismDtc, ExerciseManagement::Interface::Dtc* exmDtc, + QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_session(session), + m_menuGroup(menuGroup), m_freqPlanningDialogIdentifier(freqPlanningDialogIdentifier), + m_ui(new Ui::EditFrequencyPlanningDialog), m_planning(planning), m_avmDtc(avmDtc), m_avmFtc(avmFtc), + m_ppmDtc(ppmDtc), m_ismDtc(ismDtc), m_exmDtc(exmDtc), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_frequencyDataModel( + new EditFrequencyPlanningFrequencyDataModel(planning, m_session->exerciseId(), avmDtc, ismDtc, ppmDtc, this)), + m_frequencyPlanningId(copy ? 0 : planning.id()), m_exerciseId(session->exerciseId()), + m_isEdit(EditFrequencyPlanningSetResourceDialog::DialogMode::Assign), m_activeFrequencyPlanningStatus(0) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_ui->leName->setText(QString::fromStdString(m_planning.name())); - m_ui->lbDate->setText(DTG::toStringMSec(m_planning.date())); + m_ui->leName->setText(QString::fromStdString(m_planning.name())); + m_ui->lbDate->setText(DTG::toStringMSec(m_planning.date())); - - m_uiRequirements->addRequirement( { m_ui->label, [this]() { return !m_ui->leName->text().isEmpty(); } }); + m_uiRequirements->addRequirement({m_ui->label, [this]() { return !m_ui->leName->text().isEmpty(); }}); - FPFDelegate *treeDelegate = new FPFDelegate(m_frequencyDataModel); - m_ui->dvFrequencyData->treeView()->setItemDelegateForColumn(EditFrequencyPlanningFrequencyDataModel::Columns::PROPERTIES, treeDelegate); + FPFDelegate* treeDelegate = new FPFDelegate(m_frequencyDataModel); + m_ui->dvFrequencyData->treeView()->setItemDelegateForColumn( + EditFrequencyPlanningFrequencyDataModel::Columns::PROPERTIES, treeDelegate); - m_ui->dvFrequencyData->setModel(m_frequencyDataModel); - m_ui->dvFrequencyData->expandAll(); + m_ui->dvFrequencyData->setModel(m_frequencyDataModel); + m_ui->dvFrequencyData->expandAll(); #ifndef LTS_DEBUG - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::RADIO_CIRCUIT_ID); - + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::RADIO_CIRCUIT_ID); + #endif - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::AKW_BUNDLE); - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::AKW_RADIO_CIRCUIT); - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::FSB_BUNDLE); - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::COMSEC); - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::DEVICE); - m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::PILOTTON); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::AKW_BUNDLE); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::AKW_RADIO_CIRCUIT); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::FSB_BUNDLE); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::COMSEC); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::DEVICE); + m_ui->dvFrequencyData->hideColumn(EditFrequencyPlanningFrequencyDataModel::Columns::PILOTTON); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &EditFrequencyPlanningDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &EditFrequencyPlanningDialog::onRemoveClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EditFrequencyPlanningDialog::onPrint); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &EditFrequencyPlanningDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &EditFrequencyPlanningDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EditFrequencyPlanningDialog::onPrint); - connect(m_ui->dvFrequencyData, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &EditFrequencyPlanningDialog::enableSelectedUnassignButton); + connect(m_ui->dvFrequencyData, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &EditFrequencyPlanningDialog::enableSelectedUnassignButton); - connect(m_ui->dvFrequencyData, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &EditFrequencyPlanningDialog::onAddClicked); + connect(m_ui->dvFrequencyData, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &EditFrequencyPlanningDialog::onAddClicked); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - if (m_frequencyPlanningId == 0) - slotChangesMade(); + if (m_frequencyPlanningId == 0) + slotChangesMade(); - - m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Assign")); - m_buttonBox->setText(LtsWidgets::DialogButton::Remove, tr("Unassign")); + m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Assign")); + m_buttonBox->setText(LtsWidgets::DialogButton::Remove, tr("Unassign")); - - m_buttonBox->connectLibraryButton(this, - &EditFrequencyPlanningDialog::onImportButtonClicked, - &EditFrequencyPlanningDialog::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &EditFrequencyPlanningDialog::onImportButtonClicked, + &EditFrequencyPlanningDialog::onExportButtonClicked); - if (!session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); + setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); } EditFrequencyPlanningDialog::~EditFrequencyPlanningDialog() { - emit aboutToCloseMe(m_frequencyPlanningId); + emit aboutToCloseMe(m_frequencyPlanningId); } void EditFrequencyPlanningDialog::retranslate() { - translate(m_ui.get(), m_avmDtc->frequencyPlanning(m_frequencyPlanningId), tr("Frequency Planning")); + translate(m_ui.get(), m_avmDtc->frequencyPlanning(m_frequencyPlanningId), tr("Frequency Planning")); } -void EditFrequencyPlanningDialog::onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject &reply) +void EditFrequencyPlanningDialog::onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject& reply) { - if (reply.error()) - ERROR_LOG(m_logger) << reply.str(); - m_requestHelper->requestReply(reply); + if (reply.error()) + ERROR_LOG(m_logger) << reply.str(); + m_requestHelper->requestReply(reply); } -void EditFrequencyPlanningDialog::onModifyFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) +void EditFrequencyPlanningDialog::onModifyFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) { - if (!replyObject.error()) - m_frequencyDataModel->setFrequencePlanningId(replyObject.id()); - m_requestHelper->requestReply(replyObject); + if (!replyObject.error()) + m_frequencyDataModel->setFrequencePlanningId(replyObject.id()); + m_requestHelper->requestReply(replyObject); } - bool EditFrequencyPlanningDialog::apply() { - if (!m_frequencyDataModel->checkResourceAssignments()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Multiple assignments with the same resource are not possible. Please correct the selected entries.")); - return false; - } - ModifyFrequencyPlanningRequest request = m_frequencyDataModel->modifyFrequencyPlanningRequest(); + if (!m_frequencyDataModel->checkResourceAssignments()) + { + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Multiple assignments with the same resource are not possible. Please correct the selected entries.")); + return false; + } + ModifyFrequencyPlanningRequest request = m_frequencyDataModel->modifyFrequencyPlanningRequest(); - request.date(m_session->partitionTime()); - m_ui->lbDate->setText(DTG::toStringMSec(request.date())); - m_planning.date() = request.date(); - request.id(m_frequencyPlanningId); - request.name(m_ui->leName->text().toStdString()); + request.date(m_session->partitionTime()); + m_ui->lbDate->setText(DTG::toStringMSec(request.date())); + m_planning.date() = request.date(); + request.id(m_frequencyPlanningId); + request.name(m_ui->leName->text().toStdString()); - return m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->modifyFrequencyPlanningRequest(request, this); - }); + return m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->modifyFrequencyPlanningRequest(request, this); }); } -void EditFrequencyPlanningDialog::onAddClicked() +void EditFrequencyPlanningDialog::onAddClicked() { - - QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); + int row = idx.row(); + if (row < 0) + return; - CnrConfig cnrConfigRow = m_frequencyDataModel->itemData(idx).cnrConfig; - int cnrConfigId = cnrConfigRow.id(); - if (cnrConfigId <= 0) - return; + CnrConfig cnrConfigRow = m_frequencyDataModel->itemData(idx).cnrConfig; + int cnrConfigId = cnrConfigRow.id(); + if (cnrConfigId <= 0) + return; - DEBUG_LOG(m_logger) << "---RessourceDialog aufrufen...." - << " cnrConfigId: " << cnrConfigId - << " radioCircuit: " << cnrConfigRow.radioCircuit() - << " FrequencySetId: " << m_frequencyDataModel->getFrequencySetId(); + DEBUG_LOG(m_logger) << "---RessourceDialog aufrufen...." + << " cnrConfigId: " << cnrConfigId << " radioCircuit: " << cnrConfigRow.radioCircuit() + << " FrequencySetId: " << m_frequencyDataModel->getFrequencySetId(); - FrequencyPlanningData fpd = m_frequencyDataModel->getfrequencyPlanningData(cnrConfigId); - if (!fpd.cnrConfigId()) - { - fpd.cnrConfigId(cnrConfigId); - } - - - EditFrequencyPlanningResourceDialog *frequencyPlanningResourceDialog - = new EditFrequencyPlanningResourceDialog(m_frequencyDataModel->getFrequencySetId(), - m_isEdit, - this ); + FrequencyPlanningData fpd = m_frequencyDataModel->getfrequencyPlanningData(cnrConfigId); + if (!fpd.cnrConfigId()) + { + fpd.cnrConfigId(cnrConfigId); + } - frequencyPlanningResourceDialog->init(m_session, fpd, m_frequencyDataModel->getAllocatedFrequencyPlanningSetIds()); - - connect(this, &QObject::destroyed, - frequencyPlanningResourceDialog, &QObject::deleteLater); + EditFrequencyPlanningResourceDialog* frequencyPlanningResourceDialog = + new EditFrequencyPlanningResourceDialog(m_frequencyDataModel->getFrequencySetId(), m_isEdit, this); - addDialog(frequencyPlanningResourceDialog, m_menuGroup, QLatin1String("avmFrequencyPlanning") + QString::number(cnrConfigId), LtsWidgets::LayoutArea::eDialogTab); + frequencyPlanningResourceDialog->init(m_session, fpd, m_frequencyDataModel->getAllocatedFrequencyPlanningSetIds()); - connect(frequencyPlanningResourceDialog, &EditFrequencyPlanningResourceDialog::signalAssignRadioCircuit, - this, &EditFrequencyPlanningDialog::onAssignRadioCircuit); + connect(this, &QObject::destroyed, frequencyPlanningResourceDialog, &QObject::deleteLater); + + addDialog(frequencyPlanningResourceDialog, m_menuGroup, + QLatin1String("avmFrequencyPlanning") + QString::number(cnrConfigId), LtsWidgets::LayoutArea::eDialogTab); + + connect(frequencyPlanningResourceDialog, &EditFrequencyPlanningResourceDialog::signalAssignRadioCircuit, this, + &EditFrequencyPlanningDialog::onAssignRadioCircuit); m_ui->dvFrequencyData->expandAll(); } -void EditFrequencyPlanningDialog::onRemoveClicked() +void EditFrequencyPlanningDialog::onRemoveClicked() { - QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); + int row = idx.row(); + if (row < 0) + return; - CnrConfig cnrConfigRow = m_frequencyDataModel->itemData(idx).cnrConfig; - int cnrConfigId = cnrConfigRow.id(); - if (cnrConfigId <= 0) - return; - unassignRadioCircuit(cnrConfigId); + CnrConfig cnrConfigRow = m_frequencyDataModel->itemData(idx).cnrConfig; + int cnrConfigId = cnrConfigRow.id(); + if (cnrConfigId <= 0) + return; + unassignRadioCircuit(cnrConfigId); } void EditFrequencyPlanningDialog::enableSelectedUnassignButton() { - QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + QModelIndex idx = m_ui->dvFrequencyData->currentIndex(); + int row = idx.row(); + if (row < 0) + return; - auto itemData = m_frequencyDataModel->itemData(idx); - CnrConfig cnrConfigRow = itemData.cnrConfig; - int cnrConfigId = cnrConfigRow.id(); - if (cnrConfigId <= 0) - return; + auto itemData = m_frequencyDataModel->itemData(idx); + CnrConfig cnrConfigRow = itemData.cnrConfig; + int cnrConfigId = cnrConfigRow.id(); + if (cnrConfigId <= 0) + return; - - FrequencyPlanningData fpd = m_frequencyDataModel->getfrequencyPlanningData(cnrConfigId); + FrequencyPlanningData fpd = m_frequencyDataModel->getfrequencyPlanningData(cnrConfigId); - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); - if( (!cnrConfigRow.exerciseId().is_set() - && m_planning.exerciseId().is_set()) - || - itemData.readOnly - ) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Show")); - m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Show; - if (circuits.size() == 0) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); - } - else if (circuits.size() > 0) - { - m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Edit; - m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Edit")); - } - else - { - m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Assign; - m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Assign")); - } + if ((!cnrConfigRow.exerciseId().is_set() && m_planning.exerciseId().is_set()) || itemData.readOnly) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Show")); + m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Show; + if (circuits.size() == 0) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + } + else if (circuits.size() > 0) + { + m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Edit; + m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Edit")); + } + else + { + m_isEdit = EditFrequencyPlanningSetResourceDialog::DialogMode::Assign; + m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Assign")); + } - DEBUG_LOG(m_logger) << "---enableAssignUnassignButtons()...." - << " cnrConfigId: " << cnrConfigId - << " radioCircuitId: " << cnrConfigRow.radioCircuit(); + DEBUG_LOG(m_logger) << "---enableAssignUnassignButtons()...." + << " cnrConfigId: " << cnrConfigId << " radioCircuitId: " << cnrConfigRow.radioCircuit(); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, !itemData.readOnly && m_isEdit == EditFrequencyPlanningSetResourceDialog::DialogMode::Edit); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, + !itemData.readOnly && + m_isEdit == EditFrequencyPlanningSetResourceDialog::DialogMode::Edit); - qDeleteAll(circuits); + qDeleteAll(circuits); } -void EditFrequencyPlanningDialog::onAssignRadioCircuit(const FrequencyPlanningData &fpd) +void EditFrequencyPlanningDialog::onAssignRadioCircuit(const FrequencyPlanningData& fpd) { DEBUG_LOG(m_logger) << "---onAssignRadioCircuit()...." - << "CnrConfigId: " << fpd.cnrConfigId(); + << "CnrConfigId: " << fpd.cnrConfigId(); - m_frequencyDataModel->setFrequencyPlanningData(fpd); - - if (!m_frequencyDataModel->checkResourceAssignments()) - { - - focusDialog(m_menuGroup, m_freqPlanningDialogIdentifier, LtsWidgets::LayoutArea::eDialogTab); - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Multiple assignments with the same resource are not possible. Please correct the selected entries.")); - return; - } - enableSelectedUnassignButton(); - slotChangesMade(); - m_ui->dvFrequencyData->repaint(); - m_ui->dvFrequencyData->expandAll(); + m_frequencyDataModel->setFrequencyPlanningData(fpd); + + if (!m_frequencyDataModel->checkResourceAssignments()) + { + + focusDialog(m_menuGroup, m_freqPlanningDialogIdentifier, LtsWidgets::LayoutArea::eDialogTab); + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Multiple assignments with the same resource are not possible. Please correct the selected entries.")); + return; + } + enableSelectedUnassignButton(); + slotChangesMade(); + m_ui->dvFrequencyData->repaint(); + m_ui->dvFrequencyData->expandAll(); } void EditFrequencyPlanningDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dvFrequencyData->treeView() ); + LtsPrinting::printView(m_session, this, m_ui->dvFrequencyData->treeView()); } int32_t EditFrequencyPlanningDialog::currentFrequencySetId() const { - QModelIndex currentFrequencySetDataIndex = m_ui->dvFrequencyData->currentIndex(); + QModelIndex currentFrequencySetDataIndex = m_ui->dvFrequencyData->currentIndex(); - if (!currentFrequencySetDataIndex.isValid()) - return -1; + if (!currentFrequencySetDataIndex.isValid()) + return -1; - return m_frequencyDataModel->data(currentFrequencySetDataIndex, Qt::UserRole).toInt(); + return m_frequencyDataModel->data(currentFrequencySetDataIndex, Qt::UserRole).toInt(); } - - - QVector EditFrequencyPlanningDialog::otherActiveExercises() const { - const auto allExercises_ = m_exmDtc->exercises(); + const auto allExercises_ = m_exmDtc->exercises(); - Q_ASSERT(::isActive(allExercises_[m_exerciseId].state())); + Q_ASSERT(::isActive(allExercises_[m_exerciseId].state())); + auto allExercises = allExercises_.values(); + auto newEnd = std::remove_if(allExercises.begin(), allExercises.end(), + [](const ExerciseManagement::Exercise& ex) { return ex.isDeleted(); }); + allExercises.erase(newEnd, allExercises.end()); - auto allExercises = allExercises_.values(); - auto newEnd = std::remove_if(allExercises.begin(), allExercises.end(), [] (const ExerciseManagement::Exercise &ex) { return ex.isDeleted(); }); - allExercises.erase(newEnd, allExercises.end()); + QVector toBeConsidered; + for (const auto& exercise : std::as_const(allExercises)) + { + if (exercise.id() == m_exerciseId) + continue; - QVector toBeConsidered; - for (const auto &exercise : std::as_const(allExercises)) - { - if (exercise.id() == m_exerciseId) - continue; - - if (::isActive(exercise.state())) - toBeConsidered.append(exercise.id()); - } - return toBeConsidered; + if (::isActive(exercise.state())) + toBeConsidered.append(exercise.id()); + } + return toBeConsidered; } - - QVector EditFrequencyPlanningDialog::otherActivePlans() const { - QVector result; - QVector exercises = otherActiveExercises(); + QVector result; + QVector exercises = otherActiveExercises(); - const auto activePlans = m_avmDtc->activeFrequencyPlannings(); - for (const auto &activePlan : activePlans) - { - if (exercises.contains(activePlan.exerciseId())) - result.append(activePlan.frequencyPlanningId()); - } - return result; + const auto activePlans = m_avmDtc->activeFrequencyPlannings(); + for (const auto& activePlan : activePlans) + { + if (exercises.contains(activePlan.exerciseId())) + result.append(activePlan.frequencyPlanningId()); + } + return result; } void EditFrequencyPlanningDialog::unassignRadioCircuit(int32_t cnrConfigId) { - m_frequencyDataModel->unassignRadioCircuit(cnrConfigId); - enableSelectedUnassignButton(); - slotChangesMade(); - m_ui->dvFrequencyData->expandAll(); + m_frequencyDataModel->unassignRadioCircuit(cnrConfigId); + enableSelectedUnassignButton(); + slotChangesMade(); + m_ui->dvFrequencyData->expandAll(); } void EditFrequencyPlanningDialog::onExportButtonClicked() { - QByteArray byteArray = m_frequencyDataModel->uiToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + QByteArray byteArray = m_frequencyDataModel->uiToJson(); + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void EditFrequencyPlanningDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << "--- onImportButtonClicked() "; + DEBUG_LOG(m_logger) << "--- onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning))) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + LoadFrequencyPlanningDialog loadingDialog(content, m_frequencyDataModel->toFrequencyPlanning(), m_avmDtc, + m_ismDtc); + loadingDialog.exec(); + + if (loadingDialog.isApplied()) + { + const QVector unassignments = loadingDialog.unassignments(); + + for (int idToUnassign : unassignments) + m_frequencyDataModel->unassignRadioCircuit(idToUnassign); + + const QVector planningData = loadingDialog.newPlanningData(); + + for (const FrequencyPlanningData& currentData : planningData) + m_frequencyDataModel->setFrequencyPlanningData(currentData); + + slotChangesMade(); + m_ui->dvFrequencyData->expandAll(); + } + } } - else - { - LoadFrequencyPlanningDialog loadingDialog(content, m_frequencyDataModel->toFrequencyPlanning(), m_avmDtc, m_ismDtc) ; - loadingDialog.exec(); - - if (loadingDialog.isApplied()) - { - const QVector unassignments = loadingDialog.unassignments(); - - for (int idToUnassign : unassignments) - m_frequencyDataModel->unassignRadioCircuit(idToUnassign); - - const QVector planningData = loadingDialog.newPlanningData(); - - for (const FrequencyPlanningData ¤tData : planningData) - m_frequencyDataModel->setFrequencyPlanningData(currentData); - - slotChangesMade(); - m_ui->dvFrequencyData->expandAll(); - } - } - } } - - -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_frequency_data_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_frequency_data_model.cpp old mode 100755 new mode 100644 index f98277614..a7a9cdf16 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_frequency_data_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_frequency_data_model.cpp @@ -1,941 +1,878 @@ - #include "avm_edit_frequency_planning_frequency_data_model.h" -#include -#include -#include -#include #include +#include #include -#include #include -#include - -#include -#include -#include +#include +#include +#include #include - +#include +#include +#include +#include +#include namespace AudioVideoManagement { -void EditFrequencyPlanningFrequencyDataModel::onFrequencyPlanningChanged(const FrequencyPlanning &planning, DataModification dm) +void EditFrequencyPlanningFrequencyDataModel::onFrequencyPlanningChanged(const FrequencyPlanning& planning, + DataModification dm) { - - if (planning.id() != m_initPlan.id() && planning.exerciseId().is_set()) - return; - - if (dm == DataModification::eRemoved) - { - beginResetModel(); - + if (planning.id() != m_initPlan.id() && planning.exerciseId().is_set()) + return; + + if (dm == DataModification::eRemoved) + { + beginResetModel(); + + for (NGLTreeItem* item : m_rootItem->constChildren()) + { + if (!item->data().canConvert()) + continue; + + ItemData data = item->data().value(); + delete data.radioCircuit; + data.radioCircuit = nullptr; + item->setData(QVariant::fromValue(data)); + } + endResetModel(); + return; + } + QHash fpdMap; + for (const auto& elem : planning.data()) + fpdMap.insert(elem.cnrConfigId(), elem); for (NGLTreeItem* item : m_rootItem->constChildren()) { - if (!item->data().canConvert()) - continue; + if (!item->data().canConvert()) + continue; - ItemData data = item->data().value(); - delete data.radioCircuit; - data.radioCircuit = nullptr; - item->setData(QVariant::fromValue(data)); - } - endResetModel(); - return; - } - QHash fpdMap; - for(const auto &elem : planning.data()) - fpdMap.insert(elem.cnrConfigId(), elem); - for (NGLTreeItem* item : m_rootItem->constChildren()) - { - if (!item->data().canConvert()) - continue; + ItemData itemData = item->data().value(); + if (itemData.cnrConfig.exerciseId().is_set() && itemData.cnrConfig.exerciseId().get() != m_exerciseId) + continue; - ItemData itemData = item->data().value(); - if (itemData.cnrConfig.exerciseId().is_set() && itemData.cnrConfig.exerciseId().get() != m_exerciseId) - continue; + if (!itemData.cnrConfig.exerciseId().is_set() && 0 != m_exerciseId) + continue; - if (!itemData.cnrConfig.exerciseId().is_set() && 0 != m_exerciseId) - continue; - - if (fpdMap.contains(itemData.cnrConfig.id())) - { - - const FrequencyPlanningData &fpd = fpdMap[itemData.cnrConfig.id()]; - - if (item->childCount()) - { - beginRemoveRows(indexFromItem(item),0,item->childCount()-1); - item->removeAllChildren(); - endRemoveRows(); - } - - delete itemData.radioCircuit; - itemData.radioCircuit = nullptr; - - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - if (circuits.size() > 1) - { - for (RadioCircuit *circuit : std::as_const(circuits)) + if (fpdMap.contains(itemData.cnrConfig.id())) { - itemData.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(itemData)); - insertRow(item->childCount(), indexFromItem(item), childItem); - } - } - else if (circuits.size() == 1) - { - itemData.radioCircuit = circuits[0]; - item->setData(QVariant::fromValue(itemData)); - } - m_frequencyPlanningData[fpd.cnrConfigId()] = fpd; - fpdMap.remove(itemData.cnrConfig.id()); - } - else - { - - if (item->childCount()) - { - beginRemoveRows(indexFromItem(item),0,item->childCount()-1); - item->removeAllChildren(); - endRemoveRows(); - } - delete itemData.radioCircuit; - itemData.radioCircuit = nullptr; - item->setData(QVariant::fromValue(itemData)); - m_frequencyPlanningData.remove(itemData.cnrConfig.id()); - } - } - - for (const FrequencyPlanningData &item : std::as_const(fpdMap)) - { - setFrequencyPlanningData(item); - } + const FrequencyPlanningData& fpd = fpdMap[itemData.cnrConfig.id()]; + + if (item->childCount()) + { + beginRemoveRows(indexFromItem(item), 0, item->childCount() - 1); + item->removeAllChildren(); + endRemoveRows(); + } + + delete itemData.radioCircuit; + itemData.radioCircuit = nullptr; + + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + if (circuits.size() > 1) + { + for (RadioCircuit* circuit : std::as_const(circuits)) + { + itemData.radioCircuit = circuit; + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(itemData)); + insertRow(item->childCount(), indexFromItem(item), childItem); + } + } + else if (circuits.size() == 1) + { + itemData.radioCircuit = circuits[0]; + item->setData(QVariant::fromValue(itemData)); + } + m_frequencyPlanningData[fpd.cnrConfigId()] = fpd; + fpdMap.remove(itemData.cnrConfig.id()); + } + else + { + + if (item->childCount()) + { + beginRemoveRows(indexFromItem(item), 0, item->childCount() - 1); + item->removeAllChildren(); + endRemoveRows(); + } + delete itemData.radioCircuit; + itemData.radioCircuit = nullptr; + item->setData(QVariant::fromValue(itemData)); + m_frequencyPlanningData.remove(itemData.cnrConfig.id()); + } + } + + for (const FrequencyPlanningData& item : std::as_const(fpdMap)) + { + setFrequencyPlanningData(item); + } } -EditFrequencyPlanningFrequencyDataModel::EditFrequencyPlanningFrequencyDataModel(const FrequencyPlanning &initPlanning, - int exerciseId, - const std::shared_ptr &avmDtc, - const std::shared_ptr &ismDtc, - const std::shared_ptr &ppmDtc, - QObject *parent) +EditFrequencyPlanningFrequencyDataModel::EditFrequencyPlanningFrequencyDataModel( + const FrequencyPlanning& initPlanning, int exerciseId, const std::shared_ptr& avmDtc, + const std::shared_ptr& ismDtc, + const std::shared_ptr& ppmDtc, QObject* parent) : NGLTreeModel(parent, new ConfigTreeItem(QVariant()), + { + tr("Channel Number"), + tr("RC id"), + tr("Radio Circuit"), + tr("Party"), + tr("Unit"), + tr("Radio Station"), + tr("Frequency"), + tr("Function"), + tr("Device"), + tr("AKW Bundle"), + tr("FSB Bundle"), + tr("AKW Radio Circuit"), + tr("COMSEC"), + tr("Pilotton"), + tr("Operating Mode"), + tr("Properties"), + tr("Channel Spacing"), + tr("Squelch"), + tr("Global"), + }), + m_exerciseId(exerciseId), m_avmDtc(avmDtc), m_ismDtc(ismDtc), m_ppmDtc(ppmDtc), m_initPlan(initPlanning) { - tr("Channel Number"), - tr("RC id"), - tr("Radio Circuit"), - tr("Party"), - tr("Unit"), - tr("Radio Station"), - tr("Frequency"), - tr("Function"), - tr("Device"), - tr("AKW Bundle"), - tr("FSB Bundle"), - tr("AKW Radio Circuit"), - tr("COMSEC"), - tr("Pilotton"), - tr("Operating Mode"), - tr("Properties"), - tr("Channel Spacing"), - tr("Squelch"), - tr("Global"), -}) - , m_exerciseId(exerciseId) - , m_avmDtc(avmDtc) - , m_ismDtc(ismDtc) - , m_ppmDtc(ppmDtc) - , m_initPlan(initPlanning) -{ - Q_ASSERT(avmDtc); - Q_ASSERT(ppmDtc); - DEBUG_LOG(m_logger) << "---EditFrequencyPlanningDataMod m_frequencyPlanningData[c.id()];el() "; + Q_ASSERT(avmDtc); + Q_ASSERT(ppmDtc); + DEBUG_LOG(m_logger) << "---EditFrequencyPlanningDataMod m_frequencyPlanningData[c.id()];el() "; - int frequencySetId = initPlanning.frequencySetId(); - std::vector fsdVec = m_avmDtc->frequencySet(frequencySetId).data(); - for(FrequencySetDataWithId fsd : fsdVec) - m_freqSetData.insert(fsd.id(), fsd); + int frequencySetId = initPlanning.frequencySetId(); + std::vector fsdVec = m_avmDtc->frequencySet(frequencySetId).data(); + for (FrequencySetDataWithId fsd : fsdVec) + m_freqSetData.insert(fsd.id(), fsd); - m_units = m_ppmDtc->units(); + m_units = m_ppmDtc->units(); - QVector dataVec; - const auto &cnrConfigs = m_avmDtc->cnrConfigs(); - for (const CnrConfig &cnrConfig : cnrConfigs) - { - - if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId().get() != m_exerciseId) - continue; - dataVec.append(cnrConfig); - } - setCnrConfigs(dataVec); - m_avmDtc->activeFrequencyPlannings([this](const ActiveFrequencyPlanning &afp) - { - if (afp.exerciseId() <= 0) + QVector dataVec; + const auto& cnrConfigs = m_avmDtc->cnrConfigs(); + for (const CnrConfig& cnrConfig : cnrConfigs) { - onFrequencyPlanningChanged(m_avmDtc->frequencyPlanning(afp.frequencyPlanningId()), DataModification::eAdded); + + if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId().get() != m_exerciseId) + continue; + dataVec.append(cnrConfig); } - }); - onFrequencyPlanningChanged(initPlanning, DataModification::eAdded); - - connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, &EditFrequencyPlanningFrequencyDataModel::onCnrConfigChanged); - connect(m_avmDtc.get(), &Interface::Dtc::frequencyPlanningChanged, this, &EditFrequencyPlanningFrequencyDataModel::onFrequencyPlanningChanged); - -} - -void EditFrequencyPlanningFrequencyDataModel::setCnrConfigs(const QVector &dataVec) -{ - m_cnrConfigs.clear(); - for(const CnrConfig &c : dataVec) - { - m_cnrConfigs.insert(c.id(), c); - ItemData id(c); - if (m_frequencyPlanningData.contains(c.id())) - { - FrequencyPlanningData fpd = m_frequencyPlanningData[c.id()]; - id.readOnly = isReadOnly(fpd.properties()); - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - if (circuits.size() > 1) - { - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - for (RadioCircuit *circuit : std::as_const(circuits)) + setCnrConfigs(dataVec); + m_avmDtc->activeFrequencyPlannings([this](const ActiveFrequencyPlanning& afp) { + if (afp.exerciseId() <= 0) { - id.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(id)); - insertRow(configItem->childCount(), indexFromItem(configItem), childItem); + onFrequencyPlanningChanged(m_avmDtc->frequencyPlanning(afp.frequencyPlanningId()), + DataModification::eAdded); } - } - else if (circuits.size() == 1) - { - id.radioCircuit = circuits[0]; - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - } + }); + onFrequencyPlanningChanged(initPlanning, DataModification::eAdded); - } - else - { - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - } - } + connect(m_avmDtc.get(), &Interface::Dtc::cnrConfigChanged, this, + &EditFrequencyPlanningFrequencyDataModel::onCnrConfigChanged); + connect(m_avmDtc.get(), &Interface::Dtc::frequencyPlanningChanged, this, + &EditFrequencyPlanningFrequencyDataModel::onFrequencyPlanningChanged); } -EditFrequencyPlanningFrequencyDataModel::ItemData EditFrequencyPlanningFrequencyDataModel::itemData(const QModelIndex &index) +void EditFrequencyPlanningFrequencyDataModel::setCnrConfigs(const QVector& dataVec) { - NGLTreeItem *item = privateData(index); - if (!item->data().canConvert()) - return {}; - - return item->data().value(); + m_cnrConfigs.clear(); + for (const CnrConfig& c : dataVec) + { + m_cnrConfigs.insert(c.id(), c); + ItemData id(c); + if (m_frequencyPlanningData.contains(c.id())) + { + FrequencyPlanningData fpd = m_frequencyPlanningData[c.id()]; + id.readOnly = isReadOnly(fpd.properties()); + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + if (circuits.size() > 1) + { + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + for (RadioCircuit* circuit : std::as_const(circuits)) + { + id.radioCircuit = circuit; + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(id)); + insertRow(configItem->childCount(), indexFromItem(configItem), childItem); + } + } + else if (circuits.size() == 1) + { + id.radioCircuit = circuits[0]; + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + } + } + else + { + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + } + } } -QVariant EditFrequencyPlanningFrequencyDataModel::data(const QModelIndex &index, int role) const +EditFrequencyPlanningFrequencyDataModel::ItemData +EditFrequencyPlanningFrequencyDataModel::itemData(const QModelIndex& index) { - if ((role != Qt::DisplayRole && role != Qt::ToolTipRole && role != Qt::UserRole && role != Qt::TextColorRole && role != Qt::BackgroundRole) || !index.isValid()) - return NGLTreeModel::data(index, role); - ConfigTreeItem *item = static_cast(privateData(index)); - - if (!item->data().canConvert()) - return NGLTreeModel::data(index, role); - - ItemData id = item->data().value(); - - const CnrConfig &setData = id.cnrConfig; - RadioCircuit *rc = id.radioCircuit; - - if (role == Qt::ToolTipRole) - { - if (index.column() != PROPERTIES) - return {}; - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (rcVhf && !isAkwMode(rcVhf->operatingMode)) - return tr("Pilot Tone: %1") - .arg(rcVhf->pilotTone ? tr("On") : tr("Off")); - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - if (rcUhf) - return tr("Clipper: %1, AGC: %2, Modulation Type: %3") - .arg(rcUhf->clipper ? tr("On") : tr("Off"), - rcUhf->agc ? tr("On") : tr("Off"), - toString(rcUhf->modulationType)); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcHf) - return tr("Channel Spacing: %1, Squelch: %2") - .arg(toString(rcHf->channelSpacing), - rcHf->squelch > 0 ? QString::number(rcHf->squelch) : tr("Off")); - } - - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - - case RADIO_CIRCUIT_ID: - return setData.id(); - case FUNCTION: - { - if (!rc) - return QStringLiteral("-"); - return QString::fromStdString(m_freqSetData[rc->frequencySetDataId()].function()); - } - case DEVICE: - { - - if (!rc) - return QStringLiteral("-"); - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - return toString(m_freqSetData[rc->frequencySetDataId()].frequencyBand().underlying()); - } - case FREQUENCY: - { - QLocale locale(QLocale::German); - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() > 0) - { - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (rcVhf && isAkwMode(rcVhf->operatingMode)) - return QStringLiteral("-"); - return tr("%1 MHz").arg(locale.toString(m_freqSetData[rc->frequencySetDataId()].frequency() / 1000., 'f', 3)); - } - else - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - - if (rcUhf) - return tr("%1 MHz").arg(locale.toString(rcUhf->frequency / 1000000., 'f', 3)); - if (rcHf) - return tr("%1 MHz").arg(locale.toString(rcHf->frequency / 1000000., 'f', 3)); - - return QStringLiteral("-"); - } - } - case AKW_BUNDLE: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].akwBundle().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].akwBundle().get(); - } - case FSB_BUNDLE: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].fsbBundle().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].fsbBundle().get(); - } - case AKW_RADIO_CIRCUIT: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().get(); - } - case COMSEC: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].comsec().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].comsec().get(); - } - - case RADIO_CIRCUIT: - { - if (!rc) - return QString::fromStdString(setData.radioCircuit()); - - return id.name(); - } - case PARTY: - { - ParticipantManagement::Party party = m_ppmDtc->party(setData.partyId()); - - return ParticipantManagement::trPartyName(party.name()); - } - case UNIT: - { - if (!setData.unitId().is_set()) + NGLTreeItem* item = privateData(index); + if (!item->data().canConvert()) return {}; - const int unitId = setData.unitId().get(); - if (!m_units.contains(unitId)) - return QStringLiteral("-"); - const auto unit = m_units[unitId]; - INFO_LOG(m_logger) << " config.unitId()=" << unitId - << " Str=" << unit.name(); - - QString unitStr; - if (unit.designator().size() > 0) - unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); - unitStr.append(QString::fromStdString(unit.tacticalIdentifier())); - INFO_LOG(m_logger) << "unitStr = " << unitStr; - - return unitStr; - } - case RADIO_STATION: - { - if (!rc) - return QStringLiteral("-"); - - if (rc->radioStationId == 0) - return tr("Automatic"); - else - return QString::fromStdString(m_ismDtc->mainStructureElement(rc->radioStationId).name()); - } - case PILOTTON: - { - if (!rc) - return QStringLiteral("-"); - - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - - return rcVhf->pilotTone ? tr("On") : tr("Off"); - } - case OPERATING_MODE: - { - if (!rc) - return QStringLiteral("-"); - - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - - return toString(rcVhf->operatingMode); - } - case CHANNEL: - { - CnrChannel channel = m_avmDtc->cnrChannel(setData.cnrChannelId()); - return QString::fromStdString(channel.name()); - } - case GLOBAL: - { - return setData.exerciseId().is_set() ? tr("No") : tr("Yes"); - } - case PROPERTIES: - { - if (!rc) - return QStringLiteral("-"); - else - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - QStringList sl; - if (rcUhf) - { - sl << createIcon(ICON_CLIPPER, rcUhf->clipper ); - sl << createIcon(ICON_AGC, rcUhf->agc ); - sl << createIcon(ICON_MODULATION_TYPE, 0, rcUhf->modulationType); - return sl.join(QStringLiteral(" ")); - } - if (rcVhf && !isAkwMode(rcVhf->operatingMode)) - { - sl << createIcon(ICON_PILOTTON, rcVhf->pilotTone > 0); - return sl.join(QStringLiteral(" ")); - } - if (rcHf) - { - return sl.join(QStringLiteral(" ")); - } - return QStringLiteral("-"); - } - } - case CHANNEL_SPACING: - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcUhf) - return toString(rcUhf->channelSpacing); - if (rcHf) - return toString(rcHf->channelSpacing); - return {}; - } - case SQUELCH: - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcUhf) - return rcUhf->squelchDB > 0 ? tr("%1 dB").arg(rcUhf->squelchDB) : QVariant(); - if (rcHf) - return rcHf->squelch > 0 ? QString::number(rcHf->squelch) : QVariant(); - return {}; - } - default: - break; - } - } - - if (role == Qt::UserRole) - return setData.id(); - - if (role == Qt::TextColorRole) - { - - for (int id : m_multipleAssignedCnrIds) - { - if (id == setData.id()) - return QColor(Qt::red); - } - } - if (role == Qt::BackgroundRole) - { - if (setData.exerciseId().is_set() && setData.exerciseId().get() == m_exerciseId) - return NGLTreeModel::data(index, role); - if (!setData.exerciseId().is_set() && m_exerciseId <= 0) - return NGLTreeModel::data(index, role); - return QColor(Qt::gray); - } - - return NGLTreeModel::data(index, role); + return item->data().value(); } -QString EditFrequencyPlanningFrequencyDataModel::createIcon(PropertyData propertyDataType, bool on, ModulationType type) const +QVariant EditFrequencyPlanningFrequencyDataModel::data(const QModelIndex& index, int role) const { - QString imgHeader = QStringLiteral(""); + if ((role != Qt::DisplayRole && role != Qt::ToolTipRole && role != Qt::UserRole && role != Qt::TextColorRole && + role != Qt::BackgroundRole) || + !index.isValid()) + return NGLTreeModel::data(index, role); + ConfigTreeItem* item = static_cast(privateData(index)); - switch(propertyDataType) - { - case ICON_PILOTTON: - return imgHeader - .arg(on ? - QStringLiteral(":/style/pilotton-on.svg") - : QStringLiteral(":/style/pilotton-off.svg"), - on ? - tr("Pilot Tone: On") - : tr("Pilot Tone: Off")); - case ICON_MODULATION_TYPE: - return imgHeader - .arg(type == ModulationType::AM ? - QStringLiteral(":/style/AM.svg") - : QStringLiteral(":/style/FM.svg"), - on ? - tr("Modulation Type: AM") - : tr("Modulation Type: FM")); - case ICON_SQUELCH: - return imgHeader - .arg(on ? - QStringLiteral(":/style/squelch-on.svg") - : QStringLiteral(":/style/squelch-off.svg"), - on ? - tr("Squelch: On") - : tr("Squelch: Off")); - case ICON_CLIPPER: - return imgHeader - .arg(on ? - QStringLiteral(":/style/clipper-on.svg") - : QStringLiteral(":/style/clipper-off.svg"), - on ? - tr("Clipper: On") - : tr("Clipper: Off")); - case ICON_AGC: - return imgHeader - .arg(on ? - QStringLiteral(":/style/agc-on.svg") - : QStringLiteral(":/style/agc-off.svg"), - on ? - tr("Automatic Gain Control (AGC): On") - : tr("Automatic Gain Control (AGC): Off")); - case ICON_CHANNEL_SPACING: - return imgHeader - .arg(QStringLiteral(":/style/channel-spacing-on.svg"), - tr("Channel Spacing")); - case ICON_SPACER: - return imgHeader - .arg(QStringLiteral(":/style/line_style_solid_v.svg"), - tr("Channel Spacing")); - default: - return QStringLiteral("-"); - } + if (!item->data().canConvert()) + return NGLTreeModel::data(index, role); + + ItemData id = item->data().value(); + + const CnrConfig& setData = id.cnrConfig; + RadioCircuit* rc = id.radioCircuit; + + if (role == Qt::ToolTipRole) + { + if (index.column() != PROPERTIES) + return {}; + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (rcVhf && !isAkwMode(rcVhf->operatingMode)) + return tr("Pilot Tone: %1").arg(rcVhf->pilotTone ? tr("On") : tr("Off")); + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + if (rcUhf) + return tr("Clipper: %1, AGC: %2, Modulation Type: %3") + .arg(rcUhf->clipper ? tr("On") : tr("Off"), rcUhf->agc ? tr("On") : tr("Off"), + toString(rcUhf->modulationType)); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcHf) + return tr("Channel Spacing: %1, Squelch: %2") + .arg(toString(rcHf->channelSpacing), rcHf->squelch > 0 ? QString::number(rcHf->squelch) : tr("Off")); + } + + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + + case RADIO_CIRCUIT_ID: + return setData.id(); + case FUNCTION: { + if (!rc) + return QStringLiteral("-"); + return QString::fromStdString(m_freqSetData[rc->frequencySetDataId()].function()); + } + case DEVICE: { + + if (!rc) + return QStringLiteral("-"); + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + return toString(m_freqSetData[rc->frequencySetDataId()].frequencyBand().underlying()); + } + case FREQUENCY: { + QLocale locale(QLocale::German); + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() > 0) + { + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (rcVhf && isAkwMode(rcVhf->operatingMode)) + return QStringLiteral("-"); + return tr("%1 MHz").arg( + locale.toString(m_freqSetData[rc->frequencySetDataId()].frequency() / 1000., 'f', 3)); + } + else + { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + + if (rcUhf) + return tr("%1 MHz").arg(locale.toString(rcUhf->frequency / 1000000., 'f', 3)); + if (rcHf) + return tr("%1 MHz").arg(locale.toString(rcHf->frequency / 1000000., 'f', 3)); + + return QStringLiteral("-"); + } + } + case AKW_BUNDLE: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].akwBundle().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].akwBundle().get(); + } + case FSB_BUNDLE: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].fsbBundle().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].fsbBundle().get(); + } + case AKW_RADIO_CIRCUIT: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().get(); + } + case COMSEC: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].comsec().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].comsec().get(); + } + + case RADIO_CIRCUIT: { + if (!rc) + return QString::fromStdString(setData.radioCircuit()); + + return id.name(); + } + case PARTY: { + ParticipantManagement::Party party = m_ppmDtc->party(setData.partyId()); + + return ParticipantManagement::trPartyName(party.name()); + } + case UNIT: { + if (!setData.unitId().is_set()) + return {}; + const int unitId = setData.unitId().get(); + if (!m_units.contains(unitId)) + return QStringLiteral("-"); + const auto unit = m_units[unitId]; + + INFO_LOG(m_logger) << " config.unitId()=" << unitId << " Str=" << unit.name(); + + QString unitStr; + if (unit.designator().size() > 0) + unitStr = QString::fromStdString(unit.designator()) + QLatin1Char('/'); + unitStr.append(QString::fromStdString(unit.tacticalIdentifier())); + INFO_LOG(m_logger) << "unitStr = " << unitStr; + + return unitStr; + } + case RADIO_STATION: { + if (!rc) + return QStringLiteral("-"); + + if (rc->radioStationId == 0) + return tr("Automatic"); + else + return QString::fromStdString(m_ismDtc->mainStructureElement(rc->radioStationId).name()); + } + case PILOTTON: { + if (!rc) + return QStringLiteral("-"); + + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + + return rcVhf->pilotTone ? tr("On") : tr("Off"); + } + case OPERATING_MODE: { + if (!rc) + return QStringLiteral("-"); + + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + + return toString(rcVhf->operatingMode); + } + case CHANNEL: { + CnrChannel channel = m_avmDtc->cnrChannel(setData.cnrChannelId()); + return QString::fromStdString(channel.name()); + } + case GLOBAL: { + return setData.exerciseId().is_set() ? tr("No") : tr("Yes"); + } + case PROPERTIES: { + if (!rc) + return QStringLiteral("-"); + else + { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + QStringList sl; + if (rcUhf) + { + sl << createIcon(ICON_CLIPPER, rcUhf->clipper); + sl << createIcon(ICON_AGC, rcUhf->agc); + sl << createIcon(ICON_MODULATION_TYPE, 0, rcUhf->modulationType); + return sl.join(QStringLiteral(" ")); + } + if (rcVhf && !isAkwMode(rcVhf->operatingMode)) + { + sl << createIcon(ICON_PILOTTON, rcVhf->pilotTone > 0); + return sl.join(QStringLiteral(" ")); + } + if (rcHf) + { + return sl.join(QStringLiteral(" ")); + } + return QStringLiteral("-"); + } + } + case CHANNEL_SPACING: { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcUhf) + return toString(rcUhf->channelSpacing); + if (rcHf) + return toString(rcHf->channelSpacing); + return {}; + } + case SQUELCH: { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcUhf) + return rcUhf->squelchDB > 0 ? tr("%1 dB").arg(rcUhf->squelchDB) : QVariant(); + if (rcHf) + return rcHf->squelch > 0 ? QString::number(rcHf->squelch) : QVariant(); + return {}; + } + default: + break; + } + } + + if (role == Qt::UserRole) + return setData.id(); + + if (role == Qt::TextColorRole) + { + + for (int id : m_multipleAssignedCnrIds) + { + if (id == setData.id()) + return QColor(Qt::red); + } + } + if (role == Qt::BackgroundRole) + { + if (setData.exerciseId().is_set() && setData.exerciseId().get() == m_exerciseId) + return NGLTreeModel::data(index, role); + if (!setData.exerciseId().is_set() && m_exerciseId <= 0) + return NGLTreeModel::data(index, role); + return QColor(Qt::gray); + } + + return NGLTreeModel::data(index, role); +} + +QString EditFrequencyPlanningFrequencyDataModel::createIcon(PropertyData propertyDataType, bool on, + ModulationType type) const +{ + QString imgHeader = + QStringLiteral(""); + + switch (propertyDataType) + { + case ICON_PILOTTON: + return imgHeader.arg(on ? QStringLiteral(":/style/pilotton-on.svg") + : QStringLiteral(":/style/pilotton-off.svg"), + on ? tr("Pilot Tone: On") : tr("Pilot Tone: Off")); + case ICON_MODULATION_TYPE: + return imgHeader.arg(type == ModulationType::AM ? QStringLiteral(":/style/AM.svg") + : QStringLiteral(":/style/FM.svg"), + on ? tr("Modulation Type: AM") : tr("Modulation Type: FM")); + case ICON_SQUELCH: + return imgHeader.arg(on ? QStringLiteral(":/style/squelch-on.svg") + : QStringLiteral(":/style/squelch-off.svg"), + on ? tr("Squelch: On") : tr("Squelch: Off")); + case ICON_CLIPPER: + return imgHeader.arg(on ? QStringLiteral(":/style/clipper-on.svg") + : QStringLiteral(":/style/clipper-off.svg"), + on ? tr("Clipper: On") : tr("Clipper: Off")); + case ICON_AGC: + return imgHeader.arg(on ? QStringLiteral(":/style/agc-on.svg") : QStringLiteral(":/style/agc-off.svg"), + on ? tr("Automatic Gain Control (AGC): On") : tr("Automatic Gain Control (AGC): Off")); + case ICON_CHANNEL_SPACING: + return imgHeader.arg(QStringLiteral(":/style/channel-spacing-on.svg"), tr("Channel Spacing")); + case ICON_SPACER: + return imgHeader.arg(QStringLiteral(":/style/line_style_solid_v.svg"), tr("Channel Spacing")); + default: + return QStringLiteral("-"); + } } bool EditFrequencyPlanningFrequencyDataModel::unassignRadioCircuit(int32_t cnrConfigId) { - if (cnrConfigId < 0) - return false; + if (cnrConfigId < 0) + return false; - - m_multipleAssignedCnrIds.erase( + m_multipleAssignedCnrIds.erase( std::remove(m_multipleAssignedCnrIds.begin(), m_multipleAssignedCnrIds.end(), cnrConfigId), m_multipleAssignedCnrIds.end()); - beginResetModel(); - m_frequencyPlanningData.remove(cnrConfigId); - ConfigTreeItem* item = searchCnrConfig(m_rootItem, cnrConfigId); - if(!item) - return false; - ItemData id = item->data().value(); - id.clearRadioCircuit(); - item->setData(QVariant::fromValue(id)); - item->removeAllChildren(); - endResetModel(); - return true; + beginResetModel(); + m_frequencyPlanningData.remove(cnrConfigId); + ConfigTreeItem* item = searchCnrConfig(m_rootItem, cnrConfigId); + if (!item) + return false; + ItemData id = item->data().value(); + id.clearRadioCircuit(); + item->setData(QVariant::fromValue(id)); + item->removeAllChildren(); + endResetModel(); + return true; } - void EditFrequencyPlanningFrequencyDataModel::setFrequencePlanningId(int id) { - if (m_initPlan.id() == id) - return; - if (m_initPlan.id() <= 0) - { - m_initPlan.id(id); - return; - } - WARNING_LOG(m_logger) << "Trying to set a new frequency planning id but there is alreay an id set (" - << m_initPlan.id() << " - " << id << ")"; + if (m_initPlan.id() == id) + return; + if (m_initPlan.id() <= 0) + { + m_initPlan.id(id); + return; + } + WARNING_LOG(m_logger) << "Trying to set a new frequency planning id but there is alreay an id set (" + << m_initPlan.id() << " - " << id << ")"; } ModifyFrequencyPlanningRequest EditFrequencyPlanningFrequencyDataModel::modifyFrequencyPlanningRequest() const { - std::vector planningDataVec; - planningDataVec.reserve(m_frequencyPlanningData.size()); + std::vector planningDataVec; + planningDataVec.reserve(m_frequencyPlanningData.size()); - for (const auto &keyValue : overKeyValue(m_frequencyPlanningData)) - { - Q_ASSERT(keyValue.first > 0); - CnrConfig config = m_avmDtc->cnrConfig(keyValue.second.cnrConfigId()); - if(( config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) || - (!config.exerciseId().is_set() && m_exerciseId == 0)) + for (const auto& keyValue : overKeyValue(m_frequencyPlanningData)) { - FrequencyPlanningData fpd = keyValue.second; - fpd.frequencyPlanningId() = m_initPlan.id(); - planningDataVec.push_back(fpd); + Q_ASSERT(keyValue.first > 0); + CnrConfig config = m_avmDtc->cnrConfig(keyValue.second.cnrConfigId()); + if ((config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) || + (!config.exerciseId().is_set() && m_exerciseId == 0)) + { + FrequencyPlanningData fpd = keyValue.second; + fpd.frequencyPlanningId() = m_initPlan.id(); + planningDataVec.push_back(fpd); + } } - } - return { m_initPlan.id(), - m_initPlan.exerciseId().is_set() ? m_initPlan.exerciseId().get() : 0, - m_initPlan.name(), - m_initPlan.date(), - m_initPlan.frequencySetId(), - planningDataVec}; + return {m_initPlan.id(), + m_initPlan.exerciseId().is_set() ? m_initPlan.exerciseId().get() : 0, + m_initPlan.name(), + m_initPlan.date(), + m_initPlan.frequencySetId(), + planningDataVec}; } FrequencyPlanning EditFrequencyPlanningFrequencyDataModel::toFrequencyPlanning() const { - std::vector planningDataVec; - planningDataVec.reserve(m_frequencyPlanningData.size()); + std::vector planningDataVec; + planningDataVec.reserve(m_frequencyPlanningData.size()); - for (const auto &keyValue : overKeyValue(m_frequencyPlanningData)) - { - Q_ASSERT(keyValue.first > 0); - CnrConfig config = m_avmDtc->cnrConfig(keyValue.second.cnrConfigId()); - if(( config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) || - (!config.exerciseId().is_set() && m_exerciseId == 0)) + for (const auto& keyValue : overKeyValue(m_frequencyPlanningData)) { - FrequencyPlanningData fpd = keyValue.second; - fpd.frequencyPlanningId() = m_initPlan.id(); - planningDataVec.push_back(fpd); + Q_ASSERT(keyValue.first > 0); + CnrConfig config = m_avmDtc->cnrConfig(keyValue.second.cnrConfigId()); + if ((config.exerciseId().is_set() && config.exerciseId().get() == m_exerciseId) || + (!config.exerciseId().is_set() && m_exerciseId == 0)) + { + FrequencyPlanningData fpd = keyValue.second; + fpd.frequencyPlanningId() = m_initPlan.id(); + planningDataVec.push_back(fpd); + } } - } - FrequencyPlanning frequencyPlanning = m_initPlan; - frequencyPlanning.data(planningDataVec); + FrequencyPlanning frequencyPlanning = m_initPlan; + frequencyPlanning.data(planningDataVec); - return frequencyPlanning; + return frequencyPlanning; } -int EditFrequencyPlanningFrequencyDataModel::findCnrConfigByName(const QString &name) const +int EditFrequencyPlanningFrequencyDataModel::findCnrConfigByName(const QString& name) const { - int id = -1; - std::function findByNameInExercise = [this, &name, &id] (const CnrConfig &cnrConfig) - { - if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId() != m_initPlan.exerciseId()) - return false; - if (QString::fromStdString(cnrConfig.radioCircuit()) != name) - return false; + int id = -1; + std::function findByNameInExercise = [this, &name, &id](const CnrConfig& cnrConfig) { + if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId() != m_initPlan.exerciseId()) + return false; + if (QString::fromStdString(cnrConfig.radioCircuit()) != name) + return false; - id = cnrConfig.id(); - return true; - }; + id = cnrConfig.id(); + return true; + }; - m_avmDtc->cnrConfigs(findByNameInExercise); - return id; + m_avmDtc->cnrConfigs(findByNameInExercise); + return id; } - - QByteArray EditFrequencyPlanningFrequencyDataModel::uiToJson() const { - QJsonObject obj; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning); - obj[QStringLiteral("frequencySetId")] = m_initPlan.frequencySetId(); + QJsonObject obj; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMEditFrequencyPlanning); + obj[QStringLiteral("frequencySetId")] = m_initPlan.frequencySetId(); - QJsonArray arr; - for (const auto &keyValue : overKeyValue(m_frequencyPlanningData)) - { - QJsonObject inner; - const FrequencyPlanningData &info = keyValue.second; + QJsonArray arr; + for (const auto& keyValue : overKeyValue(m_frequencyPlanningData)) + { + QJsonObject inner; + const FrequencyPlanningData& info = keyValue.second; - inner[QStringLiteral("cnrChannelId")] = m_avmDtc->cnrConfig(info.cnrConfigId()).cnrChannelId(); - inner[QStringLiteral("properties")] = QString::fromStdString(info.properties()); + inner[QStringLiteral("cnrChannelId")] = m_avmDtc->cnrConfig(info.cnrConfigId()).cnrChannelId(); + inner[QStringLiteral("properties")] = QString::fromStdString(info.properties()); - arr.append(inner); - } + arr.append(inner); + } - obj[QStringLiteral("planningInfos")] = arr; + obj[QStringLiteral("planningInfos")] = arr; - QJsonDocument doc(obj); + QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + return doc.toJson(QJsonDocument::Compact); } - -void EditFrequencyPlanningFrequencyDataModel::setFrequencyPlanningData(const FrequencyPlanningData &fpd) +void EditFrequencyPlanningFrequencyDataModel::setFrequencyPlanningData(const FrequencyPlanningData& fpd) { - ConfigTreeItem* item = searchCnrConfig(m_rootItem, fpd.cnrConfigId()); - if(!item) - { - if (!m_cnrConfigs.contains(fpd.cnrConfigId())) - return; - beginResetModel(); - ItemData data(m_cnrConfigs[fpd.cnrConfigId()]); - data.readOnly = isReadOnly(fpd.properties()); + ConfigTreeItem* item = searchCnrConfig(m_rootItem, fpd.cnrConfigId()); + if (!item) + { + if (!m_cnrConfigs.contains(fpd.cnrConfigId())) + return; + beginResetModel(); + ItemData data(m_cnrConfigs[fpd.cnrConfigId()]); + data.readOnly = isReadOnly(fpd.properties()); + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + if (circuits.size() > 1) + { + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(data)); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + for (RadioCircuit* circuit : std::as_const(circuits)) + { + data.radioCircuit = circuit; + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(data)); + insertRow(configItem->childCount(), indexFromItem(configItem), childItem); + } + } + else if (circuits.size() == 1) + { + data.radioCircuit = circuits[0]; + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(data)); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + } + m_frequencyPlanningData[fpd.cnrConfigId()] = fpd; + endResetModel(); + return; + } + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - if (circuits.size() > 1) + ItemData data = item->data().value(); + item->removeAllChildren(); + + if (circuits.size() == 1) + { + data.radioCircuit = circuits[0]; + item->setData(QVariant::fromValue(data)); + m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); + } + if (circuits.size() <= 1) + return; + + for (RadioCircuit* circuit : std::as_const(circuits)) { - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(data)); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - for (RadioCircuit *circuit : std::as_const(circuits)) - { data.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(data)); - insertRow(configItem->childCount(), indexFromItem(configItem), childItem); - } + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(data)); + insertRow(item->childCount(), indexFromItem(item), childItem); } - else if (circuits.size() == 1) - { - data.radioCircuit = circuits[0]; - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(data)); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - } - m_frequencyPlanningData[fpd.cnrConfigId()] = fpd; - endResetModel(); - return; - } - - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - ItemData data = item->data().value(); - item->removeAllChildren(); - - if (circuits.size() == 1) - { - data.radioCircuit = circuits[0]; - item->setData(QVariant::fromValue(data)); m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); - } - if (circuits.size() <= 1) - return; - - for (RadioCircuit *circuit : std::as_const(circuits)) - { - data.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(data)); - insertRow(item->childCount(), indexFromItem(item), childItem); - } - m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); - endResetModel(); + endResetModel(); } bool EditFrequencyPlanningFrequencyDataModel::checkResourceAssignments() { - bool bOk = true; + bool bOk = true; - m_multipleAssignedCnrIds.clear(); - for (auto it = m_frequencyPlanningData.constBegin(); it != m_frequencyPlanningData.constEnd();) - { - const FrequencyPlanningData &p = it.value(); - - QSet fsdIdsOuter = frequencySetDataIds(p.properties()); - - for (auto startSearchIt = ++it; startSearchIt != m_frequencyPlanningData.constEnd();++startSearchIt) + m_multipleAssignedCnrIds.clear(); + for (auto it = m_frequencyPlanningData.constBegin(); it != m_frequencyPlanningData.constEnd();) { - const FrequencyPlanningData &pI= startSearchIt.value(); - QSet fsdIdsInner = frequencySetDataIds(pI.properties()); - for (int inner : std::as_const(fsdIdsInner)) - { - for (int outer : std::as_const(fsdIdsOuter)) + const FrequencyPlanningData& p = it.value(); + + QSet fsdIdsOuter = frequencySetDataIds(p.properties()); + + for (auto startSearchIt = ++it; startSearchIt != m_frequencyPlanningData.constEnd(); ++startSearchIt) { - if (inner != outer) - { - DEBUG_LOG(m_logger) << "---ist ungleich cnrConfigId(A): " << p.cnrConfigId() - << " (B): " << pI.cnrConfigId(); - } - else - { - DEBUG_LOG(m_logger) << "---ist gleich cnrConfigId(A): " << p.cnrConfigId() - << " (B): " << pI.cnrConfigId(); - if (!m_multipleAssignedCnrIds.contains(p.cnrConfigId()) ) - m_multipleAssignedCnrIds.append(p.cnrConfigId()); + const FrequencyPlanningData& pI = startSearchIt.value(); + QSet fsdIdsInner = frequencySetDataIds(pI.properties()); + for (int inner : std::as_const(fsdIdsInner)) + { + for (int outer : std::as_const(fsdIdsOuter)) + { + if (inner != outer) + { + DEBUG_LOG(m_logger) + << "---ist ungleich cnrConfigId(A): " << p.cnrConfigId() << " (B): " << pI.cnrConfigId(); + } + else + { + DEBUG_LOG(m_logger) + << "---ist gleich cnrConfigId(A): " << p.cnrConfigId() << " (B): " << pI.cnrConfigId(); + if (!m_multipleAssignedCnrIds.contains(p.cnrConfigId())) + m_multipleAssignedCnrIds.append(p.cnrConfigId()); - if (!m_multipleAssignedCnrIds.contains(pI.cnrConfigId()) ) - m_multipleAssignedCnrIds.append(pI.cnrConfigId()); - bOk = false; - } + if (!m_multipleAssignedCnrIds.contains(pI.cnrConfigId())) + m_multipleAssignedCnrIds.append(pI.cnrConfigId()); + bOk = false; + } + } + } } - } } - } #ifdef LTS_DEBUG - QString qs; - for (int id : std::as_const(m_multipleAssignedCnrIds)) - { - qs.append(QString::number(id)); - qs.append(QStringLiteral(", ")); - } - DEBUG_LOG(m_logger) << "---Number of multiple assigned frequency set data: " << m_multipleAssignedCnrIds.size() - << " cnrConfigIds: " << qs; + QString qs; + for (int id : std::as_const(m_multipleAssignedCnrIds)) + { + qs.append(QString::number(id)); + qs.append(QStringLiteral(", ")); + } + DEBUG_LOG(m_logger) << "---Number of multiple assigned frequency set data: " << m_multipleAssignedCnrIds.size() + << " cnrConfigIds: " << qs; #endif - return bOk; + return bOk; } -bool EditFrequencyPlanningFrequencyDataModel::onCnrConfigChanged(const AudioVideoManagement::CnrConfig &data, DataModification modType) +bool EditFrequencyPlanningFrequencyDataModel::onCnrConfigChanged(const AudioVideoManagement::CnrConfig& data, + DataModification modType) { - ConfigTreeItem* item = searchCnrConfig(m_rootItem, data.id()); + ConfigTreeItem* item = searchCnrConfig(m_rootItem, data.id()); - if (modType == DataModification::eRemoved) - { - - if (!item) - return true; - m_cnrConfigs.remove(data.id()); - m_frequencyPlanningData.remove(data.id()); - return removeRow(item->row()); - } + if (modType == DataModification::eRemoved) + { - - if (modType == DataModification::eAdded || - (!item && data.exerciseId().is_set() && m_exerciseId == data.exerciseId().get()) - ) - { - Q_ASSERT(!item); + if (!item) + return true; + m_cnrConfigs.remove(data.id()); + m_frequencyPlanningData.remove(data.id()); + return removeRow(item->row()); + } - m_cnrConfigs.insert(data.id(), data); - ConfigTreeItem *newItem = new ConfigTreeItem(QVariant::fromValue(ItemData(data))); - m_rootItem->setModified(true); - insertRow(0, indexFromItem(m_rootItem), newItem); - return true; - } + if (modType == DataModification::eAdded || + (!item && data.exerciseId().is_set() && m_exerciseId == data.exerciseId().get())) + { + Q_ASSERT(!item); - - if (item && data.exerciseId().is_set() && m_exerciseId != data.exerciseId().get()) - return removeRow(item->row()); + m_cnrConfigs.insert(data.id(), data); + ConfigTreeItem* newItem = new ConfigTreeItem(QVariant::fromValue(ItemData(data))); + m_rootItem->setModified(true); + insertRow(0, indexFromItem(m_rootItem), newItem); + return true; + } - - if(item) - { - ItemData id = item->data().value(); - id.cnrConfig = data; - item->setData(QVariant::fromValue(id)); + if (item && data.exerciseId().is_set() && m_exerciseId != data.exerciseId().get()) + return removeRow(item->row()); - - if(id.radioCircuit) - id.radioCircuit->name = QString::fromStdString(data.radioCircuit()); + if (item) + { + ItemData id = item->data().value(); + id.cnrConfig = data; + item->setData(QVariant::fromValue(id)); - item->setModified(true); - return true; - } - return false; + if (id.radioCircuit) + id.radioCircuit->name = QString::fromStdString(data.radioCircuit()); + + item->setModified(true); + return true; + } + return false; } -EditFrequencyPlanningFrequencyDataModel::ConfigTreeItem* EditFrequencyPlanningFrequencyDataModel::searchCnrConfig(const NGLTreeItem *parentItem, int cnrConfigId) const +EditFrequencyPlanningFrequencyDataModel::ConfigTreeItem* +EditFrequencyPlanningFrequencyDataModel::searchCnrConfig(const NGLTreeItem* parentItem, int cnrConfigId) const { - const int rowCount = parentItem->childCount(); - for (int r = 0; r < rowCount; ++r) - { - ConfigTreeItem *child = static_cast(parentItem->child(r)); - if (child->data().value().cnrConfig.id() == cnrConfigId) - return child; - child = searchCnrConfig(child, cnrConfigId); - if (child) - return child; - } - return nullptr; + const int rowCount = parentItem->childCount(); + for (int r = 0; r < rowCount; ++r) + { + ConfigTreeItem* child = static_cast(parentItem->child(r)); + if (child->data().value().cnrConfig.id() == cnrConfigId) + return child; + child = searchCnrConfig(child, cnrConfigId); + if (child) + return child; + } + return nullptr; } QSet EditFrequencyPlanningFrequencyDataModel::getAllocatedFrequencyPlanningSetIds() { - QSet result; - for (const auto &fpd : std::as_const(m_frequencyPlanningData)) - { - result += AudioVideoManagement::frequencySetDataIds(fpd.properties()); - } - - if(m_exerciseId == 0) - { - QMap frequencyPlannings = m_avmDtc->frequencyPlannings(); - for(const auto &frequencyPlanning : std::as_const(frequencyPlannings)) + QSet result; + for (const auto& fpd : std::as_const(m_frequencyPlanningData)) { - if(!frequencyPlanning.exerciseId().is_set()) - continue; - - for(const auto &frequencyPlanningData : frequencyPlanning.data()) - { - result += AudioVideoManagement::frequencySetDataIds(frequencyPlanningData.properties()); - } + result += AudioVideoManagement::frequencySetDataIds(fpd.properties()); } - } - return result; + + if (m_exerciseId == 0) + { + QMap frequencyPlannings = m_avmDtc->frequencyPlannings(); + for (const auto& frequencyPlanning : std::as_const(frequencyPlannings)) + { + if (!frequencyPlanning.exerciseId().is_set()) + continue; + + for (const auto& frequencyPlanningData : frequencyPlanning.data()) + { + result += AudioVideoManagement::frequencySetDataIds(frequencyPlanningData.properties()); + } + } + } + return result; } - - - -FPFDelegate::FPFDelegate(QObject *parent) : QStyledItemDelegate(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} -void FPFDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +FPFDelegate::FPFDelegate(QObject* parent) : QStyledItemDelegate(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - if (index.column() == EditFrequencyPlanningFrequencyDataModel::Columns::PROPERTIES) - { - QStyleOptionViewItem options = option; - initStyleOption(&options, index); - - painter->save(); - - QTextDocument doc; - doc.setHtml(options.text); - - options.text = QString(); - options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); - - painter->translate(options.rect.left(), options.rect.top()); - QRect clip(0, 0, options.rect.width(), options.rect.height()); - doc.drawContents(painter, clip); - - painter->restore(); - } - else - QStyledItemDelegate::paint(painter, option, index); } +void FPFDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + if (index.column() == EditFrequencyPlanningFrequencyDataModel::Columns::PROPERTIES) + { + QStyleOptionViewItem options = option; + initStyleOption(&options, index); -QSize FPFDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const + painter->save(); + + QTextDocument doc; + doc.setHtml(options.text); + + options.text = QString(); + options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); + + painter->translate(options.rect.left(), options.rect.top()); + QRect clip(0, 0, options.rect.width(), options.rect.height()); + doc.drawContents(painter, clip); + + painter->restore(); + } + else + QStyledItemDelegate::paint(painter, option, index); +} + +QSize FPFDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem options = option; initStyleOption(&options, index); @@ -946,5 +883,4 @@ QSize FPFDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIn return QSize(doc.idealWidth(), doc.size().height()); } -} - +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_resource_data_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_resource_data_model.cpp old mode 100755 new mode 100644 index 2958ca468..91acbf579 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_resource_data_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_edit_frequency_planning_resource_data_model.cpp @@ -1,99 +1,94 @@ - #include "avm_edit_frequency_planning_resource_data_model.h" -#include + #include +#include namespace AudioVideoManagement { -EditFrequencyPlanningResourceDataModel::EditFrequencyPlanningResourceDataModel(const QSet &assignedFrequencySetDataIds, - const FrequencyBand frequencyBand, - QObject *parent) - : LtsAbstractTableModel( -{ - tr("FSD id"), - tr("Function"), - tr("Device"), - tr("Frequency"), - tr("AKW Bundle"), - tr("FSB Bundle"), - tr("AKW Radio Circuit"), - tr("COMSEC"), -}, parent) - , m_assignedFrequencySetDataIds(assignedFrequencySetDataIds) - , m_frequencyBand(frequencyBand) +EditFrequencyPlanningResourceDataModel::EditFrequencyPlanningResourceDataModel( + const QSet& assignedFrequencySetDataIds, const FrequencyBand frequencyBand, QObject* parent) + : LtsAbstractTableModel( + { + tr("FSD id"), + tr("Function"), + tr("Device"), + tr("Frequency"), + tr("AKW Bundle"), + tr("FSB Bundle"), + tr("AKW Radio Circuit"), + tr("COMSEC"), + }, + parent), + m_assignedFrequencySetDataIds(assignedFrequencySetDataIds), m_frequencyBand(frequencyBand) { } -QVariant EditFrequencyPlanningResourceDataModel::data(const QModelIndex &index, int role) const +QVariant EditFrequencyPlanningResourceDataModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) - return QVariant(); + if ((role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) + return QVariant(); - const FrequencySetDataWithId &setData = m_vecData.at(index.row()); - if (role == Qt::DisplayRole) - { - QLocale locale(QLocale::German); - switch (index.column()) + const FrequencySetDataWithId& setData = m_vecData.at(index.row()); + if (role == Qt::DisplayRole) { - case FREQ_SET_DATA_ID: - return setData.id(); - case FUNCTION: - return QString::fromStdString(setData.function()); - case DEVICE: - return toString(setData.frequencyBand()); - case FREQUENCY: - return tr("%1 MHz").arg(locale.toString(setData.frequency() / 1000., 'f', 3)); - case AKW_BUNDLE: - if (setData.akwBundle().is_set()) - return setData.akwBundle().get(); - return QStringLiteral("-"); - case FSB_BUNDLE: - if (setData.fsbBundle().is_set()) - return setData.fsbBundle().get(); - return QStringLiteral("-"); - case AKW_RADIO_CIRCUIT: - if (setData.akwRadioCircuit()) - return setData.akwRadioCircuit().get(); - return QStringLiteral("-"); - case COMSEC: - if (setData.comsec().is_set()) - return setData.comsec().get(); - return QStringLiteral("-"); + QLocale locale(QLocale::German); + switch (index.column()) + { + case FREQ_SET_DATA_ID: + return setData.id(); + case FUNCTION: + return QString::fromStdString(setData.function()); + case DEVICE: + return toString(setData.frequencyBand()); + case FREQUENCY: + return tr("%1 MHz").arg(locale.toString(setData.frequency() / 1000., 'f', 3)); + case AKW_BUNDLE: + if (setData.akwBundle().is_set()) + return setData.akwBundle().get(); + return QStringLiteral("-"); + case FSB_BUNDLE: + if (setData.fsbBundle().is_set()) + return setData.fsbBundle().get(); + return QStringLiteral("-"); + case AKW_RADIO_CIRCUIT: + if (setData.akwRadioCircuit()) + return setData.akwRadioCircuit().get(); + return QStringLiteral("-"); + case COMSEC: + if (setData.comsec().is_set()) + return setData.comsec().get(); + return QStringLiteral("-"); + } } - } - else if (role == Qt::UserRole) - return setData.id(); + else if (role == Qt::UserRole) + return setData.id(); - return QVariant(); + return QVariant(); } -bool EditFrequencyPlanningResourceDataModel::isFiltered(const AudioVideoManagement::FrequencySetDataWithId &data, DataModification modType) const +bool EditFrequencyPlanningResourceDataModel::isFiltered(const AudioVideoManagement::FrequencySetDataWithId& data, + DataModification modType) const { - - - if (m_frequencyBand != FrequencyBand_def::REL && - data.frequencyBand() != m_frequencyBand) - return true; + if (m_frequencyBand != FrequencyBand_def::REL && data.frequencyBand() != m_frequencyBand) + return true; - - if(m_frequencyBand == FrequencyBand_def::REL && - data.frequencyBand() != FrequencyBand_def::VHF) - return true; + if (m_frequencyBand == FrequencyBand_def::REL && data.frequencyBand() != FrequencyBand_def::VHF) + return true; - Q_UNUSED(modType); - - if (m_assignedFrequencySetDataIds.contains(data.id())) - { - DEBUG_LOG(m_logger) << "---m_assignments.size(): " << m_assignedFrequencySetDataIds.size() - << " frequencySetDataId: " << data.id() << " ist bereits enthalten"; - return true; - } + Q_UNUSED(modType); - return false; + if (m_assignedFrequencySetDataIds.contains(data.id())) + { + DEBUG_LOG(m_logger) << "---m_assignments.size(): " << m_assignedFrequencySetDataIds.size() + << " frequencySetDataId: " << data.id() << " ist bereits enthalten"; + return true; + } + + return false; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.cpp old mode 100755 new mode 100644 index 689120cd8..ea8d65b1b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.cpp @@ -1,491 +1,471 @@ - #include "avm_frequency_planning_dialog.h" -#include "ui_avm_frequency_planning_dialog.h" -#include "avm_frequency_planning_dialog_model.h" + #include "avm_edit_frequency_planning_dialog.h" +#include "avm_frequency_planning_dialog_model.h" #include "avm_init_frequency_planning_dialog.h" +#include "ui_avm_frequency_planning_dialog.h" -#include -#include -#include -#include -#include -#include #include - -#include +#include +#include #include -#include +#include +#include +#include +#include +#include #include +#include namespace AudioVideoManagement { -FrequencyPlanningDialog::FrequencyPlanningDialog(LtsSession::LtsSession *session, const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::FrequencyPlanningDialog) - , m_menuGroup(menuGroup) - , m_copy(false) - , m_session(session) - , m_model(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_activePlanning( { -1, -1 }) - , m_avmDtc(nullptr) - , m_avmFtc(nullptr) - , m_ppmDtc(nullptr) - , m_ismDtc(nullptr) - , m_flmGui(nullptr) - , m_activeFrequencyPlanningStatus(0) +FrequencyPlanningDialog::FrequencyPlanningDialog(LtsSession::LtsSession* session, const QString& menuGroup, + QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ui(new Ui::FrequencyPlanningDialog), + m_menuGroup(menuGroup), m_copy(false), m_session(session), m_model(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_activePlanning({-1, -1}), m_avmDtc(nullptr), + m_avmFtc(nullptr), m_ppmDtc(nullptr), m_ismDtc(nullptr), m_flmGui(nullptr), m_activeFrequencyPlanningStatus(0) { - m_ui->setupUi(this); + m_ui->setupUi(this); - DEBUG_LOG(m_logger) << "---FrequencyPlanningDialog() "; - m_ui->dataView->setSelectionMode(QAbstractItemView::SingleSelection); - m_ui->dataView->treeView()->setSelectionBehavior(QAbstractItemView::SelectRows); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &FrequencyPlanningDialog::onPrint); + DEBUG_LOG(m_logger) << "---FrequencyPlanningDialog() "; + m_ui->dataView->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->dataView->treeView()->setSelectionBehavior(QAbstractItemView::SelectRows); - setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &FrequencyPlanningDialog::onPrint); + + setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); } FrequencyPlanningDialog::~FrequencyPlanningDialog() { - delete m_ui; + delete m_ui; } void FrequencyPlanningDialog::retranslate() { - translate(m_ui, tr("Frequency Planning")); + translate(m_ui, tr("Frequency Planning")); } void FrequencyPlanningDialog::unsetActiveFrequencyPlanning() { - m_ui->lbActiveFrequencyPlanning->setText(tr("No Frequency Planning set")); - m_activePlanning = { -1, -1 }; - m_model->unsetActivePlanning(); - onSelectionChanged(); + m_ui->lbActiveFrequencyPlanning->setText(tr("No Frequency Planning set")); + m_activePlanning = {-1, -1}; + m_model->unsetActivePlanning(); + onSelectionChanged(); } -void FrequencyPlanningDialog::setActiveFrequencyPlanning(const ActiveFrequencyPlanning &activePlanning) +void FrequencyPlanningDialog::setActiveFrequencyPlanning(const ActiveFrequencyPlanning& activePlanning) { - m_ui->lbActiveFrequencyPlanning->setText(QString::fromStdString(m_avmDtc->frequencyPlanning(activePlanning.frequencyPlanningId()).name())); - m_activePlanning = activePlanning; - m_model->setActivePlanning(m_activePlanning.frequencyPlanningId()); - onSelectionChanged(); + m_ui->lbActiveFrequencyPlanning->setText( + QString::fromStdString(m_avmDtc->frequencyPlanning(activePlanning.frequencyPlanningId()).name())); + m_activePlanning = activePlanning; + m_model->setActivePlanning(m_activePlanning.frequencyPlanningId()); + onSelectionChanged(); } -bool FrequencyPlanningDialog::init(const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &ismDtc, - ExerciseManagement::Interface::Dtc *exmDtc) +bool FrequencyPlanningDialog::init(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& ismDtc, + ExerciseManagement::Interface::Dtc* exmDtc) { - if (!(ppmDtc->enableParty() && - ppmDtc->enableParticipant() && - ppmDtc->enableType() && - avmDtc->enableCnrConfig() && - avmDtc->enableFrequencyPlanning() && - avmDtc->enableFrequencySet() && - avmDtc->enableActiveFrequencyPlanning() && - ismDtc->enableMainStructureElement())) - { - ERROR_LOG(m_logger) << "Could not enable topics"; - return false; - } + if (!(ppmDtc->enableParty() && ppmDtc->enableParticipant() && ppmDtc->enableType() && avmDtc->enableCnrConfig() && + avmDtc->enableFrequencyPlanning() && avmDtc->enableFrequencySet() && + avmDtc->enableActiveFrequencyPlanning() && ismDtc->enableMainStructureElement())) + { + ERROR_LOG(m_logger) << "Could not enable topics"; + return false; + } - delete m_model; - m_model = new FrequencyPlanningDialogModel(m_session->exerciseId(), this); - - m_avmDtc = avmDtc; - m_avmFtc = avmFtc; - m_ppmDtc = ppmDtc; - m_ismDtc = ismDtc; - m_exmDtc = exmDtc; - - if (!m_model->init(avmDtc)) - { delete m_model; - m_model = nullptr; - ERROR_LOG(m_logger) << "Could not init model"; - return false; - } + m_model = new FrequencyPlanningDialogModel(m_session->exerciseId(), this); - m_proxyModel = new FrequencyPlanningDialogProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->dataView->setModel(m_proxyModel); + m_avmDtc = avmDtc; + m_avmFtc = avmFtc; + m_ppmDtc = ppmDtc; + m_ismDtc = ismDtc; + m_exmDtc = exmDtc; - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &FrequencyPlanningDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &FrequencyPlanningDialog::onEditClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &FrequencyPlanningDialog::onRemoveClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &FrequencyPlanningDialog::onActivateDeactivatePlanningClicked); + if (!m_model->init(avmDtc)) + { + delete m_model; + m_model = nullptr; + ERROR_LOG(m_logger) << "Could not init model"; + return false; + } - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &FrequencyPlanningDialog::onSelectionChanged); + m_proxyModel = new FrequencyPlanningDialogProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->dataView->setModel(m_proxyModel); - unsetActiveFrequencyPlanning(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &FrequencyPlanningDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &FrequencyPlanningDialog::onEditClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &FrequencyPlanningDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, + &FrequencyPlanningDialog::onActivateDeactivatePlanningClicked); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &FrequencyPlanningDialog::onSelectionChanged); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &FrequencyPlanningDialog::onEditClicked); - connect(m_avmDtc.get(), &Interface::Dtc::activeFrequencyPlanningChanged, - this, &FrequencyPlanningDialog::onActiveFrequencyPlanningChanged); + unsetActiveFrequencyPlanning(); - m_ui->dataView->hideColumn(FrequencyPlanningDialogModel::Columns::SET); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &FrequencyPlanningDialog::onEditClicked); + connect(m_avmDtc.get(), &Interface::Dtc::activeFrequencyPlanningChanged, this, + &FrequencyPlanningDialog::onActiveFrequencyPlanningChanged); - m_avmDtc->activeFrequencyPlannings([this](const ActiveFrequencyPlanning & data) - { - onActiveFrequencyPlanningChanged(data, DataModification::eAdded); - }); - onSelectionChanged(); + m_ui->dataView->hideColumn(FrequencyPlanningDialogModel::Columns::SET); - setStatus(tr("No active Radio Controller connected."), {}, time(0) * 1000, TransmissionReason::TR_Unknown, Qt::red); - for(auto &elem : m_avmDtc->frequencyPlanningStatuss()) - { - if (!elem.isActive()) - continue; - m_activeFrequencyPlanningStatus = elem.id(); - onFrequencyPlanningStatusChanged(elem, DataModification::eAdded); - } - connect(m_avmDtc.get(), &Interface::Dtc::frequencyPlanningStatusChanged, this, &FrequencyPlanningDialog::onFrequencyPlanningStatusChanged); + m_avmDtc->activeFrequencyPlannings([this](const ActiveFrequencyPlanning& data) { + onActiveFrequencyPlanningChanged(data, DataModification::eAdded); + }); + onSelectionChanged(); - return true; -} - -void FrequencyPlanningDialog::onFrequencyPlanningStatusChanged(const AudioVideoManagement::FrequencyPlanningStatus &data, DataModification modType) -{ - if (modType == DataModification::eModified) - { - if (data.id() != m_activeFrequencyPlanningStatus) - return; - } - else if (modType == DataModification::eRemoved) - { - if (data.id() != m_activeFrequencyPlanningStatus) - return; - - m_activeFrequencyPlanningStatus = 0; setStatus(tr("No active Radio Controller connected."), {}, time(0) * 1000, TransmissionReason::TR_Unknown, Qt::red); - return; - } - else - { - if (!data.isActive()) - return; - m_activeFrequencyPlanningStatus = data.id(); - } + for (auto& elem : m_avmDtc->frequencyPlanningStatuss()) + { + if (!elem.isActive()) + continue; + m_activeFrequencyPlanningStatus = elem.id(); + onFrequencyPlanningStatusChanged(elem, DataModification::eAdded); + } + connect(m_avmDtc.get(), &Interface::Dtc::frequencyPlanningStatusChanged, this, + &FrequencyPlanningDialog::onFrequencyPlanningStatusChanged); - - - if (data.activated().is_set()) - { - setStatus(tr("Activated"), QString::fromStdString(data.requester()), data.activated().get(), data.reason(), Qt::green); - return; - } - - if (data.received().is_set()) - { - setStatus(tr("In Progress"), QString::fromStdString(data.requester()), data.received().get(), data.reason(), Qt::yellow); - return; - } - - if (data.sent().is_set()) - { - setStatus(tr("Sent"), QString::fromStdString(data.requester()), data.sent().get(), TransmissionReason::TR_Unknown, Qt::yellow); - return; - } - setStatus(tr("Connection established, status unknown."), {}, time(0) * 1000, TransmissionReason::TR_Unknown, Qt::yellow); + return true; } -void FrequencyPlanningDialog::setStatus(const QString &statusText, const QString &requester, qint64 timeStampMsecs, TransmissionReason reason, Qt::GlobalColor color) +void FrequencyPlanningDialog::onFrequencyPlanningStatusChanged( + const AudioVideoManagement::FrequencyPlanningStatus& data, DataModification modType) { - m_ui->lblStatus->setText(statusText); - m_ui->lblStatusTime->setText(DTG::toStringMSec(timeStampMsecs)); - m_ui->lblStatus->setToolTip(toString(reason)); - m_ui->lblStatusTime->setToolTip(requester); - setBackgroundColor(m_ui->lblStatus, color, color != Qt::black); + if (modType == DataModification::eModified) + { + if (data.id() != m_activeFrequencyPlanningStatus) + return; + } + else if (modType == DataModification::eRemoved) + { + if (data.id() != m_activeFrequencyPlanningStatus) + return; + + m_activeFrequencyPlanningStatus = 0; + setStatus(tr("No active Radio Controller connected."), {}, time(0) * 1000, TransmissionReason::TR_Unknown, + Qt::red); + return; + } + else + { + if (!data.isActive()) + return; + m_activeFrequencyPlanningStatus = data.id(); + } + + if (data.activated().is_set()) + { + setStatus(tr("Activated"), QString::fromStdString(data.requester()), data.activated().get(), data.reason(), + Qt::green); + return; + } + + if (data.received().is_set()) + { + setStatus(tr("In Progress"), QString::fromStdString(data.requester()), data.received().get(), data.reason(), + Qt::yellow); + return; + } + + if (data.sent().is_set()) + { + setStatus(tr("Sent"), QString::fromStdString(data.requester()), data.sent().get(), + TransmissionReason::TR_Unknown, Qt::yellow); + return; + } + setStatus(tr("Connection established, status unknown."), {}, time(0) * 1000, TransmissionReason::TR_Unknown, + Qt::yellow); +} + +void FrequencyPlanningDialog::setStatus(const QString& statusText, const QString& requester, qint64 timeStampMsecs, + TransmissionReason reason, Qt::GlobalColor color) +{ + m_ui->lblStatus->setText(statusText); + m_ui->lblStatusTime->setText(DTG::toStringMSec(timeStampMsecs)); + m_ui->lblStatus->setToolTip(toString(reason)); + m_ui->lblStatusTime->setToolTip(requester); + setBackgroundColor(m_ui->lblStatus, color, color != Qt::black); } void FrequencyPlanningDialog::tableColumnOrganiserSetting() { - - m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); } -void FrequencyPlanningDialog::setBackgroundColor(QWidget *w, Qt::GlobalColor color, bool bSetColor) +void FrequencyPlanningDialog::setBackgroundColor(QWidget* w, Qt::GlobalColor color, bool bSetColor) { - if (!w) - return; + if (!w) + return; - if (bSetColor) - { - QPalette pal = QApplication::palette(w); - pal.setColor(QPalette::Window, color); - w->setPalette(pal); - w->setAutoFillBackground(true); - } - else - { - - w->setPalette(QApplication::palette(w)); - w->setAutoFillBackground(false); - } -} - -void FrequencyPlanningDialog::onModifyFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); -} - -void FrequencyPlanningDialog::onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); -} - -void FrequencyPlanningDialog::onRemoveActiveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); -} - -void FrequencyPlanningDialog::onModifyActiveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); -} - -void FrequencyPlanningDialog::onAddClicked() -{ - const QModelIndexList selectedRows = m_ui->dataView->selectedRows(); - Q_ASSERT(selectedRows.empty() || selectedRows.size() == 1); - QMap frequencySets = m_avmDtc->frequencySets(); - if (selectedRows.empty()) - { - if(frequencySets.size() == 1) + if (bSetColor) { - FrequencyPlanning planning; - - planning.id(0); - if(m_session->exerciseId() != 0) - planning.exerciseId(m_session->exerciseId()); - planning.frequencySetId(frequencySets.first().id()); - planning.date(m_session->partitionTime()); - showEditDialog(planning); + QPalette pal = QApplication::palette(w); + pal.setColor(QPalette::Window, color); + w->setPalette(pal); + w->setAutoFillBackground(true); } else { - InitFrequencyPlanningDialog *initDialog = new InitFrequencyPlanningDialog(m_session, m_avmDtc, this); - connect(initDialog, &InitFrequencyPlanningDialog::newInitFrequencyPlanning, - this, &FrequencyPlanningDialog::showEditDialog); + w->setPalette(QApplication::palette(w)); + w->setAutoFillBackground(false); + } +} - m_copy = false; - addDialog(initDialog, m_menuGroup, QStringLiteral("NewFrequencyPlanning")); +void FrequencyPlanningDialog::onModifyFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); +} + +void FrequencyPlanningDialog::onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); +} + +void FrequencyPlanningDialog::onRemoveActiveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); +} + +void FrequencyPlanningDialog::onModifyActiveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); +} + +void FrequencyPlanningDialog::onAddClicked() +{ + const QModelIndexList selectedRows = m_ui->dataView->selectedRows(); + Q_ASSERT(selectedRows.empty() || selectedRows.size() == 1); + QMap frequencySets = m_avmDtc->frequencySets(); + if (selectedRows.empty()) + { + if (frequencySets.size() == 1) + { + FrequencyPlanning planning; + + planning.id(0); + if (m_session->exerciseId() != 0) + planning.exerciseId(m_session->exerciseId()); + planning.frequencySetId(frequencySets.first().id()); + planning.date(m_session->partitionTime()); + showEditDialog(planning); + } + else + { + InitFrequencyPlanningDialog* initDialog = new InitFrequencyPlanningDialog(m_session, m_avmDtc, this); + + connect(initDialog, &InitFrequencyPlanningDialog::newInitFrequencyPlanning, this, + &FrequencyPlanningDialog::showEditDialog); + + m_copy = false; + addDialog(initDialog, m_menuGroup, QStringLiteral("NewFrequencyPlanning")); + } + } + else + { + m_copy = true; + qint64 dateOfCreation = m_session->partitionTime(); + FrequencyPlanning planning = m_model->data(selectedRows.constFirst(), Qt::UserRole).value(); + planning.date(dateOfCreation); + showEditDialog(planning); } - } - else - { - m_copy = true; - qint64 dateOfCreation = m_session->partitionTime(); - FrequencyPlanning planning = m_model->data(selectedRows.constFirst(), Qt::UserRole).value(); - planning.date(dateOfCreation); - showEditDialog(planning); - } } void FrequencyPlanningDialog::onEditClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - const FrequencyPlanning &fp = m_model->data(currentIndex, Qt::UserRole).value(); - DEBUG_LOG(m_logger) << "---onEditClicked() FrequencyPlanningId: " << fp.id() << " FrequencySetDataId: " << fp.frequencySetId(); + const FrequencyPlanning& fp = m_model->data(currentIndex, Qt::UserRole).value(); + DEBUG_LOG(m_logger) << "---onEditClicked() FrequencyPlanningId: " << fp.id() + << " FrequencySetDataId: " << fp.frequencySetId(); - m_copy = false; - showEditDialog(m_model->data(currentIndex, Qt::UserRole).value()); + m_copy = false; + showEditDialog(m_model->data(currentIndex, Qt::UserRole).value()); } void FrequencyPlanningDialog::onRemoveClicked() { - const QModelIndex currentIndex = m_ui->dataView->currentIndex(); + const QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - int planningId = m_model->data(currentIndex, Qt::UserRole).value().id(); - - if (m_editDlgMap.contains(planningId)) - { - m_editDlgMap.value(planningId)->deleteLater(); - m_editDlgMap.remove(planningId); - } + int planningId = m_model->data(currentIndex, Qt::UserRole).value().id(); - Core::RemoveElementRequest req; + if (m_editDlgMap.contains(planningId)) + { + m_editDlgMap.value(planningId)->deleteLater(); + m_editDlgMap.remove(planningId); + } - req.id(planningId); + Core::RemoveElementRequest req; - m_requestHelper->startSingleRequest([this, req]() - { - return m_avmFtc->removeFrequencyPlanningRequest(req, this); - }); + req.id(planningId); + + m_requestHelper->startSingleRequest([this, req]() { return m_avmFtc->removeFrequencyPlanningRequest(req, this); }); } void FrequencyPlanningDialog::onSelectionChanged() { - const QModelIndexList selectedRows = m_ui->dataView->selectedRows(); - bool hasSelection = !selectedRows.empty(); - bool selectedIsActive = false; - if (hasSelection) - { - const QModelIndex currentIndex = selectedRows.constFirst(); - selectedIsActive = m_model->data(currentIndex, Qt::UserRole).value().id() == m_activePlanning.frequencyPlanningId(); - } + const QModelIndexList selectedRows = m_ui->dataView->selectedRows(); + bool hasSelection = !selectedRows.empty(); + bool selectedIsActive = false; + if (hasSelection) + { + const QModelIndex currentIndex = selectedRows.constFirst(); + selectedIsActive = m_model->data(currentIndex, Qt::UserRole).value().id() == + m_activePlanning.frequencyPlanningId(); + } - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, hasSelection); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, hasSelection && !selectedIsActive); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, hasSelection && m_session->exerciseId() && m_session->exerciseState() == LtsWidgets::ExcState::eStarted); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, hasSelection); - if (selectedIsActive) - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Deactivate")); - else - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Activate")); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, hasSelection && !selectedIsActive); - bool disableGlobalPlanning = m_session->exerciseId() == 0 && m_proxyModel->rowCount() !=0; - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, !disableGlobalPlanning); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, + hasSelection && m_session->exerciseId() && + m_session->exerciseState() == LtsWidgets::ExcState::eStarted); + + if (selectedIsActive) + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Deactivate")); + else + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Activate")); + + bool disableGlobalPlanning = m_session->exerciseId() == 0 && m_proxyModel->rowCount() != 0; + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, !disableGlobalPlanning); } void FrequencyPlanningDialog::onActivateDeactivatePlanningClicked() -{ - if (QMessageBox::question(this, tr("Frequency Planning"), tr("Are you sure you want to switch the active frequency planning?"), - QMessageBox::StandardButtons(QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No)) - == QMessageBox::StandardButton::No) - return; +{ + if (QMessageBox::question( + this, tr("Frequency Planning"), tr("Are you sure you want to switch the active frequency planning?"), + QMessageBox::StandardButtons(QMessageBox::StandardButton::Yes | QMessageBox::StandardButton::No)) == + QMessageBox::StandardButton::No) + return; - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - int32_t planningId = m_model->data(currentIndex, Qt::UserRole).value().id(); + int32_t planningId = m_model->data(currentIndex, Qt::UserRole).value().id(); - bool isActive = planningId == m_activePlanning.frequencyPlanningId(); - if (!isActive) - { - ModifyActiveFrequencyPlanningRequest request(m_session->exerciseId(), planningId); - - m_requestHelper->startSingleRequest([this, request]() + bool isActive = planningId == m_activePlanning.frequencyPlanningId(); + if (!isActive) { - return m_avmFtc->modifyActiveFrequencyPlanningRequest(request, this); - }); - } - else - { - RemoveActiveFrequencyPlanningRequest request(m_session->exerciseId()); + ModifyActiveFrequencyPlanningRequest request(m_session->exerciseId(), planningId); - m_requestHelper->startSingleRequest([this, request]() + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->modifyActiveFrequencyPlanningRequest(request, this); }); + } + else { - return m_avmFtc->removeActiveFrequencyPlanningRequest(request, this); - }); - } + RemoveActiveFrequencyPlanningRequest request(m_session->exerciseId()); + + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->removeActiveFrequencyPlanningRequest(request, this); }); + } } -void FrequencyPlanningDialog::showEditDialog(const FrequencyPlanning &planning) +void FrequencyPlanningDialog::showEditDialog(const FrequencyPlanning& planning) { - QString widgetIdentifier(QStringLiteral("FrequencyPlanning%1").arg(QString::number(planning.id()))); - if (m_copy) - widgetIdentifier.append(QStringLiteral("Copy")); + QString widgetIdentifier(QStringLiteral("FrequencyPlanning%1").arg(QString::number(planning.id()))); + if (m_copy) + widgetIdentifier.append(QStringLiteral("Copy")); - if (baseLayoutWidget()->focusTab(menuGroup(), widgetIdentifier, LtsWidgets::LayoutArea::eDialogTab)) - return; - EditFrequencyPlanningDialog *dlg = new EditFrequencyPlanningDialog(m_session, m_menuGroup, widgetIdentifier, planning, m_copy, m_avmDtc, m_avmFtc, m_ppmDtc, m_ismDtc, m_exmDtc, this); - connect(dlg, &EditFrequencyPlanningDialog::aboutToCloseMe, this , [this](int planningId) - { - if (planningId <= 0 || !m_editDlgMap.contains(planningId)) - return; - m_editDlgMap.remove(planningId); - }); + if (baseLayoutWidget()->focusTab(menuGroup(), widgetIdentifier, LtsWidgets::LayoutArea::eDialogTab)) + return; + EditFrequencyPlanningDialog* dlg = + new EditFrequencyPlanningDialog(m_session, m_menuGroup, widgetIdentifier, planning, m_copy, m_avmDtc, m_avmFtc, + m_ppmDtc, m_ismDtc, m_exmDtc, this); + connect(dlg, &EditFrequencyPlanningDialog::aboutToCloseMe, this, [this](int planningId) { + if (planningId <= 0 || !m_editDlgMap.contains(planningId)) + return; + m_editDlgMap.remove(planningId); + }); + addDialog(dlg, m_menuGroup, widgetIdentifier); - addDialog(dlg, m_menuGroup, widgetIdentifier); - - if (!m_copy) - { - m_editDlgMap.insert(planning.id(), dlg); - } + if (!m_copy) + { + m_editDlgMap.insert(planning.id(), dlg); + } } -void FrequencyPlanningDialog::onActiveFrequencyPlanningChanged(const ActiveFrequencyPlanning &data, DataModification modType) +void FrequencyPlanningDialog::onActiveFrequencyPlanningChanged(const ActiveFrequencyPlanning& data, + DataModification modType) { - if (data.exerciseId() != m_session->exerciseId()) - return; + if (data.exerciseId() != m_session->exerciseId()) + return; - if (modType == DataModification::eRemoved) - unsetActiveFrequencyPlanning(); - else - setActiveFrequencyPlanning(data); + if (modType == DataModification::eRemoved) + unsetActiveFrequencyPlanning(); + else + setActiveFrequencyPlanning(data); } void FrequencyPlanningDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dataView->treeView() ); + LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); } - void FrequencyPlanningDialog::onExportButtonClicked() { - QByteArray byteArray = m_model->modelToJson(); + QByteArray byteArray = m_model->modelToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void FrequencyPlanningDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - if (m_model->rowCount() > 0) - { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Only available if the list is empty."), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - return; - } + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + if (m_model->rowCount() > 0) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available if the list is empty."), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + return; + } - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - const QVector requests = m_model->jsonToFrequencyPlanningVector(content); - for (const auto &request : requests) - { - m_requestHelper->startSingleRequest([this, request]() + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning))) { - return m_avmFtc->modifyFrequencyPlanningRequest(request, this); - }); - } - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + const QVector requests = m_model->jsonToFrequencyPlanningVector(content); + for (const auto& request : requests) + { + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->modifyFrequencyPlanningRequest(request, this); }); + } + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + } } - } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.h old mode 100755 new mode 100644 index bd5ccd1b9..bd1d9d5cf --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog.h @@ -1,14 +1,12 @@ - #pragma once -#include - -#include #include -#include +#include #include +#include +#include #include namespace Ui @@ -27,7 +25,7 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace InfrastructureManagement { @@ -35,7 +33,7 @@ namespace Interface { class Dtc; } -} +} // namespace InfrastructureManagement namespace ExerciseManagement { @@ -43,7 +41,7 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace LtsSession { @@ -60,71 +58,70 @@ class FrequencyPlanningDialogModel; class FrequencyPlanningDialogProxyModel; class EditFrequencyPlanningDialog; -class FrequencyPlanningDialog - : public LtsWidgets::LtsDialog - , protected Interface::Ftc::ModifyFrequencyPlanningReplyHandler - , protected Interface::Ftc::RemoveFrequencyPlanningReplyHandler - , protected Interface::Ftc::ModifyActiveFrequencyPlanningReplyHandler - , protected Interface::Ftc::RemoveActiveFrequencyPlanningReplyHandler +class FrequencyPlanningDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::ModifyFrequencyPlanningReplyHandler, + protected Interface::Ftc::RemoveFrequencyPlanningReplyHandler, + protected Interface::Ftc::ModifyActiveFrequencyPlanningReplyHandler, + protected Interface::Ftc::RemoveActiveFrequencyPlanningReplyHandler { - Q_OBJECT -public: - explicit FrequencyPlanningDialog(LtsSession::LtsSession *session, const QString &menuGroup, QWidget *parent = nullptr); - ~FrequencyPlanningDialog(); + Q_OBJECT + public: + explicit FrequencyPlanningDialog(LtsSession::LtsSession* session, const QString& menuGroup, + QWidget* parent = nullptr); + ~FrequencyPlanningDialog(); - bool init(const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &ismDtc, - ExerciseManagement::Interface::Dtc *exmDtc); + bool init(const std::shared_ptr& avmDtc, const std::shared_ptr& avmFtc, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& ismDtc, + ExerciseManagement::Interface::Dtc* exmDtc); - void onModifyFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) override final; - void onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) override final; - void onRemoveActiveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) override final; - void onModifyActiveFrequencyPlanningReply(const Core::FunctionReplyObject &replyObject) override final; + void onModifyFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) override final; + void onRemoveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) override final; + void onRemoveActiveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) override final; + void onModifyActiveFrequencyPlanningReply(const Core::FunctionReplyObject& replyObject) override final; -private Q_SLOTS: - void onAddClicked(); - void onEditClicked(); - void onRemoveClicked(); - void onSelectionChanged(); - void onActivateDeactivatePlanningClicked(); - void showEditDialog(const FrequencyPlanning &planning); - void onActiveFrequencyPlanningChanged(const ActiveFrequencyPlanning &data, DataModification modType); - void onFrequencyPlanningStatusChanged(const FrequencyPlanningStatus &data, DataModification modType); - void onPrint(); - void onExportButtonClicked(); - void onImportButtonClicked(); -signals: - void aboutToCloseMe(int); + private Q_SLOTS: + void onAddClicked(); + void onEditClicked(); + void onRemoveClicked(); + void onSelectionChanged(); + void onActivateDeactivatePlanningClicked(); + void showEditDialog(const FrequencyPlanning& planning); + void onActiveFrequencyPlanningChanged(const ActiveFrequencyPlanning& data, DataModification modType); + void onFrequencyPlanningStatusChanged(const FrequencyPlanningStatus& data, DataModification modType); + void onPrint(); + void onExportButtonClicked(); + void onImportButtonClicked(); + signals: + void aboutToCloseMe(int); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void unsetActiveFrequencyPlanning(); + void setActiveFrequencyPlanning(const ActiveFrequencyPlanning& activePlanning); + void setButtonSetActivePlanningEnabled(); + static void setBackgroundColor(QWidget* w, Qt::GlobalColor color, bool bSetColor); + void setStatus(const QString& statusText, const QString& requester, qint64 timeStampMsecs, + TransmissionReason reason = TransmissionReason_def::TR_Unknown, Qt::GlobalColor color = Qt::black); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void unsetActiveFrequencyPlanning(); - void setActiveFrequencyPlanning(const ActiveFrequencyPlanning &activePlanning); - void setButtonSetActivePlanningEnabled(); - static void setBackgroundColor(QWidget *w, Qt::GlobalColor color, bool bSetColor); - void setStatus(const QString &statusText, const QString &requester, qint64 timeStampMsecs, TransmissionReason reason = TransmissionReason_def::TR_Unknown, Qt::GlobalColor color = Qt::black); - void tableColumnOrganiserSetting() override; - -private: - Ui::FrequencyPlanningDialog *m_ui; - QString m_menuGroup; - bool m_copy; - LtsSession::LtsSession *m_session; - FrequencyPlanningDialogModel *m_model; - FrequencyPlanningDialogProxyModel *m_proxyModel; - LtsUtils::RequestHelper *m_requestHelper; - ActiveFrequencyPlanning m_activePlanning; - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_ismDtc; - ExerciseManagement::Interface::Dtc *m_exmDtc; - std::shared_ptr m_flmGui; - QMap m_editDlgMap; - int m_activeFrequencyPlanningStatus; -}; -} + private: + Ui::FrequencyPlanningDialog* m_ui; + QString m_menuGroup; + bool m_copy; + LtsSession::LtsSession* m_session; + FrequencyPlanningDialogModel* m_model; + FrequencyPlanningDialogProxyModel* m_proxyModel; + LtsUtils::RequestHelper* m_requestHelper; + ActiveFrequencyPlanning m_activePlanning; + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_ismDtc; + ExerciseManagement::Interface::Dtc* m_exmDtc; + std::shared_ptr m_flmGui; + QMap m_editDlgMap; + int m_activeFrequencyPlanningStatus; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.cpp old mode 100755 new mode 100644 index 4f5ff2502..71cf585ab --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.cpp @@ -1,197 +1,183 @@ - #include "avm_frequency_planning_dialog_model.h" -#include -#include +#include #include -#include #include +#include +#include namespace AudioVideoManagement { -FrequencyPlanningDialogModel::FrequencyPlanningDialogModel(int32_t exerciseId, QObject *parent) - : LtsAbstractTableModel( +FrequencyPlanningDialogModel::FrequencyPlanningDialogModel(int32_t exerciseId, QObject* parent) + : LtsAbstractTableModel({tr("Name"), tr("Date"), tr("Set"), tr("Active")}, parent), + m_exerciseId(exerciseId) { - tr("Name"), - tr("Date"), - tr("Set"), - tr("Active") - }, parent) - , m_exerciseId(exerciseId) -{ - DEBUG_LOG(m_logger) << "---FrequencyPlanningDialogModel() "; + DEBUG_LOG(m_logger) << "---FrequencyPlanningDialogModel() "; } -QVariant FrequencyPlanningDialogModel::data(const QModelIndex &index, int role) const +QVariant FrequencyPlanningDialogModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) + if ((role != Qt::DisplayRole && role != Qt::UserRole) || !indexIsValid(index)) + return QVariant(); + + const FrequencyPlanning& planning = m_vecData.at(index.row()); + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case NAME: + return QString::fromStdString(planning.name()); + case DATE: + return QDateTime::fromMSecsSinceEpoch(planning.date()); + case SET: { + const FrequencySet frequencySet = m_avmDtc->frequencySet(planning.frequencySetId()); + return QString::fromStdString(frequencySet.name()); + } + case ACTIVE: + return planning.id() == m_activePlanningId ? tr("Active") : QStringLiteral("-"); + } + } + else if (role == Qt::UserRole) + return QVariant::fromValue(planning); + return QVariant(); - - const FrequencyPlanning &planning = m_vecData.at(index.row()); - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case NAME: - return QString::fromStdString(planning.name()); - case DATE: - return QDateTime::fromMSecsSinceEpoch(planning.date()); - case SET: - { - const FrequencySet frequencySet = m_avmDtc->frequencySet(planning.frequencySetId()); - return QString::fromStdString(frequencySet.name()); - } - case ACTIVE: - return planning.id() == m_activePlanningId ? tr("Active") : QStringLiteral("-"); - } - } - else if (role == Qt::UserRole) - return QVariant::fromValue(planning); - - return QVariant(); } -bool FrequencyPlanningDialogModel::init(const std::shared_ptr &avmDtc) +bool FrequencyPlanningDialogModel::init(const std::shared_ptr& avmDtc) { - m_avmDtc = avmDtc; + m_avmDtc = avmDtc; - m_frequencySets = m_avmDtc->frequencySets(); + m_frequencySets = m_avmDtc->frequencySets(); - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::frequencyPlanningChanged, - this, &FrequencyPlanningDialogModel::onFrequencyPlanningChanged); + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::frequencyPlanningChanged, this, + &FrequencyPlanningDialogModel::onFrequencyPlanningChanged); - m_avmDtc->frequencyPlannings([this](const FrequencyPlanning & p) - { - if (p.exerciseId().is_set() && p.exerciseId().get() == m_exerciseId) - insertRow(p); - }); + m_avmDtc->frequencyPlannings([this](const FrequencyPlanning& p) { + if (p.exerciseId().is_set() && p.exerciseId().get() == m_exerciseId) + insertRow(p); + }); - return true; + return true; } -FrequencySet FrequencyPlanningDialogModel::frequencySetByIndex(const QModelIndex &index) const +FrequencySet FrequencyPlanningDialogModel::frequencySetByIndex(const QModelIndex& index) const { - if (!indexIsValid(index)) - return FrequencySet(); + if (!indexIsValid(index)) + return FrequencySet(); - return m_frequencySets.value(m_vecData.at(index.row()).frequencySetId()); + return m_frequencySets.value(m_vecData.at(index.row()).frequencySetId()); } -void FrequencyPlanningDialogModel::onFrequencyPlanningChanged(const FrequencyPlanning &data, DataModification modType) +void FrequencyPlanningDialogModel::onFrequencyPlanningChanged(const FrequencyPlanning& data, DataModification modType) { - INFO_LOG(m_logger) << "onFrequencyPlanningChanged " - << " data.exerciseId()" << data.exerciseId() - << " m_exerciseId=" << m_exerciseId; - if ((data.exerciseId().is_set() && data.exerciseId().get() != m_exerciseId) - || (!data.exerciseId().is_set() && m_exerciseId != 0)) - return; + INFO_LOG(m_logger) << "onFrequencyPlanningChanged " + << " data.exerciseId()" << data.exerciseId() << " m_exerciseId=" << m_exerciseId; + if ((data.exerciseId().is_set() && data.exerciseId().get() != m_exerciseId) || + (!data.exerciseId().is_set() && m_exerciseId != 0)) + return; - onDataChanged(data, modType); + onDataChanged(data, modType); } QByteArray FrequencyPlanningDialogModel::modelToJson() { - QJsonObject obj; - QJsonArray arr; - QJsonArray arrData; + QJsonObject obj; + QJsonArray arr; + QJsonArray arrData; - for (int row = 0; row < rowCount(); row++) - { - DEBUG_LOG(m_logger) << "row =" << ": " << row; - QJsonObject inner; - const FrequencyPlanning &planning = m_vecData.at(row); - - inner[QStringLiteral("id")] = planning.id(); - inner[QStringLiteral("name")] = QString::fromStdString(planning.name()); - inner[QStringLiteral("dateOfCreation")] = planning.date(); - if(planning.exerciseId().is_set()) + for (int row = 0; row < rowCount(); row++) { - inner[QStringLiteral("exerciseId")] = planning.exerciseId().get(); + DEBUG_LOG(m_logger) << "row =" << ": " << row; + QJsonObject inner; + const FrequencyPlanning& planning = m_vecData.at(row); + + inner[QStringLiteral("id")] = planning.id(); + inner[QStringLiteral("name")] = QString::fromStdString(planning.name()); + inner[QStringLiteral("dateOfCreation")] = planning.date(); + if (planning.exerciseId().is_set()) + { + inner[QStringLiteral("exerciseId")] = planning.exerciseId().get(); + } + inner[QStringLiteral("frequencySetId")] = planning.frequencySetId(); + + arrData = {}; + for (const FrequencyPlanningData& planningData : planning.data()) + { + QJsonObject innerData; + innerData[QStringLiteral("cnrConfigId")] = planningData.cnrConfigId(); + innerData[QStringLiteral("properties")] = QString::fromStdString(planningData.properties()); + arrData += innerData; + } + inner[QStringLiteral("data")] = arrData; + arr += inner; } - inner[QStringLiteral("frequencySetId")] = planning.frequencySetId(); - - arrData = {}; - for (const FrequencyPlanningData &planningData : planning.data()) - { - QJsonObject innerData; - innerData[QStringLiteral("cnrConfigId")] = planningData.cnrConfigId(); - innerData[QStringLiteral("properties")] = QString::fromStdString(planningData.properties()); - arrData += innerData; - } - inner[QStringLiteral("data")] = arrData; - arr += inner; - } - - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning); - obj[QStringLiteral("FrequencyPlanning")] = arr; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMFrequencyPlanning); + obj[QStringLiteral("FrequencyPlanning")] = arr; + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -QVector FrequencyPlanningDialogModel::jsonToFrequencyPlanningVector(const QByteArray &content) +QVector +FrequencyPlanningDialogModel::jsonToFrequencyPlanningVector(const QByteArray& content) { - QVector result; - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject toplevelObj(doc.object()); - const QJsonArray arr(toplevelObj.value(QStringLiteral("FrequencyPlanning")).toArray()); - for (const auto &ele : arr) - { - const QJsonObject obj(ele.toObject()); - ModifyFrequencyPlanningRequest frequencyPlanning; - frequencyPlanning.date(obj[QStringLiteral("dateOfCreation")].toDouble()); - frequencyPlanning.exerciseId(m_exerciseId); - frequencyPlanning.frequencySetId(obj[QStringLiteral("frequencySetId")].toInt()); - frequencyPlanning.id(0); - frequencyPlanning.name(obj[QStringLiteral("name")].toString().toStdString()); - - - const QJsonArray arrData = (obj.value(QStringLiteral("data")).toArray()); - frequencyPlanning.data().reserve(arrData.size()); - for (const auto &eleData : arrData) + QVector result; + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject toplevelObj(doc.object()); + const QJsonArray arr(toplevelObj.value(QStringLiteral("FrequencyPlanning")).toArray()); + for (const auto& ele : arr) { - const QJsonObject objData(eleData.toObject()); - FrequencyPlanningData frequencyPlanningData; - frequencyPlanningData.cnrConfigId(objData[QStringLiteral("cnrConfigId")].toInt()); - frequencyPlanningData.properties(objData[QStringLiteral("properties")].toString().toStdString()); - frequencyPlanning.data().push_back(frequencyPlanningData); + const QJsonObject obj(ele.toObject()); + ModifyFrequencyPlanningRequest frequencyPlanning; + frequencyPlanning.date(obj[QStringLiteral("dateOfCreation")].toDouble()); + frequencyPlanning.exerciseId(m_exerciseId); + frequencyPlanning.frequencySetId(obj[QStringLiteral("frequencySetId")].toInt()); + frequencyPlanning.id(0); + frequencyPlanning.name(obj[QStringLiteral("name")].toString().toStdString()); + + const QJsonArray arrData = (obj.value(QStringLiteral("data")).toArray()); + frequencyPlanning.data().reserve(arrData.size()); + for (const auto& eleData : arrData) + { + const QJsonObject objData(eleData.toObject()); + FrequencyPlanningData frequencyPlanningData; + frequencyPlanningData.cnrConfigId(objData[QStringLiteral("cnrConfigId")].toInt()); + frequencyPlanningData.properties(objData[QStringLiteral("properties")].toString().toStdString()); + frequencyPlanning.data().push_back(frequencyPlanningData); + } + + result.push_back(std::move(frequencyPlanning)); } - - - result.push_back(std::move(frequencyPlanning)); - } - return result; + return result; } -void FrequencyPlanningDialogProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void FrequencyPlanningDialogProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } -bool FrequencyPlanningDialogProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +bool FrequencyPlanningDialogProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case FrequencyPlanningDialogModel::DATE: + return dataLeft.date() < dataRight.date(); + case FrequencyPlanningDialogModel::NAME: + case FrequencyPlanningDialogModel::SET: + case FrequencyPlanningDialogModel::ACTIVE: + case FrequencyPlanningDialogModel::COUNT: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case FrequencyPlanningDialogModel::DATE: - return dataLeft.date() < dataRight.date(); - case FrequencyPlanningDialogModel::NAME: - case FrequencyPlanningDialogModel::SET: - case FrequencyPlanningDialogModel::ACTIVE: - case FrequencyPlanningDialogModel::COUNT: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.h old mode 100755 new mode 100644 index 86a4e832d..fe3d37cc0 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_dialog_model.h @@ -1,73 +1,71 @@ - #pragma once +#include +#include #include #include - -#include -#include #include #include namespace AudioVideoManagement { -class FrequencyPlanningDialogModel final - : public LtsWidgets::LtsAbstractTableModel +class FrequencyPlanningDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - NAME, - DATE, - SET, - ACTIVE, - COUNT - }; + public: + enum Columns { NAME, DATE, SET, ACTIVE, COUNT }; - explicit FrequencyPlanningDialogModel(int32_t exerciseId, QObject *parent = nullptr); + explicit FrequencyPlanningDialogModel(int32_t exerciseId, QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role) const override final; + QVariant data(const QModelIndex& index, int role) const override final; - bool init(const std::shared_ptr &avmDtc); + bool init(const std::shared_ptr& avmDtc); - void setActivePlanning(int activePlanningId) { m_activePlanningId = activePlanningId; } - void unsetActivePlanning() { m_activePlanningId.reset(); } + void setActivePlanning(int activePlanningId) + { + m_activePlanningId = activePlanningId; + } - FrequencySet frequencySetByIndex(const QModelIndex &index) const; - QByteArray modelToJson(); - QVector jsonToFrequencyPlanningVector(const QByteArray &content); + void unsetActivePlanning() + { + m_activePlanningId.reset(); + } -private Q_SLOTS: - void onFrequencyPlanningChanged(const FrequencyPlanning &data, DataModification modType); + FrequencySet frequencySetByIndex(const QModelIndex& index) const; + QByteArray modelToJson(); + QVector jsonToFrequencyPlanningVector(const QByteArray& content); -private: + private Q_SLOTS: + void onFrequencyPlanningChanged(const FrequencyPlanning& data, DataModification modType); -NGL::INGLLogger &m_logger; - int32_t m_exerciseId; - boost::optional m_activePlanningId; - std::shared_ptr m_avmDtc; + private: + NGL::INGLLogger& m_logger; + int32_t m_exerciseId; + boost::optional m_activePlanningId; + std::shared_ptr m_avmDtc; - QMap m_frequencySets; + QMap m_frequencySets; - friend class FrequencyPlanningDialogProxyModel; -}; + friend class FrequencyPlanningDialogProxyModel; +}; class FrequencyPlanningDialogProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - FrequencyPlanningDialogModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + FrequencyPlanningDialogModel* m_sourceModel = nullptr; }; -} +} // namespace AudioVideoManagement Q_DECLARE_METATYPE(AudioVideoManagement::FrequencyPlanning) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_widget.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_widget.cpp old mode 100755 new mode 100644 index 0c881c624..bd0f38c34 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_widget.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_frequency_planning_widget.cpp @@ -1,238 +1,231 @@ - #include "avm_frequency_planning_widget.h" -#include -#include "ui_avm_frequency_planning_widget.h" + #include "avm_edit_frequency_planning_set_resource_dialog.h" #include "avm_radio_specifica_hf_widget.h" -#include "avm_radio_specifica_vhf_widget.h" #include "avm_radio_specifica_uhf_widget.h" +#include "avm_radio_specifica_vhf_widget.h" +#include "ui_avm_frequency_planning_widget.h" #include #include - +#include #include namespace AudioVideoManagement { -FrequencyPlanningWidget::FrequencyPlanningWidget(const std::shared_ptr &avmDtc, QSet &allocatedDataSets, QWidget *parent) : QWidget(parent) - , m_ui(new Ui::FrequencyPlanningWidget) - , m_assignedFrequencySetDataIds(allocatedDataSets) - , m_avmDtc(avmDtc), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_ui->setupUi(this); +FrequencyPlanningWidget::FrequencyPlanningWidget(const std::shared_ptr& avmDtc, + QSet& allocatedDataSets, QWidget* parent) + : QWidget(parent), m_ui(new Ui::FrequencyPlanningWidget), m_assignedFrequencySetDataIds(allocatedDataSets), + m_avmDtc(avmDtc), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + m_ui->setupUi(this); - m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::VHF), FrequencyBand_def::VHF); - m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::HF), FrequencyBand_def::HF); - m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::UHF), FrequencyBand_def::UHF); + m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::VHF), FrequencyBand_def::VHF); + m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::HF), FrequencyBand_def::HF); + m_ui->cbFrequencyBand->addItem(toString(FrequencyBand_def::UHF), FrequencyBand_def::UHF); - connect(m_ui->leName, &QLineEdit::textChanged, - this, &FrequencyPlanningWidget::onNameChanged); - connect(m_ui->cbFrequencyBand, qOverload(&QComboBox::currentIndexChanged), - this, &FrequencyPlanningWidget::onFrequencyBandChanged); - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, - this, &FrequencyPlanningWidget::onCnrConfigChanged); + connect(m_ui->leName, &QLineEdit::textChanged, this, &FrequencyPlanningWidget::onNameChanged); + connect(m_ui->cbFrequencyBand, qOverload(&QComboBox::currentIndexChanged), this, + &FrequencyPlanningWidget::onFrequencyBandChanged); + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, this, + &FrequencyPlanningWidget::onCnrConfigChanged); } -bool FrequencyPlanningWidget::init(LtsSession::LtsSession *session, RadioCircuit *data, const CnrConfig &cnrConfigId, int frequencySetId, FrequencyBand ft) +bool FrequencyPlanningWidget::init(LtsSession::LtsSession* session, RadioCircuit* data, const CnrConfig& cnrConfigId, + int frequencySetId, FrequencyBand ft) { - m_frequencySetId = frequencySetId; - m_cnrConfigId = cnrConfigId.id(); - m_hasParty = cnrConfigId.partyId() != 0; + m_frequencySetId = frequencySetId; + m_cnrConfigId = cnrConfigId.id(); + m_hasParty = cnrConfigId.partyId() != 0; - if (!session->getForeignGuiInterface(m_ismCbxIfc)) - return false; - - m_ui->cbFrequencyBand->setCurrentIndex(m_ui->cbFrequencyBand->findData(ft.underlying())); - m_ui->cbFrequencyBand->setVisible(false); - m_ui->lbxFrequencyBand->setVisible(false); - - switch (ft.underlying()) - { - - case FrequencyBand_def::HF: - { - createHFWidget(data); - break; - } - case FrequencyBand_def::UHF: - { - createUHFWidget(data); - break; - } - case FrequencyBand_def::VHF: - { - createVHFWidget(data); - break; - } - default: - { - ft = data ? data->freqBand : FrequencyBand::VHF; - m_isRelay = true; + if (!session->getForeignGuiInterface(m_ismCbxIfc)) + return false; m_ui->cbFrequencyBand->setCurrentIndex(m_ui->cbFrequencyBand->findData(ft.underlying())); - m_ui->cbFrequencyBand->setVisible(true); - m_ui->lbxFrequencyBand->setVisible(true); + m_ui->cbFrequencyBand->setVisible(false); + m_ui->lbxFrequencyBand->setVisible(false); + switch (ft.underlying()) { - case FrequencyBand_def::HF: - createHFWidget(data); - break; - case FrequencyBand_def::UHF: - createUHFWidget(data); - break; - case FrequencyBand_def::VHF: - createVHFWidget(data); - break; - default: - break; - break; + + case FrequencyBand_def::HF: { + createHFWidget(data); + break; + } + case FrequencyBand_def::UHF: { + createUHFWidget(data); + break; + } + case FrequencyBand_def::VHF: { + createVHFWidget(data); + break; + } + default: { + ft = data ? data->freqBand : FrequencyBand::VHF; + m_isRelay = true; + + m_ui->cbFrequencyBand->setCurrentIndex(m_ui->cbFrequencyBand->findData(ft.underlying())); + m_ui->cbFrequencyBand->setVisible(true); + m_ui->lbxFrequencyBand->setVisible(true); + switch (ft.underlying()) + { + case FrequencyBand_def::HF: + createHFWidget(data); + break; + case FrequencyBand_def::UHF: + createUHFWidget(data); + break; + case FrequencyBand_def::VHF: + createVHFWidget(data); + break; + default: + break; + break; + } + } } - } - } - m_ismCbxIfc->fillRadioStationsComboBox(m_ui->cbRadioStation, ft.underlying()); - if (m_hasParty && !m_isRelay) - m_ui->cbRadioStation->addItem(tr("Automatic"), 0); - if (!data) - m_ui->leName->clear(); - else - { - m_ui->leName->setText(data->name); - m_ui->cbRadioStation->setCurrentIndex(m_ui->cbRadioStation->findData(data->radioStationId)); - } + m_ismCbxIfc->fillRadioStationsComboBox(m_ui->cbRadioStation, ft.underlying()); + if (m_hasParty && !m_isRelay) + m_ui->cbRadioStation->addItem(tr("Automatic"), 0); + if (!data) + m_ui->leName->clear(); + else + { + m_ui->leName->setText(data->name); + m_ui->cbRadioStation->setCurrentIndex(m_ui->cbRadioStation->findData(data->radioStationId)); + } - adjustSize(); - return true; + adjustSize(); + return true; } void FrequencyPlanningWidget::setNameDisabled(bool disable) { - m_ui->leName->setDisabled(disable); + m_ui->leName->setDisabled(disable); } -void FrequencyPlanningWidget::setName(const QString &name) +void FrequencyPlanningWidget::setName(const QString& name) { - m_ui->leName->setText(name); + m_ui->leName->setText(name); } - void FrequencyPlanningWidget::setRelaisRestrictions(bool restrict) { - if (restrict) - { - m_ui->cbFrequencyBand->setCurrentIndex(m_ui->cbFrequencyBand->findData(FrequencyBand_def::VHF)); - m_ui->cbFrequencyBand->setEnabled(false); - } - else - { - m_ui->cbFrequencyBand->setEnabled(true); - } - + if (restrict) + { + m_ui->cbFrequencyBand->setCurrentIndex(m_ui->cbFrequencyBand->findData(FrequencyBand_def::VHF)); + m_ui->cbFrequencyBand->setEnabled(false); + } + else + { + m_ui->cbFrequencyBand->setEnabled(true); + } } QJsonObject FrequencyPlanningWidget::toJson() const { - return frequencyPlanningJson(m_radioSpecificaWidget->toJson(), - m_ui->leName->text(), - static_cast(m_ui->cbFrequencyBand->currentData().toInt()), - m_ui->cbRadioStation->currentData().toInt()); + return frequencyPlanningJson(m_radioSpecificaWidget->toJson(), m_ui->leName->text(), + static_cast(m_ui->cbFrequencyBand->currentData().toInt()), + m_ui->cbRadioStation->currentData().toInt()); } -QVector > > FrequencyPlanningWidget::requirements() const +QVector>> FrequencyPlanningWidget::requirements() const { - return m_radioSpecificaWidget->requirements(); + return m_radioSpecificaWidget->requirements(); } FrequencyPlanningWidget::~FrequencyPlanningWidget() { - if(m_radioSpecificaWidget) - { - delete m_radioSpecificaWidget; - m_radioSpecificaWidget = nullptr; - } - delete m_ui; + if (m_radioSpecificaWidget) + { + delete m_radioSpecificaWidget; + m_radioSpecificaWidget = nullptr; + } + delete m_ui; } void FrequencyPlanningWidget::onFrequencyBandChanged() { - switch (m_ui->cbFrequencyBand->currentData().toInt()) - { - case FrequencyBand_def::HF: - createHFWidget(); - break; - case FrequencyBand_def::UHF: - createUHFWidget(); - break; - case FrequencyBand_def::VHF: - createVHFWidget(); - break; - } + switch (m_ui->cbFrequencyBand->currentData().toInt()) + { + case FrequencyBand_def::HF: + createHFWidget(); + break; + case FrequencyBand_def::UHF: + createUHFWidget(); + break; + case FrequencyBand_def::VHF: + createVHFWidget(); + break; + } - m_ui->cbRadioStation->clear(); - m_ismCbxIfc->fillRadioStationsComboBox(m_ui->cbRadioStation, m_ui->cbFrequencyBand->currentData().toInt()); - if(m_hasParty && !m_isRelay) - m_ui->cbRadioStation->addItem(tr("Automatic"), 0); + m_ui->cbRadioStation->clear(); + m_ismCbxIfc->fillRadioStationsComboBox(m_ui->cbRadioStation, m_ui->cbFrequencyBand->currentData().toInt()); + if (m_hasParty && !m_isRelay) + m_ui->cbRadioStation->addItem(tr("Automatic"), 0); - if(m_radioSpecificaWidget) - m_ui->gridLayout->addWidget(m_radioSpecificaWidget,5,0,1,2); - adjustSize(); + if (m_radioSpecificaWidget) + m_ui->gridLayout->addWidget(m_radioSpecificaWidget, 5, 0, 1, 2); + adjustSize(); } void FrequencyPlanningWidget::createHFWidget(RadioCircuit* circuit) { - if(m_radioSpecificaWidget) - { - delete m_radioSpecificaWidget; - m_radioSpecificaWidget = nullptr; - } - m_radioSpecificaWidget = new RadioSpecificaHfWidget(m_ui->radioSpecificaWidget); - if(!circuit) - return; - RadioCircuitHF *dataHf = dynamic_cast(circuit); - m_radioSpecificaWidget->setValues(dataHf); + if (m_radioSpecificaWidget) + { + delete m_radioSpecificaWidget; + m_radioSpecificaWidget = nullptr; + } + m_radioSpecificaWidget = new RadioSpecificaHfWidget(m_ui->radioSpecificaWidget); + if (!circuit) + return; + RadioCircuitHF* dataHf = dynamic_cast(circuit); + m_radioSpecificaWidget->setValues(dataHf); } void FrequencyPlanningWidget::createUHFWidget(RadioCircuit* circuit) { - if(m_radioSpecificaWidget) - { - delete m_radioSpecificaWidget; - m_radioSpecificaWidget = nullptr; - } - m_radioSpecificaWidget = new RadioSpecificaUhfWidget(m_ui->radioSpecificaWidget); - if(!circuit) - return; - RadioCircuitUHF* dataUhf = dynamic_cast(circuit); - m_radioSpecificaWidget->setValues(dataUhf); + if (m_radioSpecificaWidget) + { + delete m_radioSpecificaWidget; + m_radioSpecificaWidget = nullptr; + } + m_radioSpecificaWidget = new RadioSpecificaUhfWidget(m_ui->radioSpecificaWidget); + if (!circuit) + return; + RadioCircuitUHF* dataUhf = dynamic_cast(circuit); + m_radioSpecificaWidget->setValues(dataUhf); } void FrequencyPlanningWidget::createVHFWidget(RadioCircuit* circuit) { - if(m_radioSpecificaWidget) - { - delete m_radioSpecificaWidget; - m_radioSpecificaWidget = nullptr; - } - auto *widget = new RadioSpecificaVhfWidget(m_assignedFrequencySetDataIds, m_ui->radioSpecificaWidget); - widget->init(m_frequencySetId, m_avmDtc, m_cnrConfigId); - m_radioSpecificaWidget = widget; + if (m_radioSpecificaWidget) + { + delete m_radioSpecificaWidget; + m_radioSpecificaWidget = nullptr; + } + auto* widget = new RadioSpecificaVhfWidget(m_assignedFrequencySetDataIds, m_ui->radioSpecificaWidget); + widget->init(m_frequencySetId, m_avmDtc, m_cnrConfigId); + m_radioSpecificaWidget = widget; - if(!circuit) - return; - RadioCircuitVHF* dataVhf = dynamic_cast(circuit); - m_radioSpecificaWidget->setValues(dataVhf); + if (!circuit) + return; + RadioCircuitVHF* dataVhf = dynamic_cast(circuit); + m_radioSpecificaWidget->setValues(dataVhf); } -void FrequencyPlanningWidget::onCnrConfigChanged(const AudioVideoManagement::CnrConfig &config, DataModification modType) +void FrequencyPlanningWidget::onCnrConfigChanged(const AudioVideoManagement::CnrConfig& config, + DataModification modType) { - Q_UNUSED(modType); - if (m_cnrConfigId == config.id()) - { - m_ui->leName->setText(QString::fromStdString(config.radioCircuit())); - } + Q_UNUSED(modType); + if (m_cnrConfigId == config.id()) + { + m_ui->leName->setText(QString::fromStdString(config.radioCircuit())); + } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.cpp old mode 100755 new mode 100644 index 19ba4beda..361c66347 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.cpp @@ -1,70 +1,66 @@ - #include "avm_init_frequency_planning_dialog.h" + #include "ui_avm_init_frequency_planning_dialog.h" + #include #include - namespace AudioVideoManagement { -InitFrequencyPlanningDialog::InitFrequencyPlanningDialog(LtsSession::LtsSession *session, const std::shared_ptr &avmDtc, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel) - , m_ui(new Ui::InitFrequencyPlanningDialog) - , m_dateOfCreation(session->partitionTime()) - , m_session(session) +InitFrequencyPlanningDialog::InitFrequencyPlanningDialog(LtsSession::LtsSession* session, + const std::shared_ptr& avmDtc, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel), m_ui(new Ui::InitFrequencyPlanningDialog), + m_dateOfCreation(session->partitionTime()), m_session(session) { - DEBUG_LOG(m_logger) << "---InitFrequencyPlanningDialog() "; - m_ui->setupUi(this); + DEBUG_LOG(m_logger) << "---InitFrequencyPlanningDialog() "; + m_ui->setupUi(this); - QMap frequencySets = avmDtc->frequencySets(); + QMap frequencySets = avmDtc->frequencySets(); - for (auto it = frequencySets.constBegin(); it != frequencySets.constEnd(); ++it) - m_ui->cbFrequencySets->addItem(QString::fromStdString(it.value().name()), QVariant::fromValue(it.key())); + for (auto it = frequencySets.constBegin(); it != frequencySets.constEnd(); ++it) + m_ui->cbFrequencySets->addItem(QString::fromStdString(it.value().name()), QVariant::fromValue(it.key())); - m_ui->tbTime->setText(DTG::toStringMSec(m_dateOfCreation)); - - connect(m_ui->tbTime, &QToolButton::clicked, this, [this]() - { - m_dateOfCreation = m_session->partitionTime(); m_ui->tbTime->setText(DTG::toStringMSec(m_dateOfCreation)); - }); - m_uiRequirements->addRequirement( { m_ui->lblName, [this]() { return !m_ui->leName->text().isEmpty(); } }); - m_uiRequirements->addRequirement( { m_ui->lblFrequencySets, [this]() { return !m_ui->cbFrequencySets->currentText().isEmpty(); } }); + connect(m_ui->tbTime, &QToolButton::clicked, this, [this]() { + m_dateOfCreation = m_session->partitionTime(); + m_ui->tbTime->setText(DTG::toStringMSec(m_dateOfCreation)); + }); - setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); + m_uiRequirements->addRequirement({m_ui->lblName, [this]() { return !m_ui->leName->text().isEmpty(); }}); + m_uiRequirements->addRequirement( + {m_ui->lblFrequencySets, [this]() { return !m_ui->cbFrequencySets->currentText().isEmpty(); }}); + + setOnlineHelpFilename(QStringLiteral("Situation-Frequency_Planning")); } - InitFrequencyPlanningDialog::~InitFrequencyPlanningDialog() { - delete m_ui; + delete m_ui; } - void InitFrequencyPlanningDialog::retranslate() { - translate(m_ui, tr("New Frequency Planning")); + translate(m_ui, tr("New Frequency Planning")); } - bool InitFrequencyPlanningDialog::apply() { - FrequencyPlanning planning; + FrequencyPlanning planning; - planning.id(0); - if(m_session->exerciseId() != 0) - planning.exerciseId(m_session->exerciseId()); - planning.frequencySetId(m_ui->cbFrequencySets->currentData().toInt()); - planning.name(m_ui->leName->text().toStdString()); - planning.date(m_dateOfCreation); + planning.id(0); + if (m_session->exerciseId() != 0) + planning.exerciseId(m_session->exerciseId()); + planning.frequencySetId(m_ui->cbFrequencySets->currentData().toInt()); + planning.name(m_ui->leName->text().toStdString()); + planning.date(m_dateOfCreation); - emit newInitFrequencyPlanning(planning); + emit newInitFrequencyPlanning(planning); - return true; + return true; } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.h old mode 100755 new mode 100644 index 05db57880..dfac31ffc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_init_frequency_planning_dialog.h @@ -1,12 +1,10 @@ - #pragma once -#include - -#include #include +#include +#include class QCheckBox; @@ -24,23 +22,23 @@ namespace AudioVideoManagement { class InitFrequencyPlanningDialog : public LtsWidgets::LtsDialog { - Q_OBJECT -public: - explicit InitFrequencyPlanningDialog(LtsSession::LtsSession *session, const std::shared_ptr &avmDtc, QWidget *parent); + Q_OBJECT + public: + explicit InitFrequencyPlanningDialog(LtsSession::LtsSession* session, const std::shared_ptr& avmDtc, + QWidget* parent); - ~InitFrequencyPlanningDialog(); + ~InitFrequencyPlanningDialog(); -signals: - void newInitFrequencyPlanning(const FrequencyPlanning &); + signals: + void newInitFrequencyPlanning(const FrequencyPlanning&); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override; - - Ui::InitFrequencyPlanningDialog *m_ui; - qint64 m_dateOfCreation; - LtsSession::LtsSession *m_session; -}; -} + Ui::InitFrequencyPlanningDialog* m_ui; + qint64 m_dateOfCreation; + LtsSession::LtsSession* m_session; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog.h old mode 100755 new mode 100644 index 97864bf33..9bafa3ea2 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog.h @@ -1,11 +1,10 @@ - #pragma once -#include #include #include +#include namespace Ui { @@ -23,7 +22,7 @@ namespace Interface { class Dtc; } -} +} // namespace InfrastructureManagement namespace ExerciseManagement { @@ -31,38 +30,35 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace AudioVideoManagement { class LoadFrequencyPlanningDialogModel; -class LoadFrequencyPlanningDialog - : public LtsWidgets::LtsFramelessDialog +class LoadFrequencyPlanningDialog : public LtsWidgets::LtsFramelessDialog { - Q_OBJECT -public: - explicit LoadFrequencyPlanningDialog(const QByteArray &data, - const FrequencyPlanning &initPlan, - const std::shared_ptr &avmDtc, - const std::shared_ptr &ismDtc, - QWidget *parent = nullptr); + Q_OBJECT + public: + explicit LoadFrequencyPlanningDialog(const QByteArray& data, const FrequencyPlanning& initPlan, + const std::shared_ptr& avmDtc, + const std::shared_ptr& ismDtc, + QWidget* parent = nullptr); - ~LoadFrequencyPlanningDialog(); + ~LoadFrequencyPlanningDialog(); - QVector unassignments() const; - QVector newPlanningData() const; + QVector unassignments() const; + QVector newPlanningData() const; - bool isApplied() const; + bool isApplied() const; -private Q_SLOTS: - void onOk(); + private Q_SLOTS: + void onOk(); -private: - -NGL::INGLLogger &m_logger; - std::unique_ptr m_ui; - LoadFrequencyPlanningDialogModel *m_model; - bool m_isApplied = false; -}; -} + private: + NGL::INGLLogger& m_logger; + std::unique_ptr m_ui; + LoadFrequencyPlanningDialogModel* m_model; + bool m_isApplied = false; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog_model.cpp old mode 100755 new mode 100644 index d2163af5f..ee38dbe33 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/CombatNetRadio/FrequencyPlanning/avm_load_frequency_planning_dialog_model.cpp @@ -1,961 +1,900 @@ - #include "avm_load_frequency_planning_dialog_model.h" -#include -#include -#include #include +#include #include -#include #include -#include - -#include -#include -#include +#include +#include #include - +#include +#include +#include +#include +#include namespace AudioVideoManagement { -void LoadFrequencyPlanningDialogModel::onFrequencyPlanningChanged(const FrequencyPlanning &initPlanning, DataModification dm) +void LoadFrequencyPlanningDialogModel::onFrequencyPlanningChanged(const FrequencyPlanning& initPlanning, + DataModification dm) { - Q_UNUSED(dm) + Q_UNUSED(dm) - - if (initPlanning.exerciseId().is_set() && initPlanning.exerciseId().get() != m_exerciseId) - return; + if (initPlanning.exerciseId().is_set() && initPlanning.exerciseId().get() != m_exerciseId) + return; - - if (m_exerciseId > 0 && initPlanning.exerciseId().is_set() && initPlanning.id() != m_initPlan.id()) - return; - - - + if (m_exerciseId > 0 && initPlanning.exerciseId().is_set() && initPlanning.id() != m_initPlan.id()) + return; - beginResetModel(); - const int rowCount = getRootItem()->childCount(); - for (int r = 0; r < rowCount; ++r) - { - ConfigTreeItem *item = static_cast(getRootItem()->child(r)); - - if(!item) - continue; - ItemData id = item->data().value(); - - if (m_exerciseId == 0 && !initPlanning.exerciseId().is_set()) + beginResetModel(); + const int rowCount = getRootItem()->childCount(); + for (int r = 0; r < rowCount; ++r) { - id.clearRadioCircuit(); - item->setData(QVariant::fromValue(id)); - item->removeAllChildren(); - continue; - } + ConfigTreeItem* item = static_cast(getRootItem()->child(r)); - - - if (m_exerciseId > 0) - { - - if (initPlanning.exerciseId().is_set()) - { - - if (id.cnrConfig.exerciseId().is_set()) + if (!item) + continue; + ItemData id = item->data().value(); + + if (m_exerciseId == 0 && !initPlanning.exerciseId().is_set()) { - id.clearRadioCircuit(); - item->setData(QVariant::fromValue(id)); - item->removeAllChildren(); + id.clearRadioCircuit(); + item->setData(QVariant::fromValue(id)); + item->removeAllChildren(); + continue; } - } - - else - { - - if (!id.cnrConfig.exerciseId().is_set()) + + if (m_exerciseId > 0) { - id.clearRadioCircuit(); - item->setData(QVariant::fromValue(id)); - item->removeAllChildren(); + + if (initPlanning.exerciseId().is_set()) + { + + if (id.cnrConfig.exerciseId().is_set()) + { + id.clearRadioCircuit(); + item->setData(QVariant::fromValue(id)); + item->removeAllChildren(); + } + } + + else + { + + if (!id.cnrConfig.exerciseId().is_set()) + { + id.clearRadioCircuit(); + item->setData(QVariant::fromValue(id)); + item->removeAllChildren(); + } + } } - } } - } - m_frequencyPlanningData.clear(); + m_frequencyPlanningData.clear(); - - - QMap frequencyPlannings = m_avmDtc->frequencyPlannings(); - for(const auto &frequencyPlanning : std::as_const(frequencyPlannings)) - { - - - if((initPlanning.exerciseId().is_set() && frequencyPlanning.exerciseId().is_set()) - || (!initPlanning.exerciseId().is_set() && frequencyPlanning.exerciseId().is_set() && frequencyPlanning.exerciseId().get() != m_exerciseId)) - continue; - - for(const auto &frequencyPlanningData : frequencyPlanning.data()) + QMap frequencyPlannings = m_avmDtc->frequencyPlannings(); + for (const auto& frequencyPlanning : std::as_const(frequencyPlannings)) { - m_frequencyPlanningData.insert(frequencyPlanningData.cnrConfigId(), frequencyPlanningData); - setFrequencyPlanningData(frequencyPlanningData); - } - break; - } - for(const auto &frequencyPlanningData : initPlanning.data()) - { - m_frequencyPlanningData.insert(frequencyPlanningData.cnrConfigId(), frequencyPlanningData); - setFrequencyPlanningData(frequencyPlanningData); - } - endResetModel(); + if ((initPlanning.exerciseId().is_set() && frequencyPlanning.exerciseId().is_set()) || + (!initPlanning.exerciseId().is_set() && frequencyPlanning.exerciseId().is_set() && + frequencyPlanning.exerciseId().get() != m_exerciseId)) + continue; + + for (const auto& frequencyPlanningData : frequencyPlanning.data()) + { + m_frequencyPlanningData.insert(frequencyPlanningData.cnrConfigId(), frequencyPlanningData); + setFrequencyPlanningData(frequencyPlanningData); + } + break; + } + + for (const auto& frequencyPlanningData : initPlanning.data()) + { + m_frequencyPlanningData.insert(frequencyPlanningData.cnrConfigId(), frequencyPlanningData); + setFrequencyPlanningData(frequencyPlanningData); + } + endResetModel(); } -LoadFrequencyPlanningDialogModel::LoadFrequencyPlanningDialogModel(const FrequencyPlanning &initPlan, - const std::shared_ptr &avmDtc, - const std::shared_ptr &ismDtc, - QObject *parent) - : NGLTreeModel(parent, new ConfigTreeItem(QVariant()), +LoadFrequencyPlanningDialogModel::LoadFrequencyPlanningDialogModel( + const FrequencyPlanning& initPlan, const std::shared_ptr& avmDtc, + const std::shared_ptr& ismDtc, QObject* parent) + : NGLTreeModel(parent, new ConfigTreeItem(QVariant()), + { + tr("Channel Number"), + tr("Conflicts"), + tr("Radio Circuit"), + tr("Radio Station"), + tr("Frequency"), + tr("Function"), + tr("Device"), + tr("AKW Bundle"), + tr("FSB Bundle"), + tr("AKW Radio Circuit"), + tr("COMSEC"), + tr("Pilotton"), + tr("Operating Mode"), + tr("Properties"), + tr("Channel Spacing"), + tr("Squelch"), + }), + m_avmDtc(avmDtc), m_ismDtc(ismDtc), m_initPlan(initPlan), m_parentPlan(initPlan), + m_exerciseId(initPlan.exerciseId().is_set() ? initPlan.exerciseId().get() : 0) { - tr("Channel Number"), - tr("Conflicts"), - tr("Radio Circuit"), - tr("Radio Station"), - tr("Frequency"), - tr("Function"), - tr("Device"), - tr("AKW Bundle"), - tr("FSB Bundle"), - tr("AKW Radio Circuit"), - tr("COMSEC"), - tr("Pilotton"), - tr("Operating Mode"), - tr("Properties"), - tr("Channel Spacing"), - tr("Squelch"), -}) - , m_avmDtc(avmDtc) - , m_ismDtc(ismDtc) - , m_initPlan(initPlan) - , m_parentPlan(initPlan) - , m_exerciseId(initPlan.exerciseId().is_set() ? initPlan.exerciseId().get() : 0) -{ - Q_ASSERT(avmDtc); - DEBUG_LOG(m_logger) << "---EditFrequencyPlanningDataMod m_frequencyPlanningData[c.id()];el() "; + Q_ASSERT(avmDtc); + DEBUG_LOG(m_logger) << "---EditFrequencyPlanningDataMod m_frequencyPlanningData[c.id()];el() "; - m_initPlan.data().clear(); + m_initPlan.data().clear(); - int frequencySetId = m_initPlan.frequencySetId(); - std::vector fsdVec = m_avmDtc->frequencySet(frequencySetId).data(); - for(FrequencySetDataWithId fsd : fsdVec) - { - m_freqSetData.insert(fsd.id(), fsd); - } - onFrequencyPlanningChanged(m_initPlan,DataModification::eAdded); + int frequencySetId = m_initPlan.frequencySetId(); + std::vector fsdVec = m_avmDtc->frequencySet(frequencySetId).data(); + for (FrequencySetDataWithId fsd : fsdVec) + { + m_freqSetData.insert(fsd.id(), fsd); + } + onFrequencyPlanningChanged(m_initPlan, DataModification::eAdded); - m_cnrConfigs = m_avmDtc->cnrConfigs(); - m_existingCnrConfigs = m_cnrConfigs; - m_frequencyPlannings = m_avmDtc->frequencyPlannings(); - m_ownTakenFrequencySetDataIds = getOwnTakenFrequencySetIds(); + m_cnrConfigs = m_avmDtc->cnrConfigs(); + m_existingCnrConfigs = m_cnrConfigs; + m_frequencyPlannings = m_avmDtc->frequencyPlannings(); + m_ownTakenFrequencySetDataIds = getOwnTakenFrequencySetIds(); } -void LoadFrequencyPlanningDialogModel::setData(const QByteArray &data) +void LoadFrequencyPlanningDialogModel::setData(const QByteArray& data) { - using namespace LtsUtils; - const JsonObject obj = JsonObject::fromJson(data); + using namespace LtsUtils; + const JsonObject obj = JsonObject::fromJson(data); - if (m_initPlan.frequencySetId() != obj.value("frequencySetId")) - { - ERROR_LOG(m_logger) << "false frequency set!"; - - return; - } - - beginResetModel(); - m_initPlan.data().clear(); - for (const JsonObject &association : obj.value>("planningInfos")) - { - FrequencyPlanningData info; - int channelId = association.value("cnrChannelId"); - int cnrConfigId = findCnrConfigByChannelId(channelId); - - if (cnrConfigId == -1) + if (m_initPlan.frequencySetId() != obj.value("frequencySetId")) { - cnrConfigId = m_cnrConfigs.size(); - for(;m_cnrConfigs.contains(cnrConfigId); ++cnrConfigId); - CnrConfig invalidConfig; + ERROR_LOG(m_logger) << "false frequency set!"; - invalidConfig.id(cnrConfigId); - invalidConfig.cnrChannelId(channelId); - - m_cnrConfigs.insert(cnrConfigId, invalidConfig); + return; } - info.cnrConfigId(cnrConfigId); - info.properties(association.value("properties").toStdString()); - - m_frequencyPlanningData.insert(cnrConfigId, info); - - m_initPlan.data().push_back(info); - - const CnrConfig cnrConfig = m_cnrConfigs.value(cnrConfigId); - - ItemData id(cnrConfig); - if (m_frequencyPlanningData.contains(cnrConfig.id())) + beginResetModel(); + m_initPlan.data().clear(); + for (const JsonObject& association : obj.value>("planningInfos")) { - FrequencyPlanningData fpd = info; - id.readOnly = isReadOnly(fpd.properties()); - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + FrequencyPlanningData info; + int channelId = association.value("cnrChannelId"); + int cnrConfigId = findCnrConfigByChannelId(channelId); - if (circuits.size() > 1) - { - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - for (RadioCircuit *circuit : std::as_const(circuits)) + if (cnrConfigId == -1) { - id.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(id)); + cnrConfigId = m_cnrConfigs.size(); + for (; m_cnrConfigs.contains(cnrConfigId); ++cnrConfigId) + ; + CnrConfig invalidConfig; - insertRow(configItem->childCount(), indexFromItem(childItem), childItem); + invalidConfig.id(cnrConfigId); + invalidConfig.cnrChannelId(channelId); + + m_cnrConfigs.insert(cnrConfigId, invalidConfig); } - } - else if (circuits.size() == 1) - { - id.radioCircuit = circuits[0]; - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - } + info.cnrConfigId(cnrConfigId); + info.properties(association.value("properties").toStdString()); + + m_frequencyPlanningData.insert(cnrConfigId, info); + + m_initPlan.data().push_back(info); + + const CnrConfig cnrConfig = m_cnrConfigs.value(cnrConfigId); + + ItemData id(cnrConfig); + if (m_frequencyPlanningData.contains(cnrConfig.id())) + { + FrequencyPlanningData fpd = info; + id.readOnly = isReadOnly(fpd.properties()); + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + + if (circuits.size() > 1) + { + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + for (RadioCircuit* circuit : std::as_const(circuits)) + { + id.radioCircuit = circuit; + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(id)); + + insertRow(configItem->childCount(), indexFromItem(childItem), childItem); + } + } + else if (circuits.size() == 1) + { + id.radioCircuit = circuits[0]; + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + } + } + else + { + ConfigTreeItem* configItem = new ConfigTreeItem(QVariant::fromValue(id)); + m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); + insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); + } } - else - { - ConfigTreeItem *configItem = new ConfigTreeItem(QVariant::fromValue(id)); - m_checkStates.insert(m_rootItem->childCount(), Qt::Unchecked); - insertRow(m_rootItem->childCount(), indexFromItem(m_rootItem), configItem); - } - } - onFrequencyPlanningChanged(m_initPlan, DataModification::eAdded); + onFrequencyPlanningChanged(m_initPlan, DataModification::eAdded); - endResetModel(); + endResetModel(); - checkConflicts(); - setCheckStates(); + checkConflicts(); + setCheckStates(); } -LoadFrequencyPlanningDialogModel::ItemData LoadFrequencyPlanningDialogModel::itemData(const QModelIndex &index) +LoadFrequencyPlanningDialogModel::ItemData LoadFrequencyPlanningDialogModel::itemData(const QModelIndex& index) { - NGLTreeItem *item = privateData(index); - if (!item->data().canConvert()) - return {}; + NGLTreeItem* item = privateData(index); + if (!item->data().canConvert()) + return {}; - return item->data().value(); + return item->data().value(); } -QVariant LoadFrequencyPlanningDialogModel::data(const QModelIndex &index, int role) const +QVariant LoadFrequencyPlanningDialogModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole && role != Qt::ToolTipRole && role != Qt::UserRole && role != Qt::TextColorRole && role != Qt::BackgroundRole && role != Qt::CheckStateRole) || !index.isValid()) - return NGLTreeModel::data(index, role); - ConfigTreeItem *item = static_cast(privateData(index)); + if ((role != Qt::DisplayRole && role != Qt::ToolTipRole && role != Qt::UserRole && role != Qt::TextColorRole && + role != Qt::BackgroundRole && role != Qt::CheckStateRole) || + !index.isValid()) + return NGLTreeModel::data(index, role); + ConfigTreeItem* item = static_cast(privateData(index)); - if (!item->data().canConvert()) - return NGLTreeModel::data(index, role); - - ItemData id = item->data().value(); - - const CnrConfig &setData = id.cnrConfig; - RadioCircuit *rc = id.radioCircuit; - - if (role == Qt::ToolTipRole) - { - if (index.column() != PROPERTIES) - return {}; - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (rcVhf && !isAkwMode(rcVhf->operatingMode)) - return tr("Pilot Tone: %1") - .arg(rcVhf->pilotTone ? tr("On") : tr("Off")); - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - if (rcUhf) - return tr("Clipper: %1, AGC: %2, Modulation Type: %3") - .arg(rcUhf->clipper ? tr("On") : tr("Off")) - .arg(rcUhf->agc ? tr("On") : tr("Off")) - .arg(toString(rcUhf->modulationType)); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcHf) - return tr("Channel Spacing: %1, Squelch: %2") - .arg(toString(rcHf->channelSpacing)) - .arg(rcHf->squelch > 0 ? QString::number(rcHf->squelch) : tr("Off")); - } - - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - - case FUNCTION: - { - if (!rc) - return QStringLiteral("-"); - return QString::fromStdString(m_freqSetData[rc->frequencySetDataId()].function()); - } - case DEVICE: - { - - if (!rc) - return QStringLiteral("-"); - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - return toString(m_freqSetData[rc->frequencySetDataId()].frequencyBand().underlying()); - } - case FREQUENCY: - { - QLocale locale(QLocale::German); - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() > 0) - { - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (rcVhf && isAkwMode(rcVhf->operatingMode)) - return QStringLiteral("-"); - return tr("%1 MHz").arg(locale.toString(m_freqSetData[rc->frequencySetDataId()].frequency() / 1000., 'f', 3)); - } - else - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - - if (rcUhf) - return tr("%1 MHz").arg(locale.toString(rcUhf->frequency / 1000000., 'f', 3)); - if (rcHf) - return tr("%1 MHz").arg(locale.toString(rcHf->frequency / 1000000., 'f', 3)); - - return QStringLiteral("-"); - } - } - case AKW_BUNDLE: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].akwBundle().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].akwBundle().get(); - } - case FSB_BUNDLE: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].fsbBundle().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].fsbBundle().get(); - } - case AKW_RADIO_CIRCUIT: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().get(); - } - case COMSEC: - { - if (!rc) - return QStringLiteral("-"); - if (rc->frequencySetDataId() <= 0) - return QStringLiteral("-"); - if (!m_freqSetData[rc->frequencySetDataId()].comsec().is_set()) - return QStringLiteral("-"); - - return m_freqSetData[rc->frequencySetDataId()].comsec().get(); - } - - case RADIO_CIRCUIT: - { - if (!rc) - return QString::fromStdString(setData.radioCircuit()); - - return id.name(); - } - case RADIO_STATION: - { - if (!rc) - return QStringLiteral("-"); - - if (rc->radioStationId == 0) - return tr("Automatic"); - else - return QString::fromStdString(m_ismDtc->mainStructureElement(rc->radioStationId).name()); - } - case PILOTTON: - { - if (!rc) - return QStringLiteral("-"); - - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - - return rcVhf->pilotTone ? tr("On") : tr("Off"); - } - case OPERATING_MODE: - { - if (!rc) - return QStringLiteral("-"); - - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - if (!rcVhf) - return QStringLiteral("-"); - - return toString(rcVhf->operatingMode); - } - case CHANNEL: - { - CnrChannel channel = m_avmDtc->cnrChannel(setData.cnrChannelId()); - return QString::fromStdString(channel.name()); - } - case PROPERTIES: - { - if (!rc) - return QStringLiteral("-"); - else - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - RadioCircuitVHF *rcVhf = dynamic_cast(rc); - QStringList sl; - if (rcUhf) - { - sl << createIcon(ICON_CLIPPER, rcUhf->clipper ); - sl << createIcon(ICON_AGC, rcUhf->agc ); - sl << createIcon(ICON_MODULATION_TYPE, 0, rcUhf->modulationType); - - - - - - - return sl.join(QStringLiteral(" ")); - } - if (rcVhf && !isAkwMode(rcVhf->operatingMode)) - { - sl << createIcon(ICON_PILOTTON, rcVhf->pilotTone > 0); - return sl.join(QStringLiteral(" ")); - } - if (rcHf) - { - - - - - - - return sl.join(QStringLiteral(" ")); - } - return QStringLiteral("-"); - } - } - case CHANNEL_SPACING: - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcUhf) - return toString(rcUhf->channelSpacing); - if (rcHf) - return toString(rcHf->channelSpacing); - return {}; - } - case SQUELCH: - { - RadioCircuitUHF *rcUhf = dynamic_cast(rc); - RadioCircuitHF *rcHf = dynamic_cast(rc); - if (rcUhf) - return rcUhf->squelchDB > 0 ? tr("%1 dB").arg(rcUhf->squelchDB) : QVariant(); - if (rcHf) - return rcHf->squelch > 0 ? QString::number(rcHf->squelch) : QVariant(); - return {}; - } - case CONFLICTS: - { - if (index.parent() != QModelIndex()) + if (!item->data().canConvert()) return NGLTreeModel::data(index, role); - if (m_conflicts.contains(index.row())) - return getConflictText(m_conflicts.value(index.row())); + ItemData id = item->data().value(); - return QLatin1String("-"); - } - default: - break; - } - } + const CnrConfig& setData = id.cnrConfig; + RadioCircuit* rc = id.radioCircuit; - if (role == Qt::UserRole) - return setData.id(); - - if (role == Qt::TextColorRole) - { - - for (int id : m_multipleAssignedCnrIds) + if (role == Qt::ToolTipRole) { - if (id == setData.id()) - return QColor(Qt::red); + if (index.column() != PROPERTIES) + return {}; + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (rcVhf && !isAkwMode(rcVhf->operatingMode)) + return tr("Pilot Tone: %1").arg(rcVhf->pilotTone ? tr("On") : tr("Off")); + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + if (rcUhf) + return tr("Clipper: %1, AGC: %2, Modulation Type: %3") + .arg(rcUhf->clipper ? tr("On") : tr("Off")) + .arg(rcUhf->agc ? tr("On") : tr("Off")) + .arg(toString(rcUhf->modulationType)); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcHf) + return tr("Channel Spacing: %1, Squelch: %2") + .arg(toString(rcHf->channelSpacing)) + .arg(rcHf->squelch > 0 ? QString::number(rcHf->squelch) : tr("Off")); } - } - if (role == Qt::BackgroundRole) - { - if (index.parent() == QModelIndex()) + if (role == Qt::DisplayRole) { - if (m_conflicts.contains(index.row())) - return getConflictColor(m_conflicts.value(index.row())); + switch (index.column()) + { - return QColor(Qt::green).lighter(); + case FUNCTION: { + if (!rc) + return QStringLiteral("-"); + return QString::fromStdString(m_freqSetData[rc->frequencySetDataId()].function()); + } + case DEVICE: { + + if (!rc) + return QStringLiteral("-"); + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + return toString(m_freqSetData[rc->frequencySetDataId()].frequencyBand().underlying()); + } + case FREQUENCY: { + QLocale locale(QLocale::German); + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() > 0) + { + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (rcVhf && isAkwMode(rcVhf->operatingMode)) + return QStringLiteral("-"); + return tr("%1 MHz").arg( + locale.toString(m_freqSetData[rc->frequencySetDataId()].frequency() / 1000., 'f', 3)); + } + else + { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + + if (rcUhf) + return tr("%1 MHz").arg(locale.toString(rcUhf->frequency / 1000000., 'f', 3)); + if (rcHf) + return tr("%1 MHz").arg(locale.toString(rcHf->frequency / 1000000., 'f', 3)); + + return QStringLiteral("-"); + } + } + case AKW_BUNDLE: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].akwBundle().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].akwBundle().get(); + } + case FSB_BUNDLE: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].fsbBundle().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].fsbBundle().get(); + } + case AKW_RADIO_CIRCUIT: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].akwRadioCircuit().get(); + } + case COMSEC: { + if (!rc) + return QStringLiteral("-"); + if (rc->frequencySetDataId() <= 0) + return QStringLiteral("-"); + if (!m_freqSetData[rc->frequencySetDataId()].comsec().is_set()) + return QStringLiteral("-"); + + return m_freqSetData[rc->frequencySetDataId()].comsec().get(); + } + + case RADIO_CIRCUIT: { + if (!rc) + return QString::fromStdString(setData.radioCircuit()); + + return id.name(); + } + case RADIO_STATION: { + if (!rc) + return QStringLiteral("-"); + + if (rc->radioStationId == 0) + return tr("Automatic"); + else + return QString::fromStdString(m_ismDtc->mainStructureElement(rc->radioStationId).name()); + } + case PILOTTON: { + if (!rc) + return QStringLiteral("-"); + + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + + return rcVhf->pilotTone ? tr("On") : tr("Off"); + } + case OPERATING_MODE: { + if (!rc) + return QStringLiteral("-"); + + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + if (!rcVhf) + return QStringLiteral("-"); + + return toString(rcVhf->operatingMode); + } + case CHANNEL: { + CnrChannel channel = m_avmDtc->cnrChannel(setData.cnrChannelId()); + return QString::fromStdString(channel.name()); + } + case PROPERTIES: { + if (!rc) + return QStringLiteral("-"); + else + { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + RadioCircuitVHF* rcVhf = dynamic_cast(rc); + QStringList sl; + if (rcUhf) + { + sl << createIcon(ICON_CLIPPER, rcUhf->clipper); + sl << createIcon(ICON_AGC, rcUhf->agc); + sl << createIcon(ICON_MODULATION_TYPE, 0, rcUhf->modulationType); + + return sl.join(QStringLiteral(" ")); + } + if (rcVhf && !isAkwMode(rcVhf->operatingMode)) + { + sl << createIcon(ICON_PILOTTON, rcVhf->pilotTone > 0); + return sl.join(QStringLiteral(" ")); + } + if (rcHf) + { + + return sl.join(QStringLiteral(" ")); + } + return QStringLiteral("-"); + } + } + case CHANNEL_SPACING: { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcUhf) + return toString(rcUhf->channelSpacing); + if (rcHf) + return toString(rcHf->channelSpacing); + return {}; + } + case SQUELCH: { + RadioCircuitUHF* rcUhf = dynamic_cast(rc); + RadioCircuitHF* rcHf = dynamic_cast(rc); + if (rcUhf) + return rcUhf->squelchDB > 0 ? tr("%1 dB").arg(rcUhf->squelchDB) : QVariant(); + if (rcHf) + return rcHf->squelch > 0 ? QString::number(rcHf->squelch) : QVariant(); + return {}; + } + case CONFLICTS: { + if (index.parent() != QModelIndex()) + return NGLTreeModel::data(index, role); + + if (m_conflicts.contains(index.row())) + return getConflictText(m_conflicts.value(index.row())); + + return QLatin1String("-"); + } + default: + break; + } } - return data(index.parent(), role); - } + if (role == Qt::UserRole) + return setData.id(); - if (role == Qt::CheckStateRole && index.column() == 0 && index.parent() == QModelIndex()) - return m_checkStates.value(index.row()); + if (role == Qt::TextColorRole) + { - return NGLTreeModel::data(index, role); + for (int id : m_multipleAssignedCnrIds) + { + if (id == setData.id()) + return QColor(Qt::red); + } + } + + if (role == Qt::BackgroundRole) + { + if (index.parent() == QModelIndex()) + { + if (m_conflicts.contains(index.row())) + return getConflictColor(m_conflicts.value(index.row())); + + return QColor(Qt::green).lighter(); + } + + return data(index.parent(), role); + } + + if (role == Qt::CheckStateRole && index.column() == 0 && index.parent() == QModelIndex()) + return m_checkStates.value(index.row()); + + return NGLTreeModel::data(index, role); } QString LoadFrequencyPlanningDialogModel::createIcon(PropertyData propertyDataType, bool on, ModulationType type) const { - QString imgHeader = QStringLiteral(""); + QString imgHeader = + QStringLiteral(""); - switch(propertyDataType) - { - case ICON_PILOTTON: - return imgHeader - .arg(on ? - QStringLiteral(":/style/pilotton-on.svg") - : QStringLiteral(":/style/pilotton-off.svg")) - .arg(on ? - tr("Pilot Tone: On") - : tr("Pilot Tone: Off")); - case ICON_MODULATION_TYPE: - return imgHeader - .arg(type == ModulationType::AM ? - QStringLiteral(":/style/AM.svg") - : QStringLiteral(":/style/FM.svg")) - .arg(on ? - tr("Modulation Type: AM") - : tr("Modulation Type: FM")); - case ICON_SQUELCH: - return imgHeader - .arg(on ? - QStringLiteral(":/style/squelch-on.svg") - : QStringLiteral(":/style/squelch-off.svg")) - .arg(on ? - tr("Squelch: On") - : tr("Squelch: Off")); - case ICON_CLIPPER: - return imgHeader - .arg(on ? - QStringLiteral(":/style/clipper-on.svg") - : QStringLiteral(":/style/clipper-off.svg")) - .arg(on ? - tr("Clipper: On") - : tr("Clipper: Off")); - case ICON_AGC: - return imgHeader - .arg(on ? - QStringLiteral(":/style/agc-on.svg") - : QStringLiteral(":/style/agc-off.svg")) - .arg(on ? - tr("Automatic Gain Control (AGC): On") - : tr("Automatic Gain Control (AGC): Off")); - case ICON_CHANNEL_SPACING: - return imgHeader - .arg(QStringLiteral(":/style/channel-spacing-on.svg")) - .arg(tr("Channel Spacing")); - case ICON_SPACER: - return imgHeader - .arg(QStringLiteral(":/style/line_style_solid_v.svg")) - .arg(tr("Channel Spacing")); - default: - return QStringLiteral("-"); - } + switch (propertyDataType) + { + case ICON_PILOTTON: + return imgHeader + .arg(on ? QStringLiteral(":/style/pilotton-on.svg") : QStringLiteral(":/style/pilotton-off.svg")) + .arg(on ? tr("Pilot Tone: On") : tr("Pilot Tone: Off")); + case ICON_MODULATION_TYPE: + return imgHeader + .arg(type == ModulationType::AM ? QStringLiteral(":/style/AM.svg") : QStringLiteral(":/style/FM.svg")) + .arg(on ? tr("Modulation Type: AM") : tr("Modulation Type: FM")); + case ICON_SQUELCH: + return imgHeader + .arg(on ? QStringLiteral(":/style/squelch-on.svg") : QStringLiteral(":/style/squelch-off.svg")) + .arg(on ? tr("Squelch: On") : tr("Squelch: Off")); + case ICON_CLIPPER: + return imgHeader + .arg(on ? QStringLiteral(":/style/clipper-on.svg") : QStringLiteral(":/style/clipper-off.svg")) + .arg(on ? tr("Clipper: On") : tr("Clipper: Off")); + case ICON_AGC: + return imgHeader.arg(on ? QStringLiteral(":/style/agc-on.svg") : QStringLiteral(":/style/agc-off.svg")) + .arg(on ? tr("Automatic Gain Control (AGC): On") : tr("Automatic Gain Control (AGC): Off")); + case ICON_CHANNEL_SPACING: + return imgHeader.arg(QStringLiteral(":/style/channel-spacing-on.svg")).arg(tr("Channel Spacing")); + case ICON_SPACER: + return imgHeader.arg(QStringLiteral(":/style/line_style_solid_v.svg")).arg(tr("Channel Spacing")); + default: + return QStringLiteral("-"); + } } int LoadFrequencyPlanningDialogModel::findCnrConfigByChannelId(int32_t channelId) const { - int id = -1; - std::function findByChannelIdInExercise = [this, channelId, &id] (const CnrConfig &cnrConfig) - { - if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId() != m_exerciseId) - return false; - if (cnrConfig.cnrChannelId() != channelId) - return false; + int id = -1; + std::function findByChannelIdInExercise = [this, channelId, + &id](const CnrConfig& cnrConfig) { + if (cnrConfig.exerciseId().is_set() && cnrConfig.exerciseId() != m_exerciseId) + return false; + if (cnrConfig.cnrChannelId() != channelId) + return false; - id = cnrConfig.id(); - return true; - }; + id = cnrConfig.id(); + return true; + }; - m_avmDtc->cnrConfigs(findByChannelIdInExercise); + m_avmDtc->cnrConfigs(findByChannelIdInExercise); - return id; + return id; } void LoadFrequencyPlanningDialogModel::checkConflicts() { - for (int32_t row = 0; row < rowCount(); ++row) - { - QModelIndex rowIndex = index(row, 0); - ConfigTreeItem *item = static_cast(privateData(rowIndex)); - - if (!item || !item->data().canConvert()) + for (int32_t row = 0; row < rowCount(); ++row) { - DEBUG_LOG(m_logger) << "Could not get item for row " << row; - continue; - } + QModelIndex rowIndex = index(row, 0); + ConfigTreeItem* item = static_cast(privateData(rowIndex)); - QVector itemsInRow; - itemsInRow.reserve(item->childCount() + 1); - - itemsInRow.append(item); - itemsInRow += item->children(); - - for (NGLTreeItem *treeItem : std::as_const(itemsInRow)) - { - ItemData itemData = treeItem->data().value(); - - if (!isCnrChannelInOwnConfig(itemData.cnrConfig.cnrChannelId())) - { - m_conflicts.insert(row, CHANNEL_NOT_IN_CNR_CONFIG); - emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); - break; - } - - if (itemData.radioCircuit) - { - if (isFrequencySetDataTakenInOtherExercise(itemData.radioCircuit->frequencySetDataId())) + if (!item || !item->data().canConvert()) { - if (m_conflicts.value(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) > FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE) - { - m_conflicts.insert(row, FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE); - emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); - } - break; + DEBUG_LOG(m_logger) << "Could not get item for row " << row; + continue; } - if (isFrequencySetDataTakenInOwnFrequencyPlanning(itemData.radioCircuit->frequencySetDataId())) + QVector itemsInRow; + itemsInRow.reserve(item->childCount() + 1); + + itemsInRow.append(item); + itemsInRow += item->children(); + + for (NGLTreeItem* treeItem : std::as_const(itemsInRow)) { - if (m_conflicts.value(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) == FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) - { - m_conflicts.insert(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING); - addUnassignmentForRow(parentCnrConfigIdByFrequencySetDataId(itemData.radioCircuit->frequencySetDataId()), row); - emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); - } - break; + ItemData itemData = treeItem->data().value(); + + if (!isCnrChannelInOwnConfig(itemData.cnrConfig.cnrChannelId())) + { + m_conflicts.insert(row, CHANNEL_NOT_IN_CNR_CONFIG); + emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); + break; + } + + if (itemData.radioCircuit) + { + if (isFrequencySetDataTakenInOtherExercise(itemData.radioCircuit->frequencySetDataId())) + { + if (m_conflicts.value(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) > + FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE) + { + m_conflicts.insert(row, FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE); + emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); + } + break; + } + + if (isFrequencySetDataTakenInOwnFrequencyPlanning(itemData.radioCircuit->frequencySetDataId())) + { + if (m_conflicts.value(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) == + FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING) + { + m_conflicts.insert(row, FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING); + addUnassignmentForRow( + parentCnrConfigIdByFrequencySetDataId(itemData.radioCircuit->frequencySetDataId()), row); + emit dataChanged(rowIndex, rowIndex, {Qt::BackgroundRole, Qt::DisplayRole}); + } + break; + } + } } - } } - } } void LoadFrequencyPlanningDialogModel::setCheckStates() { - for (int32_t row = 0; row < rowCount(); ++row) - { - if (m_conflicts.contains(row)) - continue; + for (int32_t row = 0; row < rowCount(); ++row) + { + if (m_conflicts.contains(row)) + continue; - m_checkStates[row] = Qt::Checked; + m_checkStates[row] = Qt::Checked; - QModelIndex changeIndex = index(row, 0); + QModelIndex changeIndex = index(row, 0); - emit dataChanged(changeIndex, changeIndex, {Qt::CheckStateRole}); - } + emit dataChanged(changeIndex, changeIndex, {Qt::CheckStateRole}); + } } bool LoadFrequencyPlanningDialogModel::isCnrChannelInOwnConfig(int32_t channelId) const { - for (auto it = m_existingCnrConfigs.constBegin(); it != m_existingCnrConfigs.constEnd(); ++it) - { - const CnrConfig cnrConfig = it.value(); - const int32_t exerciseId = cnrConfig.exerciseId().is_set() ? cnrConfig.exerciseId().get() : 0; + for (auto it = m_existingCnrConfigs.constBegin(); it != m_existingCnrConfigs.constEnd(); ++it) + { + const CnrConfig cnrConfig = it.value(); + const int32_t exerciseId = cnrConfig.exerciseId().is_set() ? cnrConfig.exerciseId().get() : 0; - if (exerciseId == m_exerciseId && cnrConfig.cnrChannelId() == channelId) - return true; - } + if (exerciseId == m_exerciseId && cnrConfig.cnrChannelId() == channelId) + return true; + } - return false; + return false; } bool LoadFrequencyPlanningDialogModel::isFrequencySetDataTakenInOwnFrequencyPlanning(int32_t frequencySetDataId) const { - return m_ownTakenFrequencySetDataIds.contains(frequencySetDataId); + return m_ownTakenFrequencySetDataIds.contains(frequencySetDataId); } bool LoadFrequencyPlanningDialogModel::isFrequencySetDataTakenInOtherExercise(int32_t frequencySetDataId) const { - for (auto it = m_frequencyPlannings.constBegin(); it != m_frequencyPlannings.constEnd(); ++it) - { - const FrequencyPlanning frequencyPlanning = it.value(); - const int32_t currentExerciseId = frequencyPlanning.exerciseId().is_set() ? frequencyPlanning.exerciseId().get() : 0; - - if (currentExerciseId == m_exerciseId) - continue; - - for (const FrequencyPlanningData &data : frequencyPlanning.data()) + for (auto it = m_frequencyPlannings.constBegin(); it != m_frequencyPlannings.constEnd(); ++it) { - QSet frequencySetDataIds = AudioVideoManagement::frequencySetDataIds(data.properties()); + const FrequencyPlanning frequencyPlanning = it.value(); + const int32_t currentExerciseId = + frequencyPlanning.exerciseId().is_set() ? frequencyPlanning.exerciseId().get() : 0; - if (frequencySetDataIds.contains(frequencySetDataId)) - return true; + if (currentExerciseId == m_exerciseId) + continue; + + for (const FrequencyPlanningData& data : frequencyPlanning.data()) + { + QSet frequencySetDataIds = AudioVideoManagement::frequencySetDataIds(data.properties()); + + if (frequencySetDataIds.contains(frequencySetDataId)) + return true; + } } - } - return false; + return false; } int32_t LoadFrequencyPlanningDialogModel::parentCnrConfigIdByFrequencySetDataId(int32_t frequencySetDataId) const { - for (const FrequencyPlanningData ¤tPlanning : m_parentPlan.data()) - { - QSet parentFrequencySetDataIds = AudioVideoManagement::frequencySetDataIds(currentPlanning.properties()); + for (const FrequencyPlanningData& currentPlanning : m_parentPlan.data()) + { + QSet parentFrequencySetDataIds = AudioVideoManagement::frequencySetDataIds(currentPlanning.properties()); - if (parentFrequencySetDataIds.contains(frequencySetDataId)) - return currentPlanning.cnrConfigId(); - } + if (parentFrequencySetDataIds.contains(frequencySetDataId)) + return currentPlanning.cnrConfigId(); + } - return -1; + return -1; } QString LoadFrequencyPlanningDialogModel::getConflictText(LoadFrequencyPlanningDialogModel::Conflict conflict) const { - switch (conflict) - { - case CHANNEL_NOT_IN_CNR_CONFIG: - return tr("Cnr Channel not included in Cnr Config"); - case FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE: - return tr("Frequency Set data already taken in another exercise"); - case FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING: - return tr("Frequency set data already taken in own frequency planning"); - } + switch (conflict) + { + case CHANNEL_NOT_IN_CNR_CONFIG: + return tr("Cnr Channel not included in Cnr Config"); + case FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE: + return tr("Frequency Set data already taken in another exercise"); + case FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING: + return tr("Frequency set data already taken in own frequency planning"); + } - return QString(); + return QString(); } QColor LoadFrequencyPlanningDialogModel::getConflictColor(LoadFrequencyPlanningDialogModel::Conflict conflict) const { - switch (conflict) - { - case CHANNEL_NOT_IN_CNR_CONFIG: - case FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE: - return QColor(Qt::red).lighter(); - case FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING: - return QColor(Qt::yellow).lighter(); - } + switch (conflict) + { + case CHANNEL_NOT_IN_CNR_CONFIG: + case FREQUENCYSET_DATA_TAKEN_IN_OTHER_EXERCISE: + return QColor(Qt::red).lighter(); + case FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING: + return QColor(Qt::yellow).lighter(); + } - return QColor(); + return QColor(); } bool LoadFrequencyPlanningDialogModel::isSolvableConflict(LoadFrequencyPlanningDialogModel::Conflict conflict) const { - return conflict >= FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING; + return conflict >= FREQUENCYSET_DATA_TAKEN_IN_OWN_FREQUENCY_PLANNING; } QSet LoadFrequencyPlanningDialogModel::getOwnTakenFrequencySetIds() const { - QSet ownTakenFrequencySetIds; - ownTakenFrequencySetIds.reserve(m_parentPlan.data().size() * 2); + QSet ownTakenFrequencySetIds; + ownTakenFrequencySetIds.reserve(m_parentPlan.data().size() * 2); - for (const FrequencyPlanningData &data : m_parentPlan.data()) - ownTakenFrequencySetIds += AudioVideoManagement::frequencySetDataIds(data.properties()); + for (const FrequencyPlanningData& data : m_parentPlan.data()) + ownTakenFrequencySetIds += AudioVideoManagement::frequencySetDataIds(data.properties()); - return ownTakenFrequencySetIds; + return ownTakenFrequencySetIds; } void LoadFrequencyPlanningDialogModel::addUnassignmentForRow(int32_t unassignment, int32_t row) { - if (!m_unassignmentsPerRow.contains(row)) - m_unassignmentsPerRow.insert(row, {}); + if (!m_unassignmentsPerRow.contains(row)) + m_unassignmentsPerRow.insert(row, {}); - m_unassignmentsPerRow[row].append(unassignment); + m_unassignmentsPerRow[row].append(unassignment); } - -void LoadFrequencyPlanningDialogModel::setFrequencyPlanningData(const FrequencyPlanningData &fpd) +void LoadFrequencyPlanningDialogModel::setFrequencyPlanningData(const FrequencyPlanningData& fpd) { - beginResetModel(); - ConfigTreeItem* item = searchCnrConfig(m_rootItem, fpd.cnrConfigId()); - if(!item) - return; - QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); - ItemData data = item->data().value(); - item->removeAllChildren(); + beginResetModel(); + ConfigTreeItem* item = searchCnrConfig(m_rootItem, fpd.cnrConfigId()); + if (!item) + return; + QVector circuits = AudioVideoManagement::fromJson(fpd.properties()); + ItemData data = item->data().value(); + item->removeAllChildren(); - if (circuits.size() == 1) - { - data.radioCircuit = circuits[0]; - item->setData(QVariant::fromValue(data)); + if (circuits.size() == 1) + { + data.radioCircuit = circuits[0]; + item->setData(QVariant::fromValue(data)); + m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); + } + if (circuits.size() <= 1) + return; + + for (RadioCircuit* circuit : std::as_const(circuits)) + { + data.radioCircuit = circuit; + ConfigTreeItem* childItem = new ConfigTreeItem(QVariant::fromValue(data)); + insertRow(item->childCount(), indexFromItem(item), childItem); + } m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); - } - if (circuits.size() <= 1) - return; - - for (RadioCircuit *circuit : std::as_const(circuits)) - { - data.radioCircuit = circuit; - ConfigTreeItem *childItem = new ConfigTreeItem(QVariant::fromValue(data)); - insertRow(item->childCount(), indexFromItem(item), childItem); - } - m_frequencyPlanningData.insert(fpd.cnrConfigId(), fpd); - endResetModel(); + endResetModel(); } -Qt::ItemFlags LoadFrequencyPlanningDialogModel::flags(const QModelIndex &index) const +Qt::ItemFlags LoadFrequencyPlanningDialogModel::flags(const QModelIndex& index) const { - if (index.isValid() && index.column() == 0) - { - if (m_conflicts.contains(index.row()) && !isSolvableConflict(m_conflicts.value(index.row()))) - return Qt::NoItemFlags; + if (index.isValid() && index.column() == 0) + { + if (m_conflicts.contains(index.row()) && !isSolvableConflict(m_conflicts.value(index.row()))) + return Qt::NoItemFlags; - return Qt::ItemIsUserCheckable | NGLTreeModel::flags(index); - } + return Qt::ItemIsUserCheckable | NGLTreeModel::flags(index); + } - return NGLTreeModel::flags(index); + return NGLTreeModel::flags(index); } -bool LoadFrequencyPlanningDialogModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool LoadFrequencyPlanningDialogModel::setData(const QModelIndex& index, const QVariant& value, int role) { - if (role != Qt::CheckStateRole || !index.isValid() || index.parent() != QModelIndex()) - return NGLTreeModel::setData(index, value, role); + if (role != Qt::CheckStateRole || !index.isValid() || index.parent() != QModelIndex()) + return NGLTreeModel::setData(index, value, role); - m_checkStates[index.row()] = value.value(); + m_checkStates[index.row()] = value.value(); - return true; + return true; } QVector LoadFrequencyPlanningDialogModel::unassignments() const { - QVector unassignmentsVec; - unassignmentsVec.reserve(m_conflicts.size()); + QVector unassignmentsVec; + unassignmentsVec.reserve(m_conflicts.size()); - for (auto it = m_conflicts.constBegin(); it != m_conflicts.constEnd(); ++it) - { - if (!m_unassignmentsPerRow.contains(it.key()) || m_checkStates.value(it.key()) != Qt::Checked) - continue; + for (auto it = m_conflicts.constBegin(); it != m_conflicts.constEnd(); ++it) + { + if (!m_unassignmentsPerRow.contains(it.key()) || m_checkStates.value(it.key()) != Qt::Checked) + continue; - unassignmentsVec += m_unassignmentsPerRow.value(it.key()); - } + unassignmentsVec += m_unassignmentsPerRow.value(it.key()); + } - return unassignmentsVec; + return unassignmentsVec; } QVector LoadFrequencyPlanningDialogModel::planningData() const { - QVector planningDataVec; - planningDataVec.reserve(rowCount()); + QVector planningDataVec; + planningDataVec.reserve(rowCount()); - for (int32_t row = 0; row < rowCount(); ++row) - { - if (m_checkStates.value(row, Qt::Unchecked) == Qt::Unchecked) - continue; - - QModelIndex rowIndex = index(row, 0); - ConfigTreeItem *item = static_cast(privateData(rowIndex)); - - if (!item || !item->data().canConvert()) + for (int32_t row = 0; row < rowCount(); ++row) { - DEBUG_LOG(m_logger) << "Could not get item for row " << row; - continue; + if (m_checkStates.value(row, Qt::Unchecked) == Qt::Unchecked) + continue; + + QModelIndex rowIndex = index(row, 0); + ConfigTreeItem* item = static_cast(privateData(rowIndex)); + + if (!item || !item->data().canConvert()) + { + DEBUG_LOG(m_logger) << "Could not get item for row " << row; + continue; + } + + ItemData itemData = item->data().value(); + + planningDataVec.append(m_frequencyPlanningData.value(itemData.cnrConfig.id())); } - ItemData itemData = item->data().value(); - - planningDataVec.append(m_frequencyPlanningData.value(itemData.cnrConfig.id())); - } - - return planningDataVec; + return planningDataVec; } void LoadFrequencyPlanningDialogModel::checkAll(bool isChecked) { - for (int32_t row = 0; row < rowCount(); ++row) - { - if ((m_conflicts.contains(row) && !isSolvableConflict(m_conflicts.value(row))) || !m_checkStates.contains(row)) - continue; + for (int32_t row = 0; row < rowCount(); ++row) + { + if ((m_conflicts.contains(row) && !isSolvableConflict(m_conflicts.value(row))) || !m_checkStates.contains(row)) + continue; - m_checkStates[row] = isChecked ? Qt::Checked : Qt::Unchecked; + m_checkStates[row] = isChecked ? Qt::Checked : Qt::Unchecked; - QModelIndex changedIndex = index(row, 0); + QModelIndex changedIndex = index(row, 0); - emit dataChanged(changedIndex, changedIndex, {Qt::CheckStateRole}); - } + emit dataChanged(changedIndex, changedIndex, {Qt::CheckStateRole}); + } } -LoadFrequencyPlanningDialogModel::ConfigTreeItem* LoadFrequencyPlanningDialogModel::searchCnrConfig(const NGLTreeItem *parentItem, int cnrConfigId) const +LoadFrequencyPlanningDialogModel::ConfigTreeItem* +LoadFrequencyPlanningDialogModel::searchCnrConfig(const NGLTreeItem* parentItem, int cnrConfigId) const { - const int rowCount = parentItem->childCount(); - for (int r = 0; r < rowCount; ++r) - { - ConfigTreeItem *child = static_cast(parentItem->child(r)); - if (child->data().value().cnrConfig.id() == cnrConfigId) - return child; - child = searchCnrConfig(child, cnrConfigId); - if (child) - return child; - } - return nullptr; + const int rowCount = parentItem->childCount(); + for (int r = 0; r < rowCount; ++r) + { + ConfigTreeItem* child = static_cast(parentItem->child(r)); + if (child->data().value().cnrConfig.id() == cnrConfigId) + return child; + child = searchCnrConfig(child, cnrConfigId); + if (child) + return child; + } + return nullptr; } +DrawDelegate::DrawDelegate(QObject* parent) + : QStyledItemDelegate(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} + +void DrawDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + if (index.column() == LoadFrequencyPlanningDialogModel::Columns::PROPERTIES) + { + QStyleOptionViewItem options = option; + initStyleOption(&options, index); + + painter->save(); + QTextDocument doc; + doc.setHtml(options.text); + options.text = QString(); + options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); -DrawDelegate::DrawDelegate(QObject *parent) : QStyledItemDelegate(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { + painter->translate(options.rect.left(), options.rect.top()); + QRect clip(0, 0, options.rect.width(), options.rect.height()); + doc.drawContents(painter, clip); + + painter->restore(); + } + else + QStyledItemDelegate::paint(painter, option, index); } -void DrawDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const + +QSize DrawDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { - if (index.column() == LoadFrequencyPlanningDialogModel::Columns::PROPERTIES) - { QStyleOptionViewItem options = option; initStyleOption(&options, index); - painter->save(); - QTextDocument doc; doc.setHtml(options.text); - - options.text = QString(); - options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter); - - painter->translate(options.rect.left(), options.rect.top()); - QRect clip(0, 0, options.rect.width(), options.rect.height()); - doc.drawContents(painter, clip); - - painter->restore(); - } - else - QStyledItemDelegate::paint(painter, option, index); + doc.setTextWidth(options.rect.width()); + return QSize(doc.idealWidth(), doc.size().height()); } - -QSize DrawDelegate::sizeHint( const QStyleOptionViewItem & option, const QModelIndex & index ) const -{ - QStyleOptionViewItem options = option; - initStyleOption(&options, index); - - QTextDocument doc; - doc.setHtml(options.text); - doc.setTextWidth(options.rect.width()); - return QSize(doc.idealWidth(), doc.size().height()); -} - -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_dialog.cpp old mode 100755 new mode 100644 index f76bb0cb6..91422d22b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_dialog.cpp @@ -1,329 +1,298 @@ - #include "avm_eloka_dialog.h" -#include + #include "ui_avm_eloka_dialog.h" -#include -#include -#include #include +#include +#include #include -#include - #include +#include #include +#include +#include namespace AudioVideoManagement { -ElokaDialog::ElokaDialog(LtsSession::LtsSession *session, AvaSession *avaSession, Interface::Dtc *avmDtc, StreamNameMapping *streamNameMapping, - const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::ElokaDialog) - , m_menuGroup(menuGroup) - , m_elokaModel(new ElokaModel(session, this)) - , m_session(session) - , m_avaSession(avaSession) - , m_elokaListCollector(m_avaSession->control()->comm(), [this] (QVector &&eloka) { onQueryElokaResponse(std::move(eloka)); }) - , m_streamNameMapping(streamNameMapping) - , m_avmDtc(avmDtc) - , m_avaSessionEstablished(false) - , m_usedCnr() - , m_usedTvc() - , m_usedAnnouncement() +ElokaDialog::ElokaDialog(LtsSession::LtsSession* session, AvaSession* avaSession, Interface::Dtc* avmDtc, + StreamNameMapping* streamNameMapping, const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ui(new Ui::ElokaDialog), + m_menuGroup(menuGroup), m_elokaModel(new ElokaModel(session, this)), m_session(session), m_avaSession(avaSession), + m_elokaListCollector(m_avaSession->control()->comm(), + [this](QVector&& eloka) { onQueryElokaResponse(std::move(eloka)); }), + m_streamNameMapping(streamNameMapping), m_avmDtc(avmDtc), m_avaSessionEstablished(false), m_usedCnr(), + m_usedTvc(), m_usedAnnouncement() { - Q_ASSERT(session); - Q_ASSERT(avaSession); - Q_ASSERT(streamNameMapping); - Q_ASSERT(avmDtc); + Q_ASSERT(session); + Q_ASSERT(avaSession); + Q_ASSERT(streamNameMapping); + Q_ASSERT(avmDtc); - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_avaSession, &AvaSession::sessionEstablished, - this, &ElokaDialog::onAvaSessionEstablished); - connect(m_avaSession, &AvaSession::disconnected, - this, &ElokaDialog::onAvaSessionDisconnected); + connect(m_avaSession, &AvaSession::sessionEstablished, this, &ElokaDialog::onAvaSessionEstablished); + connect(m_avaSession, &AvaSession::disconnected, this, &ElokaDialog::onAvaSessionDisconnected); - m_elokaListCollector.start(); + m_elokaListCollector.start(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, - this, &ElokaDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, - this, &ElokaDialog::onEditClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, - this, &ElokaDialog::onRemoveClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, - this, &ElokaDialog::onPrint); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ElokaDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ElokaDialog::onEditClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ElokaDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &ElokaDialog::onPrint); - m_ui->tvEloka->setModel(m_elokaModel); + m_ui->tvEloka->setModel(m_elokaModel); - connect(m_ui->tvEloka, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ElokaDialog::onSelectionChanged); - onSelectionChanged(); + connect(m_ui->tvEloka, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ElokaDialog::onSelectionChanged); + onSelectionChanged(); - connect(m_ui->tvEloka, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ElokaDialog::onEditClicked); + connect(m_ui->tvEloka, &LtsDataView::LtsDataView::signalDoubleClicked, this, &ElokaDialog::onEditClicked); - setAvaSessionStatus(m_avaSession->isEstablished()); + setAvaSessionStatus(m_avaSession->isEstablished()); - setOnlineHelpFilename(QStringLiteral("Situation-Electronic_Warfare_Measures")); + setOnlineHelpFilename(QStringLiteral("Situation-Electronic_Warfare_Measures")); } ElokaDialog::~ElokaDialog() { - delete m_elokaModel; - delete m_ui; - m_avaSession->control()->queryEloka(AvaQueryElokaMode::Stop); + delete m_elokaModel; + delete m_ui; + m_avaSession->control()->queryEloka(AvaQueryElokaMode::Stop); } void ElokaDialog::retranslate() { - translate(m_ui, tr("Eloka")); + translate(m_ui, tr("Eloka")); } void ElokaDialog::onAvaSessionEstablished() { - setAvaSessionStatus(true); + setAvaSessionStatus(true); } void ElokaDialog::onAvaSessionDisconnected() { - m_elokaListCollector.reset(); - m_elokaListCollector.start(); - setAvaSessionStatus(false); + m_elokaListCollector.reset(); + m_elokaListCollector.start(); + setAvaSessionStatus(false); } void ElokaDialog::setAvaSessionStatus(bool established) { - m_avaSessionEstablished = established; + m_avaSessionEstablished = established; - - if (established) - m_avaSession->control()->queryEloka(AvaQueryElokaMode::Push); + if (established) + m_avaSession->control()->queryEloka(AvaQueryElokaMode::Push); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, established); - m_ui->lblAvaSessionStatus->setVisible(!established); - onSelectionChanged(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, established); + m_ui->lblAvaSessionStatus->setVisible(!established); + onSelectionChanged(); } void ElokaDialog::onAddClicked() { - DEBUG_LOG(m_logger) << "**** onAddClicked() "; + DEBUG_LOG(m_logger) << "**** onAddClicked() "; - ElokaEditDialog *dialog = new ElokaEditDialog(m_session, m_avaSession, m_avmDtc, m_streamNameMapping, - ElokaData(), this); + ElokaEditDialog* dialog = + new ElokaEditDialog(m_session, m_avaSession, m_avmDtc, m_streamNameMapping, ElokaData(), this); - connect(dialog, &ElokaEditDialog::signalNewEloka, this, - [this](const ElokaData & data) - { - m_elokaModel->insertRow(data); - }); + connect(dialog, &ElokaEditDialog::signalNewEloka, this, + [this](const ElokaData& data) { m_elokaModel->insertRow(data); }); - getUsedRadioCircuits(); - dialog->init(m_usedCnr, m_usedTvc, m_usedAnnouncement); + getUsedRadioCircuits(); + dialog->init(m_usedCnr, m_usedTvc, m_usedAnnouncement); - addDialog(dialog, m_menuGroup, QStringLiteral("AddEloka")); + addDialog(dialog, m_menuGroup, QStringLiteral("AddEloka")); } void ElokaDialog::onEditClicked() { - DEBUG_LOG(m_logger) << "**** onEditClicked() "; + DEBUG_LOG(m_logger) << "**** onEditClicked() "; - const QModelIndex idx = m_ui->tvEloka->currentIndex(); + const QModelIndex idx = m_ui->tvEloka->currentIndex(); - if (!idx.isValid()) - return; + if (!idx.isValid()) + return; - const ElokaData data = m_elokaModel->getRowData(idx.row()); + const ElokaData data = m_elokaModel->getRowData(idx.row()); - ElokaEditDialog *dialog = new ElokaEditDialog(m_session, m_avaSession, m_avmDtc, m_streamNameMapping, - data, this); + ElokaEditDialog* dialog = new ElokaEditDialog(m_session, m_avaSession, m_avmDtc, m_streamNameMapping, data, this); - connect(dialog, &ElokaEditDialog::signalNewEloka, this, - [ = ](const ElokaData & data) - { - m_elokaModel->setRowData(idx.row(), data); - }); + connect(dialog, &ElokaEditDialog::signalNewEloka, this, + [=](const ElokaData& data) { m_elokaModel->setRowData(idx.row(), data); }); - getUsedRadioCircuits(); - dialog->init(m_usedCnr, m_usedTvc, m_usedAnnouncement); + getUsedRadioCircuits(); + dialog->init(m_usedCnr, m_usedTvc, m_usedAnnouncement); - addDialog(dialog, m_menuGroup, QStringLiteral("EditEloka")); + addDialog(dialog, m_menuGroup, QStringLiteral("EditEloka")); } void ElokaDialog::onRemoveClicked() { - DEBUG_LOG(m_logger) << "**** onRemoveClicked() "; + DEBUG_LOG(m_logger) << "**** onRemoveClicked() "; - const QModelIndex idx = m_ui->tvEloka->currentIndex(); + const QModelIndex idx = m_ui->tvEloka->currentIndex(); - if (!idx.isValid()) - return; - m_avaSession->control()->releaseEloka(m_elokaModel->getRowData(idx.row()).internalName); - m_elokaModel->removeRow(idx.row()); + if (!idx.isValid()) + return; + m_avaSession->control()->releaseEloka(m_elokaModel->getRowData(idx.row()).internalName); + m_elokaModel->removeRow(idx.row()); } void ElokaDialog::onSelectionChanged() { - QModelIndexList selectedRows = m_ui->tvEloka->selectedRows(); - const int cntSelectedRows = selectedRows.size(); + QModelIndexList selectedRows = m_ui->tvEloka->selectedRows(); + const int cntSelectedRows = selectedRows.size(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, - cntSelectedRows == 1 && m_avaSessionEstablished); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, - cntSelectedRows > 0 && m_avaSessionEstablished); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, - !(m_elokaModel->rowCount() >= 20)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1 && m_avaSessionEstablished); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows > 0 && m_avaSessionEstablished); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, !(m_elokaModel->rowCount() >= 20)); } void ElokaDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->tvEloka->treeView() ); + LtsPrinting::printView(m_session, this, m_ui->tvEloka->treeView()); } -void ElokaDialog::onQueryElokaResponse(const QVector &&eloka) +void ElokaDialog::onQueryElokaResponse(const QVector&& eloka) { - DEBUG_LOG(m_logger) << "onQueryElokaResponse"; + DEBUG_LOG(m_logger) << "onQueryElokaResponse"; - m_elokaListCollector.start(); - m_elokaModel->clear(); + m_elokaListCollector.start(); + m_elokaModel->clear(); - if (eloka.isEmpty()) - return; + if (eloka.isEmpty()) + return; - const auto cnrTvcProfiles = m_avmDtc->cnrTvcProfiles(); - QMultiMap userProfile; - int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - int exerciseId = m_session->exerciseId(); + const auto cnrTvcProfiles = m_avmDtc->cnrTvcProfiles(); + QMultiMap userProfile; + int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + int exerciseId = m_session->exerciseId(); - for (const auto &cnrTvcProfile : cnrTvcProfiles) - { - if (cnrTvcProfile.exerciseId() == exerciseId && - cnrTvcProfile.operatorId() == operatorId) + for (const auto& cnrTvcProfile : cnrTvcProfiles) { - for (const auto &cnrTvcProfileData : cnrTvcProfile.data()) - { - if (cnrTvcProfileData.radioSystemId() == RadioSystem::inner_enum::Cnr) - userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Cnr); - else - userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Tvc); - } + if (cnrTvcProfile.exerciseId() == exerciseId && cnrTvcProfile.operatorId() == operatorId) + { + for (const auto& cnrTvcProfileData : cnrTvcProfile.data()) + { + if (cnrTvcProfileData.radioSystemId() == RadioSystem::inner_enum::Cnr) + userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Cnr); + else + userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Tvc); + } - break; + break; + } } - } - ElokaData data; - for (const auto &elokaData : eloka) - { - data.internalName = elokaData.stream; - data.displayName = elokaData.stream; - data.action = elokaData.signal; - data.mode = AvaElokaMode::EndlessLoop; - data.startTime = toMSecSinceEpoch(elokaData.time); + ElokaData data; + for (const auto& elokaData : eloka) + { + data.internalName = elokaData.stream; + data.displayName = elokaData.stream; + data.action = elokaData.signal; + data.mode = AvaElokaMode::EndlessLoop; + data.startTime = toMSecSinceEpoch(elokaData.time); - if (isCnr(data, userProfile) || - isTvc(data, userProfile) || - isAnnouncement(data)) - m_elokaModel->insertRow(data); - } + if (isCnr(data, userProfile) || isTvc(data, userProfile) || isAnnouncement(data)) + m_elokaModel->insertRow(data); + } } void ElokaDialog::tableColumnOrganiserSetting() { - - m_ui->tvEloka->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->tvEloka->setColumnsOrganiserEnabled(identifier(), true); } bool ElokaDialog::isCnr(ElokaData& data, const QMultiMap& userProfile) { - const QMap cnrs = m_avmDtc->cnrConfigs(); + const QMap cnrs = m_avmDtc->cnrConfigs(); - for (const auto &cnr : cnrs) - { - if ((QString::fromStdString(cnr.radioCircuit()) == data.internalName) && - (userProfile.contains(cnr.id(), ElokaCircuitType::Cnr))) + for (const auto& cnr : cnrs) { - data.circuitType = ElokaCircuitType::Cnr; - data.party = cnr.partyId(); - data.id = cnr.id(); - return true; + if ((QString::fromStdString(cnr.radioCircuit()) == data.internalName) && + (userProfile.contains(cnr.id(), ElokaCircuitType::Cnr))) + { + data.circuitType = ElokaCircuitType::Cnr; + data.party = cnr.partyId(); + data.id = cnr.id(); + return true; + } } - } - return false; + return false; } bool ElokaDialog::isTvc(ElokaData& data, const QMultiMap& userProfile) { - const QMap tvcs = m_avmDtc->tvcConfigs(); + const QMap tvcs = m_avmDtc->tvcConfigs(); - for (const auto &tvc : tvcs) - { - if (tvc.exerciseId() != m_session->exerciseId()) - continue; - if ((QString::fromStdString(tvc.radioCircuit()) == data.internalName) && - (userProfile.contains(tvc.id(), ElokaCircuitType::Tvc))) + for (const auto& tvc : tvcs) { - data.circuitType = ElokaCircuitType::Tvc; - data.party = 0; - data.id = tvc.id(); - return true; + if (tvc.exerciseId() != m_session->exerciseId()) + continue; + if ((QString::fromStdString(tvc.radioCircuit()) == data.internalName) && + (userProfile.contains(tvc.id(), ElokaCircuitType::Tvc))) + { + data.circuitType = ElokaCircuitType::Tvc; + data.party = 0; + data.id = tvc.id(); + return true; + } } - } - return false; + return false; } bool ElokaDialog::isAnnouncement(ElokaData& data) { - QMap announcements; - QMap streams = m_avmDtc->streams(); - for (const Stream &stream : std::as_const(streams)) - { - if ((stream.type() == StreamType_def::AudioOut) || - (stream.type() == StreamType_def::AudioInOut)) - announcements.insert(stream.id(), stream); - } - - for (const auto &announcement : announcements) - { - if (QString::fromStdString(announcement.name()) == data.internalName) + QMap announcements; + QMap streams = m_avmDtc->streams(); + for (const Stream& stream : std::as_const(streams)) { - data.circuitType = ElokaCircuitType::Announcement; - data.party = -1; - data.id = announcement.id(); - data.exerciseId = m_session->exerciseId(); - data.displayName = m_streamNameMapping->displayName(data.internalName); - return true; + if ((stream.type() == StreamType_def::AudioOut) || (stream.type() == StreamType_def::AudioInOut)) + announcements.insert(stream.id(), stream); } - } - return false; + + for (const auto& announcement : announcements) + { + if (QString::fromStdString(announcement.name()) == data.internalName) + { + data.circuitType = ElokaCircuitType::Announcement; + data.party = -1; + data.id = announcement.id(); + data.exerciseId = m_session->exerciseId(); + data.displayName = m_streamNameMapping->displayName(data.internalName); + return true; + } + } + return false; } void ElokaDialog::getUsedRadioCircuits() { - m_usedAnnouncement.clear(); - m_usedCnr.clear(); - m_usedTvc.clear(); + m_usedAnnouncement.clear(); + m_usedCnr.clear(); + m_usedTvc.clear(); - for (int i=0; i < m_elokaModel->rowCount(); ++i) - { - ElokaData elokaData = m_elokaModel->getRowData(i); - switch (elokaData.circuitType) + for (int i = 0; i < m_elokaModel->rowCount(); ++i) { - case ElokaCircuitType::Cnr: - m_usedCnr.push_back(elokaData.id); - break; - case ElokaCircuitType::Tvc: - m_usedTvc.push_back(elokaData.id); - break; - case ElokaCircuitType::Announcement: - m_usedAnnouncement.push_back(elokaData.id); - break; - default: - break; + ElokaData elokaData = m_elokaModel->getRowData(i); + switch (elokaData.circuitType) + { + case ElokaCircuitType::Cnr: + m_usedCnr.push_back(elokaData.id); + break; + case ElokaCircuitType::Tvc: + m_usedTvc.push_back(elokaData.id); + break; + case ElokaCircuitType::Announcement: + m_usedAnnouncement.push_back(elokaData.id); + break; + default: + break; + } } - } } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_edit_dialog.cpp old mode 100755 new mode 100644 index 41454723f..a73f2b46a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/Eloka/avm_eloka_edit_dialog.cpp @@ -1,264 +1,233 @@ - -#include -#include - #include "avm_eloka_edit_dialog.h" -#include "ui_avm_eloka_edit_dialog.h" -#include -#include -#include -#include +#include "ui_avm_eloka_edit_dialog.h" + +#include +#include +#include +#include +#include +#include namespace { - - struct ComboBoxUserData { - QString internalName; - AudioVideoManagement::ElokaCircuitType circuitType; - int id; + QString internalName; + AudioVideoManagement::ElokaCircuitType circuitType; + int id; }; - -ComboBoxUserData userDataAt(QComboBox *cb, int index) +ComboBoxUserData userDataAt(QComboBox* cb, int index) { - Q_ASSERT(cb); - Q_ASSERT(index >= 0 && index < cb->count()); - QVariant userData = cb->itemData(index); - Q_ASSERT(userData.canConvert()); - return userData.value(); + Q_ASSERT(cb); + Q_ASSERT(index >= 0 && index < cb->count()); + QVariant userData = cb->itemData(index); + Q_ASSERT(userData.canConvert()); + return userData.value(); } ComboBoxUserData currentUserData(QComboBox* cb) { - Q_ASSERT(cb); - return userDataAt(cb, cb->currentIndex()); + Q_ASSERT(cb); + return userDataAt(cb, cb->currentIndex()); } - - -boost::optional currentId(QComboBox *comboBox, AudioVideoManagement::ElokaCircuitType circuitType) +boost::optional currentId(QComboBox* comboBox, AudioVideoManagement::ElokaCircuitType circuitType) { - Q_ASSERT(comboBox); + Q_ASSERT(comboBox); - int selectedIndex = comboBox->currentIndex(); - if (selectedIndex == -1) - return boost::none; + int selectedIndex = comboBox->currentIndex(); + if (selectedIndex == -1) + return boost::none; - QVariant userData_ = comboBox->itemData(selectedIndex); - Q_ASSERT(userData_.canConvert()); - ComboBoxUserData userData = userData_.value(); - if (userData.circuitType != circuitType) - return boost::none; - - return userData.id; -} - - - -void selectItemWithId(QComboBox *comboBox, boost::optional id) -{ - Q_ASSERT(comboBox); - - if (comboBox->count() == 0) - return; - - if (!id.is_initialized()) - { - comboBox->setCurrentIndex(0); - return; - } - - for (int i = 0; i < comboBox->count(); ++i) - { - QVariant userData_ = comboBox->itemData(i); + QVariant userData_ = comboBox->itemData(selectedIndex); Q_ASSERT(userData_.canConvert()); - ComboBoxUserData userData = userData_.value(); - if (userData.id == *id) - { - comboBox->setCurrentIndex(i); - return; - } - } + ComboBoxUserData userData = userData_.value(); + if (userData.circuitType != circuitType) + return boost::none; - comboBox->setCurrentIndex(0); + return userData.id; } -} +void selectItemWithId(QComboBox* comboBox, boost::optional id) +{ + Q_ASSERT(comboBox); + if (comboBox->count() == 0) + return; + + if (!id.is_initialized()) + { + comboBox->setCurrentIndex(0); + return; + } + + for (int i = 0; i < comboBox->count(); ++i) + { + QVariant userData_ = comboBox->itemData(i); + Q_ASSERT(userData_.canConvert()); + ComboBoxUserData userData = userData_.value(); + if (userData.id == *id) + { + comboBox->setCurrentIndex(i); + return; + } + } + + comboBox->setCurrentIndex(0); +} + +} // namespace Q_DECLARE_METATYPE(ComboBoxUserData) namespace AudioVideoManagement { -ElokaEditDialog::ElokaEditDialog(LtsSession::LtsSession *session, AvaSession *avaSession, Interface::Dtc *avmDtc, StreamNameMapping *streamNameMapping, - const ElokaData &data, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::ElokaEditDialog) - , m_session(session) - , m_streamNameMapping(streamNameMapping) - , m_avaCtrl(avaSession->control()) - , m_avmDtc(avmDtc) - , m_elokaData(data) - , m_cnrConfigMap() - , m_tvcConfigMap() - , m_announcementMap() - , m_userProfile() +ElokaEditDialog::ElokaEditDialog(LtsSession::LtsSession* session, AvaSession* avaSession, Interface::Dtc* avmDtc, + StreamNameMapping* streamNameMapping, const ElokaData& data, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ui(new Ui::ElokaEditDialog), + m_session(session), m_streamNameMapping(streamNameMapping), m_avaCtrl(avaSession->control()), m_avmDtc(avmDtc), + m_elokaData(data), m_cnrConfigMap(), m_tvcConfigMap(), m_announcementMap(), m_userProfile() { - Q_ASSERT(session); - Q_ASSERT(avaSession); - Q_ASSERT(streamNameMapping); - Q_ASSERT(avmDtc); + Q_ASSERT(session); + Q_ASSERT(avaSession); + Q_ASSERT(streamNameMapping); + Q_ASSERT(avmDtc); - m_ui->setupUi(this); + m_ui->setupUi(this); - m_uiRequirements->addRequirement( { m_ui->lbAction, [this]() { return !m_ui->cmbAction->currentText().isEmpty(); } }); - m_uiRequirements->addRequirement( { m_ui->lbCircuit, [this]() { return !m_ui->cmbCircuit->currentText().isEmpty(); } }); + m_uiRequirements->addRequirement({m_ui->lbAction, [this]() { return !m_ui->cmbAction->currentText().isEmpty(); }}); + m_uiRequirements->addRequirement( + {m_ui->lbCircuit, [this]() { return !m_ui->cmbCircuit->currentText().isEmpty(); }}); - setOnlineHelpFilename(QStringLiteral("Situation-Electronic_Warfare_Measures")); + setOnlineHelpFilename(QStringLiteral("Situation-Electronic_Warfare_Measures")); } ElokaEditDialog::~ElokaEditDialog() { - delete m_ui; + delete m_ui; } void ElokaEditDialog::retranslate() { - bool isNew = true; - if (!m_elokaData.internalName.isEmpty()) - isNew = false; + bool isNew = true; + if (!m_elokaData.internalName.isEmpty()) + isNew = false; - translate(m_ui, QString(), isNew, tr("Eloka")); + translate(m_ui, QString(), isNew, tr("Eloka")); } -bool ElokaEditDialog::init(const std::vector &usedCnr, - const std::vector &usedTvc, - const std::vector &usedAnnouncement) +bool ElokaEditDialog::init(const std::vector& usedCnr, const std::vector& usedTvc, + const std::vector& usedAnnouncement) { - setUnchangeable(true); + setUnchangeable(true); #ifndef LTS_DEBUG - m_ui->rbTvc->hide(); + m_ui->rbTvc->hide(); #endif - - getUserProfile(); - - getActiveCnrs(); - - if (m_elokaData.internalName.isEmpty()) - { - for (int used : usedCnr) - m_cnrConfigMap.remove(used); - } - else - { - m_cnrConfigMap.remove(m_elokaData.id); - } + getUserProfile(); - - m_tvcConfigMap = m_avmDtc->tvcConfigs(); - - if (m_elokaData.internalName.isEmpty()) - { - for (int used : usedTvc) - m_tvcConfigMap.remove(used); - } - else - { - m_tvcConfigMap.remove(m_elokaData.id); - } + getActiveCnrs(); - - const QMap streams = m_avmDtc->streams(); - for (const Stream &stream : streams) - { - if ((stream.type() == StreamType_def::AudioOut) || - (stream.type() == StreamType_def::AudioInOut)) - m_announcementMap.insert(stream.id(), stream); - } - - if (m_elokaData.internalName.isEmpty()) - { - for (int used : usedAnnouncement) - m_announcementMap.remove(used); - } - else - { - m_announcementMap.remove(m_elokaData.id); - } - - connect(m_avmDtc, - &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, - this, &ElokaEditDialog::onCnrConfigChanged); - connect(m_avmDtc, - &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, - this, &ElokaEditDialog::onTvcConfigChanged); - connect(m_avmDtc, - &AudioVideoManagement::Interface::Dtc::cnrTvcProfileChanged, - this, &ElokaEditDialog::onCnrTvcProfileChanged); - connect(m_avmDtc, - &AudioVideoManagement::Interface::Dtc::streamChanged, - this, &ElokaEditDialog::onStreamChanged); - - connect(m_ui->cmbCircuit, - QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &ElokaEditDialog::onCmbCircuitChanged); - connect(m_ui->rbCnr, &QRadioButton::toggled, - this, &ElokaEditDialog::onCbCnrToggled); - connect(m_ui->rbAnnouncement, &QRadioButton::toggled, - this, &ElokaEditDialog::onCbAnnouncementToggled); - connect(m_ui->rbTvc, &QRadioButton::toggled, - this, &ElokaEditDialog::onCbTvcToggled); - connect(m_avaCtrl, &AvaControl::getElokaListResponse, - this, &ElokaEditDialog::onGetElokaListResponse); - - if (m_elokaData.internalName.isEmpty()) - { - - checkedRadioButtons(true, false, false); - enabledRadioButtons(true, true, true); - } - else - { - if (m_elokaData.circuitType == ElokaCircuitType::Cnr) + if (m_elokaData.internalName.isEmpty()) { - checkedRadioButtons(true, false, false); - enabledRadioButtons(true, false, false); + for (int used : usedCnr) + m_cnrConfigMap.remove(used); } - if (m_elokaData.circuitType == ElokaCircuitType::Tvc) + else { - checkedRadioButtons(false, true, false); - enabledRadioButtons(false, true, false); + m_cnrConfigMap.remove(m_elokaData.id); } - if (m_elokaData.circuitType == ElokaCircuitType::Announcement) + + m_tvcConfigMap = m_avmDtc->tvcConfigs(); + + if (m_elokaData.internalName.isEmpty()) { - checkedRadioButtons(false, false, true); - enabledRadioButtons(false, false, true); + for (int used : usedTvc) + m_tvcConfigMap.remove(used); + } + else + { + m_tvcConfigMap.remove(m_elokaData.id); } - if (m_elokaData.mode == AvaElokaMode::EndlessLoop) - m_ui->chbEndlessPlayback->setChecked(true); - setCurrentCircuit(m_elokaData); - m_ui->cmbAction->setCurrentText(m_elokaData.action); - } + const QMap streams = m_avmDtc->streams(); + for (const Stream& stream : streams) + { + if ((stream.type() == StreamType_def::AudioOut) || (stream.type() == StreamType_def::AudioInOut)) + m_announcementMap.insert(stream.id(), stream); + } - setUnchangeable(false); - return true; + if (m_elokaData.internalName.isEmpty()) + { + for (int used : usedAnnouncement) + m_announcementMap.remove(used); + } + else + { + m_announcementMap.remove(m_elokaData.id); + } + + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::cnrConfigChanged, this, + &ElokaEditDialog::onCnrConfigChanged); + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, this, + &ElokaEditDialog::onTvcConfigChanged); + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::cnrTvcProfileChanged, this, + &ElokaEditDialog::onCnrTvcProfileChanged); + connect(m_avmDtc, &AudioVideoManagement::Interface::Dtc::streamChanged, this, &ElokaEditDialog::onStreamChanged); + + connect(m_ui->cmbCircuit, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &ElokaEditDialog::onCmbCircuitChanged); + connect(m_ui->rbCnr, &QRadioButton::toggled, this, &ElokaEditDialog::onCbCnrToggled); + connect(m_ui->rbAnnouncement, &QRadioButton::toggled, this, &ElokaEditDialog::onCbAnnouncementToggled); + connect(m_ui->rbTvc, &QRadioButton::toggled, this, &ElokaEditDialog::onCbTvcToggled); + connect(m_avaCtrl, &AvaControl::getElokaListResponse, this, &ElokaEditDialog::onGetElokaListResponse); + + if (m_elokaData.internalName.isEmpty()) + { + + checkedRadioButtons(true, false, false); + enabledRadioButtons(true, true, true); + } + else + { + if (m_elokaData.circuitType == ElokaCircuitType::Cnr) + { + checkedRadioButtons(true, false, false); + enabledRadioButtons(true, false, false); + } + if (m_elokaData.circuitType == ElokaCircuitType::Tvc) + { + checkedRadioButtons(false, true, false); + enabledRadioButtons(false, true, false); + } + if (m_elokaData.circuitType == ElokaCircuitType::Announcement) + { + checkedRadioButtons(false, false, true); + enabledRadioButtons(false, false, true); + } + if (m_elokaData.mode == AvaElokaMode::EndlessLoop) + m_ui->chbEndlessPlayback->setChecked(true); + + setCurrentCircuit(m_elokaData); + m_ui->cmbAction->setCurrentText(m_elokaData.action); + } + + setUnchangeable(false); + return true; } void ElokaEditDialog::checkedRadioButtons(bool cnr, bool tvc, bool announcement) { - m_ui->rbCnr->setChecked(cnr); - m_ui->rbTvc->setChecked(tvc); - m_ui->rbAnnouncement->setChecked(announcement); + m_ui->rbCnr->setChecked(cnr); + m_ui->rbTvc->setChecked(tvc); + m_ui->rbAnnouncement->setChecked(announcement); } void ElokaEditDialog::enabledRadioButtons(bool cnr, bool tvc, bool announcement) @@ -270,288 +239,274 @@ void ElokaEditDialog::enabledRadioButtons(bool cnr, bool tvc, bool announcement) void ElokaEditDialog::onCmbCircuitChanged(int index) { - Q_UNUSED(index); + Q_UNUSED(index); - m_ui->cmbAction->clear(); + m_ui->cmbAction->clear(); - if (m_ui->cmbCircuit->currentText().isEmpty()) - return; + if (m_ui->cmbCircuit->currentText().isEmpty()) + return; - - ComboBoxUserData userData = currentUserData(m_ui->cmbCircuit); - m_avaCtrl->getElokaList(userData.internalName); + ComboBoxUserData userData = currentUserData(m_ui->cmbCircuit); + m_avaCtrl->getElokaList(userData.internalName); } bool ElokaEditDialog::apply() { - ComboBoxUserData userData = currentUserData(m_ui->cmbCircuit); + ComboBoxUserData userData = currentUserData(m_ui->cmbCircuit); - ElokaData data; - data.id = userData.id; - data.internalName = userData.internalName; - data.displayName = m_ui->cmbCircuit->currentText(); - data.party = -1; - data.exerciseId = m_session->exerciseId(); - data.circuitType = userData.circuitType; - data.action = m_ui->cmbAction->currentText(); - data.mode = m_ui->chbEndlessPlayback->isChecked() ? AvaElokaMode::EndlessLoop : AvaElokaMode::Once; - data.startTime = m_session->partitionTime(); + ElokaData data; + data.id = userData.id; + data.internalName = userData.internalName; + data.displayName = m_ui->cmbCircuit->currentText(); + data.party = -1; + data.exerciseId = m_session->exerciseId(); + data.circuitType = userData.circuitType; + data.action = m_ui->cmbAction->currentText(); + data.mode = m_ui->chbEndlessPlayback->isChecked() ? AvaElokaMode::EndlessLoop : AvaElokaMode::Once; + data.startTime = m_session->partitionTime(); - if (userData.circuitType == ElokaCircuitType::Cnr) - data.party = m_cnrConfigMap.value(userData.id).partyId(); + if (userData.circuitType == ElokaCircuitType::Cnr) + data.party = m_cnrConfigMap.value(userData.id).partyId(); + if (m_elokaData.internalName.isEmpty()) + m_avaCtrl->chooseEloka(data.internalName, data.action, data.mode); + else if (m_elokaData.action != data.action) + { + m_avaCtrl->releaseEloka(m_elokaData.internalName); + m_avaCtrl->chooseEloka(data.internalName, data.action, data.mode); + } - if (m_elokaData.internalName.isEmpty()) - m_avaCtrl->chooseEloka(data.internalName, data.action, data.mode); - else if (m_elokaData.action != data.action) - { - m_avaCtrl->releaseEloka(m_elokaData.internalName); - m_avaCtrl->chooseEloka(data.internalName, data.action, data.mode); - } - - m_elokaData = data; - emit signalNewEloka(data); - return true; + m_elokaData = data; + emit signalNewEloka(data); + return true; } void ElokaEditDialog::onCbCnrToggled(bool checked) { - if (!checked) - return; + if (!checked) + return; - fillComboBoxCircuit(ElokaCircuitType::Cnr); + fillComboBoxCircuit(ElokaCircuitType::Cnr); } void ElokaEditDialog::onCbAnnouncementToggled(bool checked) { - if (!checked) - return; + if (!checked) + return; - fillComboBoxCircuit(ElokaCircuitType::Announcement); + fillComboBoxCircuit(ElokaCircuitType::Announcement); } void ElokaEditDialog::onCbTvcToggled(bool checked) { - if (!checked) - return; + if (!checked) + return; - fillComboBoxCircuit(ElokaCircuitType::Tvc); + fillComboBoxCircuit(ElokaCircuitType::Tvc); } void ElokaEditDialog::getActiveCnrs() { - const QMap cnrs = m_avmDtc->cnrConfigs(); - for (const CnrConfig &cnr : cnrs) - { - if (cnr.isActive() == true) - m_cnrConfigMap.insert(cnr.id(), cnr); - } + const QMap cnrs = m_avmDtc->cnrConfigs(); + for (const CnrConfig& cnr : cnrs) + { + if (cnr.isActive() == true) + m_cnrConfigMap.insert(cnr.id(), cnr); + } } -void ElokaEditDialog::onCnrConfigChanged(const CnrConfig &data, - DataModification modType) +void ElokaEditDialog::onCnrConfigChanged(const CnrConfig& data, DataModification modType) { - DEBUG_LOG(m_logger) << "onCnrConfigChanged"; - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - m_cnrConfigMap.insert(data.id(), data); - break; - } - case DataModification::eRemoved: - { - m_cnrConfigMap.remove(data.id()); - break; - } - } + DEBUG_LOG(m_logger) << "onCnrConfigChanged"; + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: { + m_cnrConfigMap.insert(data.id(), data); + break; + } + case DataModification::eRemoved: { + m_cnrConfigMap.remove(data.id()); + break; + } + } - if (m_ui->rbCnr->isChecked()) - fillComboBoxCircuit(ElokaCircuitType::Cnr); + if (m_ui->rbCnr->isChecked()) + fillComboBoxCircuit(ElokaCircuitType::Cnr); } -void ElokaEditDialog::onTvcConfigChanged(const TvcConfig &data, - DataModification modType) +void ElokaEditDialog::onTvcConfigChanged(const TvcConfig& data, DataModification modType) { - DEBUG_LOG(m_logger) << "onTvcConfigChanged"; + DEBUG_LOG(m_logger) << "onTvcConfigChanged"; - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - m_tvcConfigMap.insert(data.id(), data); - break; - } - case DataModification::eRemoved: - { - m_tvcConfigMap.remove(data.id()); - break; - } - } + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: { + m_tvcConfigMap.insert(data.id(), data); + break; + } + case DataModification::eRemoved: { + m_tvcConfigMap.remove(data.id()); + break; + } + } - if (m_ui->rbTvc->isChecked()) - fillComboBoxCircuit(ElokaCircuitType::Tvc); + if (m_ui->rbTvc->isChecked()) + fillComboBoxCircuit(ElokaCircuitType::Tvc); } -void ElokaEditDialog::onStreamChanged(const Stream &data, - DataModification modType) +void ElokaEditDialog::onStreamChanged(const Stream& data, DataModification modType) { - DEBUG_LOG(m_logger) << "onStreamChanged"; + DEBUG_LOG(m_logger) << "onStreamChanged"; - if ((data.type() != StreamType_def::AudioOut) && - (data.type() != StreamType_def::AudioInOut)) - return; + if ((data.type() != StreamType_def::AudioOut) && (data.type() != StreamType_def::AudioInOut)) + return; - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - m_announcementMap.insert(data.id(), data); - break; - } - case DataModification::eRemoved: - { - m_announcementMap.remove(data.id()); - break; - } - } + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: { + m_announcementMap.insert(data.id(), data); + break; + } + case DataModification::eRemoved: { + m_announcementMap.remove(data.id()); + break; + } + } - if (m_ui->rbAnnouncement->isChecked()) - fillComboBoxCircuit(ElokaCircuitType::Announcement); + if (m_ui->rbAnnouncement->isChecked()) + fillComboBoxCircuit(ElokaCircuitType::Announcement); } -void ElokaEditDialog::onCnrTvcProfileChanged(const CnrTvcProfile &data, - DataModification modType) +void ElokaEditDialog::onCnrTvcProfileChanged(const CnrTvcProfile& data, DataModification modType) { - Q_UNUSED(modType); - DEBUG_LOG(m_logger) << "onCnrTvcProfileChanged"; + Q_UNUSED(modType); + DEBUG_LOG(m_logger) << "onCnrTvcProfileChanged"; - if (data.exerciseId() != m_session->exerciseId() || - data.operatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId()) - return; + if (data.exerciseId() != m_session->exerciseId() || + data.operatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId()) + return; - getUserProfile(); + getUserProfile(); - if (m_ui->rbCnr->isChecked()) - fillComboBoxCircuit(ElokaCircuitType::Cnr); - else if (m_ui->rbTvc->isChecked()) - fillComboBoxCircuit(ElokaCircuitType::Tvc); + if (m_ui->rbCnr->isChecked()) + fillComboBoxCircuit(ElokaCircuitType::Cnr); + else if (m_ui->rbTvc->isChecked()) + fillComboBoxCircuit(ElokaCircuitType::Tvc); } void ElokaEditDialog::getUserProfile() { - m_userProfile.clear(); + m_userProfile.clear(); - const QMap cnrTvcProfiles = m_avmDtc->cnrTvcProfiles(); - int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - int exerciseId = m_session->exerciseId(); + const QMap cnrTvcProfiles = m_avmDtc->cnrTvcProfiles(); + int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + int exerciseId = m_session->exerciseId(); - for (const auto &cnrTvcProfile : cnrTvcProfiles) - { - if (cnrTvcProfile.exerciseId() == exerciseId && - cnrTvcProfile.operatorId() == operatorId) + for (const auto& cnrTvcProfile : cnrTvcProfiles) { - for (const auto &cnrTvcProfileData : cnrTvcProfile.data()) - if (cnrTvcProfileData.radioSystemId() == RadioSystem::inner_enum::Cnr) - m_userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Cnr); - else - m_userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Tvc); + if (cnrTvcProfile.exerciseId() == exerciseId && cnrTvcProfile.operatorId() == operatorId) + { + for (const auto& cnrTvcProfileData : cnrTvcProfile.data()) + if (cnrTvcProfileData.radioSystemId() == RadioSystem::inner_enum::Cnr) + m_userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Cnr); + else + m_userProfile.insert(cnrTvcProfileData.radioCircuitId(), ElokaCircuitType::Tvc); - break; + break; + } } - } } void ElokaEditDialog::fillComboBoxCircuit(ElokaCircuitType type) { - boost::optional selectedId = currentId(m_ui->cmbCircuit, type); - m_ui->cmbCircuit->clear(); + boost::optional selectedId = currentId(m_ui->cmbCircuit, type); + m_ui->cmbCircuit->clear(); - switch (type) - { - case ElokaCircuitType::Cnr: - { - for (const CnrConfig &cnr : std::as_const(m_cnrConfigMap)) + switch (type) { - if (!m_userProfile.contains(cnr.id(), ElokaCircuitType::Cnr)) - continue; + case ElokaCircuitType::Cnr: { + for (const CnrConfig& cnr : std::as_const(m_cnrConfigMap)) + { + if (!m_userProfile.contains(cnr.id(), ElokaCircuitType::Cnr)) + continue; - QString internalName = QString::fromStdString(cnr.radioCircuit()); - QVariant userData = QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Cnr, cnr.id()}); - m_ui->cmbCircuit->addItem(internalName, userData); - } - break; - } - case ElokaCircuitType::Tvc: - { - for (const TvcConfig &tvc : std::as_const(m_tvcConfigMap)) - { - if (!m_userProfile.contains(tvc.id(), ElokaCircuitType::Tvc)) - continue; + QString internalName = QString::fromStdString(cnr.radioCircuit()); + QVariant userData = + QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Cnr, cnr.id()}); + m_ui->cmbCircuit->addItem(internalName, userData); + } + break; + } + case ElokaCircuitType::Tvc: { + for (const TvcConfig& tvc : std::as_const(m_tvcConfigMap)) + { + if (!m_userProfile.contains(tvc.id(), ElokaCircuitType::Tvc)) + continue; - QString internalName = QString::fromStdString(tvc.radioCircuit()); - QVariant userData = QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Tvc, tvc.id()}); - m_ui->cmbCircuit->addItem(internalName, userData); + QString internalName = QString::fromStdString(tvc.radioCircuit()); + QVariant userData = + QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Tvc, tvc.id()}); + m_ui->cmbCircuit->addItem(internalName, userData); + } + break; + } + case ElokaCircuitType::Announcement: { + for (const Stream& stream : std::as_const(m_announcementMap)) + { + QString internalName = QString::fromStdString(stream.name()); + QString displayName = m_streamNameMapping->displayName(internalName); + QVariant userData = + QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Announcement, stream.id()}); + m_ui->cmbCircuit->addItem(displayName, userData); + } + break; + } } - break; - } - case ElokaCircuitType::Announcement: - { - for (const Stream &stream : std::as_const(m_announcementMap)) - { - QString internalName = QString::fromStdString(stream.name()); - QString displayName = m_streamNameMapping->displayName(internalName); - QVariant userData = QVariant::fromValue(ComboBoxUserData{internalName, ElokaCircuitType::Announcement, stream.id()}); - m_ui->cmbCircuit->addItem(displayName, userData); - } - break; - } - } - m_ui->cmbCircuit->model()->sort(0); - selectItemWithId(m_ui->cmbCircuit, selectedId); + m_ui->cmbCircuit->model()->sort(0); + selectItemWithId(m_ui->cmbCircuit, selectedId); } -void ElokaEditDialog::setCurrentCircuit(const ElokaData &data) +void ElokaEditDialog::setCurrentCircuit(const ElokaData& data) { - for (int i = 0; i < m_ui->cmbCircuit->count(); ++i) - { - ComboBoxUserData userData = userDataAt(m_ui->cmbCircuit, i); - if (userData.circuitType != data.circuitType) - continue; + for (int i = 0; i < m_ui->cmbCircuit->count(); ++i) + { + ComboBoxUserData userData = userDataAt(m_ui->cmbCircuit, i); + if (userData.circuitType != data.circuitType) + continue; - if (userData.id != data.id) - continue; + if (userData.id != data.id) + continue; - m_ui->cmbCircuit->setCurrentIndex(i); - return; - } + m_ui->cmbCircuit->setCurrentIndex(i); + return; + } - Q_ASSERT(false); + Q_ASSERT(false); } -void ElokaEditDialog::onGetElokaListResponse(const QVector &actions) +void ElokaEditDialog::onGetElokaListResponse(const QVector& actions) { - DEBUG_LOG(m_logger) << "onGetElokaListResponse"; - if (!m_elokaData.internalName.isEmpty()) - setUnchangeable(true); + DEBUG_LOG(m_logger) << "onGetElokaListResponse"; + if (!m_elokaData.internalName.isEmpty()) + setUnchangeable(true); - m_ui->cmbAction->clear(); + m_ui->cmbAction->clear(); - if (actions.isEmpty()) - return; + if (actions.isEmpty()) + return; - for (const QString &action : actions) - m_ui->cmbAction->addItem(action); + for (const QString& action : actions) + m_ui->cmbAction->addItem(action); - if(m_elokaData.action.isEmpty() == false) - m_ui->cmbAction->setCurrentText(m_elokaData.action); + if (m_elokaData.action.isEmpty() == false) + m_ui->cmbAction->setCurrentText(m_elokaData.action); - if (!m_elokaData.internalName.isEmpty()) - setUnchangeable(false); + if (!m_elokaData.internalName.isEmpty()) + setUnchangeable(false); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.cpp old mode 100755 new mode 100644 index 2d4509c48..775e38187 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.cpp @@ -1,218 +1,191 @@ - #include "avm_mvs_dialog.h" -#include "ui_avm_mvs_dialog.h" -#include "avm_mvs_edit_dialog.h" -#include -#include -#include -#include +#include "avm_mvs_edit_dialog.h" +#include "ui_avm_mvs_dialog.h" + +#include #include +#include +#include +#include #include namespace AudioVideoManagement { -MvsDialog::MvsDialog(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_session(session) - , m_ui(new Ui::MvsDialog) - , m_menuGroup(menuGroup) - , m_model(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_avmDtc(nullptr) - , m_avmFtc(nullptr) +MvsDialog::MvsDialog(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_session(session), + m_ui(new Ui::MvsDialog), m_menuGroup(menuGroup), m_model(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_avmDtc(nullptr), m_avmFtc(nullptr) { - m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-Configuration_Video_Teams")); + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Situation-Configuration_Video_Teams")); } MvsDialog::~MvsDialog() { - delete m_ui; + delete m_ui; } void MvsDialog::retranslate() { - translate(m_ui, tr("Configure Mobile Video Teams")); + translate(m_ui, tr("Configure Mobile Video Teams")); } void MvsDialog::tableColumnOrganiserSetting() { - - m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); } -bool MvsDialog::init(const std::shared_ptr &avmDtc, const std::shared_ptr &avmFtc) +bool MvsDialog::init(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc) { - delete m_model; - m_model = new MvsModel(this); - - m_avmDtc = avmDtc; - m_avmFtc = avmFtc; - - if (!m_model->init(m_session->exerciseId(), avmDtc)) - { delete m_model; - m_model = nullptr; - ERROR_LOG(m_logger) << "Could not init model"; - return false; - } + m_model = new MvsModel(this); - m_ui->dataView->setModel(m_model); + m_avmDtc = avmDtc; + m_avmFtc = avmFtc; - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MvsDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MvsDialog::onEditClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MvsDialog::onRemoveClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &MvsDialog::onPrint); + if (!m_model->init(m_session->exerciseId(), avmDtc)) + { + delete m_model; + m_model = nullptr; + ERROR_LOG(m_logger) << "Could not init model"; + return false; + } - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &MvsDialog::onSelectionChanged); + m_ui->dataView->setModel(m_model); - onSelectionChanged(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MvsDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MvsDialog::onEditClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MvsDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &MvsDialog::onPrint); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &MvsDialog::onEditClicked); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, &MvsDialog::onSelectionChanged); - - m_buttonBox->connectLibraryButton(this, - &MvsDialog::onImportButtonClicked, - &MvsDialog::onExportButtonClicked); + onSelectionChanged(); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, this, &MvsDialog::onEditClicked); - return true; + m_buttonBox->connectLibraryButton(this, &MvsDialog::onImportButtonClicked, &MvsDialog::onExportButtonClicked); + + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + + return true; } -void MvsDialog::onVideoTeamModifyReply(const Core::FunctionReplyObject &replyObject) +void MvsDialog::onVideoTeamModifyReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } - void MvsDialog::onAddClicked() { - EditVideoTeamDialog *dialog = new EditVideoTeamDialog(m_avmDtc, m_session->exerciseId(), this); + EditVideoTeamDialog* dialog = new EditVideoTeamDialog(m_avmDtc, m_session->exerciseId(), this); - connect(dialog, &EditVideoTeamDialog::modifyRequest, this, [this](const AudioVideoManagement::VideoTeamModifyRequest & request) - { - m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->videoTeamModifyRequest(request, this); - }); - }); + connect(dialog, &EditVideoTeamDialog::modifyRequest, this, + [this](const AudioVideoManagement::VideoTeamModifyRequest& request) { + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->videoTeamModifyRequest(request, this); }); + }); - addDialog(dialog, m_menuGroup, QStringLiteral("NewVideoTeam"), LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, QStringLiteral("NewVideoTeam"), LtsWidgets::LayoutArea::eDialogTab); } void MvsDialog::onEditClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - AudioVideoManagement::VideoTeam config = m_model->getRowData(currentIndex.row()); - EditVideoTeamDialog *dialog = new EditVideoTeamDialog(config.id(), - m_avmDtc, - m_session->exerciseId(), - config, - this); + AudioVideoManagement::VideoTeam config = m_model->getRowData(currentIndex.row()); + EditVideoTeamDialog* dialog = new EditVideoTeamDialog(config.id(), m_avmDtc, m_session->exerciseId(), config, this); - connect(dialog, &EditVideoTeamDialog::modifyRequest, this, [this](const AudioVideoManagement::VideoTeamModifyRequest & request) - { - m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->videoTeamModifyRequest(request, this); - }); - }); + connect(dialog, &EditVideoTeamDialog::modifyRequest, this, + [this](const AudioVideoManagement::VideoTeamModifyRequest& request) { + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->videoTeamModifyRequest(request, this); }); + }); - addDialog(dialog, m_menuGroup, QStringLiteral("EditVideoTeam%1").arg(config.id()), LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, QStringLiteral("EditVideoTeam%1").arg(config.id()), + LtsWidgets::LayoutArea::eDialogTab); } void MvsDialog::onRemoveClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - AudioVideoManagement::VideoTeamModifyRequest request; - const VideoTeam team = m_model->getRowData(currentIndex.row()); - request.id(team.id()); - request.name(team.name()); - request.ssrc(team.ssrc()); - request.streamName(team.streamName()); - request.vtPort(team.vtPort()); - request.exerciseId(0); + AudioVideoManagement::VideoTeamModifyRequest request; + const VideoTeam team = m_model->getRowData(currentIndex.row()); + request.id(team.id()); + request.name(team.name()); + request.ssrc(team.ssrc()); + request.streamName(team.streamName()); + request.vtPort(team.vtPort()); + request.exerciseId(0); - m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->videoTeamModifyRequest(request, this); - }); - m_model->removeRow(currentIndex.row()); + m_requestHelper->startSingleRequest([this, request]() { return m_avmFtc->videoTeamModifyRequest(request, this); }); + m_model->removeRow(currentIndex.row()); } void MvsDialog::onSelectionChanged() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, currentIndex.isValid()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, currentIndex.isValid()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, currentIndex.isValid()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, currentIndex.isValid()); } void MvsDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); + LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); } - - void MvsDialog::onExportButtonClicked() { - QByteArray byteArray = m_model->modelToJson(); + QByteArray byteArray = m_model->modelToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void MvsDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMMvsDialog)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMMvsDialog))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMMvsDialog)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - const QVector requests = m_model->jsonToVideoTeamVector(content); - for (const auto &request : requests) - { - m_requestHelper->startSingleRequest([this, request]() + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMMvsDialog))) { - return m_avmFtc->videoTeamModifyRequest(request, this); - }); - } - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + const QVector requests = m_model->jsonToVideoTeamVector(content); + for (const auto& request : requests) + { + m_requestHelper->startSingleRequest( + [this, request]() { return m_avmFtc->videoTeamModifyRequest(request, this); }); + } + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + } } - } -} } +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.h old mode 100755 new mode 100644 index 7f4765d35..4114907fd --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_dialog.h @@ -1,16 +1,13 @@ - #pragma once -#include - -#include -#include -#include - #include "avm_mvs_model.h" +#include +#include +#include +#include #include namespace Ui @@ -34,7 +31,7 @@ namespace Interface { class Dtc; } -} +} // namespace AudioVideoManagement namespace ParticipantManagement { @@ -42,48 +39,47 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace AudioVideoManagement { -class MvsDialog - : public LtsWidgets::LtsDialog - , protected AudioVideoManagement::Interface::Ftc::VideoTeamModifyReplyHandler +class MvsDialog : public LtsWidgets::LtsDialog, + protected AudioVideoManagement::Interface::Ftc::VideoTeamModifyReplyHandler { - Q_OBJECT -public: - explicit MvsDialog(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~MvsDialog(); + Q_OBJECT + public: + explicit MvsDialog(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~MvsDialog(); - bool init(const std::shared_ptr &avmDtc, const std::shared_ptr &avmFtc); + bool init(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc); - void onVideoTeamModifyReply(const Core::FunctionReplyObject &replyObject) override final; + void onVideoTeamModifyReply(const Core::FunctionReplyObject& replyObject) override final; -private Q_SLOTS: - void onAddClicked(); - void onEditClicked(); - void onRemoveClicked(); - void onSelectionChanged(); - void onPrint(); - void onExportButtonClicked(); - void onImportButtonClicked(); + private Q_SLOTS: + void onAddClicked(); + void onEditClicked(); + void onRemoveClicked(); + void onSelectionChanged(); + void onPrint(); + void onExportButtonClicked(); + void onImportButtonClicked(); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void tableColumnOrganiserSetting() override; + private: + LtsSession::LtsSession* m_session; + Ui::MvsDialog* m_ui; + QString m_menuGroup; + MvsModel* m_model; + LtsUtils::RequestHelper* m_requestHelper; -private: - LtsSession::LtsSession *m_session; - Ui::MvsDialog *m_ui; - QString m_menuGroup; - MvsModel *m_model; - LtsUtils::RequestHelper *m_requestHelper; - - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - std::shared_ptr m_flmGui; -}; -} + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + std::shared_ptr m_flmGui; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_edit_dialog.h old mode 100755 new mode 100644 index 55da771d4..d1727f5c4 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_edit_dialog.h @@ -1,13 +1,11 @@ - #pragma once -#include - -#include #include #include +#include +#include class QCheckBox; @@ -16,55 +14,46 @@ namespace Ui class EditVideoTeamDialog; } - namespace AudioVideoManagement { -class EditVideoTeamDialog - : public LtsWidgets::LtsDialog +class EditVideoTeamDialog : public LtsWidgets::LtsDialog { - Q_OBJECT -public: - explicit EditVideoTeamDialog(const std::shared_ptr &avmDtc, - int32_t exerciseId, - QWidget *parent = nullptr); - explicit EditVideoTeamDialog(int32_t id, - const std::shared_ptr &avmDtc, - int32_t exerciseId, - const VideoTeam &team, - QWidget *parent); + Q_OBJECT + public: + explicit EditVideoTeamDialog(const std::shared_ptr& avmDtc, + int32_t exerciseId, QWidget* parent = nullptr); + explicit EditVideoTeamDialog(int32_t id, const std::shared_ptr& avmDtc, + int32_t exerciseId, const VideoTeam& team, QWidget* parent); - ~EditVideoTeamDialog(); + ~EditVideoTeamDialog(); - void retranslate() override; + void retranslate() override; -Q_SIGNALS: - void modifyRequest(const AudioVideoManagement::VideoTeamModifyRequest &request); + Q_SIGNALS: + void modifyRequest(const AudioVideoManagement::VideoTeamModifyRequest& request); -protected: + protected: + NGL::INGLLogger& m_logger; + bool apply() override; -NGL::INGLLogger &m_logger; - bool apply() override; + private: + EditVideoTeamDialog(int32_t id, const std::shared_ptr& avmDtc, + int32_t exerciseId, QWidget* parent); -private: - EditVideoTeamDialog(int32_t id, - const std::shared_ptr &avmDtc, - int32_t exerciseId, - QWidget *parent); + void init(); - void init(); + private Q_SLOTS: + void onCheckTakenTeams(); + void onCurrentTeamChanged(); -private Q_SLOTS: - void onCheckTakenTeams(); - void onCurrentTeamChanged(); + private: + Ui::EditVideoTeamDialog* m_ui; -private: - Ui::EditVideoTeamDialog *m_ui; - - int32_t m_exerciseId; - int32_t m_id; - VideoTeam m_videoTeam; - std::shared_ptr m_avmDtc; - QMap m_takenTeams; - QMap m_teamsToIndex; -}; -} + int32_t m_exerciseId; + int32_t m_id; + VideoTeam m_videoTeam; + std::shared_ptr m_avmDtc; + QMap m_takenTeams; + QMap m_teamsToIndex; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.cpp old mode 100755 new mode 100644 index 008ac1543..52a52ba6e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.cpp @@ -1,138 +1,130 @@ - #include "avm_mvs_dialog.h" -#include +#include #include -#include #include +#include namespace AudioVideoManagement { -MvsModel::MvsModel(QObject *parent) - : LtsAbstractTableModel( +MvsModel::MvsModel(QObject* parent) + : LtsAbstractTableModel({tr("Video Team Name"), tr("Stream Name")}, parent), + m_exerciseId(-1) { - tr("Video Team Name"), - tr("Stream Name") -}, parent) -, m_exerciseId(-1) -{} - -QVariant MvsModel::data(const QModelIndex &index, int role) const -{ - if (role != Qt::DisplayRole || !indexIsValid(index)) - return QVariant(); - - const AudioVideoManagement::VideoTeam &config = m_vecData.at(index.row()); - - switch (index.column()) - { - case CHANNEL: - return QString::fromStdString(m_videoTeams.value(config.id()).name()); - case STREAM_NAME: - return QString::fromStdString(config.streamName()); - } - - return QVariant(); } -bool MvsModel::init(int32_t exerciseId, const std::shared_ptr &avmDtc) +QVariant MvsModel::data(const QModelIndex& index, int role) const { - m_avmDtc = avmDtc; - m_exerciseId = exerciseId; + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); - m_videoTeams = avmDtc->videoTeams(); + const AudioVideoManagement::VideoTeam& config = m_vecData.at(index.row()); - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, - this, [this](const AudioVideoManagement::VideoTeam & data, DataModification modType) - { - Q_UNUSED(modType); + switch (index.column()) + { + case CHANNEL: + return QString::fromStdString(m_videoTeams.value(config.id()).name()); + case STREAM_NAME: + return QString::fromStdString(config.streamName()); + } - if (data.exerciseId() == m_exerciseId) - onDataChanged(data, DataModification::eAdded); - else - onDataChanged(data, DataModification::eRemoved); - } - ); + return QVariant(); +} - QVector configs; - const QMap configMap = m_avmDtc->videoTeams(); - for (auto it = configMap.begin(); it != configMap.end(); ++it) - { - if (it.value().exerciseId() == m_exerciseId) - configs.append(it.value()); - } - setData(configs); +bool MvsModel::init(int32_t exerciseId, const std::shared_ptr& avmDtc) +{ + m_avmDtc = avmDtc; + m_exerciseId = exerciseId; - return true; + m_videoTeams = avmDtc->videoTeams(); + + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::videoTeamChanged, this, + [this](const AudioVideoManagement::VideoTeam& data, DataModification modType) { + Q_UNUSED(modType); + + if (data.exerciseId() == m_exerciseId) + onDataChanged(data, DataModification::eAdded); + else + onDataChanged(data, DataModification::eRemoved); + }); + + QVector configs; + const QMap configMap = m_avmDtc->videoTeams(); + for (auto it = configMap.begin(); it != configMap.end(); ++it) + { + if (it.value().exerciseId() == m_exerciseId) + configs.append(it.value()); + } + setData(configs); + + return true; } QByteArray MvsModel::modelToJson() { - QJsonObject obj; - QJsonArray arr; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMMvsDialog); + QJsonObject obj; + QJsonArray arr; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMMvsDialog); - for (int row = 0; row < rowCount(); row++) - { - DEBUG_LOG(m_logger) << "row =" << ": " << row; - QJsonObject inner; - const VideoTeam &config = m_vecData.at(row); - inner[QStringLiteral("id")] = config.id(); - inner[QStringLiteral("exerciseId")] = config.exerciseId(); - inner[QStringLiteral("name")] = QString::fromStdString(config.name()); - inner[QStringLiteral("streamName")] = QString::fromStdString(config.streamName()); - arr += inner; - } + for (int row = 0; row < rowCount(); row++) + { + DEBUG_LOG(m_logger) << "row =" << ": " << row; + QJsonObject inner; + const VideoTeam& config = m_vecData.at(row); + inner[QStringLiteral("id")] = config.id(); + inner[QStringLiteral("exerciseId")] = config.exerciseId(); + inner[QStringLiteral("name")] = QString::fromStdString(config.name()); + inner[QStringLiteral("streamName")] = QString::fromStdString(config.streamName()); + arr += inner; + } - obj[QStringLiteral("videoTeams")] = arr; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + obj[QStringLiteral("videoTeams")] = arr; + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -QVector MvsModel::jsonToVideoTeamVector(const QByteArray &content) -{ - - QVector result; - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); - const QJsonArray arr(obj.value(QStringLiteral("videoTeams")).toArray()); - for (const auto &ele : arr) - { - const QJsonObject obj(ele.toObject()); - int id = obj[QStringLiteral("id")].toInt(); - if (id <= 0) - return QVector(); - - const VideoTeam team = m_avmDtc->videoTeam(id); - if (!m_avmDtc->isFreeVideoTeam(m_exerciseId, id)) - continue; - - VideoTeamModifyRequest config; - config.id(id); - config.name(team.name()); - config.ssrc(team.ssrc()); - config.vtPort(team.vtPort()); - config.exerciseId(m_exerciseId); - config.streamName(obj[QStringLiteral("streamName")].toString().toStdString()); - - INFO_LOG(m_logger) << "insertRow: " << config.name() - << " VideoTeamId=" << config.id(); - result.append(std::move(config)); - } - return result; -} - -bool MvsModel::isFiltered(const VideoTeam &data, DataModification modType) const +QVector MvsModel::jsonToVideoTeamVector(const QByteArray& content) { - Q_UNUSED(modType) - if (data.exerciseId() != m_exerciseId) - return true; - return false; + QVector result; + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); + const QJsonArray arr(obj.value(QStringLiteral("videoTeams")).toArray()); + for (const auto& ele : arr) + { + const QJsonObject obj(ele.toObject()); + int id = obj[QStringLiteral("id")].toInt(); + if (id <= 0) + return QVector(); + const VideoTeam team = m_avmDtc->videoTeam(id); + if (!m_avmDtc->isFreeVideoTeam(m_exerciseId, id)) + continue; + + VideoTeamModifyRequest config; + config.id(id); + config.name(team.name()); + config.ssrc(team.ssrc()); + config.vtPort(team.vtPort()); + config.exerciseId(m_exerciseId); + config.streamName(obj[QStringLiteral("streamName")].toString().toStdString()); + + INFO_LOG(m_logger) << "insertRow: " << config.name() << " VideoTeamId=" << config.id(); + result.append(std::move(config)); + } + return result; } -} +bool MvsModel::isFiltered(const VideoTeam& data, DataModification modType) const +{ + + Q_UNUSED(modType) + if (data.exerciseId() != m_exerciseId) + return true; + return false; +} + +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.h old mode 100755 new mode 100644 index ed6a9f416..e2a82db0a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_model.h @@ -1,46 +1,38 @@ - #pragma once -#include - -#include #include - +#include +#include #include namespace AudioVideoManagement { -class MvsModel final - : public LtsWidgets::LtsAbstractTableModel +class MvsModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - CHANNEL, - STREAM_NAME, - COUNT - }; + public: + enum Columns { CHANNEL, STREAM_NAME, COUNT }; - explicit MvsModel(QObject *parent = nullptr); + explicit MvsModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role) const override final; + QVariant data(const QModelIndex& index, int role) const override final; - bool init(int32_t exerciseId, const std::shared_ptr &avmDtc); - QByteArray modelToJson(); - QVector jsonToVideoTeamVector(const QByteArray &content); - bool isFiltered(const VideoTeam &data, DataModification modType) const override; -private: -NGL::INGLLogger &m_logger; - std::shared_ptr m_avmDtc; - int32_t m_exerciseId; + bool init(int32_t exerciseId, const std::shared_ptr& avmDtc); + QByteArray modelToJson(); + QVector jsonToVideoTeamVector(const QByteArray& content); + bool isFiltered(const VideoTeam& data, DataModification modType) const override; - QMap m_videoTeams; -}; -} + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_avmDtc; + int32_t m_exerciseId; + + QMap m_videoTeams; +}; +} // namespace AudioVideoManagement Q_DECLARE_METATYPE(AudioVideoManagement::VideoTeam) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.cpp old mode 100755 new mode 100644 index f54c53947..22ee9eaaf --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.cpp @@ -1,265 +1,237 @@ - #include "avm_mvs_video_team_dialog.h" -#include "ui_avm_mvs_video_team_dialog.h" #include "receiverelement.h" +#include "ui_avm_mvs_video_team_dialog.h" +#include #include #include -#include #include namespace AudioVideoManagement { -MvsVideoTeamDialog::MvsVideoTeamDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::MvsVideoTeamDialog) - , m_session(nullptr) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_flmGui(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +MvsVideoTeamDialog::MvsVideoTeamDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ui(new Ui::MvsVideoTeamDialog), + m_session(nullptr), m_dtc(nullptr), m_ftc(nullptr), m_flmGui(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-Mobile_Video_System")); - -} + setOnlineHelpFilename(QStringLiteral("Situation-Mobile_Video_System")); +} MvsVideoTeamDialog::~MvsVideoTeamDialog() { - delete m_ui; -} + delete m_ui; +} void MvsVideoTeamDialog::retranslate() { - QString text = tr("Mobile Video System"); - translate(m_ui, text); + QString text = tr("Mobile Video System"); + translate(m_ui, text); } void MvsVideoTeamDialog::enaDisa(bool enable) { - Q_UNUSED(enable); - - if (!m_flmGui) - { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Export, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Import, false); - } + Q_UNUSED(enable); + if (!m_flmGui) + { + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Export, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Import, false); + } } - -bool MvsVideoTeamDialog::init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc) +bool MvsVideoTeamDialog::init(LtsSession::LtsSession* session, + const std::shared_ptr& dtc, + const std::shared_ptr& ftc) { - m_session = session; + m_session = session; - m_dtc = dtc; - m_ftc = ftc; + m_dtc = dtc; + m_ftc = ftc; - session->getForeignGuiInterface(m_flmGui); - session->getDtc(m_ismDtc); + session->getForeignGuiInterface(m_flmGui); + session->getDtc(m_ismDtc); - m_receiverMap = m_dtc->videoReceivers(); + m_receiverMap = m_dtc->videoReceivers(); + int row = 1; + int column = 2; - - int row = 1; - int column = 2; + QMap teamMap; + auto cbVt = [this, &row, &teamMap](const AudioVideoManagement::VideoTeam& vt) { + if (vt.exerciseId() != m_session->exerciseId()) + return; - QMap teamMap; - auto cbVt = [this, &row, &teamMap](const AudioVideoManagement::VideoTeam & vt) - { - if (vt.exerciseId() != m_session->exerciseId()) - return; - - - m_teamToRow.insert(vt.programId() == 3 ? 2 : 1, vt.programId() == 3 ? 2 : 1); - teamMap.insert(vt.name(), vt); - }; - m_dtc->videoTeams(cbVt); + m_teamToRow.insert(vt.programId() == 3 ? 2 : 1, vt.programId() == 3 ? 2 : 1); + teamMap.insert(vt.name(), vt); + }; + m_dtc->videoTeams(cbVt); - const QMap vts = m_dtc->videoReceivers(); - QSet teamId; - for (auto rec : vts) - { - if (teamMap.value(rec.streamName()).id() > 0) - teamId.insert(rec.teamId()); - } - for (auto team: teamId) - { - QLabel *lbl = new QLabel(QStringLiteral("MLVS")+QString::number(team), this); - m_ui->glMvs->addWidget(lbl, team == 1 ? 1 : 2, 0); - } - - auto cbMs = [this, &column](const InfrastructureManagement::MainStructureElement & mse) - { - if (mse.structureElementTypeId() == InfrastructureManagement::StructureElementType::RadioStation && !mse.isDeleted() && mse.id() > 0) + const QMap vts = m_dtc->videoReceivers(); + QSet teamId; + for (auto rec : vts) { - m_stationToColumn.insert(mse.id(), column); - QLabel *lblStation = new QLabel(QString::fromStdString(mse.name()), this); - lblStation->setProperty("RadioStation", true); - lblStation->setProperty("column", column); - lblStation->setProperty("name", QString::fromStdString(mse.name())); - m_ui->glMvs->addWidget(lblStation, 0, column++); - lblStation->hide(); + if (teamMap.value(rec.streamName()).id() > 0) + teamId.insert(rec.teamId()); } - }; - m_ismDtc->mainStructureElements(cbMs); - - auto cbRec = [this, teamMap](const AudioVideoManagement::VideoReceiver & rec) - { - if (m_teamToRow.value(rec.teamId()) <= 0) - return; - if (!teamMap.contains(rec.streamName())) - return; - m_receiverMap.insert(rec.id(), rec); - if (m_stationToColumn.value(rec.mainStructureElementId()) > 0 && m_teamToRow.value(rec.teamId()) > 0) + for (auto team : teamId) { - ReceiverElement *btn = createReceiverElement(rec); - - int row = m_teamToRow.value(rec.teamId()); - int column = m_stationToColumn.value(rec.mainStructureElementId()); - if (!m_videoTeamButtonGroup.contains(row)) - { - QRadioButton *none = new QRadioButton(tr("None"), this); - none->setChecked(true); + QLabel* lbl = new QLabel(QStringLiteral("MLVS") + QString::number(team), this); + m_ui->glMvs->addWidget(lbl, team == 1 ? 1 : 2, 0); + } - m_ui->glMvs->addWidget(none, row, 1); - m_videoTeamButtonGroup.insert(row, new QButtonGroup(this)); - m_videoTeamButtonGroup[row]->addButton(none, 0); - } - m_videoTeamButtonGroup[row]->addButton(btn->radioButton(), rec.mainStructureElementId()); - m_videoTeamButtonGroup[row]->setProperty("teamId", rec.teamId()); - m_receiverIds.insert(QPair(rec.mainStructureElementId(), rec.teamId()), rec.id()); - bool isActive = rec.isActive(); - btn->setButtonChecked(isActive); - btn->radioButton()->setChecked(isActive); - m_ui->glMvs->addWidget(btn, row, column); - - for (int i = 0; i < m_ui->glMvs->count(); i++) - { - QWidget* widget = m_ui->glMvs->itemAt(i)->widget(); - if ( widget->property("RadioStation").toBool() && widget->property("column").toInt() == column) + auto cbMs = [this, &column](const InfrastructureManagement::MainStructureElement& mse) { + if (mse.structureElementTypeId() == InfrastructureManagement::StructureElementType::RadioStation && + !mse.isDeleted() && mse.id() > 0) { - widget->show(); + m_stationToColumn.insert(mse.id(), column); + QLabel* lblStation = new QLabel(QString::fromStdString(mse.name()), this); + lblStation->setProperty("RadioStation", true); + lblStation->setProperty("column", column); + lblStation->setProperty("name", QString::fromStdString(mse.name())); + m_ui->glMvs->addWidget(lblStation, 0, column++); + lblStation->hide(); } - } - } - }; - m_dtc->videoReceivers(cbRec); - enaDisa(true); + }; + m_ismDtc->mainStructureElements(cbMs); + auto cbRec = [this, teamMap](const AudioVideoManagement::VideoReceiver& rec) { + if (m_teamToRow.value(rec.teamId()) <= 0) + return; + if (!teamMap.contains(rec.streamName())) + return; + m_receiverMap.insert(rec.id(), rec); + if (m_stationToColumn.value(rec.mainStructureElementId()) > 0 && m_teamToRow.value(rec.teamId()) > 0) + { + ReceiverElement* btn = createReceiverElement(rec); - connect(m_dtc.get(), &AudioVideoManagement::Interface::Dtc::videoReceiverChanged, this, &MvsVideoTeamDialog::updateReceiverButton); + int row = m_teamToRow.value(rec.teamId()); + int column = m_stationToColumn.value(rec.mainStructureElementId()); + if (!m_videoTeamButtonGroup.contains(row)) + { + QRadioButton* none = new QRadioButton(tr("None"), this); + none->setChecked(true); - return true; + m_ui->glMvs->addWidget(none, row, 1); + m_videoTeamButtonGroup.insert(row, new QButtonGroup(this)); + m_videoTeamButtonGroup[row]->addButton(none, 0); + } + m_videoTeamButtonGroup[row]->addButton(btn->radioButton(), rec.mainStructureElementId()); + m_videoTeamButtonGroup[row]->setProperty("teamId", rec.teamId()); + m_receiverIds.insert(QPair(rec.mainStructureElementId(), rec.teamId()), rec.id()); + bool isActive = rec.isActive(); + btn->setButtonChecked(isActive); + btn->radioButton()->setChecked(isActive); + m_ui->glMvs->addWidget(btn, row, column); + + for (int i = 0; i < m_ui->glMvs->count(); i++) + { + QWidget* widget = m_ui->glMvs->itemAt(i)->widget(); + if (widget->property("RadioStation").toBool() && widget->property("column").toInt() == column) + { + widget->show(); + } + } + } + }; + m_dtc->videoReceivers(cbRec); + enaDisa(true); + + connect(m_dtc.get(), &AudioVideoManagement::Interface::Dtc::videoReceiverChanged, this, + &MvsVideoTeamDialog::updateReceiverButton); + + return true; } -void MvsVideoTeamDialog::setData() -{ - -} +void MvsVideoTeamDialog::setData() {} bool MvsVideoTeamDialog::apply() { - VideoReceiverModifyActiveRequest req; - DEBUG_LOG(m_logger) << "apply m_videoTeamButtonGroup.size=" << m_videoTeamButtonGroup.size(); - QMap ::const_iterator itBg; - for (itBg = m_videoTeamButtonGroup.constBegin(); itBg != m_videoTeamButtonGroup.constEnd(); ++itBg) - { - int teamId = itBg.value()->property("teamId").toInt(); - int mainStructureElementId = itBg.value()->checkedId(); - int oldActiveId = m_dtc->getActiveVideoReceiver(teamId); - - DEBUG_LOG(m_logger) << "Team id = " << teamId; - DEBUG_LOG(m_logger) << "Main structure element id = " << mainStructureElementId; - DEBUG_LOG(m_logger) << "Old active video receiver = " << oldActiveId; - - if (itBg.value()->checkedId() == 0) + VideoReceiverModifyActiveRequest req; + DEBUG_LOG(m_logger) << "apply m_videoTeamButtonGroup.size=" << m_videoTeamButtonGroup.size(); + QMap::const_iterator itBg; + for (itBg = m_videoTeamButtonGroup.constBegin(); itBg != m_videoTeamButtonGroup.constEnd(); ++itBg) { - req.isActive(false); - req.id(0); - QMapIterator i(m_receiverMap); - while (i.hasNext()) - { - i.next(); - if ((i.value().isActive()) - && i.value().teamId() == teamId) - req.id(i.value().id()); - } - } - else - { - req.isActive(true); - req.id(m_receiverIds.value(QPair(mainStructureElementId, teamId))); - } - DEBUG_LOG(m_logger) << "itBg.key=" << itBg.key() - << " mainStructureElementId=" << mainStructureElementId - << " teamId=" << teamId - << " id=" << req.id() - << " isActive=" << req.isActive(); + int teamId = itBg.value()->property("teamId").toInt(); + int mainStructureElementId = itBg.value()->checkedId(); + int oldActiveId = m_dtc->getActiveVideoReceiver(teamId); - - if ((m_receiverMap.value(req.id()).isActive() != req.isActive()) - && req.id() > 0) - { - - if (oldActiveId > 0) - { - VideoReceiverModifyActiveRequest reqInactive; - reqInactive.id(oldActiveId); - reqInactive.isActive(false); - m_requestHelper->addRequest([this, reqInactive]() + DEBUG_LOG(m_logger) << "Team id = " << teamId; + DEBUG_LOG(m_logger) << "Main structure element id = " << mainStructureElementId; + DEBUG_LOG(m_logger) << "Old active video receiver = " << oldActiveId; + + if (itBg.value()->checkedId() == 0) { - return m_ftc->videoReceiverModifyActiveRequest(reqInactive, this); - }); - } - m_requestHelper->addRequest([this, req]() - { - return m_ftc->videoReceiverModifyActiveRequest(req, this); - }); + req.isActive(false); + req.id(0); + QMapIterator i(m_receiverMap); + while (i.hasNext()) + { + i.next(); + if ((i.value().isActive()) && i.value().teamId() == teamId) + req.id(i.value().id()); + } + } + else + { + req.isActive(true); + req.id(m_receiverIds.value(QPair(mainStructureElementId, teamId))); + } + DEBUG_LOG(m_logger) << "itBg.key=" << itBg.key() << " mainStructureElementId=" << mainStructureElementId + << " teamId=" << teamId << " id=" << req.id() << " isActive=" << req.isActive(); + + if ((m_receiverMap.value(req.id()).isActive() != req.isActive()) && req.id() > 0) + { + + if (oldActiveId > 0) + { + VideoReceiverModifyActiveRequest reqInactive; + reqInactive.id(oldActiveId); + reqInactive.isActive(false); + m_requestHelper->addRequest( + [this, reqInactive]() { return m_ftc->videoReceiverModifyActiveRequest(reqInactive, this); }); + } + m_requestHelper->addRequest([this, req]() { return m_ftc->videoReceiverModifyActiveRequest(req, this); }); + } } - } - return m_requestHelper->startRequests(); + return m_requestHelper->startRequests(); } -ReceiverElement *MvsVideoTeamDialog::createReceiverElement(const VideoReceiver &rec) +ReceiverElement* MvsVideoTeamDialog::createReceiverElement(const VideoReceiver& rec) { - ReceiverElement *re = new ReceiverElement(this); - re->init(rec); - if (rec.isActive()) - m_oldActiveTeamToRec.insert(rec.teamId(), rec.id()); - m_elementList.insert(rec.teamId(), re); - return re; + ReceiverElement* re = new ReceiverElement(this); + re->init(rec); + if (rec.isActive()) + m_oldActiveTeamToRec.insert(rec.teamId(), rec.id()); + m_elementList.insert(rec.teamId(), re); + return re; } -void MvsVideoTeamDialog::updateReceiverButton(const AudioVideoManagement::VideoReceiver &rec, DataModification modType) +void MvsVideoTeamDialog::updateReceiverButton(const AudioVideoManagement::VideoReceiver& rec, DataModification modType) { - Q_UNUSED(modType); - m_receiverMap.insert(rec.id(), rec); - for (auto it = m_elementList.lowerBound(rec.teamId()) ; it != m_elementList.end(); ++it) - { - if (it.key() != rec.teamId()) - break; - auto *receiverElement = it.value(); - if (receiverElement->property("recId").toInt() != rec.id()) - continue; + Q_UNUSED(modType); + m_receiverMap.insert(rec.id(), rec); + for (auto it = m_elementList.lowerBound(rec.teamId()); it != m_elementList.end(); ++it) + { + if (it.key() != rec.teamId()) + break; + auto* receiverElement = it.value(); + if (receiverElement->property("recId").toInt() != rec.id()) + continue; - receiverElement->setButtonChecked(rec.isActive()); - receiverElement->setSnr(rec.snr()); - receiverElement->setDbm(rec.dbm()); - receiverElement->setStreamName(QString::fromStdString(rec.streamName())); - receiverElement->setFrequency(rec.frequency()); - receiverElement->setIsLocked(rec.isLocked()); - } + receiverElement->setButtonChecked(rec.isActive()); + receiverElement->setSnr(rec.snr()); + receiverElement->setDbm(rec.dbm()); + receiverElement->setStreamName(QString::fromStdString(rec.streamName())); + receiverElement->setFrequency(rec.frequency()); + receiverElement->setIsLocked(rec.isLocked()); + } } - -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.h old mode 100755 new mode 100644 index c7c92ccd7..16f6908c0 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/MobileVideoSystem/avm_mvs_video_team_dialog.h @@ -1,21 +1,15 @@ - #pragma once - -#include #include #include - -#include - -#include -#include - +#include #include #include - +#include +#include +#include namespace LtsWidgets { @@ -28,66 +22,64 @@ class MvsVideoTeamDialog; } class ReceiverElement; + namespace AudioVideoManagement { class MvsVideoTeamDialog : public LtsWidgets::LtsDialog, - private AudioVideoManagement::Interface::Ftc::VideoReceiverModifyActiveReplyHandler + private AudioVideoManagement::Interface::Ftc::VideoReceiverModifyActiveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit MvsVideoTeamDialog(QWidget *parent = nullptr); - ~MvsVideoTeamDialog(); + public: + explicit MvsVideoTeamDialog(QWidget* parent = nullptr); + ~MvsVideoTeamDialog(); - bool init(LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc); + bool init(LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc); - void onVideoReceiverModifyActiveReply(const Core::FunctionReplyObject &reply) override final { m_requestHelper->requestReply(reply); } + void onVideoReceiverModifyActiveReply(const Core::FunctionReplyObject& reply) override final + { + m_requestHelper->requestReply(reply); + } -private: + private: + NGL::INGLLogger& m_logger; + ReceiverElement* createReceiverElement(const VideoReceiver& rec); -NGL::INGLLogger &m_logger; - ReceiverElement *createReceiverElement(const VideoReceiver &rec); + private slots: + bool apply() override; + void updateReceiverButton(const AudioVideoManagement::VideoReceiver& rec, DataModification modType); -private slots: - bool apply() override; - void updateReceiverButton(const AudioVideoManagement::VideoReceiver &rec, DataModification modType); + private: + void retranslate() override; + void enaDisa(bool enable); + void setData(); + private: + Ui::MvsVideoTeamDialog* m_ui; + LtsSession::LtsSession* m_session; + QString m_menuGroup; -private: - void retranslate() override; - void enaDisa(bool enable); - void setData(); + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; -private: - Ui::MvsVideoTeamDialog *m_ui; - LtsSession::LtsSession *m_session; - QString m_menuGroup; + std::shared_ptr m_ismDtc; + std::shared_ptr m_flmGui; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; + AudioVideoManagement::VideoReceiver m_data; - std::shared_ptr m_ismDtc; - std::shared_ptr m_flmGui; + LtsUtils::RequestHelper* m_requestHelper; - AudioVideoManagement::VideoReceiver m_data; + QMap m_receiverMap; + QMap m_videoTeamButtonGroup; + QMap m_stationToColumn; + QMap m_teamToRow; + QMultiMap m_elementList; + QMap m_oldActiveTeamToRec; - LtsUtils::RequestHelper *m_requestHelper; + QHash, int> m_receiverIds; - QMap m_receiverMap; - QMap m_videoTeamButtonGroup; - QMap m_stationToColumn; - QMap m_teamToRow; - QMultiMap m_elementList; - QMap m_oldActiveTeamToRec; - - - - - QHash, int> m_receiverIds; - - QVector mainStructureElementIds; + QVector mainStructureElementIds; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_edit_training_voice_communication_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_edit_training_voice_communication_dialog.h old mode 100755 new mode 100644 index 5865e2b51..e9537cf11 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_edit_training_voice_communication_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_edit_training_voice_communication_dialog.h @@ -1,16 +1,13 @@ - #pragma once -#include - -#include -#include #include - -#include +#include +#include +#include #include +#include class QCheckBox; @@ -25,7 +22,7 @@ namespace Interface { class Dtc; } -} +} // namespace AudioVideoManagement namespace ExerciseManagement { @@ -33,80 +30,70 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace LtsUtils { class RequestHelper; } - namespace AudioVideoManagement { -class EditTrainingVoiceCommunicationDialog - : public LtsWidgets::LtsDialog - , protected Interface::Ftc::ModifyTvcConfigReplyHandler +class EditTrainingVoiceCommunicationDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::ModifyTvcConfigReplyHandler { - Q_OBJECT -public: - + Q_OBJECT + public: + explicit EditTrainingVoiceCommunicationDialog(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, int32_t exerciseId, + QWidget* parent = nullptr); - explicit EditTrainingVoiceCommunicationDialog(const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - int32_t exerciseId, - QWidget *parent = nullptr); - + explicit EditTrainingVoiceCommunicationDialog(const TvcConfig& config, + const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, int32_t exerciseId, + QWidget* parent); - explicit EditTrainingVoiceCommunicationDialog(const TvcConfig &config, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - int32_t exerciseId, - QWidget *parent); + ~EditTrainingVoiceCommunicationDialog(); - ~EditTrainingVoiceCommunicationDialog(); + void retranslate() override; - void retranslate() override; + protected: + NGL::INGLLogger& m_logger; + bool apply() override; + void onModifyTvcConfigReply(const Core::FunctionReplyObject& reply) override; -protected: + private: + EditTrainingVoiceCommunicationDialog(int32_t id, const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc, int32_t exerciseId, + QWidget* parent); -NGL::INGLLogger &m_logger; - bool apply() override; - void onModifyTvcConfigReply(const Core::FunctionReplyObject &reply) override; + void init(); + void checkToDisableChkRecording(); -private: - EditTrainingVoiceCommunicationDialog(int32_t id, - const std::shared_ptr &avmDtc, - const std::shared_ptr &avmFtc, - ExerciseManagement::Interface::Dtc *exmDtc, - int32_t exerciseId, - QWidget *parent); + private slots: + void updateFreeChannelsAndTakenNames(); - void init(); - void checkToDisableChkRecording(); + private: + void updateCbChannels(QVector&& freeChannels); + QVector exercisesToConsider() const; + QVector exercisesToIgnore() const; -private slots: - void updateFreeChannelsAndTakenNames(); + void initCbChannelsForCreate(); + void initCbChannelsForEdit(int channelId); -private: - void updateCbChannels(QVector &&freeChannels); - QVector exercisesToConsider() const; - QVector exercisesToIgnore() const; + bool isNameValid(const QString& name) const; - void initCbChannelsForCreate(); - void initCbChannelsForEdit(int channelId); - - bool isNameValid(const QString &name) const; - -private: - std::unique_ptr m_ui; - int32_t m_id; - int32_t m_exerciseId; - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - ExerciseManagement::Interface::Dtc *m_exmDtc; - QVector m_takenNames; - std::unique_ptr m_requestHelper; -}; -} + private: + std::unique_ptr m_ui; + int32_t m_id; + int32_t m_exerciseId; + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + ExerciseManagement::Interface::Dtc* m_exmDtc; + QVector m_takenNames; + std::unique_ptr m_requestHelper; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.cpp old mode 100755 new mode 100644 index 5bdd6c464..aab31a9d9 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.cpp @@ -1,209 +1,198 @@ - #include "avm_training_voice_communication_dialog.h" -#include "ui_avm_training_voice_communication_dialog.h" -#include "avm_training_voice_communication_dialog_model.h" -#include "avm_edit_training_voice_communication_dialog.h" -#include -#include -#include -#include +#include "avm_edit_training_voice_communication_dialog.h" +#include "avm_training_voice_communication_dialog_model.h" +#include "ui_avm_training_voice_communication_dialog.h" + +#include #include +#include +#include +#include #include namespace AudioVideoManagement { -TrainingVoiceCommunicationDialog::TrainingVoiceCommunicationDialog(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_session(session) - , m_ui(new Ui::TrainingVoiceCommunicationDialog) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_avmDtc(nullptr) - , m_avmFtc(nullptr) +TrainingVoiceCommunicationDialog::TrainingVoiceCommunicationDialog(const QString& menuGroup, + LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_session(session), + m_ui(new Ui::TrainingVoiceCommunicationDialog), m_menuGroup(menuGroup), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_avmDtc(nullptr), m_avmFtc(nullptr) { - m_ui->setupUi(this); + m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-Training_Voice_Communication")); + setOnlineHelpFilename(QStringLiteral("Situation-Training_Voice_Communication")); } TrainingVoiceCommunicationDialog::~TrainingVoiceCommunicationDialog() = default; void TrainingVoiceCommunicationDialog::retranslate() { - translate(m_ui.get(), tr("Training Voice Communication")); + translate(m_ui.get(), tr("Training Voice Communication")); } void TrainingVoiceCommunicationDialog::tableColumnOrganiserSetting() { - - m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dataView->setColumnsOrganiserEnabled(identifier(), true); } -bool TrainingVoiceCommunicationDialog::init(const std::shared_ptr &avmDtc, const std::shared_ptr &avmFtc, ExerciseManagement::Interface::Dtc *exmDtc) +bool TrainingVoiceCommunicationDialog::init(const std::shared_ptr& avmDtc, + const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc) { - Q_ASSERT(exmDtc); + Q_ASSERT(exmDtc); - if (!(avmDtc->enableTvcChannel() && - avmDtc->enableTvcConfig() && - avmFtc->enableModifyTvcConfig() && - avmFtc->enableRemoveTvcConfig())) - { - ERROR_LOG(m_logger) << "Could not enable topics"; - return false; - } + if (!(avmDtc->enableTvcChannel() && avmDtc->enableTvcConfig() && avmFtc->enableModifyTvcConfig() && + avmFtc->enableRemoveTvcConfig())) + { + ERROR_LOG(m_logger) << "Could not enable topics"; + return false; + } - m_model.reset(new TrainingVoiceCommunicationDialogModel(this)); - m_filter.reset(new TrainingVoiceCommunicationDialogFilter(m_session->exerciseId(), m_model.get())); + m_model.reset(new TrainingVoiceCommunicationDialogModel(this)); + m_filter.reset(new TrainingVoiceCommunicationDialogFilter(m_session->exerciseId(), m_model.get())); + m_avmDtc = avmDtc; + m_avmFtc = avmFtc; + m_exmDtc = exmDtc; - m_avmDtc = avmDtc; - m_avmFtc = avmFtc; - m_exmDtc = exmDtc; + if (!m_model->init(m_session->exerciseId(), avmDtc)) + { + m_filter.reset(); + m_model.reset(); + ERROR_LOG(m_logger) << "Could not init model"; + return false; + } - if (!m_model->init(m_session->exerciseId(), avmDtc)) - { - m_filter.reset(); - m_model.reset(); - ERROR_LOG(m_logger) << "Could not init model"; - return false; - } + m_ui->dataView->setModel(m_filter.get()); - m_ui->dataView->setModel(m_filter.get()); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &TrainingVoiceCommunicationDialog::onAddClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &TrainingVoiceCommunicationDialog::onEditClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, + &TrainingVoiceCommunicationDialog::onRemoveClicked); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &TrainingVoiceCommunicationDialog::onPrint); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &TrainingVoiceCommunicationDialog::onAddClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &TrainingVoiceCommunicationDialog::onEditClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &TrainingVoiceCommunicationDialog::onRemoveClicked); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &TrainingVoiceCommunicationDialog::onPrint); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &TrainingVoiceCommunicationDialog::onSelectionChanged); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &TrainingVoiceCommunicationDialog::onSelectionChanged); + onSelectionChanged(); - onSelectionChanged(); + connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &TrainingVoiceCommunicationDialog::onEditClicked); - connect(m_ui->dataView, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &TrainingVoiceCommunicationDialog::onEditClicked); + m_buttonBox->connectLibraryButton(this, &TrainingVoiceCommunicationDialog::onImportButtonClicked, + &TrainingVoiceCommunicationDialog::onExportButtonClicked); - - m_buttonBox->connectLibraryButton(this, - &TrainingVoiceCommunicationDialog::onImportButtonClicked, - &TrainingVoiceCommunicationDialog::onExportButtonClicked); - - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); #ifndef LTS_DEBUG - m_ui->dataView->hideColumn(TrainingVoiceCommunicationDialogModel::RECORDING); + m_ui->dataView->hideColumn(TrainingVoiceCommunicationDialogModel::RECORDING); #endif - return true; + return true; } -void TrainingVoiceCommunicationDialog::onModifyTvcConfigReply(const Core::FunctionReplyObject &replyObject) +void TrainingVoiceCommunicationDialog::onModifyTvcConfigReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -void TrainingVoiceCommunicationDialog::onRemoveTvcConfigReply(const Core::FunctionReplyObject &replyObject) +void TrainingVoiceCommunicationDialog::onRemoveTvcConfigReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } void TrainingVoiceCommunicationDialog::onAddClicked() { - EditTrainingVoiceCommunicationDialog *dialog = new EditTrainingVoiceCommunicationDialog(m_avmDtc, m_avmFtc, m_exmDtc, m_session->exerciseId(), this); - addDialog(dialog, m_menuGroup, QStringLiteral("NewTVCConfig"), LtsWidgets::LayoutArea::eDialogTab); + EditTrainingVoiceCommunicationDialog* dialog = + new EditTrainingVoiceCommunicationDialog(m_avmDtc, m_avmFtc, m_exmDtc, m_session->exerciseId(), this); + addDialog(dialog, m_menuGroup, QStringLiteral("NewTVCConfig"), LtsWidgets::LayoutArea::eDialogTab); } void TrainingVoiceCommunicationDialog::onEditClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - TvcConfig config = m_model->getRowData(currentIndex.row()); + TvcConfig config = m_model->getRowData(currentIndex.row()); - EditTrainingVoiceCommunicationDialog *dialog = new EditTrainingVoiceCommunicationDialog(config, m_avmDtc, m_avmFtc, m_exmDtc, m_session->exerciseId(), this); - addDialog(dialog, m_menuGroup, QStringLiteral("EditTVCConfig%1").arg(config.id()), LtsWidgets::LayoutArea::eDialogTab); + EditTrainingVoiceCommunicationDialog* dialog = + new EditTrainingVoiceCommunicationDialog(config, m_avmDtc, m_avmFtc, m_exmDtc, m_session->exerciseId(), this); + addDialog(dialog, m_menuGroup, QStringLiteral("EditTVCConfig%1").arg(config.id()), + LtsWidgets::LayoutArea::eDialogTab); } void TrainingVoiceCommunicationDialog::onRemoveClicked() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - if (!currentIndex.isValid()) - return; + if (!currentIndex.isValid()) + return; - Core::RemoveElementRequest request(m_model->getRowData(currentIndex.row()).id()); + Core::RemoveElementRequest request(m_model->getRowData(currentIndex.row()).id()); - m_requestHelper->startSingleRequest([this, request]() - { - return m_avmFtc->removeTvcConfigRequest(request, this); - }); + m_requestHelper->startSingleRequest([this, request]() { return m_avmFtc->removeTvcConfigRequest(request, this); }); } void TrainingVoiceCommunicationDialog::onSelectionChanged() { - QModelIndex currentIndex = m_ui->dataView->currentIndex(); + QModelIndex currentIndex = m_ui->dataView->currentIndex(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, currentIndex.isValid()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, currentIndex.isValid()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, currentIndex.isValid()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, currentIndex.isValid()); } void TrainingVoiceCommunicationDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); + LtsPrinting::printView(m_session, this, m_ui->dataView->treeView()); } - - void TrainingVoiceCommunicationDialog::onExportButtonClicked() { - QByteArray byteArray = m_filter->modelToJson(); + QByteArray byteArray = m_filter->modelToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void TrainingVoiceCommunicationDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication))) + QByteArray content; + int fileId = + m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - const QVector requests = m_model->jsonToTvcConfigVector(content); - for (const auto &request : requests) - { - m_requestHelper->addRequest([this, request]() + if (!m_flmGui->isXmlType(content, + FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication))) { - return m_avmFtc->modifyTvcConfigRequest(request, this); - }); - } - (void) m_requestHelper->startRequests(); - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + const QVector requests = m_model->jsonToTvcConfigVector(content); + for (const auto& request : requests) + { + m_requestHelper->addRequest( + [this, request]() { return m_avmFtc->modifyTvcConfigRequest(request, this); }); + } + (void)m_requestHelper->startRequests(); + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + } } - - } -} } +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.h old mode 100755 new mode 100644 index 37fd80622..51448aa46 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog.h @@ -1,14 +1,11 @@ - #pragma once -#include - -#include #include +#include +#include #include - #include namespace Ui @@ -32,7 +29,7 @@ namespace Interface { class Dtc; } -} +} // namespace AudioVideoManagement namespace ExerciseManagement { @@ -40,53 +37,53 @@ namespace Interface { class Dtc; } -} +} // namespace ExerciseManagement namespace AudioVideoManagement { class TrainingVoiceCommunicationDialogModel; class TrainingVoiceCommunicationDialogFilter; -class TrainingVoiceCommunicationDialog - : public LtsWidgets::LtsDialog - , protected Interface::Ftc::ModifyTvcConfigReplyHandler - , protected Interface::Ftc::RemoveTvcConfigReplyHandler +class TrainingVoiceCommunicationDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::ModifyTvcConfigReplyHandler, + protected Interface::Ftc::RemoveTvcConfigReplyHandler { - Q_OBJECT -public: - explicit TrainingVoiceCommunicationDialog(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~TrainingVoiceCommunicationDialog(); + Q_OBJECT + public: + explicit TrainingVoiceCommunicationDialog(const QString& menuGroup, LtsSession::LtsSession* session, + QWidget* parent = nullptr); + ~TrainingVoiceCommunicationDialog(); - bool init(const std::shared_ptr &avmDtc, const std::shared_ptr &avmFtc, ExerciseManagement::Interface::Dtc *exmDtc); + bool init(const std::shared_ptr& avmDtc, const std::shared_ptr& avmFtc, + ExerciseManagement::Interface::Dtc* exmDtc); - void onModifyTvcConfigReply(const Core::FunctionReplyObject &replyObject) override final; - void onRemoveTvcConfigReply(const Core::FunctionReplyObject &replyObject) override final; + void onModifyTvcConfigReply(const Core::FunctionReplyObject& replyObject) override final; + void onRemoveTvcConfigReply(const Core::FunctionReplyObject& replyObject) override final; -private Q_SLOTS: - void onAddClicked(); - void onEditClicked(); - void onRemoveClicked(); - void onSelectionChanged(); - void onPrint(); - void onExportButtonClicked(); - void onImportButtonClicked(); + private Q_SLOTS: + void onAddClicked(); + void onEditClicked(); + void onRemoveClicked(); + void onSelectionChanged(); + void onPrint(); + void onExportButtonClicked(); + void onImportButtonClicked(); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void tableColumnOrganiserSetting() override; - -private: - LtsSession::LtsSession *m_session; - std::unique_ptr m_model; - std::unique_ptr m_filter; - std::unique_ptr m_ui; - QString m_menuGroup; - std::unique_ptr m_requestHelper; - std::shared_ptr m_avmDtc; - std::shared_ptr m_avmFtc; - std::shared_ptr m_flmGui; - ExerciseManagement::Interface::Dtc *m_exmDtc{nullptr}; -}; -} + private: + LtsSession::LtsSession* m_session; + std::unique_ptr m_model; + std::unique_ptr m_filter; + std::unique_ptr m_ui; + QString m_menuGroup; + std::unique_ptr m_requestHelper; + std::shared_ptr m_avmDtc; + std::shared_ptr m_avmFtc; + std::shared_ptr m_flmGui; + ExerciseManagement::Interface::Dtc* m_exmDtc{nullptr}; +}; +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.cpp old mode 100755 new mode 100644 index f2e195c1a..488776076 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.cpp @@ -1,142 +1,132 @@ - #include "avm_training_voice_communication_dialog_model.h" -#include +#include #include -#include #include +#include namespace AudioVideoManagement { -TrainingVoiceCommunicationDialogModel::TrainingVoiceCommunicationDialogModel(QObject *parent) - : LtsAbstractTableModel( -{ - tr("Channel Number"), - tr("Radio Circuit"), - tr("Recording"), - tr("Info"), - tr("Global") -}, parent) - , m_exerciseId(-1) +TrainingVoiceCommunicationDialogModel::TrainingVoiceCommunicationDialogModel(QObject* parent) + : LtsAbstractTableModel( + {tr("Channel Number"), tr("Radio Circuit"), tr("Recording"), tr("Info"), tr("Global")}, parent), + m_exerciseId(-1) { } -QVariant TrainingVoiceCommunicationDialogModel::data(const QModelIndex &index, int role) const +QVariant TrainingVoiceCommunicationDialogModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole || !indexIsValid(index)) + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const AudioVideoManagement::TvcConfig& config = m_vecData.at(index.row()); + + switch (index.column()) + { + case CHANNEL: + return QString::fromStdString(m_tetraChannels.value(config.tetraChannelId()).name()); + case RADIO_CIRCUIT: + return QString::fromStdString(config.radioCircuit()); + case RECORDING: + return config.recording() ? tr("On") : tr("Off"); + case INFO: + return QString::fromStdString(config.info()); + case GLOBAL: + return config.exerciseId().is_set() ? tr("No") : tr("Yes"); + } + return QVariant(); - - const AudioVideoManagement::TvcConfig &config = m_vecData.at(index.row()); - - switch (index.column()) - { - case CHANNEL: - return QString::fromStdString(m_tetraChannels.value(config.tetraChannelId()).name()); - case RADIO_CIRCUIT: - return QString::fromStdString(config.radioCircuit()); - case RECORDING: - return config.recording() ? tr("On") : tr("Off"); - case INFO: - return QString::fromStdString(config.info()); - case GLOBAL: - return config.exerciseId().is_set() ? tr("No") : tr("Yes"); - } - - return QVariant(); } -bool TrainingVoiceCommunicationDialogModel::init(int32_t exerciseId, const std::shared_ptr &avmDtc) +bool TrainingVoiceCommunicationDialogModel::init(int32_t exerciseId, + const std::shared_ptr& avmDtc) { - m_avmDtc = avmDtc; - m_exerciseId = exerciseId; + m_avmDtc = avmDtc; + m_exerciseId = exerciseId; - - avmDtc->waitForHistoricalDataTvcChannel(5000); - m_tetraChannels = avmDtc->tvcChannels(); + avmDtc->waitForHistoricalDataTvcChannel(5000); + m_tetraChannels = avmDtc->tvcChannels(); - connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, this, &TrainingVoiceCommunicationDialogModel::onDataChanged); - m_avmDtc->tvcConfigs([this](const TvcConfig &config) { insertRow(config); }); + connect(m_avmDtc.get(), &AudioVideoManagement::Interface::Dtc::tvcConfigChanged, this, + &TrainingVoiceCommunicationDialogModel::onDataChanged); + m_avmDtc->tvcConfigs([this](const TvcConfig& config) { insertRow(config); }); - return true; + return true; } - - - QByteArray TrainingVoiceCommunicationDialogFilter::modelToJson() const { - QJsonObject obj; - QJsonArray arr; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication); + QJsonObject obj; + QJsonArray arr; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::AVMTrainingVoiceCommunication); - for (int row = 0; row < rowCount(); row++) - { - int sourceRow = mapToSource(index(row, 0)).row(); + for (int row = 0; row < rowCount(); row++) + { + int sourceRow = mapToSource(index(row, 0)).row(); - QJsonObject inner; - const TvcConfig &config = m_sourceModel->getRowData(sourceRow); + QJsonObject inner; + const TvcConfig& config = m_sourceModel->getRowData(sourceRow); - inner[QLatin1String("isGlobal")] = !config.exerciseId().is_set(); - inner[QLatin1String("info")] = QString::fromStdString(config.info()); - inner[QLatin1String("radioCircuit")] = QString::fromStdString(config.radioCircuit()); - inner[QLatin1String("recording")] = config.recording(); - inner[QLatin1String("tetraChannelId")] = config.tetraChannelId(); - arr += inner; - } + inner[QLatin1String("isGlobal")] = !config.exerciseId().is_set(); + inner[QLatin1String("info")] = QString::fromStdString(config.info()); + inner[QLatin1String("radioCircuit")] = QString::fromStdString(config.radioCircuit()); + inner[QLatin1String("recording")] = config.recording(); + inner[QLatin1String("tetraChannelId")] = config.tetraChannelId(); + arr += inner; + } - obj[QLatin1String("tvcConfiguration")] = arr; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + obj[QLatin1String("tvcConfiguration")] = arr; + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -QVector TrainingVoiceCommunicationDialogModel::jsonToTvcConfigVector(const QByteArray &content) const +QVector +TrainingVoiceCommunicationDialogModel::jsonToTvcConfigVector(const QByteArray& content) const { - - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject toplevelObj(doc.object()); - const QJsonArray arr(toplevelObj.value(QLatin1String("tvcConfiguration")).toArray()); - QVector result; - result.reserve(arr.size()); - for (const auto &ele : arr) - { - const QJsonObject obj(ele.toObject()); - ModifyTvcConfigRequest config; - if (!obj.contains(QLatin1String("isGlobal")) || !obj[QLatin1String("isGlobal")].toBool()) - config.exerciseId(m_exerciseId); - config.id(0); - config.info(obj[QLatin1String("info")].toString().toStdString()); - config.radioCircuit(obj[QLatin1String("radioCircuit")].toString().toStdString()); - config.recording(obj[QLatin1String("recording")].toBool()); - config.tetraChannelId(obj[QLatin1String("tetraChannelId")].toInt()); + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject toplevelObj(doc.object()); + const QJsonArray arr(toplevelObj.value(QLatin1String("tvcConfiguration")).toArray()); + QVector result; + result.reserve(arr.size()); + for (const auto& ele : arr) + { + const QJsonObject obj(ele.toObject()); + ModifyTvcConfigRequest config; - INFO_LOG(m_logger) << "insertRow: " << config.radioCircuit() - << " tvcChannelId=" << config.tetraChannelId(); - result.push_back(std::move(config)); - } - return result; + if (!obj.contains(QLatin1String("isGlobal")) || !obj[QLatin1String("isGlobal")].toBool()) + config.exerciseId(m_exerciseId); + config.id(0); + config.info(obj[QLatin1String("info")].toString().toStdString()); + config.radioCircuit(obj[QLatin1String("radioCircuit")].toString().toStdString()); + config.recording(obj[QLatin1String("recording")].toBool()); + config.tetraChannelId(obj[QLatin1String("tetraChannelId")].toInt()); + + INFO_LOG(m_logger) << "insertRow: " << config.radioCircuit() << " tvcChannelId=" << config.tetraChannelId(); + result.push_back(std::move(config)); + } + return result; } - -TrainingVoiceCommunicationDialogFilter::TrainingVoiceCommunicationDialogFilter(int32_t exerciseId, TrainingVoiceCommunicationDialogModel *sourceModel) - : m_exerciseId(exerciseId) - , m_sourceModel(sourceModel) +TrainingVoiceCommunicationDialogFilter::TrainingVoiceCommunicationDialogFilter( + int32_t exerciseId, TrainingVoiceCommunicationDialogModel* sourceModel) + : m_exerciseId(exerciseId), m_sourceModel(sourceModel) { - Q_ASSERT(sourceModel); - setSourceModel(sourceModel); + Q_ASSERT(sourceModel); + setSourceModel(sourceModel); } -bool TrainingVoiceCommunicationDialogFilter::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool TrainingVoiceCommunicationDialogFilter::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { - TvcConfig tvcConfig = m_sourceModel->getRowData(sourceRow); + TvcConfig tvcConfig = m_sourceModel->getRowData(sourceRow); - if (tvcConfig.exerciseId().is_set() && tvcConfig.exerciseId().get() != m_exerciseId) - return false; + if (tvcConfig.exerciseId().is_set() && tvcConfig.exerciseId().get() != m_exerciseId) + return false; - return LtsColumnFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); + return LtsColumnFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent); } -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.h old mode 100755 new mode 100644 index 00639ae9c..40e35e5c3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/AudioVideoManagement/Gui/TrainingVoiceCommunication/avm_training_voice_communication_dialog_model.h @@ -1,67 +1,56 @@ - #pragma once +#include +#include #include #include -#include -#include - namespace AudioVideoManagement { class TrainingVoiceCommunicationDialogModel final - : public LtsWidgets::LtsAbstractTableModel + : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - CHANNEL, - RADIO_CIRCUIT, - RECORDING, - INFO, - GLOBAL - }; + public: + enum Columns { CHANNEL, RADIO_CIRCUIT, RECORDING, INFO, GLOBAL }; - explicit TrainingVoiceCommunicationDialogModel(QObject *parent = nullptr); + explicit TrainingVoiceCommunicationDialogModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role) const override final; + QVariant data(const QModelIndex& index, int role) const override final; - bool init(int32_t exerciseId, const std::shared_ptr &avmDtc); - QVector jsonToTvcConfigVector(const QByteArray &content) const; + bool init(int32_t exerciseId, const std::shared_ptr& avmDtc); + QVector jsonToTvcConfigVector(const QByteArray& content) const; -private: + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_avmDtc; + int32_t m_exerciseId; -NGL::INGLLogger &m_logger; - std::shared_ptr m_avmDtc; - int32_t m_exerciseId; - - QMap m_tetraChannels; + QMap m_tetraChannels; }; - class TrainingVoiceCommunicationDialogFilter : public LtsWidgets::LtsColumnFilterProxyModel { -public: - explicit TrainingVoiceCommunicationDialogFilter(int32_t exerciseId, TrainingVoiceCommunicationDialogModel *sourceModel); + public: + explicit TrainingVoiceCommunicationDialogFilter(int32_t exerciseId, + TrainingVoiceCommunicationDialogModel* sourceModel); - QByteArray modelToJson() const; + QByteArray modelToJson() const; -protected: - bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; + protected: + bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override; -private: - - using LtsWidgets::LtsColumnFilterProxyModel::setSourceModel; + private: + using LtsWidgets::LtsColumnFilterProxyModel::setSourceModel; - int32_t m_exerciseId; - TrainingVoiceCommunicationDialogModel *m_sourceModel; + int32_t m_exerciseId; + TrainingVoiceCommunicationDialogModel* m_sourceModel; }; -} +} // namespace AudioVideoManagement Q_DECLARE_METATYPE(AudioVideoManagement::TvcConfig) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.cpp old mode 100755 new mode 100644 index b69706d4f..e0bf3b5db --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.cpp @@ -1,49 +1,44 @@ #include "buildingmanager.h" -#include #include "iconcomponent.h" #include "modelsplittercomponent.h" #include "motionmodel.h" #include "orthomotionmodel.h" #include "playercomponent.h" +#include "rapidxml.hpp" +#include "rapidxml_utils.hpp" #include "roomdestructioncomponent.h" #include "textcomponent.h" #include "visitors.h" -#include #include #include +#include #include #include #include - #include -#include #include +#include #include #include #include #include #include - #include #include #include #include -#include -#include #include +#include #include #include - +#include #include #include - #include +#include #include -#include "rapidxml.hpp" -#include "rapidxml_utils.hpp" - #define ROOM_OBB_Z_MIN_SUBTRACT 0.1f #define ROOM_OBB_Z_MAX_SUBTRACT 0.5f @@ -51,2697 +46,2475 @@ namespace VCtrl { - - -BuildingManager::BuildingManager(dtEntity::EntityManager &em) - : mEntityManager(&em) - , mShotOverview(false) - , mExactPos(true) - , mMapRotation(0) - , mTickFunctor(this, &BuildingManager::Tick) - , m_logger(BuildingViewer::getLogger("BuildingManager")) +BuildingManager::BuildingManager(dtEntity::EntityManager& em) + : mEntityManager(&em), mShotOverview(false), mExactPos(true), mMapRotation(0), + mTickFunctor(this, &BuildingManager::Tick), m_logger(BuildingViewer::getLogger("BuildingManager")) { - em.RegisterForMessages(dtEntity::TickMessage::TYPE, mTickFunctor); + em.RegisterForMessages(dtEntity::TickMessage::TYPE, mTickFunctor); } - BuildingManager::~BuildingManager() { - deleteAllBuildings(); + deleteAllBuildings(); } - - void BuildingManager::deleteAllBuildings() { - for (auto building : mBuildings) - { - qDeleteAll(building->mShots); - qDeleteAll(building->mDevices); - qDeleteAll(building->mNames); - delete building; - } - mBuildings.clear(); + for (auto building : mBuildings) + { + qDeleteAll(building->mShots); + qDeleteAll(building->mDevices); + qDeleteAll(building->mNames); + delete building; + } + mBuildings.clear(); } - - -osg::Vec2d BuildingManager::AddRoomUsages(const std::string& bldgname, const std::string& roomname, VCtrl::PlayerPosition& playPos) +osg::Vec2d BuildingManager::AddRoomUsages(const std::string& bldgname, const std::string& roomname, + VCtrl::PlayerPosition& playPos) { - const std::string key = bldgname + " " + roomname; - auto i = mUsedRooms.find(key); - if (i == mUsedRooms.end()) - { - RoomPlayers mroomPlayers; - mroomPlayers.push_back(playPos); - mUsedRooms[key] = mroomPlayers; - } - else - { - - RoomPlayers &mroomPlayers = i->second; - bool knownPlayer = false; - - for (auto it = mroomPlayers.begin(); it != mroomPlayers.end(); ++it) + const std::string key = bldgname + " " + roomname; + auto i = mUsedRooms.find(key); + if (i == mUsedRooms.end()) { - if (it->mWorldPlayerId == playPos.mWorldPlayerId) - { - it = mroomPlayers.erase(it); - - - break; - } + RoomPlayers mroomPlayers; + mroomPlayers.push_back(playPos); + mUsedRooms[key] = mroomPlayers; } - if (knownPlayer == false) + else { - VCtrl::OBB roomObb; - getRoomBounds(bldgname, roomname, roomObb); - double shiftVal = 0.6; - for (const PlayerPosition &pp : mroomPlayers) - { - if (qFuzzyCompare(pp.mPosition[0], playPos.mPosition[0]) && - qFuzzyCompare(pp.mPosition[1], playPos.mPosition[1])) + + RoomPlayers& mroomPlayers = i->second; + bool knownPlayer = false; + + for (auto it = mroomPlayers.begin(); it != mroomPlayers.end(); ++it) { - playPos.mPosition = shiftPosition(roomObb, playPos.mPosition, shiftVal); + if (it->mWorldPlayerId == playPos.mWorldPlayerId) + { + it = mroomPlayers.erase(it); + + break; + } + } + if (knownPlayer == false) + { + VCtrl::OBB roomObb; + getRoomBounds(bldgname, roomname, roomObb); + double shiftVal = 0.6; + for (const PlayerPosition& pp : mroomPlayers) + { + if (qFuzzyCompare(pp.mPosition[0], playPos.mPosition[0]) && + qFuzzyCompare(pp.mPosition[1], playPos.mPosition[1])) + { + playPos.mPosition = shiftPosition(roomObb, playPos.mPosition, shiftVal); + } + } + mroomPlayers.push_back(playPos); } - } - mroomPlayers.push_back(playPos); } - } - return playPos.mPosition; + return playPos.mPosition; } - - -void BuildingManager::deleteRoomUsagePlayer(const std::string& bldgname, const std::string& roomname, dtEntity::EntityId playerId) +void BuildingManager::deleteRoomUsagePlayer(const std::string& bldgname, const std::string& roomname, + dtEntity::EntityId playerId) { - const std::string key = bldgname + " " + roomname; - auto i = mUsedRooms.find(key); - if (i != mUsedRooms.end()) - { - RoomPlayers &mroomPlayers = i->second; - - - - - - - for (auto it = mroomPlayers.begin(); it != mroomPlayers.end(); ++it) + const std::string key = bldgname + " " + roomname; + auto i = mUsedRooms.find(key); + if (i != mUsedRooms.end()) { - if (mroomPlayers.size() == 0) - break; - const PlayerPosition &pp = *it; - if (pp.mWorldPlayerId == playerId) - { - if (mroomPlayers.size() > 0 ) + RoomPlayers& mroomPlayers = i->second; + + for (auto it = mroomPlayers.begin(); it != mroomPlayers.end(); ++it) { - it = mroomPlayers.erase(it); + if (mroomPlayers.size() == 0) + break; + const PlayerPosition& pp = *it; + if (pp.mWorldPlayerId == playerId) + { + if (mroomPlayers.size() > 0) + { + it = mroomPlayers.erase(it); + } + break; + } } - break; - } - - } - - - - } - if (mUsedRooms[key].empty()) - mUsedRooms.erase(key); + if (mUsedRooms[key].empty()) + mUsedRooms.erase(key); } - osg::Vec2d BuildingManager::shiftPosition(const VCtrl::OBB& obb, const osg::Vec2d& pos, double& shiftValue) { - osg::Vec2d position; - const double wall = 0.4; - osg::Vec3d v(pos[0], pos[1], 0); + osg::Vec2d position; + const double wall = 0.4; + osg::Vec3d v(pos[0], pos[1], 0); - v = v * obb.mMatrixInverse; - v.x() = v.x() + shiftValue; - if ( v.x() > (obb.mBB.xMax() - wall) ) - { - v.x() = obb.mBB.xMin() + wall; - v.y() = v.y() + shiftValue; - } - if ( v.y() > obb.mBB.yMax() - wall) - { - v.y() = obb.mBB.yMin() + wall; - shiftValue = shiftValue / 2.0; - } - v = v * obb.mMatrix; - position.x() = v.x(); - position.y() = v.y(); - return position; -} - - -void BuildingManager::Tick(const dtEntity::Message &message) -{ - - - QMutexLocker locker(&m_mutexShots); - - const dtEntity::TickMessage &msg = static_cast(message); - double simtime = msg.GetSimulationTime(); - - - - for (Building *building : mBuildings) - { - Building &bldg = *building; - - - for (BuildingDisplay &dspl : bldg.mDisplays) + v = v * obb.mMatrixInverse; + v.x() = v.x() + shiftValue; + if (v.x() > (obb.mBB.xMax() - wall)) { - - std::vector::iterator itShotDisplay = dspl.mShotDisplays.begin(); - while (itShotDisplay != dspl.mShotDisplays.end()) - { - ShotDisplay &shotdspl = *itShotDisplay; - Shot *shot =shotdspl.mShot; - - bool lifeTimeOver = (shot->lifeTime() <= simtime); - bool displayTimeOver = (shot->displayTime() <= simtime); - - - if (displayTimeOver) - { - dtEntityOSG::LayerAttachPointComponent *lac; - if (!mEntityManager->GetComponent(dspl.mAttachPointId, lac)) - { - WARNING_LOG(m_logger) << "NO sLayerAttachPointComponent"; - return; - } - if( shotdspl.mGeode.valid()) - { - DEBUG_LOG(m_logger) << "displayTimeOver OVER KILL IT drawables: !" << shotdspl.mGeode->getNumDrawables(); - while (shotdspl.mGeode->getNumDrawables() > 0) - shotdspl.mGeode->removeDrawables(0, shotdspl.mGeode->getNumDrawables()); - bool ret = lac->GetNode()->asGroup()->removeChild(shotdspl.mGeode); - DEBUG_LOG(m_logger) << "displayTimeOver OVER KILL IT! result: " << ret; - - - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); - } - } - - if (lifeTimeOver) - { - DEBUG_LOG(m_logger) << "lifeTimeOver OVER ERASE IT!"; - itShotDisplay = dspl.mShotDisplays.erase(itShotDisplay); - } - else - ++itShotDisplay; - } - } - - - - } + v.x() = obb.mBB.xMin() + wall; + v.y() = v.y() + shiftValue; + } + if (v.y() > obb.mBB.yMax() - wall) + { + v.y() = obb.mBB.yMin() + wall; + shiftValue = shiftValue / 2.0; + } + v = v * obb.mMatrix; + position.x() = v.x(); + position.y() = v.y(); + return position; } -bool BuildingManager::getFloorOfRoom(const std::string &bdlgFeatureId, int roomNumber, int &floorOut) const +void BuildingManager::Tick(const dtEntity::Message& message) { - floorOut = -999; - auto it = mRoomToFloorPerBldg.find(bdlgFeatureId); - if (it == mRoomToFloorPerBldg.end()) - return false; - const std::map &roomToFloor = it->second; - { - auto itR = roomToFloor.find(roomNumber); - if (itR == roomToFloor.end()) - return false; - floorOut = itR->second; - } - return true; + QMutexLocker locker(&m_mutexShots); + + const dtEntity::TickMessage& msg = static_cast(message); + double simtime = msg.GetSimulationTime(); + + for (Building* building : mBuildings) + { + Building& bldg = *building; + + for (BuildingDisplay& dspl : bldg.mDisplays) + { + + std::vector::iterator itShotDisplay = dspl.mShotDisplays.begin(); + while (itShotDisplay != dspl.mShotDisplays.end()) + { + ShotDisplay& shotdspl = *itShotDisplay; + Shot* shot = shotdspl.mShot; + + bool lifeTimeOver = (shot->lifeTime() <= simtime); + bool displayTimeOver = (shot->displayTime() <= simtime); + + if (displayTimeOver) + { + dtEntityOSG::LayerAttachPointComponent* lac; + if (!mEntityManager->GetComponent(dspl.mAttachPointId, lac)) + { + WARNING_LOG(m_logger) << "NO sLayerAttachPointComponent"; + return; + } + if (shotdspl.mGeode.valid()) + { + DEBUG_LOG(m_logger) + << "displayTimeOver OVER KILL IT drawables: !" << shotdspl.mGeode->getNumDrawables(); + while (shotdspl.mGeode->getNumDrawables() > 0) + shotdspl.mGeode->removeDrawables(0, shotdspl.mGeode->getNumDrawables()); + bool ret = lac->GetNode()->asGroup()->removeChild(shotdspl.mGeode); + DEBUG_LOG(m_logger) << "displayTimeOver OVER KILL IT! result: " << ret; + + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + } + } + + if (lifeTimeOver) + { + DEBUG_LOG(m_logger) << "lifeTimeOver OVER ERASE IT!"; + itShotDisplay = dspl.mShotDisplays.erase(itShotDisplay); + } + else + ++itShotDisplay; + } + } + } +} + +bool BuildingManager::getFloorOfRoom(const std::string& bdlgFeatureId, int roomNumber, int& floorOut) const +{ + floorOut = -999; + auto it = mRoomToFloorPerBldg.find(bdlgFeatureId); + if (it == mRoomToFloorPerBldg.end()) + return false; + + const std::map& roomToFloor = it->second; + { + auto itR = roomToFloor.find(roomNumber); + if (itR == roomToFloor.end()) + return false; + floorOut = itR->second; + } + return true; } void BuildingManager::updateShotDuration(unsigned int newDuration_s) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " newDuration_s= " << newDuration_s; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " newDuration_s= " << newDuration_s; - QMutexLocker locker(&m_mutexShots); + QMutexLocker locker(&m_mutexShots); - - for (Building *building : std::as_const(mBuildings)) - { - - for (Shot *pShot : building->mShots) - pShot->setDisplayTime(newDuration_s); - - if (!building->mDisplays.empty()) + for (Building* building : std::as_const(mBuildings)) { - BuildingDisplay buildingDisplay = building->mDisplays.front(); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " buildingDisplay.mContextId " << buildingDisplay.mContextId; - updateShots(*building, buildingDisplay); - dtEntity::GetWindowInterface()->RequestRedraw(buildingDisplay.mContextId); + + for (Shot* pShot : building->mShots) + pShot->setDisplayTime(newDuration_s); + + if (!building->mDisplays.empty()) + { + BuildingDisplay buildingDisplay = building->mDisplays.front(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " buildingDisplay.mContextId " << buildingDisplay.mContextId; + updateShots(*building, buildingDisplay); + dtEntity::GetWindowInterface()->RequestRedraw(buildingDisplay.mContextId); + } } - } } -void BuildingManager::setCallbackCamPosChanged(const CallbackCamPosChanged &cb) +void BuildingManager::setCallbackCamPosChanged(const CallbackCamPosChanged& cb) { - mCbCamPosChanged = cb; - for (auto building : mBuildings) - { - for (auto &bd : building->mDisplays) + mCbCamPosChanged = cb; + for (auto building : mBuildings) { - if (bd.pMotion) - bd.pMotion->m_callbackCamPosChanged = mCbCamPosChanged; + for (auto& bd : building->mDisplays) + { + if (bd.pMotion) + bd.pMotion->m_callbackCamPosChanged = mCbCamPosChanged; + } } - } } - - - - - - - - bool BuildingManager::setCameraPosition(unsigned int contextid, const BuildingViewer::CameraViewPosition& pos) { - BuildingDisplay* pBuildingDisplay = getBuildingDisplay(contextid); - if (!pBuildingDisplay) - return false; + BuildingDisplay* pBuildingDisplay = getBuildingDisplay(contextid); + if (!pBuildingDisplay) + return false; - dtEntityOSG::CameraComponent *pCamComp = nullptr; - bool success = mEntityManager->GetComponent(pBuildingDisplay->mCameraId, pCamComp); - if (!success || !pCamComp) - return false; + dtEntityOSG::CameraComponent* pCamComp = nullptr; + bool success = mEntityManager->GetComponent(pBuildingDisplay->mCameraId, pCamComp); + if (!success || !pCamComp) + return false; - pCamComp->SetOrthoLeft(pos.m_left); - pCamComp->SetOrthoRight(pos.m_right); - pCamComp->SetOrthoBottom(pos.m_bottom); - pCamComp->SetOrthoTop(pos.m_top); - pCamComp->UpdateProjectionMatrix(); - pCamComp->UpdateViewMatrix(); + pCamComp->SetOrthoLeft(pos.m_left); + pCamComp->SetOrthoRight(pos.m_right); + pCamComp->SetOrthoBottom(pos.m_bottom); + pCamComp->SetOrthoTop(pos.m_top); + pCamComp->UpdateProjectionMatrix(); + pCamComp->UpdateViewMatrix(); - dtEntity::GetWindowInterface()->RequestRedraw(contextid); + dtEntity::GetWindowInterface()->RequestRedraw(contextid); - return true; + return true; } - - bool BuildingManager::getCameraPosition(unsigned int contextid, BuildingViewer::CameraViewPosition& pos) { - BuildingDisplay* pBuildingDisplay = getBuildingDisplay(contextid); - if (!pBuildingDisplay) - return false; + BuildingDisplay* pBuildingDisplay = getBuildingDisplay(contextid); + if (!pBuildingDisplay) + return false; - dtEntityOSG::CameraComponent *pCamComp = nullptr; - bool success = mEntityManager->GetComponent(pBuildingDisplay->mCameraId, pCamComp); - if (!success || !pCamComp) - return false; + dtEntityOSG::CameraComponent* pCamComp = nullptr; + bool success = mEntityManager->GetComponent(pBuildingDisplay->mCameraId, pCamComp); + if (!success || !pCamComp) + return false; - double znear, zfar; - pCamComp->GetCamera()->getProjectionMatrixAsOrtho(pos.m_left, pos.m_right, pos.m_bottom, pos.m_top, znear, zfar); - return true; + double znear, zfar; + pCamComp->GetCamera()->getProjectionMatrixAsOrtho(pos.m_left, pos.m_right, pos.m_bottom, pos.m_top, znear, zfar); + return true; } - bool BuildingManager::setDefaultCameraPosition(unsigned int contextid) { - BuildingDisplay *pBuildingDisplay = getBuildingDisplay(contextid); - if (!pBuildingDisplay) - return false; + BuildingDisplay* pBuildingDisplay = getBuildingDisplay(contextid); + if (!pBuildingDisplay) + return false; - Building *building = nullptr; - for (Building *b : mBuildings) - { - for (const auto &dspl : b->mDisplays) + Building* building = nullptr; + for (Building* b : mBuildings) { - if (&dspl == pBuildingDisplay) - { - building = b; - break; - } - } - } - if (!building) - return false; - - repositionCamera(*building, *pBuildingDisplay); - return true; -} - - - - - - - -bool BuildingManager::displayBuilding(const std::string& featureId, unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4 &bgcolor, ViewMode viewmode, bool exactPos) -{ - if (!displayBuilding(contextid, buildingid, bgcolor, viewmode, exactPos)) - return false; - - Building *building = nullptr; - for (Building *b : mBuildings) - { - if (b->mWorldBuildingId == buildingid) - { - building = b; - break; - } - } - assert(building); - - auto it = m_mapBuildingRoomNames.find(featureId); - if(it == m_mapBuildingRoomNames.end()) - return false; - - const std::map& mapRoomNames = it->second; - for(const auto& e : mapRoomNames) - setRoomDisplayName(building, e.first, e.second); - - return true; -} - - - -bool BuildingManager::displayBuilding(unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4& bgcolor, ViewMode viewmode, bool exactPos) -{ - DEBUG_LOG(m_logger) << "BuildingManager::displayBuilding"; - mExactPos = exactPos; - dtEntity::EntityManager &em = *mEntityManager; - - Building *building = nullptr; - for (Building *b : mBuildings) - { - if (b->mWorldBuildingId == buildingid) - { - building = b; - break; - } - } - assert(building); - if (!building) - return false; - - - building->mDisplays.emplace_back(BuildingDisplay(contextid, viewmode)); - BuildingDisplay &buildingDisplay = building->mDisplays.back(); - - - dtEntity::WindowCreatedMessage msg; - msg.SetName("Building " + std::to_string(buildingid)); - msg.SetContextId(contextid); - em.EmitMessage(msg); - - std::string viewname = "Context_" + std::to_string(buildingDisplay.mContextId); - - dtEntity::MapSystem *mapsys; - if (!em.GetES(mapsys)) - return false; - - - { - dtEntity::Entity *e; - if (!em.CreateEntity(e)) - return false; - buildingDisplay.mAttachPointId = e->GetId(); - dtEntity::MapComponent *map; - if (!e->CreateComponent(map)) - return false; - map->SetEntityName(viewname); - map->SetMapName("attach"); - map->SetUniqueId(viewname); - dtEntityOSG::LayerAttachPointComponent *attach; - if (!e->CreateComponent(attach)) - return false; - attach->SetName(dtEntity::SID(viewname)); - mapsys->AddToScene(e->GetId()); - } - - - { - ModelSplitterComponent *msc; - bool success = em.GetComponent(buildingid, msc); - assert(success); - if (!success) - return false; - - std::vector ids; - std::vector heights; - std::vector floors; - msc->Split(ids, heights, floors, dtEntity::SID(viewname)); - - - for (unsigned int i = 0; i < ids.size(); ++i) - { - dtEntity::EntityId id = ids[i]; - int floorId = floors[i]; - float height = heights[i]; - mapsys->AddToScene(id); - - dtEntityOSG::StaticMeshComponent *smc; - success = em.GetComponent(id, smc); - assert(success); - if (!success) - continue; - - osg::ComputeBoundsVisitor v; - smc->GetNode()->accept(v); - buildingDisplay.mWorldBounds.expandBy(v.getBoundingBox()); - - buildingDisplay.mLevels.emplace_back(BuildingLevel(id, floorId, height, v.getBoundingBox())); - - - RoomDestructionComponent *btc; - if (em.CreateComponent(id, btc)) - btc->OnEnteredWorld(); - - - ClearVertexColorsVisitor vcv; - smc->GetNode()->accept(vcv); - } - } - - - { - dtEntity::Entity *cam; - if (!em.CreateEntity(cam)) - return false; - buildingDisplay.mCameraId = cam->GetId(); - - dtEntityOSG::CameraComponent *camcomp; - if (!cam->CreateComponent(camcomp)) - return false; - camcomp->SetContextId(contextid); - camcomp->SetLayerAttachPoint(dtEntity::SID(viewname)); - camcomp->SetClearColor(bgcolor); - camcomp->SetProjectionMode(dtEntityOSG::CameraComponent::ModeOrthoId); - camcomp->Finished(); - - - OrthoMotionModelComponent *motion; - if (!cam->CreateComponent(motion)) - return false; - motion->SetContextId(contextid); - motion->Finished(); - buildingDisplay.pMotion = motion; - buildingDisplay.pMotion->m_callbackCamPosChanged = mCbCamPosChanged; - - dtEntity::MapComponent *mapcomp; - if (!cam->CreateComponent(mapcomp)) - return false; - std::string name = "cam_" + std::to_string(contextid); - mapcomp->SetEntityName(name); - mapcomp->SetUniqueId(name); - mapcomp->SetMapName("cams"); - mapcomp->Finished(); - - mapsys->AddToScene(cam->GetId()); - } - - - { - dtEntity::Entity *light; - if (!em.CreateEntity(light)) - return false; - buildingDisplay.mLightId = light->GetId(); - dtEntityOSG::LightComponent *lightcomp; - if (!light->CreateComponent(lightcomp)) - return false; - lightcomp->SetVec4(dtEntityOSG::LightComponent::PositionId, osg::Vec4(0.8f, 0.2f, 1, 0)); - lightcomp->SetVec4(dtEntityOSG::LightComponent::DiffuseId, osg::Vec4(1, 1, 1, 1)); - lightcomp->SetVec4(dtEntityOSG::LightComponent::AmbientId, osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f)); - - dtEntity::MapComponent *mapc; - if (!light->CreateComponent(mapc)) - return false; - std::string name = "light_" + std::to_string(contextid); - mapc->SetEntityName(name); - mapc->SetUniqueId(name); - mapc->SetMapName("lights"); - - dtEntityOSG::LayerComponent *layer; - if (!light->CreateComponent(layer)) - return false; - layer->SetAttachedComponent(dtEntityOSG::LightComponent::TYPE); - layer->SetLayer(dtEntity::SID(viewname)); - layer->Finished(); - - mapsys->AddToScene(light->GetId()); - } - - applyViewModeToBuildingParts(*building, buildingDisplay); - repositionCamera(*building, buildingDisplay); - - - { - PlayerSystem *ps; - if (mEntityManager->GetES(ps)) - { - for (const auto &i : *ps) - { - PlayerComponent *pc = i.second; - - if (dtEntity::GetStringFromSID(pc->GetCurrentCellGroup()) == building->mNavMeshGrpName) + for (const auto& dspl : b->mDisplays) { - IconComponent *ic; - if (mEntityManager->GetComponent(i.first, ic)) - addPlayerToBuilding(*building, buildingDisplay, i.first, pc->GetColor(), ic->GetPath(), ic->GetTranslation(), ic->GetVisible()); + if (&dspl == pBuildingDisplay) + { + building = b; + break; + } } - } } - } + if (!building) + return false; - - { - QMutexLocker locker(&m_mutexShots); - if (!building->mShots.empty()) - { - for (Shot *s : building->mShots) - { - ShotDisplay sd; - sd.mShot = s; - buildingDisplay.mShotDisplays.push_back(std::move(sd)); - } - updateShots(*building, buildingDisplay); - } - } - - - { - DEBUG_LOG(m_logger) << "mDevices.size = " << building->mDevices.size(); - if (!building->mDevices.empty()) - { - for (Device *d : building->mDevices) - { - DeviceDisplay sd; - sd.mDevice = d; - sd.mWorldPlayerId = d->mWorldPlayerId; - buildingDisplay.mDeviceDisplays.push_back(std::move(sd)); - } - updateDevices(*building, buildingDisplay); - } - } - - - { - RoomDestructionComponent *btc1; - if (em.GetComponent(buildingid, btc1)) - { - const RoomDestructionComponent::RoomDestructions &rd = btc1->GetRoomDestructions(); - - for (const BuildingLevel &level : buildingDisplay.mLevels) - { - RoomDestructionComponent *btc2; - if (mEntityManager->GetComponent(level.mEntityId, btc2)) - { - if (!btc2) - continue; - for (const auto &destr : rd) - btc2->SetRoomDestructionValue(destr.first, destr.second); - } - } - } - } - - - if(building->mNames.empty()) - { - createRoomNames(buildingid, *building); - } - - - { - if(!building->mNames.empty()) - { - for (Name *n : building->mNames) - { - NameDisplay nd; - nd.mName = n; - nd.mWorldPlayerId = n->mWorldPlayerId; - nd.visible = false; - buildingDisplay.mNameDisplays.push_back(std::move(nd)); - } - updateNames(*building, buildingDisplay); - } - } - - return true; + repositionCamera(*building, *pBuildingDisplay); + return true; } +bool BuildingManager::displayBuilding(const std::string& featureId, unsigned int contextid, + dtEntity::EntityId buildingid, const osg::Vec4& bgcolor, ViewMode viewmode, + bool exactPos) +{ + if (!displayBuilding(contextid, buildingid, bgcolor, viewmode, exactPos)) + return false; + + Building* building = nullptr; + for (Building* b : mBuildings) + { + if (b->mWorldBuildingId == buildingid) + { + building = b; + break; + } + } + assert(building); + + auto it = m_mapBuildingRoomNames.find(featureId); + if (it == m_mapBuildingRoomNames.end()) + return false; + + const std::map& mapRoomNames = it->second; + for (const auto& e : mapRoomNames) + setRoomDisplayName(building, e.first, e.second); + + return true; +} + +bool BuildingManager::displayBuilding(unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4& bgcolor, + ViewMode viewmode, bool exactPos) +{ + DEBUG_LOG(m_logger) << "BuildingManager::displayBuilding"; + mExactPos = exactPos; + dtEntity::EntityManager& em = *mEntityManager; + + Building* building = nullptr; + for (Building* b : mBuildings) + { + if (b->mWorldBuildingId == buildingid) + { + building = b; + break; + } + } + assert(building); + if (!building) + return false; + + building->mDisplays.emplace_back(BuildingDisplay(contextid, viewmode)); + BuildingDisplay& buildingDisplay = building->mDisplays.back(); + + dtEntity::WindowCreatedMessage msg; + msg.SetName("Building " + std::to_string(buildingid)); + msg.SetContextId(contextid); + em.EmitMessage(msg); + + std::string viewname = "Context_" + std::to_string(buildingDisplay.mContextId); + + dtEntity::MapSystem* mapsys; + if (!em.GetES(mapsys)) + return false; + + { + dtEntity::Entity* e; + if (!em.CreateEntity(e)) + return false; + buildingDisplay.mAttachPointId = e->GetId(); + dtEntity::MapComponent* map; + if (!e->CreateComponent(map)) + return false; + map->SetEntityName(viewname); + map->SetMapName("attach"); + map->SetUniqueId(viewname); + dtEntityOSG::LayerAttachPointComponent* attach; + if (!e->CreateComponent(attach)) + return false; + attach->SetName(dtEntity::SID(viewname)); + mapsys->AddToScene(e->GetId()); + } + + { + ModelSplitterComponent* msc; + bool success = em.GetComponent(buildingid, msc); + assert(success); + if (!success) + return false; + + std::vector ids; + std::vector heights; + std::vector floors; + msc->Split(ids, heights, floors, dtEntity::SID(viewname)); + + for (unsigned int i = 0; i < ids.size(); ++i) + { + dtEntity::EntityId id = ids[i]; + int floorId = floors[i]; + float height = heights[i]; + mapsys->AddToScene(id); + + dtEntityOSG::StaticMeshComponent* smc; + success = em.GetComponent(id, smc); + assert(success); + if (!success) + continue; + + osg::ComputeBoundsVisitor v; + smc->GetNode()->accept(v); + buildingDisplay.mWorldBounds.expandBy(v.getBoundingBox()); + + buildingDisplay.mLevels.emplace_back(BuildingLevel(id, floorId, height, v.getBoundingBox())); + + RoomDestructionComponent* btc; + if (em.CreateComponent(id, btc)) + btc->OnEnteredWorld(); + + ClearVertexColorsVisitor vcv; + smc->GetNode()->accept(vcv); + } + } + + { + dtEntity::Entity* cam; + if (!em.CreateEntity(cam)) + return false; + buildingDisplay.mCameraId = cam->GetId(); + + dtEntityOSG::CameraComponent* camcomp; + if (!cam->CreateComponent(camcomp)) + return false; + camcomp->SetContextId(contextid); + camcomp->SetLayerAttachPoint(dtEntity::SID(viewname)); + camcomp->SetClearColor(bgcolor); + camcomp->SetProjectionMode(dtEntityOSG::CameraComponent::ModeOrthoId); + camcomp->Finished(); + + OrthoMotionModelComponent* motion; + if (!cam->CreateComponent(motion)) + return false; + motion->SetContextId(contextid); + motion->Finished(); + buildingDisplay.pMotion = motion; + buildingDisplay.pMotion->m_callbackCamPosChanged = mCbCamPosChanged; + + dtEntity::MapComponent* mapcomp; + if (!cam->CreateComponent(mapcomp)) + return false; + std::string name = "cam_" + std::to_string(contextid); + mapcomp->SetEntityName(name); + mapcomp->SetUniqueId(name); + mapcomp->SetMapName("cams"); + mapcomp->Finished(); + + mapsys->AddToScene(cam->GetId()); + } + + { + dtEntity::Entity* light; + if (!em.CreateEntity(light)) + return false; + buildingDisplay.mLightId = light->GetId(); + dtEntityOSG::LightComponent* lightcomp; + if (!light->CreateComponent(lightcomp)) + return false; + lightcomp->SetVec4(dtEntityOSG::LightComponent::PositionId, osg::Vec4(0.8f, 0.2f, 1, 0)); + lightcomp->SetVec4(dtEntityOSG::LightComponent::DiffuseId, osg::Vec4(1, 1, 1, 1)); + lightcomp->SetVec4(dtEntityOSG::LightComponent::AmbientId, osg::Vec4(0.5f, 0.5f, 0.5f, 1.0f)); + + dtEntity::MapComponent* mapc; + if (!light->CreateComponent(mapc)) + return false; + std::string name = "light_" + std::to_string(contextid); + mapc->SetEntityName(name); + mapc->SetUniqueId(name); + mapc->SetMapName("lights"); + + dtEntityOSG::LayerComponent* layer; + if (!light->CreateComponent(layer)) + return false; + layer->SetAttachedComponent(dtEntityOSG::LightComponent::TYPE); + layer->SetLayer(dtEntity::SID(viewname)); + layer->Finished(); + + mapsys->AddToScene(light->GetId()); + } + + applyViewModeToBuildingParts(*building, buildingDisplay); + repositionCamera(*building, buildingDisplay); + + { + PlayerSystem* ps; + if (mEntityManager->GetES(ps)) + { + for (const auto& i : *ps) + { + PlayerComponent* pc = i.second; + + if (dtEntity::GetStringFromSID(pc->GetCurrentCellGroup()) == building->mNavMeshGrpName) + { + IconComponent* ic; + if (mEntityManager->GetComponent(i.first, ic)) + addPlayerToBuilding(*building, buildingDisplay, i.first, pc->GetColor(), ic->GetPath(), + ic->GetTranslation(), ic->GetVisible()); + } + } + } + } + + { + QMutexLocker locker(&m_mutexShots); + if (!building->mShots.empty()) + { + for (Shot* s : building->mShots) + { + ShotDisplay sd; + sd.mShot = s; + buildingDisplay.mShotDisplays.push_back(std::move(sd)); + } + updateShots(*building, buildingDisplay); + } + } + + { + DEBUG_LOG(m_logger) << "mDevices.size = " << building->mDevices.size(); + if (!building->mDevices.empty()) + { + for (Device* d : building->mDevices) + { + DeviceDisplay sd; + sd.mDevice = d; + sd.mWorldPlayerId = d->mWorldPlayerId; + buildingDisplay.mDeviceDisplays.push_back(std::move(sd)); + } + updateDevices(*building, buildingDisplay); + } + } + + { + RoomDestructionComponent* btc1; + if (em.GetComponent(buildingid, btc1)) + { + const RoomDestructionComponent::RoomDestructions& rd = btc1->GetRoomDestructions(); + + for (const BuildingLevel& level : buildingDisplay.mLevels) + { + RoomDestructionComponent* btc2; + if (mEntityManager->GetComponent(level.mEntityId, btc2)) + { + if (!btc2) + continue; + for (const auto& destr : rd) + btc2->SetRoomDestructionValue(destr.first, destr.second); + } + } + } + } + + if (building->mNames.empty()) + { + createRoomNames(buildingid, *building); + } + + { + if (!building->mNames.empty()) + { + for (Name* n : building->mNames) + { + NameDisplay nd; + nd.mName = n; + nd.mWorldPlayerId = n->mWorldPlayerId; + nd.visible = false; + buildingDisplay.mNameDisplays.push_back(std::move(nd)); + } + updateNames(*building, buildingDisplay); + } + } + + return true; +} void BuildingManager::closeBuildingDisplay(unsigned int contextid) { - dtEntity::MapSystem* mapsys; - if (!mEntityManager->GetES(mapsys)) - return; - - for (Building *building : mBuildings) - { - for (auto it = building->mDisplays.begin(); it != building->mDisplays.end(); ++it) - { - const BuildingDisplay &bd = (*it); - if (bd.mContextId == contextid) - { - osgViewer::CompositeViewer* cv = static_cast(dtEntityOSG::GetOSGSystemInterface()->GetViewer()); - cv->stopThreading(); - - - osgViewer::ViewerBase::Cameras cams; - cv->getCameras(cams); - for (osg::Camera *c : cams) - { - if (c->getGraphicsContext()->getState()->getContextID() == contextid) - { - cv->removeView(dynamic_cast(c->getView())); - } - } - cv->startThreading(); - - - for (const BuildingLevel &level : bd.mLevels) - { - dtEntity::EntityId eid = level.mEntityId; - mapsys->RemoveFromScene(eid); - mEntityManager->KillEntity(eid); - } - - mapsys->RemoveFromScene(bd.mLightId); - mEntityManager->KillEntity(bd.mLightId); - mapsys->RemoveFromScene(bd.mCameraId); - mEntityManager->KillEntity(bd.mCameraId); - mapsys->RemoveFromScene(bd.mAttachPointId); - mEntityManager->KillEntity(bd.mAttachPointId); - - - for (const PlayerDisplay &pd : bd.mPlayers) - { - mapsys->RemoveFromScene(pd.mLocalPlayerId); - mEntityManager->KillEntity(pd.mLocalPlayerId); - } - - for (const DeviceDisplay &pd : bd.mDeviceDisplays) - { - mapsys->RemoveFromScene(pd.mLocalPlayerId); - mEntityManager->KillEntity(pd.mLocalPlayerId); - } - - - for (const NameDisplay &nd : bd.mNameDisplays) - { - mapsys->RemoveFromScene(nd.mLocalPlayerId); - mEntityManager->KillEntity(nd.mLocalPlayerId); - } - building->mDisplays.erase(it); + dtEntity::MapSystem* mapsys; + if (!mEntityManager->GetES(mapsys)) return; - } - } - } -} - -void BuildingManager::addBuilding(dtEntity::EntityId buildingid, const std::string &featureId) -{ - Building *b = new Building; - b->mWorldBuildingId = buildingid; - b->mFeatureId = featureId; - mBuildings.push_back(b); - - - dtEntityOSG::PositionAttitudeTransformComponent *pat; - mEntityManager->GetComponent(buildingid, pat); - if (!pat) - return; - b->mLocalToWorld.setRotate(pat->GetAttitude()); - b->mLocalToWorld.setTrans(pat->GetTranslation()); - b->mWorldToLocal = osg::Matrix::inverse(b->mLocalToWorld); - - - VCtrl::ModelSplitterComponent *msc; - mEntityManager->GetComponent(buildingid, msc); - if (!msc) - return; - b->mNavMeshGrpName = dtEntity::GetStringFromSID(msc->GetBuildingId()); - -} - - -BuildingDisplay *BuildingManager::getBuildingDisplay(unsigned int contextid) -{ - for (Building *b : mBuildings) - { - for (BuildingDisplay &bd : b->mDisplays) + for (Building* building : mBuildings) { - if (bd.mContextId == contextid) - return &bd; + for (auto it = building->mDisplays.begin(); it != building->mDisplays.end(); ++it) + { + const BuildingDisplay& bd = (*it); + if (bd.mContextId == contextid) + { + osgViewer::CompositeViewer* cv = + static_cast(dtEntityOSG::GetOSGSystemInterface()->GetViewer()); + cv->stopThreading(); + + osgViewer::ViewerBase::Cameras cams; + cv->getCameras(cams); + for (osg::Camera* c : cams) + { + if (c->getGraphicsContext()->getState()->getContextID() == contextid) + { + cv->removeView(dynamic_cast(c->getView())); + } + } + cv->startThreading(); + + for (const BuildingLevel& level : bd.mLevels) + { + dtEntity::EntityId eid = level.mEntityId; + mapsys->RemoveFromScene(eid); + mEntityManager->KillEntity(eid); + } + + mapsys->RemoveFromScene(bd.mLightId); + mEntityManager->KillEntity(bd.mLightId); + mapsys->RemoveFromScene(bd.mCameraId); + mEntityManager->KillEntity(bd.mCameraId); + mapsys->RemoveFromScene(bd.mAttachPointId); + mEntityManager->KillEntity(bd.mAttachPointId); + + for (const PlayerDisplay& pd : bd.mPlayers) + { + mapsys->RemoveFromScene(pd.mLocalPlayerId); + mEntityManager->KillEntity(pd.mLocalPlayerId); + } + + for (const DeviceDisplay& pd : bd.mDeviceDisplays) + { + mapsys->RemoveFromScene(pd.mLocalPlayerId); + mEntityManager->KillEntity(pd.mLocalPlayerId); + } + + for (const NameDisplay& nd : bd.mNameDisplays) + { + mapsys->RemoveFromScene(nd.mLocalPlayerId); + mEntityManager->KillEntity(nd.mLocalPlayerId); + } + building->mDisplays.erase(it); + return; + } + } } - } - return nullptr; } - - - - -osg::Vec3 getIsoEyeDir(const Building &bd, const BuildingDisplay &d, float maprotation) +void BuildingManager::addBuilding(dtEntity::EntityId buildingid, const std::string& featureId) { - if (d.mLockRotation) - { - osg::Vec3 eyedir(0, 1, -0.7f); - eyedir = bd.mWorldToLocal.getRotate() * eyedir; - eyedir.normalize(); - eyedir = osg::Quat(-osg::DegreesToRadians(maprotation), osg::Vec3(0, 0, 1)) * eyedir; - return eyedir; - } - else - { - osg::Vec3 eye = osg::Vec3(-1, 1, -1); - eye.normalize(); - return eye; - } + Building* b = new Building; + b->mWorldBuildingId = buildingid; + b->mFeatureId = featureId; + mBuildings.push_back(b); + + dtEntityOSG::PositionAttitudeTransformComponent* pat; + mEntityManager->GetComponent(buildingid, pat); + if (!pat) + return; + b->mLocalToWorld.setRotate(pat->GetAttitude()); + b->mLocalToWorld.setTrans(pat->GetTranslation()); + b->mWorldToLocal = osg::Matrix::inverse(b->mLocalToWorld); + + VCtrl::ModelSplitterComponent* msc; + mEntityManager->GetComponent(buildingid, msc); + if (!msc) + return; + b->mNavMeshGrpName = dtEntity::GetStringFromSID(msc->GetBuildingId()); } - - -void BuildingManager::applyViewModeToBuildingParts(const Building &bldg, BuildingDisplay &dspl) const +BuildingDisplay* BuildingManager::getBuildingDisplay(unsigned int contextid) { - dtEntity::EntityManager &em = *mEntityManager; - - - dspl.mLocalBounds = osg::BoundingBox(); - float maprotation = dspl.mLockRotation ? mMapRotation : 0; - - switch (dspl.mViewMode) - { - case ViewMode::ISOMETRIC: - { - - - float h = dspl.mWorldBounds.radius() * osg::PI_2; - int count = 0; - for (BuildingLevel &lvl : dspl.mLevels) + for (Building* b : mBuildings) { - dtEntityOSG::PositionAttitudeTransformComponent *pat; - if (!em.GetComponent(lvl.mEntityId, pat)) - { - assert(false); - continue; - } - - float height = h * count++; - lvl.mLocalToLevel.makeTranslate(osg::Vec3d(0, 0, height - lvl.mHeightAboveGround)); - pat->SetPosition(osg::Vec3d(0, 0, height - lvl.mHeightAboveGround)); - - osg::ComputeBoundsVisitor v; - pat->GetNode()->accept(v); - dspl.mLocalBounds.expandBy(v.getBoundingBox()); + for (BuildingDisplay& bd : b->mDisplays) + { + if (bd.mContextId == contextid) + return &bd; + } } - break; - } - case ViewMode::ORTHOGRAPHIC: - { - - - - - - float h = 0; - for (BuildingLevel &lvl : dspl.mLevels) - { - dtEntityOSG::PositionAttitudeTransformComponent *pat; - if (!em.GetComponent(lvl.mEntityId, pat)) - { - assert(false); - continue; - } - - pat->SetPosition(osg::Vec3d()); - osg::ComputeBoundsVisitor v; - pat->GetNode()->accept(v); - float w = v.getBoundingBox().yMax() - v.getBoundingBox().yMin(); - h += w * 0.6f; - - osg::Vec3d pos(0, h - v.getBoundingBox().center()[1], -lvl.mHeightAboveGround); - pat->SetPosition(pos); - lvl.mLocalToLevel.makeTranslate(osg::Vec3d(0, h - v.getBoundingBox().center()[1], 0)); - h += w * 0.6f; - - osg::Quat q(0, 0, 0, 1); - if (dspl.mLockRotation) - { - q = bldg.mLocalToWorld.getRotate(); - q *= osg::Quat(osg::DegreesToRadians(maprotation), osg::Vec3(0, 0, 1)); - lvl.mLocalToLevel.setRotate(q); - } - pat->SetAttitude(q); - - osg::ComputeBoundsVisitor v2; - pat->GetNode()->accept(v2); - dspl.mLocalBounds.expandBy(v2.getBoundingBox()); - } - - break; - } - default: - LOG_ERROR("Unknown view mode set!"); - return; - } - - - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + return nullptr; } - - -void BuildingManager::repositionCamera(const Building &bd, const BuildingDisplay &dspl, bool useOriginViewPos) +osg::Vec3 getIsoEyeDir(const Building& bd, const BuildingDisplay& d, float maprotation) { - float maprotation = (dspl.mLockRotation) ? mMapRotation : 0; + if (d.mLockRotation) + { + osg::Vec3 eyedir(0, 1, -0.7f); + eyedir = bd.mWorldToLocal.getRotate() * eyedir; + eyedir.normalize(); + eyedir = osg::Quat(-osg::DegreesToRadians(maprotation), osg::Vec3(0, 0, 1)) * eyedir; + return eyedir; + } + else + { + osg::Vec3 eye = osg::Vec3(-1, 1, -1); + eye.normalize(); + return eye; + } +} - osg::Vec3d eyedir; - osg::Vec3d up; +void BuildingManager::applyViewModeToBuildingParts(const Building& bldg, BuildingDisplay& dspl) const +{ + dtEntity::EntityManager& em = *mEntityManager; - switch (dspl.mViewMode) - { - case ViewMode::ISOMETRIC: - eyedir = getIsoEyeDir(bd, dspl, maprotation); - up.set(0, 0, 1); - break; - case ViewMode::ORTHOGRAPHIC: - eyedir.set(0, 0, -1); - up.set(0, 1, 0); - break; - } + dspl.mLocalBounds = osg::BoundingBox(); + float maprotation = dspl.mLockRotation ? mMapRotation : 0; - - osg::Vec3 pxa(eyedir ^ up); - osg::Vec3 pya(pxa ^ eyedir); - pya.normalize(); + switch (dspl.mViewMode) + { + case ViewMode::ISOMETRIC: { - osg::Plane py(pya, dspl.mLocalBounds.center()); - float ydist = 0; - for (unsigned int i = 0; i < 8; ++i) - { - osg::Vec3 corner = dspl.mLocalBounds.corner(i); - float dist = fabs(py.distance(corner)); - ydist = std::max(ydist, dist); - } - ydist *= 1.1f; + float h = dspl.mWorldBounds.radius() * osg::PI_2; + int count = 0; + for (BuildingLevel& lvl : dspl.mLevels) + { + dtEntityOSG::PositionAttitudeTransformComponent* pat; + if (!em.GetComponent(lvl.mEntityId, pat)) + { + assert(false); + continue; + } + float height = h * count++; + lvl.mLocalToLevel.makeTranslate(osg::Vec3d(0, 0, height - lvl.mHeightAboveGround)); + pat->SetPosition(osg::Vec3d(0, 0, height - lvl.mHeightAboveGround)); - - dtEntityOSG::CameraComponent *camcomp; - if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) - return; + osg::ComputeBoundsVisitor v; + pat->GetNode()->accept(v); + dspl.mLocalBounds.expandBy(v.getBoundingBox()); + } + break; + } + case ViewMode::ORTHOGRAPHIC: { - + float h = 0; + for (BuildingLevel& lvl : dspl.mLevels) + { + dtEntityOSG::PositionAttitudeTransformComponent* pat; + if (!em.GetComponent(lvl.mEntityId, pat)) + { + assert(false); + continue; + } - bool initialCameraPosWasSet = (m_setInitialCameraPositionSet.find(dspl.mContextId) != m_setInitialCameraPositionSet.end()); - double left, right, bottom, top, znear, zfar; - camcomp->GetCamera()->getProjectionMatrixAsOrtho(left, right, bottom, top, znear, zfar); + pat->SetPosition(osg::Vec3d()); + osg::ComputeBoundsVisitor v; + pat->GetNode()->accept(v); + float w = v.getBoundingBox().yMax() - v.getBoundingBox().yMin(); + h += w * 0.6f; + osg::Vec3d pos(0, h - v.getBoundingBox().center()[1], -lvl.mHeightAboveGround); + pat->SetPosition(pos); + lvl.mLocalToLevel.makeTranslate(osg::Vec3d(0, h - v.getBoundingBox().center()[1], 0)); + h += w * 0.6f; - - int x, y, w, h; - dtEntity::GetWindowInterface()->GetWindowGeometry(dspl.mContextId, x, y, w, h); + osg::Quat q(0, 0, 0, 1); + if (dspl.mLockRotation) + { + q = bldg.mLocalToWorld.getRotate(); + q *= osg::Quat(osg::DegreesToRadians(maprotation), osg::Vec3(0, 0, 1)); + lvl.mLocalToLevel.setRotate(q); + } + pat->SetAttitude(q); + osg::ComputeBoundsVisitor v2; + pat->GetNode()->accept(v2); + dspl.mLocalBounds.expandBy(v2.getBoundingBox()); + } - + break; + } + default: + LOG_ERROR("Unknown view mode set!"); + return; + } - camcomp->SetOrthoLeft(-ydist * w / h); - camcomp->SetOrthoRight(ydist * w / h); - camcomp->SetOrthoBottom(-ydist); - camcomp->SetOrthoTop(ydist); - camcomp->SetOrthoZNear(-1000); - camcomp->SetOrthoZFar(1000); - m_setInitialCameraPositionSet.insert(dspl.mContextId); + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); +} - camcomp->SetPosition(dspl.mLocalBounds.center()); - camcomp->SetEyeDirection(eyedir); - camcomp->SetUp(up); - camcomp->UpdateProjectionMatrix(); - camcomp->UpdateViewMatrix(); +void BuildingManager::repositionCamera(const Building& bd, const BuildingDisplay& dspl, bool useOriginViewPos) +{ + float maprotation = (dspl.mLockRotation) ? mMapRotation : 0; - + osg::Vec3d eyedir; + osg::Vec3d up; - if(!useOriginViewPos && initialCameraPosWasSet) { - camcomp->SetOrthoLeft(left); - camcomp->SetOrthoRight(right); - camcomp->SetOrthoBottom(bottom); - camcomp->SetOrthoTop(top); + switch (dspl.mViewMode) + { + case ViewMode::ISOMETRIC: + eyedir = getIsoEyeDir(bd, dspl, maprotation); + up.set(0, 0, 1); + break; + case ViewMode::ORTHOGRAPHIC: + eyedir.set(0, 0, -1); + up.set(0, 1, 0); + break; + } + + osg::Vec3 pxa(eyedir ^ up); + osg::Vec3 pya(pxa ^ eyedir); + pya.normalize(); + + osg::Plane py(pya, dspl.mLocalBounds.center()); + float ydist = 0; + for (unsigned int i = 0; i < 8; ++i) + { + osg::Vec3 corner = dspl.mLocalBounds.corner(i); + float dist = fabs(py.distance(corner)); + ydist = std::max(ydist, dist); + } + ydist *= 1.1f; + + dtEntityOSG::CameraComponent* camcomp; + if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) + return; + + bool initialCameraPosWasSet = + (m_setInitialCameraPositionSet.find(dspl.mContextId) != m_setInitialCameraPositionSet.end()); + double left, right, bottom, top, znear, zfar; + camcomp->GetCamera()->getProjectionMatrixAsOrtho(left, right, bottom, top, znear, zfar); + + int x, y, w, h; + dtEntity::GetWindowInterface()->GetWindowGeometry(dspl.mContextId, x, y, w, h); + + camcomp->SetOrthoLeft(-ydist * w / h); + camcomp->SetOrthoRight(ydist * w / h); + camcomp->SetOrthoBottom(-ydist); + camcomp->SetOrthoTop(ydist); + camcomp->SetOrthoZNear(-1000); + camcomp->SetOrthoZFar(1000); + m_setInitialCameraPositionSet.insert(dspl.mContextId); + + camcomp->SetPosition(dspl.mLocalBounds.center()); + camcomp->SetEyeDirection(eyedir); + camcomp->SetUp(up); + camcomp->UpdateProjectionMatrix(); camcomp->UpdateViewMatrix(); - } - - dtEntityOSG::LightComponent *light; - if (!mEntityManager->GetComponent(dspl.mLightId, light)) - return; - osg::Vec3 dir(0, 0, -1); - if (dspl.mViewMode == ViewMode::ISOMETRIC) - dir = pxa; - light->SetVec3(dtEntityOSG::LightComponent::DirectionId, dir); + if (!useOriginViewPos && initialCameraPosWasSet) + { + camcomp->SetOrthoLeft(left); + camcomp->SetOrthoRight(right); + camcomp->SetOrthoBottom(bottom); + camcomp->SetOrthoTop(top); + camcomp->UpdateViewMatrix(); + } + + dtEntityOSG::LightComponent* light; + if (!mEntityManager->GetComponent(dspl.mLightId, light)) + return; + osg::Vec3 dir(0, 0, -1); + if (dspl.mViewMode == ViewMode::ISOMETRIC) + dir = pxa; + light->SetVec3(dtEntityOSG::LightComponent::DirectionId, dir); } - -void BuildingManager::updatePlayerPositions(const Building &bd, BuildingDisplay &dspl) +void BuildingManager::updatePlayerPositions(const Building& bd, BuildingDisplay& dspl) { - LOG_DEBUG("BuildingManager::updatePlayerPositions: " << " mBuildingDisplayName" << bd.mBuildingDisplayName); + LOG_DEBUG("BuildingManager::updatePlayerPositions: " << " mBuildingDisplayName" << bd.mBuildingDisplayName); - - for (PlayerDisplay &pd : dspl.mPlayers) - { - IconComponent *ic; - mEntityManager->GetComponent(pd.mWorldPlayerId, ic); - if (!ic) - continue; - int roomNumber = pd.mIcon->GetRoomNumber(); + for (PlayerDisplay& pd : dspl.mPlayers) + { + IconComponent* ic; + mEntityManager->GetComponent(pd.mWorldPlayerId, ic); + if (!ic) + continue; + int roomNumber = pd.mIcon->GetRoomNumber(); - LOG_DEBUG("BuildingManager::updatePlayerPositions: " - << ", pd.mWorldPlayerId" << pd.mWorldPlayerId - << ", roomNumber" << roomNumber); + LOG_DEBUG("BuildingManager::updatePlayerPositions: " << ", pd.mWorldPlayerId" << pd.mWorldPlayerId + << ", roomNumber" << roomNumber); - pd.mIcon->SetTranslation(remapPosition(bd, dspl, ic->GetTranslation(), roomNumber)); - pd.mIcon->SetOriginAtBottom(dspl.mViewMode == ViewMode::ISOMETRIC); - } + pd.mIcon->SetTranslation(remapPosition(bd, dspl, ic->GetTranslation(), roomNumber)); + pd.mIcon->SetOriginAtBottom(dspl.mViewMode == ViewMode::ISOMETRIC); + } } - - void BuildingManager::changeViewMode(unsigned int contextId, ViewMode viewmode, bool useOriginViewPos) { - for (Building *bldg : mBuildings) - { - for (BuildingDisplay &dspl : bldg->mDisplays) + for (Building* bldg : mBuildings) { - if (dspl.mContextId == contextId) - { - if (dspl.mViewMode != viewmode) + for (BuildingDisplay& dspl : bldg->mDisplays) { - dspl.mViewMode = viewmode; + if (dspl.mContextId == contextId) + { + if (dspl.mViewMode != viewmode) + { + dspl.mViewMode = viewmode; - applyViewModeToBuildingParts(*bldg, dspl); - updateShots(*bldg, dspl); - updatePlayerPositions(*bldg, dspl); - updateDevices(*bldg, dspl); - updateNames(*bldg, dspl); - applyMapRotation(*bldg, dspl); + applyViewModeToBuildingParts(*bldg, dspl); + updateShots(*bldg, dspl); + updatePlayerPositions(*bldg, dspl); + updateDevices(*bldg, dspl); + updateNames(*bldg, dspl); + applyMapRotation(*bldg, dspl); + } + + repositionCamera(*bldg, dspl, useOriginViewPos); + dtEntity::GetWindowInterface()->RequestRedraw(contextId); + } } - - repositionCamera(*bldg, dspl, useOriginViewPos); - dtEntity::GetWindowInterface()->RequestRedraw(contextId); - } } - } } - -void BuildingManager::applyMapRotation(const Building &bd, BuildingDisplay &dspl) +void BuildingManager::applyMapRotation(const Building& bd, BuildingDisplay& dspl) { - dtEntityOSG::CameraComponent *camcomp; - if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) - return; + dtEntityOSG::CameraComponent* camcomp; + if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) + return; - if (dspl.mViewMode == VCtrl::ViewMode::ISOMETRIC) - { - camcomp->SetEyeDirection(getIsoEyeDir(bd, dspl, mMapRotation)); - camcomp->UpdateViewMatrix(); - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); - } - else - { - - applyViewModeToBuildingParts(bd, dspl); - updatePlayerPositions(bd, dspl); - updateDevices(bd, dspl); - updateNames(bd, dspl); + if (dspl.mViewMode == VCtrl::ViewMode::ISOMETRIC) + { + camcomp->SetEyeDirection(getIsoEyeDir(bd, dspl, mMapRotation)); + camcomp->UpdateViewMatrix(); + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + } + else + { - camcomp->UpdateViewMatrix(); - } + applyViewModeToBuildingParts(bd, dspl); + updatePlayerPositions(bd, dspl); + updateDevices(bd, dspl); + updateNames(bd, dspl); - updateShots(bd, dspl); + camcomp->UpdateViewMatrix(); + } + + updateShots(bd, dspl); } - void BuildingManager::lockViewRotationToMapRotation(unsigned int contextId, bool lock) { - for (Building *bldg : mBuildings) - { - for (BuildingDisplay &dspl : bldg->mDisplays) + for (Building* bldg : mBuildings) { - if (dspl.mContextId == contextId && dspl.mLockRotation != lock) - { - dspl.mLockRotation = lock; - repositionCamera(*bldg, dspl, false); - applyViewModeToBuildingParts(*bldg, dspl); - applyMapRotation(*bldg, dspl); - repositionCamera(*bldg, dspl, false); - break; - } + for (BuildingDisplay& dspl : bldg->mDisplays) + { + if (dspl.mContextId == contextId && dspl.mLockRotation != lock) + { + dspl.mLockRotation = lock; + repositionCamera(*bldg, dspl, false); + applyViewModeToBuildingParts(*bldg, dspl); + applyMapRotation(*bldg, dspl); + repositionCamera(*bldg, dspl, false); + break; + } + } } - } } - void BuildingManager::setPlayerDisplayMode(unsigned int contextId, PlayerDisplayMode mode) { - BuildingDisplay *bd = getBuildingDisplay(contextId); - if (!bd) - { - LOG_ERROR("Could not lock view rotation, view with this context id does not exist!"); - return; - } - if (bd->mPlayerDisplayMode == mode) - return; - bd->mPlayerDisplayMode = mode; + BuildingDisplay* bd = getBuildingDisplay(contextId); + if (!bd) + { + LOG_ERROR("Could not lock view rotation, view with this context id does not exist!"); + return; + } + if (bd->mPlayerDisplayMode == mode) + return; + bd->mPlayerDisplayMode = mode; - for (PlayerDisplay &pd : bd->mPlayers) - pd.mIcon->SetShowDot(mode == PlayerDisplayMode::Dots); + for (PlayerDisplay& pd : bd->mPlayers) + pd.mIcon->SetShowDot(mode == PlayerDisplayMode::Dots); - dtEntity::GetWindowInterface()->RequestRedraw(bd->mContextId); + dtEntity::GetWindowInterface()->RequestRedraw(bd->mContextId); } - void BuildingManager::setWallTransparency(unsigned int contextId, float value) { - BuildingDisplay *bd = getBuildingDisplay(contextId); - if (!bd) - { - LOG_ERROR("Could not lock view rotation, view with this context id does not exist!"); - return; - } - - SetWallsTransparentVisitor v(value); - - for (const BuildingLevel &lvl : bd->mLevels) - { - dtEntityOSG::StaticMeshComponent *smc; - if (!mEntityManager->GetComponent(lvl.mEntityId, smc)) + BuildingDisplay* bd = getBuildingDisplay(contextId); + if (!bd) { - assert(false); - continue; + LOG_ERROR("Could not lock view rotation, view with this context id does not exist!"); + return; } - smc->GetNode()->accept(v); - } - dtEntity::GetWindowInterface()->RequestRedraw(bd->mContextId); -} + SetWallsTransparentVisitor v(value); + + for (const BuildingLevel& lvl : bd->mLevels) + { + dtEntityOSG::StaticMeshComponent* smc; + if (!mEntityManager->GetComponent(lvl.mEntityId, smc)) + { + assert(false); + continue; + } + smc->GetNode()->accept(v); + } + dtEntity::GetWindowInterface()->RequestRedraw(bd->mContextId); +} float BuildingManager::getMapRotation() const { - return mMapRotation; + return mMapRotation; } - void BuildingManager::setMapRotation(float angle) { - if (qFuzzyCompare(mMapRotation, angle)) - return; - mMapRotation = angle; + if (qFuzzyCompare(mMapRotation, angle)) + return; + mMapRotation = angle; - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - if (bd.mLockRotation) - applyMapRotation(*building, bd); + for (BuildingDisplay& bd : building->mDisplays) + { + if (bd.mLockRotation) + applyMapRotation(*building, bd); + } } - } } - void BuildingManager::openOverview(unsigned int contextid) { - dtEntity::GetDebugDrawInterface()->SetEnabled(true); + dtEntity::GetDebugDrawInterface()->SetEnabled(true); - dtEntity::WindowCreatedMessage msg; - msg.SetName("Overview"); - msg.SetContextId(contextid); - mEntityManager->EmitMessage(msg); + dtEntity::WindowCreatedMessage msg; + msg.SetName("Overview"); + msg.SetContextId(contextid); + mEntityManager->EmitMessage(msg); - dtEntity::Entity *camera; - if (!mEntityManager->CreateEntity(camera)) - return; - dtEntityOSG::CameraComponent *camcomp; - if (!camera->CreateComponent(camcomp)) - return; - camcomp->SetClearColor(osg::Vec4(0.2f, 0.2f, 0.2f, 1)); - camcomp->SetContextId(contextid); - camcomp->SetEyeDirection(osg::Vec3(0, -1, 0)); - camcomp->SetLayerAttachPoint(dtEntity::SID("root")); - camcomp->SetAspectRatio(1.3); - camcomp->Finished(); + dtEntity::Entity* camera; + if (!mEntityManager->CreateEntity(camera)) + return; + dtEntityOSG::CameraComponent* camcomp; + if (!camera->CreateComponent(camcomp)) + return; + camcomp->SetClearColor(osg::Vec4(0.2f, 0.2f, 0.2f, 1)); + camcomp->SetContextId(contextid); + camcomp->SetEyeDirection(osg::Vec3(0, -1, 0)); + camcomp->SetLayerAttachPoint(dtEntity::SID("root")); + camcomp->SetAspectRatio(1.3); + camcomp->Finished(); - dtEntity::MapComponent *cammap; - if (!camera->CreateComponent(cammap)) - return; - cammap->SetEntityName("cam_overview"); - cammap->SetUniqueId("cam_overview"); - cammap->SetMapName("cams"); + dtEntity::MapComponent* cammap; + if (!camera->CreateComponent(cammap)) + return; + cammap->SetEntityName("cam_overview"); + cammap->SetUniqueId("cam_overview"); + cammap->SetMapName("cams"); - MotionModelComponent *motion; - if (!camera->CreateComponent(motion)) - return; - motion->Finished(); + MotionModelComponent* motion; + if (!camera->CreateComponent(motion)) + return; + motion->Finished(); - dtEntity::MapSystem *ms; - if (mEntityManager->GetES(ms)) - ms->AddToScene(camera->GetId()); + dtEntity::MapSystem* ms; + if (mEntityManager->GetES(ms)) + ms->AddToScene(camera->GetId()); } - -void BuildingManager::addPlayerToBuilding(const Building &bd, BuildingDisplay &dspl, dtEntity::EntityId eid, - const osg::Vec4 &color, const std::string &symbol, const osg::Vec3d &pos, bool visible) +void BuildingManager::addPlayerToBuilding(const Building& bd, BuildingDisplay& dspl, dtEntity::EntityId eid, + const osg::Vec4& color, const std::string& symbol, const osg::Vec3d& pos, + bool visible) { - PlayerDisplay pd; - pd.mWorldPlayerId = eid; + PlayerDisplay pd; + pd.mWorldPlayerId = eid; - dtEntity::Entity *e; - if (!mEntityManager->CreateEntity(e)) - return; - pd.mLocalPlayerId = e->GetId(); + dtEntity::Entity* e; + if (!mEntityManager->CreateEntity(e)) + return; + pd.mLocalPlayerId = e->GetId(); - dtEntity::MapComponent *mc; - if (!e->CreateComponent(mc)) - return; - std::string en = "ctx_" + std::to_string(dspl.mContextId) + "_plr_" + std::to_string(pd.mWorldPlayerId); - mc->SetEntityName(en); - mc->SetUniqueId(en); - mc->SetMapName("proxies"); + dtEntity::MapComponent* mc; + if (!e->CreateComponent(mc)) + return; + std::string en = "ctx_" + std::to_string(dspl.mContextId) + "_plr_" + std::to_string(pd.mWorldPlayerId); + mc->SetEntityName(en); + mc->SetUniqueId(en); + mc->SetMapName("proxies"); - if (!e->CreateComponent(pd.mIcon)) - return; - pd.mIcon->SetVisible(visible); - pd.mIcon->SetPath(symbol); - pd.mIcon->SetColor(color); - pd.mIcon->SetVOffset(0.0f); - int roomNumber = pd.mIcon->GetRoomNumber(); - pd.mIcon->SetTranslation(remapPosition(bd, dspl, pos, roomNumber)); - pd.mIcon->SetOriginAtBottom(dspl.mViewMode == ViewMode::ISOMETRIC); - pd.mIcon->SetShowDot(dspl.mPlayerDisplayMode == PlayerDisplayMode::Dots); + if (!e->CreateComponent(pd.mIcon)) + return; + pd.mIcon->SetVisible(visible); + pd.mIcon->SetPath(symbol); + pd.mIcon->SetColor(color); + pd.mIcon->SetVOffset(0.0f); + int roomNumber = pd.mIcon->GetRoomNumber(); + pd.mIcon->SetTranslation(remapPosition(bd, dspl, pos, roomNumber)); + pd.mIcon->SetOriginAtBottom(dspl.mViewMode == ViewMode::ISOMETRIC); + pd.mIcon->SetShowDot(dspl.mPlayerDisplayMode == PlayerDisplayMode::Dots); - pd.mIcon->Finished(); + pd.mIcon->Finished(); - std::string viewname = "Context_" + std::to_string(dspl.mContextId); + std::string viewname = "Context_" + std::to_string(dspl.mContextId); - dtEntityOSG::LayerComponent *lc; - if (!e->CreateComponent(lc)) - return; - lc->SetAttachedComponent(IconComponent::TYPE); - lc->SetLayer(dtEntity::SID(viewname)); + dtEntityOSG::LayerComponent* lc; + if (!e->CreateComponent(lc)) + return; + lc->SetAttachedComponent(IconComponent::TYPE); + lc->SetLayer(dtEntity::SID(viewname)); - dtEntity::MapSystem *ms; - if (!mEntityManager->GetES(ms)) - return; - ms->AddToScene(e->GetId()); - - dspl.mPlayers.push_back(std::move(pd)); - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + dtEntity::MapSystem* ms; + if (!mEntityManager->GetES(ms)) + return; + ms->AddToScene(e->GetId()); + dspl.mPlayers.push_back(std::move(pd)); + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); } - -void BuildingManager::addPlayerToBuildings(const std::string &navmeshgrpname, dtEntity::EntityId eid, - const osg::Vec4 &color, const std::string &symbol, const osg::Vec3d &pos, +void BuildingManager::addPlayerToBuildings(const std::string& navmeshgrpname, dtEntity::EntityId eid, + const osg::Vec4& color, const std::string& symbol, const osg::Vec3d& pos, bool visible) { - for (Building *building : mBuildings) - { - if (building->mNavMeshGrpName != navmeshgrpname) - continue; - for (BuildingDisplay &bd : building->mDisplays) - addPlayerToBuilding(*building, bd, eid, color, symbol, pos, visible); - } + for (Building* building : mBuildings) + { + if (building->mNavMeshGrpName != navmeshgrpname) + continue; + for (BuildingDisplay& bd : building->mDisplays) + addPlayerToBuilding(*building, bd, eid, color, symbol, pos, visible); + } } - -void BuildingManager::removePlayerFromBuilding(const std::string &navmeshgrpname, dtEntity::EntityId eid, const std::string& roomname) +void BuildingManager::removePlayerFromBuilding(const std::string& navmeshgrpname, dtEntity::EntityId eid, + const std::string& roomname) { - if (mExactPos == false) - deleteRoomUsagePlayer(navmeshgrpname, roomname, eid); + if (mExactPos == false) + deleteRoomUsagePlayer(navmeshgrpname, roomname, eid); - for (Building *building : mBuildings) - { - if (building->mNavMeshGrpName != navmeshgrpname) - continue; - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (auto it = bd.mPlayers.begin(); it != bd.mPlayers.end(); ++it) - { - const PlayerDisplay &pd = *it; - if (pd.mWorldPlayerId == eid) + if (building->mNavMeshGrpName != navmeshgrpname) + continue; + for (BuildingDisplay& bd : building->mDisplays) { - dtEntity::MapSystem *ms; - if (mEntityManager->GetES(ms)) - ms->RemoveFromScene(pd.mLocalPlayerId); - mEntityManager->KillEntity(pd.mLocalPlayerId); - bd.mPlayers.erase(it); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (auto it = bd.mPlayers.begin(); it != bd.mPlayers.end(); ++it) + { + const PlayerDisplay& pd = *it; + if (pd.mWorldPlayerId == eid) + { + dtEntity::MapSystem* ms; + if (mEntityManager->GetES(ms)) + ms->RemoveFromScene(pd.mLocalPlayerId); + mEntityManager->KillEntity(pd.mLocalPlayerId); + bd.mPlayers.erase(it); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - -void BuildingManager::updatePlayerPosition(const std::string &navmeshgrpname, dtEntity::EntityId eid, const osg::Vec3d &pos, int roomNumber) +void BuildingManager::updatePlayerPosition(const std::string& navmeshgrpname, dtEntity::EntityId eid, + const osg::Vec3d& pos, int roomNumber) { - LOG_DEBUG("BuildingManager::updatePlayerPosition: " << "navmeshgrpname='"<< navmeshgrpname << "'" - << ", eid/WorldPlayerId="<< eid - << ", pos: x=" << pos.x() << " y=" << pos.y() << " z=" << pos.z() - << ", roomNumber="<< roomNumber); + LOG_DEBUG("BuildingManager::updatePlayerPosition: " << "navmeshgrpname='" << navmeshgrpname << "'" + << ", eid/WorldPlayerId=" << eid << ", pos: x=" << pos.x() + << " y=" << pos.y() << " z=" << pos.z() + << ", roomNumber=" << roomNumber); - for (Building *building : mBuildings) - { - if (building->mNavMeshGrpName != navmeshgrpname) - continue; - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + if (building->mNavMeshGrpName != navmeshgrpname) + continue; + for (BuildingDisplay& bd : building->mDisplays) { - pd.mIcon->SetTranslation(remapPosition(*building, bd, pos, roomNumber)); - pd.mIcon->SetRoomNumber(roomNumber); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + pd.mIcon->SetTranslation(remapPosition(*building, bd, pos, roomNumber)); + pd.mIcon->SetRoomNumber(roomNumber); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - -osg::Vec3d BuildingManager::remapPosition(const Building &bd, const BuildingDisplay &dspl, const osg::Vec3d &world, int roomNumber) +osg::Vec3d BuildingManager::remapPosition(const Building& bd, const BuildingDisplay& dspl, const osg::Vec3d& world, + int roomNumber) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " mFeatureId = " << bd.mFeatureId.c_str() - << ", roomNumber= " << roomNumber; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " mFeatureId = " << bd.mFeatureId.c_str() << ", roomNumber= " << roomNumber; - if (roomNumber > 0) - { - - - - int floorOut; - if (getFloorOfRoom(bd.mFeatureId, roomNumber, floorOut)) + if (roomNumber > 0) { - for (const auto &level : dspl.mLevels) - { - if (level.mFloorId == floorOut) + + int floorOut; + if (getFloorOfRoom(bd.mFeatureId, roomNumber, floorOut)) { - const osg::Vec3d &l = world * bd.mWorldToLocal; - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " mFeatureId = " << bd.mFeatureId.c_str() - << ", roomNumber= " << roomNumber - << ", floorOut= " << floorOut - << ", world.z()= " << world.z() - << ", RET value is =" << (l * level.mLocalToLevel).z(); - return l * level.mLocalToLevel; + for (const auto& level : dspl.mLevels) + { + if (level.mFloorId == floorOut) + { + const osg::Vec3d& l = world * bd.mWorldToLocal; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " mFeatureId = " << bd.mFeatureId.c_str() + << ", roomNumber= " << roomNumber << ", floorOut= " << floorOut + << ", world.z()= " << world.z() + << ", RET value is =" << (l * level.mLocalToLevel).z(); + return l * level.mLocalToLevel; + } + } } - } } - } - - - const osg::Vec3d l = world * bd.mWorldToLocal; - const size_t numlevels = dspl.mLevels.size(); - for (unsigned int i = 0; i < numlevels; ++i) - { - if (i == (numlevels - 1) || (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f) > l[2]) + const osg::Vec3d l = world * bd.mWorldToLocal; + const size_t numlevels = dspl.mLevels.size(); + for (unsigned int i = 0; i < numlevels; ++i) { - const BuildingLevel &level = dspl.mLevels[i]; - DEBUG_LOG(m_logger) << Q_FUNC_INFO - << " remapXPosition" - << ", l.z=" << l.z() - << ", i=" << i - << ", numlevels=" << numlevels - << ", (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f)=" - << (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f) - << ", l[2]=" << l[2] - << ", ret=" << (l * level.mLocalToLevel).z(); - return l * level.mLocalToLevel; + if (i == (numlevels - 1) || (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f) > l[2]) + { + const BuildingLevel& level = dspl.mLevels[i]; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " remapXPosition" + << ", l.z=" << l.z() << ", i=" << i << ", numlevels=" << numlevels + << ", (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f)=" + << (dspl.mLevels[i + 1].mHeightAboveGround - 0.1f) << ", l[2]=" << l[2] + << ", ret=" << (l * level.mLocalToLevel).z(); + return l * level.mLocalToLevel; + } } - } - LOG_ERROR("Could not remap position!"); - return world; + LOG_ERROR("Could not remap position!"); + return world; } - -void BuildingManager::setPlayerColor(dtEntity::EntityId eid, const osg::Vec4 &color) +void BuildingManager::setPlayerColor(dtEntity::EntityId eid, const osg::Vec4& color) { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + for (BuildingDisplay& bd : building->mDisplays) { - pd.mIcon->SetColor(color); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + pd.mIcon->SetColor(color); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - -void BuildingManager::setPlayerIcon(dtEntity::EntityId eid, const std::string &path) +void BuildingManager::setPlayerIcon(dtEntity::EntityId eid, const std::string& path) { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + for (BuildingDisplay& bd : building->mDisplays) { - pd.mIcon->SetPath(path); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + pd.mIcon->SetPath(path); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - - void BuildingManager::reloadPlayerIcons() { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - pd.mIcon->Reload(); + for (BuildingDisplay& bd : building->mDisplays) + { + for (PlayerDisplay& pd : bd.mPlayers) + pd.mIcon->Reload(); - if (bd.mPlayers.size()) - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + if (bd.mPlayers.size()) + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + } } - } } - - void BuildingManager::updatePlayerPartyColor(dtEntity::EntityId eid, const VCtrl::Color& col) { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + for (BuildingDisplay& bd : building->mDisplays) { - pd.mIcon->SetColor(osg::Vec4(col.x,col.y,col.z,col.w)); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + pd.mIcon->SetColor(osg::Vec4(col.x, col.y, col.z, col.w)); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - - void BuildingManager::setShowPlayerSelection(dtEntity::EntityId eid, bool show) { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + for (BuildingDisplay& bd : building->mDisplays) { - pd.mIcon->SetShowSelection(show); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + pd.mIcon->SetShowSelection(show); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; + } + } } - } } - } } - void BuildingManager::setShowHidePlayer(dtEntity::EntityId eid, bool show) { - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - for (PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mWorldPlayerId == eid) + for (BuildingDisplay& bd : building->mDisplays) { - if (pd.mIcon->GetVisible() != show) - { - pd.mIcon->SetVisible(show); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - } - break; + for (PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mWorldPlayerId == eid) + { + if (pd.mIcon->GetVisible() != show) + { + pd.mIcon->SetVisible(show); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + } + break; + } + } } - } } - } } - -void BuildingManager::setRoomDestructionValue(dtEntity::EntityId eid, const std::string &roomname, float value) +void BuildingManager::setRoomDestructionValue(dtEntity::EntityId eid, const std::string& roomname, float value) { - for (const Building *building : mBuildings) - { - if (building->mWorldBuildingId != eid) - continue; - for (const BuildingDisplay &bd : building->mDisplays) + for (const Building* building : mBuildings) { - bool bRequestRedraw = false; - for (const BuildingLevel &level : bd.mLevels) - { - RoomDestructionComponent *btc; - if (mEntityManager->GetComponent(level.mEntityId, btc)) + if (building->mWorldBuildingId != eid) + continue; + for (const BuildingDisplay& bd : building->mDisplays) { - btc->SetRoomDestructionValue(roomname, value); - bRequestRedraw = true; + bool bRequestRedraw = false; + for (const BuildingLevel& level : bd.mLevels) + { + RoomDestructionComponent* btc; + if (mEntityManager->GetComponent(level.mEntityId, btc)) + { + btc->SetRoomDestructionValue(roomname, value); + bRequestRedraw = true; + } + } + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); } - - - - - - - - - - - - - - - - - - - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; } - break; - } } - void BuildingManager::setBuildingDestructionValue(dtEntity::EntityId eid, float value) { - for (const Building *building : mBuildings) - { - if (building->mWorldBuildingId != eid) - continue; - for (const BuildingDisplay &bd : building->mDisplays) + for (const Building* building : mBuildings) { - bool bRequestRedraw = false; - for (const BuildingLevel &level : bd.mLevels) - { - RoomDestructionComponent *btc; - if (mEntityManager->GetComponent(level.mEntityId, btc)) + if (building->mWorldBuildingId != eid) + continue; + for (const BuildingDisplay& bd : building->mDisplays) { - btc->SetBuildingDestructionValue(value); - bRequestRedraw = true; + bool bRequestRedraw = false; + for (const BuildingLevel& level : bd.mLevels) + { + RoomDestructionComponent* btc; + if (mEntityManager->GetComponent(level.mEntityId, btc)) + { + btc->SetBuildingDestructionValue(value); + bRequestRedraw = true; + } + } + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); } - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; } - break; - } } - dtEntity::EntityId BuildingManager::getWorldPlayerIdFromLocalPlayer(dtEntity::EntityId local) const { - for (const Building *building : mBuildings) - { - for (const BuildingDisplay &bd : building->mDisplays) + for (const Building* building : mBuildings) { - for (const PlayerDisplay &pd : bd.mPlayers) - { - if (pd.mLocalPlayerId == local) - return pd.mWorldPlayerId; - } + for (const BuildingDisplay& bd : building->mDisplays) + { + for (const PlayerDisplay& pd : bd.mPlayers) + { + if (pd.mLocalPlayerId == local) + return pd.mWorldPlayerId; + } - for (const DeviceDisplay &pd : bd.mDeviceDisplays) - { - if (pd.mLocalPlayerId == local) - return pd.mWorldPlayerId; - } + for (const DeviceDisplay& pd : bd.mDeviceDisplays) + { + if (pd.mLocalPlayerId == local) + return pd.mWorldPlayerId; + } + } } - } - return 0; + return 0; } - void BuildingManager::removeShoot(int32_t id) { - DEBUG_LOG(m_logger) << "removeShoot id=" << id; - QMutexLocker locker(&m_mutexShots); - for (Building *bldg : mBuildings) - { - DEBUG_LOG(m_logger) << "Vorher: bldg->mShots.size()=" << bldg->mShots.size(); - auto it = std::remove_if(bldg->mShots.begin(), bldg->mShots.end(), - [id]( Shot *shot) + DEBUG_LOG(m_logger) << "removeShoot id=" << id; + QMutexLocker locker(&m_mutexShots); + for (Building* bldg : mBuildings) { - if (shot->getId() == id) - { - - const unsigned int duration = 0; - shot->setDisplayTime(duration); - return true; - } + DEBUG_LOG(m_logger) << "Vorher: bldg->mShots.size()=" << bldg->mShots.size(); + auto it = std::remove_if(bldg->mShots.begin(), bldg->mShots.end(), [id](Shot* shot) { + if (shot->getId() == id) + { - return false; - }); + const unsigned int duration = 0; + shot->setDisplayTime(duration); + return true; + } - bool wasRemoved = (it != bldg->mShots.end()); + return false; + }); - bldg->mShots.erase(it, bldg->mShots.end()); - DEBUG_LOG(m_logger) << "Nachher: bldg->mShots.size()=" << bldg->mShots.size(); + bool wasRemoved = (it != bldg->mShots.end()); - if (wasRemoved) - for (BuildingDisplay &dspl : bldg->mDisplays) - { - DEBUG_LOG(m_logger) << "wasRemoved id=" << id; - updateShots(*bldg, dspl); - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); - } - } + bldg->mShots.erase(it, bldg->mShots.end()); + DEBUG_LOG(m_logger) << "Nachher: bldg->mShots.size()=" << bldg->mShots.size(); + + if (wasRemoved) + for (BuildingDisplay& dspl : bldg->mDisplays) + { + DEBUG_LOG(m_logger) << "wasRemoved id=" << id; + updateShots(*bldg, dspl); + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + } + } } - void BuildingManager::showShoot(int32_t id, dtEntity::EntityId shooter, dtEntity::EntityId target, - const dtEntity::Vec3d &shooterPos, const dtEntity::Vec3d &targetPos, - int buildingIdSrc, int roomNumberSrc, int buildingIdDst, int roomNumberDst, - int lineType, float duration, double simTimeCreated) + const dtEntity::Vec3d& shooterPos, const dtEntity::Vec3d& targetPos, int buildingIdSrc, + int roomNumberSrc, int buildingIdDst, int roomNumberDst, int lineType, float duration, + double simTimeCreated) { - PlayerComponent *shooterpc, *targetpc; + PlayerComponent *shooterpc, *targetpc; - mEntityManager->GetComponent(shooter, shooterpc); - mEntityManager->GetComponent(target, targetpc); - if (!shooterpc) - { - assert(false); - return; - } - - if (mShotOverview == false && targetpc) - { - if (shooterpc->GetCurrentCellGroup() != targetpc->GetCurrentCellGroup()) - return; - } - - std::string navmeshname = dtEntity::GetStringFromSID(shooterpc->GetCurrentCellGroup()); - std::string targetnavmeshname; - if (mShotOverview == true && targetpc) - targetnavmeshname = dtEntity::GetStringFromSID(targetpc->GetCurrentCellGroup()); - - - QMutexLocker locker(&m_mutexShots); - for (Building *bldg : mBuildings) - { - if ((targetpc == nullptr && target == bldg->mWorldBuildingId) || - (bldg->mNavMeshGrpName == navmeshname) || - (bldg->mNavMeshGrpName == targetnavmeshname)) + mEntityManager->GetComponent(shooter, shooterpc); + mEntityManager->GetComponent(target, targetpc); + if (!shooterpc) { - - double _simTimeCreated = simTimeCreated != 0 ? simTimeCreated : dtEntity::GetSystemInterface()->GetSimulationTime() ; - - Shot* shot = new Shot(id, - shooterPos, - targetPos, - buildingIdSrc, roomNumberSrc, - buildingIdDst, roomNumberDst, - lineType, - shooterpc->GetColor(), - static_cast(duration), - 120, - _simTimeCreated); - for(const auto it : bldg->mShots) - { - if (it->getId() == shot->getId()) - { - delete shot; - return; - } - } - bldg->mShots.push_back(shot); - DEBUG_LOG(m_logger) << "XXXX SIM TIME CREATED = " << QString::number(_simTimeCreated, 'f', 5) << " and SIM TIME IS " <GetSimulationTime(), 'f', 5); - - for (BuildingDisplay &bldgDispl : bldg->mDisplays) - { - ShotDisplay shotDispl; - shotDispl.mShot = shot; - DEBUG_LOG(m_logger) << "mShotDisplays.push_back id=" << shot->getId(); - bldgDispl.mShotDisplays.push_back(std::move(shotDispl)); - - updateShots(*bldg, bldgDispl); - dtEntity::GetWindowInterface()->RequestRedraw(bldgDispl.mContextId); - } - if (targetpc == nullptr && target == bldg->mWorldBuildingId) - break; - } - } -} - - -void BuildingManager::updateShots(const Building &bd, BuildingDisplay &dspl) -{ - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " Building= " << bd.mWorldBuildingId; - - dtEntityOSG::CameraComponent *camcomp; - if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) - return; - osg::Vec3 eyedir(camcomp->GetEyeDirection()); - - dtEntityOSG::LayerAttachPointComponent *lac; - if (!mEntityManager->GetComponent(dspl.mAttachPointId, lac)) - return; - - const double simTime = dtEntity::GetSystemInterface()->GetSimulationTime(); - - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dspl.mShotDisplays.size()= " << dspl.mShotDisplays.size() - << ", simTime=" << (int)simTime; - - for (ShotDisplay &shotdspl : dspl.mShotDisplays) - { - if (!shotdspl.mShot) - continue; - - - - - const bool bDisplay = (shotdspl.mShot->displayTime() > simTime) && (shotdspl.mShot->simTimeCreated() <= simTime); - - - - - - - while (shotdspl.mGeode.valid() && shotdspl.mGeode->getNumParents() > 0) - shotdspl.mGeode->getParent(0)->removeChild(shotdspl.mGeode); - shotdspl.mGeode = osg::ref_ptr(); - - int numParents = -1; - if (shotdspl.mGeode) - numParents = shotdspl.mGeode->getNumParents(); - - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " BB shotdspl.mShot->getId()= " << shotdspl.mShot->getId() - << ", shotdspl.mGeode=" << shotdspl.mGeode - << ", shotdspl.mGeode->getNumParents=" << numParents - << ", bDisplay=" << bDisplay; - - - if ((!shotdspl.mGeode || shotdspl.mGeode->getNumParents() == 0) && bDisplay) - { - DEBUG_LOG(m_logger) << "NEW mGeode! id " << shotdspl.mShot->getId(); - if (!shotdspl.mGeode) - shotdspl.mGeode = new osg::Geode(); - - osg::StateSet *ss = shotdspl.mGeode->getOrCreateStateSet(); - ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); - ss->setRenderBinDetails(240001, "RenderBin"); - osg::ref_ptr lw = new osg::LineWidth(); - DEBUG_LOG(m_logger) << "NEW LINE " << shotdspl.mShot->getLineType(); - - if (shotdspl.mShot->getLineType() < 2 ) - { - int stippleSize = 5; - if (shotdspl.mShot->getLineType() == 1) - stippleSize = 2; - - osg::ref_ptr ls = new osg::LineStipple(stippleSize, 0xAAAA); - ss->setAttributeAndModes(ls, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); - - } - - - - - lw->setWidth(2); - - ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF); - - - osg::Geometry *gmtr = new osg::Geometry(); - shotdspl.mGeode->addDrawable(gmtr); - - osg::Vec4Array *col = new osg::Vec4Array(1); - (*col)[0] = shotdspl.mShot->getColor(); - gmtr->setColorArray(col); - gmtr->setColorBinding(osg::Geometry::BIND_OVERALL); - - osg::Vec3d shooterpos = remapPosition(bd, dspl, shotdspl.mShot->getShooterPos(), shotdspl.mShot->getRoomNumberSrc()); - osg::Vec3d targetpos = remapPosition(bd, dspl, shotdspl.mShot->getTargetPos(), shotdspl.mShot->getRoomNumberDst()); - - - shooterpos[2] += 1; - targetpos[2] += 1; - - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " shotdspl.mShot->getId()= " << shotdspl.mShot->getId() - << ", getShooterPos.z()=" << shotdspl.mShot->getShooterPos().z() - << ", BuildingIdSrc=" << shotdspl.mShot->getBuildingIdSrc() << ", RoomNumberSrc=" << shotdspl.mShot->getRoomNumberSrc() - << ", shooterpos=" << shooterpos - << ", getTargetPos.z()=" << shotdspl.mShot->getTargetPos().z() - << ", BuildingIdDst=" << shotdspl.mShot->getBuildingIdDst() << ", RoomNumberDst=" << shotdspl.mShot->getRoomNumberDst() - << ", targetpos=" << targetpos; - - osg::Vec3Array *coords = new osg::Vec3Array(6); - (*coords)[0] = shooterpos; - (*coords)[1] = targetpos; - - osg::Vec3d edge = targetpos - shooterpos; - edge.normalize(); - edge *= 0.8; - - osg::Vec3d p1 = eyedir ^ edge; - p1.normalize(); - p1 *= 0.8; - - - (*coords)[2] = p1 - edge * 1.5 + targetpos; - (*coords)[3] = targetpos; - (*coords)[4] = -p1 - edge * 1.5 + targetpos; - (*coords)[5] = targetpos; - - gmtr->setVertexArray(coords); - - gmtr->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 6)); - - - - - - } - - if (bDisplay) - lac->GetNode()->asGroup()->addChild(shotdspl.mGeode); - - } -} - - -void BuildingManager::updateDevices(const Building &bd, BuildingDisplay &dspl) -{ - for (DeviceDisplay &ddspl : dspl.mDeviceDisplays) - { - IconComponent *icon; - if (ddspl.mLocalPlayerId == 0) - { - dtEntity::Entity *e; - if (!mEntityManager->CreateEntity(e)) - continue; - ddspl.mLocalPlayerId = e->GetId(); - - dtEntity::MapComponent *mc; - if (!e->CreateComponent(mc)) - continue; - std::string en = "ctx_" + std::to_string(dspl.mContextId) + "_plr_" + std::to_string(ddspl.mDevice->mWorldPlayerId); - mc->SetEntityName(en); - mc->SetUniqueId(en); - mc->SetMapName("deviceproxies"); - - if (!e->CreateComponent(icon)) - continue; - icon->SetPath(ddspl.mDevice->mPath); - icon->SetOriginAtBottom(false); - - - dtEntityOSG::LayerComponent *lc; - if (!e->CreateComponent(lc)) - continue; - std::string viewname = "Context_" + std::to_string(dspl.mContextId); - lc->SetAttachedComponent(IconComponent::TYPE); - lc->SetLayer(dtEntity::SID(viewname)); - - dtEntity::MapSystem *ms; - if (mEntityManager->GetES(ms)) - ms->AddToScene(e->GetId()); - } - else - { - if (!mEntityManager->GetComponent(ddspl.mLocalPlayerId, icon)) - { assert(false); - continue; - } + return; } - int roomNumber = icon->GetRoomNumber(); - icon->SetTranslation(remapPosition(bd, dspl, ddspl.mDevice->mPosition, roomNumber)); - icon->Finished(); - icon->SetVisible(true); - } + if (mShotOverview == false && targetpc) + { + if (shooterpc->GetCurrentCellGroup() != targetpc->GetCurrentCellGroup()) + return; + } + + std::string navmeshname = dtEntity::GetStringFromSID(shooterpc->GetCurrentCellGroup()); + std::string targetnavmeshname; + if (mShotOverview == true && targetpc) + targetnavmeshname = dtEntity::GetStringFromSID(targetpc->GetCurrentCellGroup()); + + QMutexLocker locker(&m_mutexShots); + for (Building* bldg : mBuildings) + { + if ((targetpc == nullptr && target == bldg->mWorldBuildingId) || (bldg->mNavMeshGrpName == navmeshname) || + (bldg->mNavMeshGrpName == targetnavmeshname)) + { + + double _simTimeCreated = + simTimeCreated != 0 ? simTimeCreated : dtEntity::GetSystemInterface()->GetSimulationTime(); + + Shot* shot = + new Shot(id, shooterPos, targetPos, buildingIdSrc, roomNumberSrc, buildingIdDst, roomNumberDst, + lineType, shooterpc->GetColor(), static_cast(duration), 120, _simTimeCreated); + for (const auto it : bldg->mShots) + { + if (it->getId() == shot->getId()) + { + delete shot; + return; + } + } + bldg->mShots.push_back(shot); + DEBUG_LOG(m_logger) << "XXXX SIM TIME CREATED = " << QString::number(_simTimeCreated, 'f', 5) + << " and SIM TIME IS " + << QString::number(dtEntity::GetSystemInterface()->GetSimulationTime(), 'f', 5); + + for (BuildingDisplay& bldgDispl : bldg->mDisplays) + { + ShotDisplay shotDispl; + shotDispl.mShot = shot; + DEBUG_LOG(m_logger) << "mShotDisplays.push_back id=" << shot->getId(); + bldgDispl.mShotDisplays.push_back(std::move(shotDispl)); + + updateShots(*bldg, bldgDispl); + dtEntity::GetWindowInterface()->RequestRedraw(bldgDispl.mContextId); + } + if (targetpc == nullptr && target == bldg->mWorldBuildingId) + break; + } + } } +void BuildingManager::updateShots(const Building& bd, BuildingDisplay& dspl) +{ + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " Building= " << bd.mWorldBuildingId; + + dtEntityOSG::CameraComponent* camcomp; + if (!mEntityManager->GetComponent(dspl.mCameraId, camcomp)) + return; + osg::Vec3 eyedir(camcomp->GetEyeDirection()); + + dtEntityOSG::LayerAttachPointComponent* lac; + if (!mEntityManager->GetComponent(dspl.mAttachPointId, lac)) + return; + + const double simTime = dtEntity::GetSystemInterface()->GetSimulationTime(); + + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dspl.mShotDisplays.size()= " << dspl.mShotDisplays.size() + << ", simTime=" << (int)simTime; + + for (ShotDisplay& shotdspl : dspl.mShotDisplays) + { + if (!shotdspl.mShot) + continue; + + const bool bDisplay = + (shotdspl.mShot->displayTime() > simTime) && (shotdspl.mShot->simTimeCreated() <= simTime); + + while (shotdspl.mGeode.valid() && shotdspl.mGeode->getNumParents() > 0) + shotdspl.mGeode->getParent(0)->removeChild(shotdspl.mGeode); + shotdspl.mGeode = osg::ref_ptr(); + + int numParents = -1; + if (shotdspl.mGeode) + numParents = shotdspl.mGeode->getNumParents(); + + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " BB shotdspl.mShot->getId()= " << shotdspl.mShot->getId() + << ", shotdspl.mGeode=" << shotdspl.mGeode + << ", shotdspl.mGeode->getNumParents=" << numParents << ", bDisplay=" << bDisplay; + + if ((!shotdspl.mGeode || shotdspl.mGeode->getNumParents() == 0) && bDisplay) + { + DEBUG_LOG(m_logger) << "NEW mGeode! id " << shotdspl.mShot->getId(); + if (!shotdspl.mGeode) + shotdspl.mGeode = new osg::Geode(); + + osg::StateSet* ss = shotdspl.mGeode->getOrCreateStateSet(); + ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); + ss->setRenderBinDetails(240001, "RenderBin"); + osg::ref_ptr lw = new osg::LineWidth(); + DEBUG_LOG(m_logger) << "NEW LINE " << shotdspl.mShot->getLineType(); + + if (shotdspl.mShot->getLineType() < 2) + { + int stippleSize = 5; + if (shotdspl.mShot->getLineType() == 1) + stippleSize = 2; + + osg::ref_ptr ls = new osg::LineStipple(stippleSize, 0xAAAA); + ss->setAttributeAndModes(ls, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); + } + + lw->setWidth(2); + + ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF); + + osg::Geometry* gmtr = new osg::Geometry(); + shotdspl.mGeode->addDrawable(gmtr); + + osg::Vec4Array* col = new osg::Vec4Array(1); + (*col)[0] = shotdspl.mShot->getColor(); + gmtr->setColorArray(col); + gmtr->setColorBinding(osg::Geometry::BIND_OVERALL); + + osg::Vec3d shooterpos = + remapPosition(bd, dspl, shotdspl.mShot->getShooterPos(), shotdspl.mShot->getRoomNumberSrc()); + osg::Vec3d targetpos = + remapPosition(bd, dspl, shotdspl.mShot->getTargetPos(), shotdspl.mShot->getRoomNumberDst()); + + shooterpos[2] += 1; + targetpos[2] += 1; + + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " shotdspl.mShot->getId()= " << shotdspl.mShot->getId() + << ", getShooterPos.z()=" << shotdspl.mShot->getShooterPos().z() + << ", BuildingIdSrc=" << shotdspl.mShot->getBuildingIdSrc() + << ", RoomNumberSrc=" << shotdspl.mShot->getRoomNumberSrc() + << ", shooterpos=" << shooterpos + << ", getTargetPos.z()=" << shotdspl.mShot->getTargetPos().z() + << ", BuildingIdDst=" << shotdspl.mShot->getBuildingIdDst() + << ", RoomNumberDst=" << shotdspl.mShot->getRoomNumberDst() + << ", targetpos=" << targetpos; + + osg::Vec3Array* coords = new osg::Vec3Array(6); + (*coords)[0] = shooterpos; + (*coords)[1] = targetpos; + + osg::Vec3d edge = targetpos - shooterpos; + edge.normalize(); + edge *= 0.8; + + osg::Vec3d p1 = eyedir ^ edge; + p1.normalize(); + p1 *= 0.8; + + (*coords)[2] = p1 - edge * 1.5 + targetpos; + (*coords)[3] = targetpos; + (*coords)[4] = -p1 - edge * 1.5 + targetpos; + (*coords)[5] = targetpos; + + gmtr->setVertexArray(coords); + + gmtr->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, 6)); + } + + if (bDisplay) + lac->GetNode()->asGroup()->addChild(shotdspl.mGeode); + } +} + +void BuildingManager::updateDevices(const Building& bd, BuildingDisplay& dspl) +{ + for (DeviceDisplay& ddspl : dspl.mDeviceDisplays) + { + IconComponent* icon; + if (ddspl.mLocalPlayerId == 0) + { + dtEntity::Entity* e; + if (!mEntityManager->CreateEntity(e)) + continue; + ddspl.mLocalPlayerId = e->GetId(); + + dtEntity::MapComponent* mc; + if (!e->CreateComponent(mc)) + continue; + std::string en = + "ctx_" + std::to_string(dspl.mContextId) + "_plr_" + std::to_string(ddspl.mDevice->mWorldPlayerId); + mc->SetEntityName(en); + mc->SetUniqueId(en); + mc->SetMapName("deviceproxies"); + + if (!e->CreateComponent(icon)) + continue; + icon->SetPath(ddspl.mDevice->mPath); + icon->SetOriginAtBottom(false); + + dtEntityOSG::LayerComponent* lc; + if (!e->CreateComponent(lc)) + continue; + std::string viewname = "Context_" + std::to_string(dspl.mContextId); + lc->SetAttachedComponent(IconComponent::TYPE); + lc->SetLayer(dtEntity::SID(viewname)); + + dtEntity::MapSystem* ms; + if (mEntityManager->GetES(ms)) + ms->AddToScene(e->GetId()); + } + else + { + if (!mEntityManager->GetComponent(ddspl.mLocalPlayerId, icon)) + { + assert(false); + continue; + } + } + + int roomNumber = icon->GetRoomNumber(); + icon->SetTranslation(remapPosition(bd, dspl, ddspl.mDevice->mPosition, roomNumber)); + icon->Finished(); + icon->SetVisible(true); + } +} void BuildingManager::addDeviceToBuilding(dtEntity::EntityId iconmainid, dtEntity::EntityId buildingid, - const osg::Vec3d &pos, const std::string &iconpath) + const osg::Vec3d& pos, const std::string& iconpath) { - DEBUG_LOG(m_logger) << "addDeviceToBuilding"; - for (Building *building : mBuildings) - { - - DEBUG_LOG(m_logger) << "mWorldBuildingId=" << building->mWorldBuildingId - << " buildingid=" << buildingid; - - if (building->mWorldBuildingId != buildingid) - continue; - DEBUG_LOG(m_logger) << "addDeviceToBuilding 1"; - - Device *device = new Device(); - device->mWorldPlayerId = iconmainid; - device->mPath = iconpath; - device->mPosition = pos; - building->mDevices.push_back(device); - - DEBUG_LOG(m_logger) << "building->mDisplays.size=" << building->mDisplays.size(); - for (BuildingDisplay &dspl : building->mDisplays) + DEBUG_LOG(m_logger) << "addDeviceToBuilding"; + for (Building* building : mBuildings) { - DEBUG_LOG(m_logger) << "addDeviceToBuilding 2"; - DeviceDisplay dd; - dd.mDevice = device; - dd.mWorldPlayerId = iconmainid; - dspl.mDeviceDisplays.push_back(std::move(dd)); - updateDevices(*building, dspl); - dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); - } - break; - } -} + DEBUG_LOG(m_logger) << "mWorldBuildingId=" << building->mWorldBuildingId << " buildingid=" << buildingid; + + if (building->mWorldBuildingId != buildingid) + continue; + DEBUG_LOG(m_logger) << "addDeviceToBuilding 1"; + + Device* device = new Device(); + device->mWorldPlayerId = iconmainid; + device->mPath = iconpath; + device->mPosition = pos; + building->mDevices.push_back(device); + + DEBUG_LOG(m_logger) << "building->mDisplays.size=" << building->mDisplays.size(); + for (BuildingDisplay& dspl : building->mDisplays) + { + DEBUG_LOG(m_logger) << "addDeviceToBuilding 2"; + DeviceDisplay dd; + dd.mDevice = device; + dd.mWorldPlayerId = iconmainid; + dspl.mDeviceDisplays.push_back(std::move(dd)); + updateDevices(*building, dspl); + dtEntity::GetWindowInterface()->RequestRedraw(dspl.mContextId); + } + break; + } +} void BuildingManager::removeDeviceFromBuilding(dtEntity::EntityId iconmainid) { - for (Building *building : mBuildings) - { - std::vector::iterator j = building->mDevices.begin(); - while (j != building->mDevices.end()) + for (Building* building : mBuildings) { - Device *device = *j; - if (device->mWorldPlayerId == iconmainid) - { - for (BuildingDisplay &bd : building->mDisplays) + std::vector::iterator j = building->mDevices.begin(); + while (j != building->mDevices.end()) { - std::vector::iterator l = bd.mDeviceDisplays.begin(); - while (l != bd.mDeviceDisplays.end()) - { - DeviceDisplay &pd = *l; - if (pd.mDevice->mWorldPlayerId == iconmainid) + Device* device = *j; + if (device->mWorldPlayerId == iconmainid) { - dtEntity::MapSystem *ms; - mEntityManager->GetES(ms); - if (ms) - ms->RemoveFromScene(pd.mLocalPlayerId); - mEntityManager->KillEntity(pd.mLocalPlayerId); - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - l = bd.mDeviceDisplays.erase(l); + for (BuildingDisplay& bd : building->mDisplays) + { + std::vector::iterator l = bd.mDeviceDisplays.begin(); + while (l != bd.mDeviceDisplays.end()) + { + DeviceDisplay& pd = *l; + if (pd.mDevice->mWorldPlayerId == iconmainid) + { + dtEntity::MapSystem* ms; + mEntityManager->GetES(ms); + if (ms) + ms->RemoveFromScene(pd.mLocalPlayerId); + mEntityManager->KillEntity(pd.mLocalPlayerId); + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + l = bd.mDeviceDisplays.erase(l); + } + else + ++l; + } + } + j = building->mDevices.erase(j); + delete device; } else - ++l; - } + ++j; } - j = building->mDevices.erase(j); - delete device; - } - else - ++j; } - } } - - -template -bool fetchAttr(T &t, const rapidxml::xml_node<> *node, const char *name) +template bool fetchAttr(T& t, const rapidxml::xml_node<>* node, const char* name) { - using namespace rapidxml; - for (xml_attribute<> *attr = node->first_attribute(); attr; attr = attr->next_attribute()) - { - if (strcmp(attr->name(), name) == 0) + using namespace rapidxml; + for (xml_attribute<>* attr = node->first_attribute(); attr; attr = attr->next_attribute()) { - std::istringstream iss(attr->value()); - return !(iss >> std::dec >> t).fail(); + if (strcmp(attr->name(), name) == 0) + { + std::istringstream iss(attr->value()); + return !(iss >> std::dec >> t).fail(); + } } - } - return false; + return false; } - - -static bool HasTagName(const rapidxml::xml_node<> *node, const char *name) +static bool HasTagName(const rapidxml::xml_node<>* node, const char* name) { - return (node->type() == rapidxml::node_element && strcmp(name, node->name()) == 0); + return (node->type() == rapidxml::node_element && strcmp(name, node->name()) == 0); } - - -bool BuildingManager::getRoomBounds(const std::string &bldgname, const std::string &roomname, VCtrl::OBB &obb) const +bool BuildingManager::getRoomBounds(const std::string& bldgname, const std::string& roomname, VCtrl::OBB& obb) const { - const std::string key = bldgname + " " + roomname; - auto i = mRooms.find(key); - if (i == mRooms.end() || !i->second.mBB.valid()) - { - for (const auto &room : mRooms) + const std::string key = bldgname + " " + roomname; + auto i = mRooms.find(key); + if (i == mRooms.end() || !i->second.mBB.valid()) { - const osg::BoundingBox &bb = room.second.mBB; - QByteArray ba("id: "); - ba += room.first.c_str(); - ba += ", min: " + - QByteArray::number(bb.xMin()) + ", " + - QByteArray::number(bb.yMin()) + ", " + - QByteArray::number(bb.zMin()); - ba += ", max: " + - QByteArray::number(bb.xMax()) + ", " + - QByteArray::number(bb.yMax()) + ", " + - QByteArray::number(bb.zMax()); + for (const auto& room : mRooms) + { + const osg::BoundingBox& bb = room.second.mBB; + QByteArray ba("id: "); + ba += room.first.c_str(); + ba += ", min: " + QByteArray::number(bb.xMin()) + ", " + QByteArray::number(bb.yMin()) + ", " + + QByteArray::number(bb.zMin()); + ba += ", max: " + QByteArray::number(bb.xMax()) + ", " + QByteArray::number(bb.yMax()) + ", " + + QByteArray::number(bb.zMax()); #ifdef LTS_DEBUG - LOG_ERROR(ba.data()); + LOG_ERROR(ba.data()); #endif - } - LOG_ERROR("Could not find room " << bldgname << "-" << roomname << ", #mRooms: " << mRooms.size()); - return false; - } - obb = i->second; - if (!obb.mBB.valid()) - { - LOG_ERROR("Room" << bldgname << "-" << roomname << " has invalid bounds"); - return false; - } - return true; -} - - - -static void readBBoxMin(const rapidxml::xml_node<> *roomnode, VCtrl::OBB &room) -{ - if (HasTagName(roomnode, "BBox_Min")) - { - fetchAttr(room.mBB._min[0], roomnode, "X"); - fetchAttr(room.mBB._min[1], roomnode, "Y"); - fetchAttr(room.mBB._min[2], roomnode, "Z"); - } -} -static void readBBoxMax(const rapidxml::xml_node<> *roomnode, VCtrl::OBB &room) -{ - if (HasTagName(roomnode, "BBox_Max")) - { - fetchAttr(room.mBB._max[0], roomnode, "X"); - fetchAttr(room.mBB._max[1], roomnode, "Y"); - fetchAttr(room.mBB._max[2], roomnode, "Z"); - } -} - -static void readPolygon(const rapidxml::xml_node<> *roomnode, VCtrl::OBB &room) -{ - if (HasTagName(roomnode, "Group")) - { - for (auto grp0node(roomnode->first_node()); grp0node != nullptr; grp0node = grp0node->next_sibling()) - { - - if (HasTagName(grp0node, "Polygon")) - { - for (auto grp1node(grp0node->first_node()); grp1node != nullptr; grp1node = grp1node->next_sibling()) - { - if (HasTagName(grp1node, "Vertex")) - { - for (auto grp2node(grp1node->first_node()); grp2node != nullptr; grp2node = grp2node->next_sibling()) - { - if (HasTagName(grp2node, "Coord")) - { - double x,y; - fetchAttr(x, grp2node, "X"); - fetchAttr(y, grp2node, "Y"); - room.mPoly.append(QPointF(x,y)); - - } - } } - } - } + LOG_ERROR("Could not find room " << bldgname << "-" << roomname << ", #mRooms: " << mRooms.size()); + return false; } - } + obb = i->second; + if (!obb.mBB.valid()) + { + LOG_ERROR("Room" << bldgname << "-" << roomname << " has invalid bounds"); + return false; + } + return true; } -bool BuildingManager::AddRoomOBBs(const BuildingData &b) +static void readBBoxMin(const rapidxml::xml_node<>* roomnode, VCtrl::OBB& room) { - LOG_DEBUG("AddRoomOBBs: " + b.mFileName); - - if (b.mBuildingXMLPath.empty()) - { - LOG_WARNING("Buildings xml is not set: " + b.mFileName); - return false; - } - - const std::string xmlpath = b.mBuildingXMLPath; - - using namespace rapidxml; - const std::string absPath = dtEntity::GetSystemInterface()->FindDataFile(xmlpath); - if (absPath.empty()) - { - LOG_ERROR("Map not found: " + absPath); - return false; - } - - file<> file(absPath.c_str()); - - try - { - xml_document<> doc; - doc.parse<0>(file.data()); - - xml_node<> *rootnode = doc.first_node("STREIF"); - if (rootnode == nullptr) + if (HasTagName(roomnode, "BBox_Min")) { - LOG_ERROR("Could not parse building xml!"); - return false; + fetchAttr(room.mBB._min[0], roomnode, "X"); + fetchAttr(room.mBB._min[1], roomnode, "Y"); + fetchAttr(room.mBB._min[2], roomnode, "Z"); } +} - int floorNumber = -999; - std::map roomToFloor; - - for (xml_node<> *hdrNode(rootnode->first_node()); hdrNode != nullptr; hdrNode = hdrNode->next_sibling()) +static void readBBoxMax(const rapidxml::xml_node<>* roomnode, VCtrl::OBB& room) +{ + if (HasTagName(roomnode, "BBox_Max")) { - if (HasTagName(hdrNode, "Header")) - { - for (xml_node<> *grp1Node(hdrNode->first_node()); grp1Node != nullptr; grp1Node = grp1Node->next_sibling()) + fetchAttr(room.mBB._max[0], roomnode, "X"); + fetchAttr(room.mBB._max[1], roomnode, "Y"); + fetchAttr(room.mBB._max[2], roomnode, "Z"); + } +} + +static void readPolygon(const rapidxml::xml_node<>* roomnode, VCtrl::OBB& room) +{ + if (HasTagName(roomnode, "Group")) + { + for (auto grp0node(roomnode->first_node()); grp0node != nullptr; grp0node = grp0node->next_sibling()) { - if (HasTagName(grp1Node, "Group")) - { - for (xml_node<> *grp2Node(grp1Node->first_node()); grp2Node != nullptr; grp2Node = grp2Node->next_sibling()) + + if (HasTagName(grp0node, "Polygon")) { - if (HasTagName(grp2Node, "Group")) - { - for (xml_node<> *swtchNode(grp2Node->first_node()); swtchNode != nullptr; swtchNode = swtchNode->next_sibling()) + for (auto grp1node(grp0node->first_node()); grp1node != nullptr; grp1node = grp1node->next_sibling()) { - std::string temp; - if (HasTagName(swtchNode, "Name")) - { - temp = swtchNode->value(); - - if (temp.substr(0,6).compare("floor_") == 0) + if (HasTagName(grp1node, "Vertex")) { - bool bOk = false; - floorNumber = QString::fromStdString(temp.substr(6)).toInt(&bOk); - if (!bOk) - floorNumber = -999; - - } - } - - if (HasTagName(swtchNode, "Switch")) - { - VCtrl::OBB room; - room.mMatrix.setTrans(b.mX, b.mY, b.mZ); - osg::Quat q; - q.makeRotate(-b.mOrientation / 180.0 * osg::PI, osg::Vec3(0, 0, 1)); - room.mMatrix.setRotate(q); - room.mMatrixInverse.invert(room.mMatrix); - std::string name; - for (xml_node<> *roomnode(swtchNode->first_node()); roomnode != nullptr; roomnode = roomnode->next_sibling()) - { - int roomNumber = -999; - if (HasTagName(roomnode, "Name")) - { - temp = roomnode->value(); - - if (temp.substr(0,8).compare("SW_room_") == 0) + for (auto grp2node(grp1node->first_node()); grp2node != nullptr; + grp2node = grp2node->next_sibling()) { - bool bOk = false; - roomNumber = QString::fromStdString(temp.substr(8)).toInt(&bOk); - if (!bOk) - roomNumber = -999; - - - - if (roomNumber>=0) - roomToFloor[roomNumber+2000]=floorNumber; + if (HasTagName(grp2node, "Coord")) + { + double x, y; + fetchAttr(x, grp2node, "X"); + fetchAttr(y, grp2node, "Y"); + room.mPoly.append(QPointF(x, y)); + } } - } - - if (HasTagName(roomnode, "SubId")) - { - for (xml_attribute<> *attr = roomnode->first_attribute(); attr; attr = attr->next_attribute()) - { - if (strcmp(attr->name(), "ID") == 0) - name = attr->value(); - } - } - if (name.empty()) - continue; - readBBoxMin(roomnode, room); - readBBoxMax(roomnode, room); } - - - - - - - - - if (!room.mBB.valid()) - { - for (auto roomnode(swtchNode->first_node()); roomnode != nullptr; roomnode = roomnode->next_sibling()) - { - if (HasTagName(roomnode, "Group")) - { - for (auto grp3node(roomnode->first_node()); grp3node != nullptr; grp3node = grp3node->next_sibling()) - { - readBBoxMin(grp3node, room); - readBBoxMax(grp3node, room); - readPolygon(grp3node, room); - } - if (room.mBB.valid() && !room.mPoly.empty()) - { - - - - - break; - } - } - } - } - - - if (!room.mBB.valid()) - LOG_ERROR("Could not parse room bounding boxes for room" << name << " in xml " << xmlpath); - - room.mBB._min[2] -= ROOM_OBB_Z_MIN_SUBTRACT; - room.mBB._max[2] -= ROOM_OBB_Z_MAX_SUBTRACT; - - - - - if (!room.mBB.valid()) - { - - LOG_ERROR("Subtract from room OBB height fails, revert... room=" << name); - room.mBB._min[2] += ROOM_OBB_Z_MIN_SUBTRACT; - room.mBB._max[2] += ROOM_OBB_Z_MAX_SUBTRACT; - } - - if (!room.mBB.valid()) - LOG_ERROR("Could not parse room bounding boxes for room " << name << " in xml " << xmlpath); - - const std::string key = b.mFeatureId + " " + name; - room.mBuilding = dtEntity::SID(b.mFeatureId); - mRooms[key] = room; - - dtEntity::GetDebugDrawInterface()->AddOBB(room.mMatrix, room.mBB._min, room.mBB._max, osg::Vec4(1, 0, 1, 1), 1, FLT_MAX, false); - osg::Vec3 pos = room.mBB.center() * room.mMatrix; - dtEntity::GetDebugDrawInterface()->AddString(pos, key, osg::Vec4(0, 1, 0, 1), FLT_MAX, false); - } } - } } - } } - } } - - mRoomToFloorPerBldg[b.mFeatureId] = roomToFloor; - - } - catch (const std::exception &ex) - { - LOG_ERROR("XML Parsing error: " + std::string(ex.what())); - return false; - } - - - return true; } -bool BuildingManager::LoadBuildings(const std::string &path, std::vector &buildings) +bool BuildingManager::AddRoomOBBs(const BuildingData& b) { - using namespace rapidxml; - const std::string absPath = dtEntity::GetSystemInterface()->FindDataFile(path); - if (absPath.empty()) - { - LOG_ERROR("Map not found: " + absPath); - return false; - } + LOG_DEBUG("AddRoomOBBs: " + b.mFileName); - file<> file(absPath.c_str()); - - try - { - xml_document<> doc; - doc.parse<0>(file.data()); - - xml_node<> *rootnode = doc.first_node("MetaData"); - if (rootnode == nullptr) + if (b.mBuildingXMLPath.empty()) { - LOG_ERROR("Could not parse map xml!"); - return false; + LOG_WARNING("Buildings xml is not set: " + b.mFileName); + return false; } - for (xml_node<> *tagNode(rootnode->first_node()); tagNode != nullptr; tagNode = tagNode->next_sibling()) + const std::string xmlpath = b.mBuildingXMLPath; + + using namespace rapidxml; + const std::string absPath = dtEntity::GetSystemInterface()->FindDataFile(xmlpath); + if (absPath.empty()) { - if (HasTagName(tagNode, "Tag")) - { - int topmesh = -1; - for (xml_node<> *groupNode(tagNode->first_node()); groupNode != nullptr; groupNode = groupNode->next_sibling()) + LOG_ERROR("Map not found: " + absPath); + return false; + } + + file<> file(absPath.c_str()); + + try + { + xml_document<> doc; + doc.parse<0>(file.data()); + + xml_node<>* rootnode = doc.first_node("STREIF"); + if (rootnode == nullptr) { - if (HasTagName(groupNode, "Group")) - { - ++topmesh; - for (xml_node<> *modelNode(groupNode->first_node()); modelNode != nullptr; modelNode = modelNode->next_sibling()) - { - if (HasTagName(modelNode, "Model")) - { - BuildingData b; - - for (xml_node<> *dataNode(modelNode->first_node()); dataNode != nullptr; dataNode = dataNode->next_sibling()) - { - if (HasTagName(dataNode, "Orientation")) - fetchAttr(b.mOrientation, dataNode, "Angle"); - else if (HasTagName(dataNode, "Position")) - { - fetchAttr(b.mX, dataNode, "X"); - fetchAttr(b.mY, dataNode, "Y"); - fetchAttr(b.mZ, dataNode, "Z"); - } - else if (HasTagName(dataNode, "Description")) - fetchAttr(b.mDescription, dataNode, "Name"); - else if (HasTagName(dataNode, "Feature")) - fetchAttr(b.mFeatureId, dataNode, "Id"); - else if (HasTagName(dataNode, "File")) - fetchAttr(b.mFileName, dataNode, "Name"); - else if (HasTagName(dataNode, "STREIF")) - fetchAttr(b.mBuildingXMLPath, dataNode, "Name"); - } - b.mBuildingGroup = topmesh; - LOG_INFO("add building " + b.mFeatureId + " - " + b.mFileName); - buildings.push_back(std::move(b)); - - } - } - } + LOG_ERROR("Could not parse building xml!"); + return false; } - } + + int floorNumber = -999; + std::map roomToFloor; + + for (xml_node<>* hdrNode(rootnode->first_node()); hdrNode != nullptr; hdrNode = hdrNode->next_sibling()) + { + if (HasTagName(hdrNode, "Header")) + { + for (xml_node<>* grp1Node(hdrNode->first_node()); grp1Node != nullptr; + grp1Node = grp1Node->next_sibling()) + { + if (HasTagName(grp1Node, "Group")) + { + for (xml_node<>* grp2Node(grp1Node->first_node()); grp2Node != nullptr; + grp2Node = grp2Node->next_sibling()) + { + if (HasTagName(grp2Node, "Group")) + { + for (xml_node<>* swtchNode(grp2Node->first_node()); swtchNode != nullptr; + swtchNode = swtchNode->next_sibling()) + { + std::string temp; + if (HasTagName(swtchNode, "Name")) + { + temp = swtchNode->value(); + + if (temp.substr(0, 6).compare("floor_") == 0) + { + bool bOk = false; + floorNumber = QString::fromStdString(temp.substr(6)).toInt(&bOk); + if (!bOk) + floorNumber = -999; + } + } + + if (HasTagName(swtchNode, "Switch")) + { + VCtrl::OBB room; + room.mMatrix.setTrans(b.mX, b.mY, b.mZ); + osg::Quat q; + q.makeRotate(-b.mOrientation / 180.0 * osg::PI, osg::Vec3(0, 0, 1)); + room.mMatrix.setRotate(q); + room.mMatrixInverse.invert(room.mMatrix); + std::string name; + for (xml_node<>* roomnode(swtchNode->first_node()); roomnode != nullptr; + roomnode = roomnode->next_sibling()) + { + int roomNumber = -999; + if (HasTagName(roomnode, "Name")) + { + temp = roomnode->value(); + + if (temp.substr(0, 8).compare("SW_room_") == 0) + { + bool bOk = false; + roomNumber = QString::fromStdString(temp.substr(8)).toInt(&bOk); + if (!bOk) + roomNumber = -999; + + if (roomNumber >= 0) + roomToFloor[roomNumber + 2000] = floorNumber; + } + } + + if (HasTagName(roomnode, "SubId")) + { + for (xml_attribute<>* attr = roomnode->first_attribute(); attr; + attr = attr->next_attribute()) + { + if (strcmp(attr->name(), "ID") == 0) + name = attr->value(); + } + } + if (name.empty()) + continue; + readBBoxMin(roomnode, room); + readBBoxMax(roomnode, room); + } + + if (!room.mBB.valid()) + { + for (auto roomnode(swtchNode->first_node()); roomnode != nullptr; + roomnode = roomnode->next_sibling()) + { + if (HasTagName(roomnode, "Group")) + { + for (auto grp3node(roomnode->first_node()); grp3node != nullptr; + grp3node = grp3node->next_sibling()) + { + readBBoxMin(grp3node, room); + readBBoxMax(grp3node, room); + readPolygon(grp3node, room); + } + if (room.mBB.valid() && !room.mPoly.empty()) + { + + break; + } + } + } + } + + if (!room.mBB.valid()) + LOG_ERROR("Could not parse room bounding boxes for room" + << name << " in xml " << xmlpath); + + room.mBB._min[2] -= ROOM_OBB_Z_MIN_SUBTRACT; + room.mBB._max[2] -= ROOM_OBB_Z_MAX_SUBTRACT; + + if (!room.mBB.valid()) + { + + LOG_ERROR("Subtract from room OBB height fails, revert... room=" << name); + room.mBB._min[2] += ROOM_OBB_Z_MIN_SUBTRACT; + room.mBB._max[2] += ROOM_OBB_Z_MAX_SUBTRACT; + } + + if (!room.mBB.valid()) + LOG_ERROR("Could not parse room bounding boxes for room " + << name << " in xml " << xmlpath); + + const std::string key = b.mFeatureId + " " + name; + room.mBuilding = dtEntity::SID(b.mFeatureId); + mRooms[key] = room; + + dtEntity::GetDebugDrawInterface()->AddOBB(room.mMatrix, room.mBB._min, + room.mBB._max, osg::Vec4(1, 0, 1, 1), + 1, FLT_MAX, false); + osg::Vec3 pos = room.mBB.center() * room.mMatrix; + dtEntity::GetDebugDrawInterface()->AddString(pos, key, osg::Vec4(0, 1, 0, 1), + FLT_MAX, false); + } + } + } + } + } + } + } + } + + mRoomToFloorPerBldg[b.mFeatureId] = roomToFloor; } - } - catch (const std::exception &ex) - { - LOG_ERROR("XML Parsing error: " + std::string(ex.what())); - return false; - } - return true; + catch (const std::exception& ex) + { + LOG_ERROR("XML Parsing error: " + std::string(ex.what())); + return false; + } + + return true; } +bool BuildingManager::LoadBuildings(const std::string& path, std::vector& buildings) +{ + using namespace rapidxml; + const std::string absPath = dtEntity::GetSystemInterface()->FindDataFile(path); + if (absPath.empty()) + { + LOG_ERROR("Map not found: " + absPath); + return false; + } + + file<> file(absPath.c_str()); + + try + { + xml_document<> doc; + doc.parse<0>(file.data()); + + xml_node<>* rootnode = doc.first_node("MetaData"); + if (rootnode == nullptr) + { + LOG_ERROR("Could not parse map xml!"); + return false; + } + + for (xml_node<>* tagNode(rootnode->first_node()); tagNode != nullptr; tagNode = tagNode->next_sibling()) + { + if (HasTagName(tagNode, "Tag")) + { + int topmesh = -1; + for (xml_node<>* groupNode(tagNode->first_node()); groupNode != nullptr; + groupNode = groupNode->next_sibling()) + { + if (HasTagName(groupNode, "Group")) + { + ++topmesh; + for (xml_node<>* modelNode(groupNode->first_node()); modelNode != nullptr; + modelNode = modelNode->next_sibling()) + { + if (HasTagName(modelNode, "Model")) + { + BuildingData b; + + for (xml_node<>* dataNode(modelNode->first_node()); dataNode != nullptr; + dataNode = dataNode->next_sibling()) + { + if (HasTagName(dataNode, "Orientation")) + fetchAttr(b.mOrientation, dataNode, "Angle"); + else if (HasTagName(dataNode, "Position")) + { + fetchAttr(b.mX, dataNode, "X"); + fetchAttr(b.mY, dataNode, "Y"); + fetchAttr(b.mZ, dataNode, "Z"); + } + else if (HasTagName(dataNode, "Description")) + fetchAttr(b.mDescription, dataNode, "Name"); + else if (HasTagName(dataNode, "Feature")) + fetchAttr(b.mFeatureId, dataNode, "Id"); + else if (HasTagName(dataNode, "File")) + fetchAttr(b.mFileName, dataNode, "Name"); + else if (HasTagName(dataNode, "STREIF")) + fetchAttr(b.mBuildingXMLPath, dataNode, "Name"); + } + b.mBuildingGroup = topmesh; + LOG_INFO("add building " + b.mFeatureId + " - " + b.mFileName); + buildings.push_back(std::move(b)); + } + } + } + } + } + } + } + catch (const std::exception& ex) + { + LOG_ERROR("XML Parsing error: " + std::string(ex.what())); + return false; + } + return true; +} size_t BuildingManager::getNumBuildings() const { - return mBuildings.size(); + return mBuildings.size(); } - -void BuildingManager::getBuildingIds(std::vector &toFill) const +void BuildingManager::getBuildingIds(std::vector& toFill) const { - toFill.reserve(mBuildings.size()); - for (const Building *building : mBuildings) - toFill.push_back(building->mWorldBuildingId); + toFill.reserve(mBuildings.size()); + for (const Building* building : mBuildings) + toFill.push_back(building->mWorldBuildingId); } -dtEntity::EntityId BuildingManager::getNextBuilding(const osg::Vec3d &pos, float &distance, std::string &featureId) const +dtEntity::EntityId BuildingManager::getNextBuilding(const osg::Vec3d& pos, float& distance, + std::string& featureId) const { - const osg::Vec2d pos2d(pos[0], pos[1]); - float minDist = 1000000.0f; - dtEntity::EntityId eid = -1; - for (const Building *building : mBuildings) - { - const osg::Vec3d currentPos = osg::Vec3d(0, 0, 0) * building->mLocalToWorld; - const osg::Vec2d currentPos2d(currentPos[0], currentPos[1]); - float dist = (currentPos2d - pos2d).length(); - if (dist < minDist) + const osg::Vec2d pos2d(pos[0], pos[1]); + float minDist = 1000000.0f; + dtEntity::EntityId eid = -1; + for (const Building* building : mBuildings) { - minDist = dist; - eid = building->mWorldBuildingId; - featureId = building->mFeatureId; + const osg::Vec3d currentPos = osg::Vec3d(0, 0, 0) * building->mLocalToWorld; + const osg::Vec2d currentPos2d(currentPos[0], currentPos[1]); + float dist = (currentPos2d - pos2d).length(); + if (dist < minDist) + { + minDist = dist; + eid = building->mWorldBuildingId; + featureId = building->mFeatureId; + } } - } - distance = minDist; - return eid; + distance = minDist; + return eid; } -Building BuildingManager::getBuildingFromFeatureId(const std::string &bldname) const +Building BuildingManager::getBuildingFromFeatureId(const std::string& bldname) const { - Building bld; - bld.mWorldBuildingId = 0; - for (const Building *building : mBuildings) - { - if (building->mFeatureId == bldname) + Building bld; + bld.mWorldBuildingId = 0; + for (const Building* building : mBuildings) { - bld.mBuildingDisplayName = building->mBuildingDisplayName; - bld.mFeatureId = building->mFeatureId; - bld.mWorldBuildingId = building->mWorldBuildingId; + if (building->mFeatureId == bldname) + { + bld.mBuildingDisplayName = building->mBuildingDisplayName; + bld.mFeatureId = building->mFeatureId; + bld.mWorldBuildingId = building->mWorldBuildingId; + } } - } - return bld; - + return bld; } + void BuildingManager::updateNames(const Building& bd, BuildingDisplay& dspl) { - for (NameDisplay& ddspl : dspl.mNameDisplays) - { - TextComponent *name; - if (ddspl.mLocalPlayerId == 0) + for (NameDisplay& ddspl : dspl.mNameDisplays) { - dtEntity::Entity* e; - if (!mEntityManager->CreateEntity(e)) - continue; - ddspl.mLocalPlayerId = e->GetId(); - - dtEntity::MapComponent* mc; - if (!e->CreateComponent(mc)) - continue; - std::string en = "ctx_" + std::to_string(dspl.mContextId) + - "_nam_" + std::to_string(ddspl.mName->mWorldPlayerId); - mc->SetEntityName(en); - mc->SetUniqueId(en); - mc->SetMapName("nameproxies"); - - if (!e->CreateComponent(name)) - continue; - name->SetText(ddspl.mName->mtext); - name->SetDisText(ddspl.mName->mdistext); - - dtEntityOSG::LayerComponent* lc; - if (!e->CreateComponent(lc)) - continue; - std::string viewname = "Context_" + std::to_string(dspl.mContextId); - lc->SetAttachedComponent(TextComponent::TYPE); - lc->SetLayer(dtEntity::SID(viewname)); - - dtEntity::MapSystem* ms; - if (mEntityManager->GetES(ms)) - ms->AddToScene(e->GetId()); - } - else - { - if (!mEntityManager->GetComponent(ddspl.mLocalPlayerId, name)) - { - assert(false); - continue; - } - } - - int roomNumber = -1; - { - bool bOk = false; - roomNumber = QString::fromStdString(ddspl.mName->mtext).toInt(&bOk);; - if (!bOk) - roomNumber = -1; - } - - name->SetTranslation(remapPosition(bd, dspl, ddspl.mName->mPosition, roomNumber)); - name->SetVisible(dspl.mNameMode); - name->SetDisText(ddspl.mName->mdistext); - name->Finished(); - } -} - - -dtEntity::EntityId BuildingManager::getWorldNameIdFromLocalName(dtEntity::EntityId local, std::string &buildingName, std::string &room) const -{ - for (const Building *building : mBuildings) - { - for (const BuildingDisplay &bd : building->mDisplays) - { - for (const NameDisplay &nd : bd.mNameDisplays) - { - if (nd.mLocalPlayerId == local) + TextComponent* name; + if (ddspl.mLocalPlayerId == 0) { - buildingName = nd.mName->mbuilding; - room = nd.mName->mtext; - return nd.mWorldPlayerId; + dtEntity::Entity* e; + if (!mEntityManager->CreateEntity(e)) + continue; + ddspl.mLocalPlayerId = e->GetId(); + + dtEntity::MapComponent* mc; + if (!e->CreateComponent(mc)) + continue; + std::string en = + "ctx_" + std::to_string(dspl.mContextId) + "_nam_" + std::to_string(ddspl.mName->mWorldPlayerId); + mc->SetEntityName(en); + mc->SetUniqueId(en); + mc->SetMapName("nameproxies"); + + if (!e->CreateComponent(name)) + continue; + name->SetText(ddspl.mName->mtext); + name->SetDisText(ddspl.mName->mdistext); + + dtEntityOSG::LayerComponent* lc; + if (!e->CreateComponent(lc)) + continue; + std::string viewname = "Context_" + std::to_string(dspl.mContextId); + lc->SetAttachedComponent(TextComponent::TYPE); + lc->SetLayer(dtEntity::SID(viewname)); + + dtEntity::MapSystem* ms; + if (mEntityManager->GetES(ms)) + ms->AddToScene(e->GetId()); } - } + else + { + if (!mEntityManager->GetComponent(ddspl.mLocalPlayerId, name)) + { + assert(false); + continue; + } + } + + int roomNumber = -1; + { + bool bOk = false; + roomNumber = QString::fromStdString(ddspl.mName->mtext).toInt(&bOk); + ; + if (!bOk) + roomNumber = -1; + } + + name->SetTranslation(remapPosition(bd, dspl, ddspl.mName->mPosition, roomNumber)); + name->SetVisible(dspl.mNameMode); + name->SetDisText(ddspl.mName->mdistext); + name->Finished(); } - } - return 0; } +dtEntity::EntityId BuildingManager::getWorldNameIdFromLocalName(dtEntity::EntityId local, std::string& buildingName, + std::string& room) const +{ + for (const Building* building : mBuildings) + { + for (const BuildingDisplay& bd : building->mDisplays) + { + for (const NameDisplay& nd : bd.mNameDisplays) + { + if (nd.mLocalPlayerId == local) + { + buildingName = nd.mName->mbuilding; + room = nd.mName->mtext; + return nd.mWorldPlayerId; + } + } + } + } + return 0; +} void BuildingManager::changeLineMode(unsigned int contextId, bool line) { - mShotOverview = line; - bool bRequestRedraw = false; - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + mShotOverview = line; + bool bRequestRedraw = false; + for (Building* building : mBuildings) { - if (bd.mContextId == contextId) - { - if (bd.mLineMode != line) + for (BuildingDisplay& bd : building->mDisplays) { - bd.mLineMode = line; - bRequestRedraw = true; + if (bd.mContextId == contextId) + { + if (bd.mLineMode != line) + { + bd.mLineMode = line; + bRequestRedraw = true; + } + } } - } } - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(contextId); + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(contextId); } - void BuildingManager::changeNameMode(unsigned int contextId, bool name) { - bool bRequestRedraw = false; - for (Building *building : mBuildings) - { - for (BuildingDisplay &bd : building->mDisplays) + bool bRequestRedraw = false; + for (Building* building : mBuildings) { - if (bd.mContextId == contextId) - { - if (bd.mNameMode != name) + for (BuildingDisplay& bd : building->mDisplays) { - bd.mNameMode = name; - setShowHideDisplayNames(building->mWorldBuildingId, contextId, name); - bRequestRedraw = true; + if (bd.mContextId == contextId) + { + if (bd.mNameMode != name) + { + bd.mNameMode = name; + setShowHideDisplayNames(building->mWorldBuildingId, contextId, name); + bRequestRedraw = true; + } + } } - } } - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(contextId); + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(contextId); } -void BuildingManager::setBuildingDisplayName(const std::string& featureId, dtEntity::EntityId eid, const std::string& strDisplayName) +void BuildingManager::setBuildingDisplayName(const std::string& featureId, dtEntity::EntityId eid, + const std::string& strDisplayName) { - m_mapBuildingDisplayNames[featureId] = strDisplayName; + m_mapBuildingDisplayNames[featureId] = strDisplayName; - - if(eid > 0) - { - setBuildingDisplayName(eid, strDisplayName); - } + if (eid > 0) + { + setBuildingDisplayName(eid, strDisplayName); + } } - - void BuildingManager::setBuildingDisplayName(dtEntity::EntityId eid, const std::string& strDisplayName) { - - for (Building *building : mBuildings) - { - if (building->mWorldBuildingId != eid) - continue; - building->mBuildingDisplayName = strDisplayName; - break; - } -} - - -void BuildingManager::setRoomDisplayName(const std::string& featureId, dtEntity::EntityId eid, const std::string& roomname, const std::string& strDisplayName) -{ - m_mapBuildingRoomNames[featureId][roomname] = strDisplayName; - - - if (eid > 0) - { - for (Building *building : mBuildings) + for (Building* building : mBuildings) { - if (building->mWorldBuildingId != eid) - continue; - setRoomDisplayName(building, roomname, strDisplayName); - return; + if (building->mWorldBuildingId != eid) + continue; + building->mBuildingDisplayName = strDisplayName; + break; } - } } - - -void BuildingManager::setRoomDisplayName(Building *building, const std::string& roomname, const std::string& strDisplayName) +void BuildingManager::setRoomDisplayName(const std::string& featureId, dtEntity::EntityId eid, + const std::string& roomname, const std::string& strDisplayName) { - for (BuildingDisplay &bd : building->mDisplays) - { - for (NameDisplay &nd : bd.mNameDisplays) + m_mapBuildingRoomNames[featureId][roomname] = strDisplayName; + + if (eid > 0) { - if (nd.mName->mtext == roomname) - { - nd.mName->mdistext = strDisplayName; - TextComponent* tc; - if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) + for (Building* building : mBuildings) { - tc->SetDisText(strDisplayName); - tc->Finished(); + if (building->mWorldBuildingId != eid) + continue; + setRoomDisplayName(building, roomname, strDisplayName); + return; } - - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); - return; - } } - } } +void BuildingManager::setRoomDisplayName(Building* building, const std::string& roomname, + const std::string& strDisplayName) +{ + for (BuildingDisplay& bd : building->mDisplays) + { + for (NameDisplay& nd : bd.mNameDisplays) + { + if (nd.mName->mtext == roomname) + { + nd.mName->mdistext = strDisplayName; + TextComponent* tc; + if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) + { + tc->SetDisText(strDisplayName); + tc->Finished(); + } + + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + return; + } + } + } +} void BuildingManager::setShowHideDisplayNames(dtEntity::EntityId eid, unsigned int contextId, bool show) { - for (Building *building : mBuildings) - { - if (building->mWorldBuildingId != eid) - continue; - for (BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - bool bRequestRedraw = false; - if ( (bd.mContextId == contextId) || (contextId == 9999) ) - { - for (NameDisplay &nd : bd.mNameDisplays) + if (building->mWorldBuildingId != eid) + continue; + for (BuildingDisplay& bd : building->mDisplays) { - nd.visible = show; - TextComponent* tc; - if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) - { - tc->SetVisible(show); - bRequestRedraw = true; - } + bool bRequestRedraw = false; + if ((bd.mContextId == contextId) || (contextId == 9999)) + { + for (NameDisplay& nd : bd.mNameDisplays) + { + nd.visible = show; + TextComponent* tc; + if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) + { + tc->SetVisible(show); + bRequestRedraw = true; + } + } + } + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); } - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); + break; } - break; - } } - void BuildingManager::setShowDisplayNamesSelection(dtEntity::EntityId eid, bool show) { - for (Building *building : mBuildings) - { - for (const BuildingDisplay &bd : building->mDisplays) + for (Building* building : mBuildings) { - bool bRequestRedraw = false; - for (const NameDisplay &nd : bd.mNameDisplays) - { - if (nd.mWorldPlayerId == eid) + for (const BuildingDisplay& bd : building->mDisplays) { - TextComponent* tc; - if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) - { - tc->SetShowSelection(show); - bRequestRedraw = true; - } + bool bRequestRedraw = false; + for (const NameDisplay& nd : bd.mNameDisplays) + { + if (nd.mWorldPlayerId == eid) + { + TextComponent* tc; + if (mEntityManager->GetComponent(nd.mLocalPlayerId, tc)) + { + tc->SetShowSelection(show); + bRequestRedraw = true; + } + } + } + if (bRequestRedraw) + dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); } - } - if (bRequestRedraw) - dtEntity::GetWindowInterface()->RequestRedraw(bd.mContextId); } - } } - - void BuildingManager::createRoomNames(dtEntity::EntityId buildingid, Building& building) { - RoomDestructionComponent* btc; - if (mEntityManager->GetComponent(buildingid, btc)) - { - const RoomDestructionComponent::RoomDestructions& rc = btc->GetRoomDestructions(); - for (const auto &i : rc) + RoomDestructionComponent* btc; + if (mEntityManager->GetComponent(buildingid, btc)) { - const std::string &roomName = i.first; - VCtrl::OBB roomObb; - getRoomBounds(building.mNavMeshGrpName, roomName, roomObb); - - osg::Vec3 posX = roomObb.mBB.center(); - - - - - if (!roomObb.mPoly.isEmpty() && !roomObb.mPoly.containsPoint(QPointF(posX.x(), posX.y()), Qt::OddEvenFill)) - { - - const QPointF qpfCenter(posX.x(), posX.y()); - QPointF nearestVertex; - qreal distance = 999999999; - for (const QPointF &vertex : std::as_const(roomObb.mPoly)) + const RoomDestructionComponent::RoomDestructions& rc = btc->GetRoomDestructions(); + for (const auto& i : rc) { - - qreal dis = (vertex-qpfCenter).manhattanLength(); - if (disCreateEntity(e)) + continue; + + dtEntity::MapComponent* mc; + if (!e->CreateComponent(mc)) + { + mEntityManager->KillEntity(e->GetId()); + continue; + } + const std::string en = "bd_" + building.mNavMeshGrpName + "_rm_" + roomName; + mc->SetEntityName(en); + mc->SetUniqueId(en); + mc->SetMapName("roomlabel"); + + dtEntity::EntityId nameMainId = e->GetId(); + Name* name = new Name(); + name->mWorldPlayerId = nameMainId; + name->mtext = roomName; + name->mdistext = ""; + name->mPosition = pos; + + name->mbuilding = building.mNavMeshGrpName; + building.mNames.push_back(name); } - if (nearestVertex.isNull()) - { - - posX.x() = roomObb.mPoly.at(0).x(); - posX.y() = roomObb.mPoly.at(0).y(); - } else { - posX.x() = nearestVertex.x(); - posX.y() = nearestVertex.y(); - } - } - const osg::Vec3 pos = posX * roomObb.mMatrix; - - - - - - dtEntity::Entity* e; - if (!mEntityManager->CreateEntity(e)) - continue; - - - dtEntity::MapComponent* mc; - if (!e->CreateComponent(mc)) - { - mEntityManager->KillEntity(e->GetId()); - continue; - } - const std::string en = "bd_" + building.mNavMeshGrpName + "_rm_" + roomName; - mc->SetEntityName(en); - mc->SetUniqueId(en); - mc->SetMapName("roomlabel"); - - dtEntity::EntityId nameMainId = e->GetId(); - Name* name = new Name(); - name->mWorldPlayerId = nameMainId; - name->mtext = roomName; - name->mdistext = ""; - name->mPosition = pos; - - name->mbuilding = building.mNavMeshGrpName; - building.mNames.push_back(name); } - } } -} +} // namespace VCtrl diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.h old mode 100755 new mode 100644 index 66ea51a4a..32e95a528 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/buildingmanager.h @@ -1,25 +1,24 @@ #pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "cameraviewposition.h" +#include "logger.h" +#include "viewerinterface.h" #include #include #include - -#include -#include +#include +#include #include -#include "viewerinterface.h" -#include "cameraviewposition.h" -#include "logger.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace dtEntity { @@ -32,451 +31,430 @@ class IconComponent; class TextComponent; class ViewWidget; - struct OBB { - osg::Matrix mMatrix; - osg::Matrix mMatrixInverse; - osg::BoundingBox mBB; - QPolygonF mPoly; - dtEntity::StringId mBuilding = 0; + osg::Matrix mMatrix; + osg::Matrix mMatrixInverse; + osg::BoundingBox mBB; + QPolygonF mPoly; + dtEntity::StringId mBuilding = 0; }; - struct BuildingData { - std::string mDescription; - std::string mDisplayName; - std::string mFeatureId; - std::string mFileName; - std::string mBuildingXMLPath; - double mX = 0; - double mY = 0; - double mZ = 0; - double mOrientation = 0; - int mBuildingGroup = 0; - bool properlySpawned = false; - bool roomBBoxedLoaded = false; + std::string mDescription; + std::string mDisplayName; + std::string mFeatureId; + std::string mFileName; + std::string mBuildingXMLPath; + double mX = 0; + double mY = 0; + double mZ = 0; + double mOrientation = 0; + int mBuildingGroup = 0; + bool properlySpawned = false; + bool roomBBoxedLoaded = false; }; - struct BuildingLevel { - - dtEntity::EntityId mEntityId; - - int mFloorId; + dtEntity::EntityId mEntityId; - - float mHeightAboveGround; + int mFloorId; - - osg::Matrix mLocalToLevel; + float mHeightAboveGround; - - osg::BoundingBox mBounds; + osg::Matrix mLocalToLevel; - BuildingLevel(dtEntity::EntityId eid, int floorId, float h, const osg::BoundingBox &bb) - : mEntityId(eid), mFloorId(floorId), mHeightAboveGround(h), mBounds(bb) - { - } + osg::BoundingBox mBounds; + + BuildingLevel(dtEntity::EntityId eid, int floorId, float h, const osg::BoundingBox& bb) + : mEntityId(eid), mFloorId(floorId), mHeightAboveGround(h), mBounds(bb) + { + } }; - struct PlayerPosition { - osg::Vec2d mPosition; - dtEntity::EntityId mWorldPlayerId = 0; + osg::Vec2d mPosition; + dtEntity::EntityId mWorldPlayerId = 0; }; - struct PlayerDisplay { - dtEntity::EntityId mWorldPlayerId = 0; - dtEntity::EntityId mLocalPlayerId = 0; - IconComponent *mIcon = nullptr; + dtEntity::EntityId mWorldPlayerId = 0; + dtEntity::EntityId mLocalPlayerId = 0; + IconComponent* mIcon = nullptr; }; - struct Device { - dtEntity::EntityId mWorldPlayerId = 0; - std::string mPath; - osg::Vec3d mPosition; + dtEntity::EntityId mWorldPlayerId = 0; + std::string mPath; + osg::Vec3d mPosition; }; - struct DeviceDisplay { - Device *mDevice = nullptr; - dtEntity::EntityId mWorldPlayerId = 0; - dtEntity::EntityId mLocalPlayerId = 0; + Device* mDevice = nullptr; + dtEntity::EntityId mWorldPlayerId = 0; + dtEntity::EntityId mLocalPlayerId = 0; }; - struct Name { - dtEntity::EntityId mWorldPlayerId; - std::string mtext; - std::string mdistext; - std::string mbuilding; - osg::Vec3d mPosition; + dtEntity::EntityId mWorldPlayerId; + std::string mtext; + std::string mdistext; + std::string mbuilding; + osg::Vec3d mPosition; }; - struct NameDisplay { - Name* mName = nullptr; - dtEntity::EntityId mWorldPlayerId = 0; - dtEntity::EntityId mLocalPlayerId = 0; - bool visible = false; + Name* mName = nullptr; + dtEntity::EntityId mWorldPlayerId = 0; + dtEntity::EntityId mLocalPlayerId = 0; + bool visible = false; }; - - class Shot { -public: - Shot(const int32_t id, - const osg::Vec3d& shooterPos, - const osg::Vec3d& targetPos, - int buildingIdSrc, - int rommNumberSrc, - int buildingIdDst, - int rommNumberDst, - int lineType, - const osg::Vec4& color, - unsigned int duration_s, - unsigned int durationMax_s, - double simTimeCreated) : - mId(id) - , mShooterPos(shooterPos) - , mTargetPos(targetPos) - , mBuildingIdSrc(buildingIdSrc) - , mRoomNumberSrc(rommNumberSrc) - , mBuildingIdDst(buildingIdDst) - , mRoomNumberDst(rommNumberDst) - , mLineType(lineType) - , mColor(color) - , mDuration_s(duration_s) - , m_DurationMax_s(durationMax_s) - , mSimTimeCreated(simTimeCreated) { + public: + Shot(const int32_t id, const osg::Vec3d& shooterPos, const osg::Vec3d& targetPos, int buildingIdSrc, + int rommNumberSrc, int buildingIdDst, int rommNumberDst, int lineType, const osg::Vec4& color, + unsigned int duration_s, unsigned int durationMax_s, double simTimeCreated) + : mId(id), mShooterPos(shooterPos), mTargetPos(targetPos), mBuildingIdSrc(buildingIdSrc), + mRoomNumberSrc(rommNumberSrc), mBuildingIdDst(buildingIdDst), mRoomNumberDst(rommNumberDst), + mLineType(lineType), mColor(color), mDuration_s(duration_s), m_DurationMax_s(durationMax_s), + mSimTimeCreated(simTimeCreated) + { + } - } + void setDisplayTime(unsigned int duration_s) + { + if (duration_s > m_DurationMax_s) + m_DurationMax_s = duration_s; + mDuration_s = duration_s; + } - void setDisplayTime(unsigned int duration_s) { - if(duration_s > m_DurationMax_s) - m_DurationMax_s = duration_s; - mDuration_s = duration_s; - } - double simTimeCreated() const { - return mSimTimeCreated; - } + double simTimeCreated() const + { + return mSimTimeCreated; + } - double displayTime() const { - return mSimTimeCreated + mDuration_s; - } + double displayTime() const + { + return mSimTimeCreated + mDuration_s; + } - double lifeTime() const { - return mSimTimeCreated + (m_DurationMax_s*2); - } + double lifeTime() const + { + return mSimTimeCreated + (m_DurationMax_s * 2); + } - const osg::Vec3d& getShooterPos() const { return mShooterPos; } - const osg::Vec3d& getTargetPos() const { return mTargetPos; } - int getBuildingIdSrc() const { return mBuildingIdSrc; } - double getSimeTimeCreated() const { return mSimTimeCreated; } - int getRoomNumberSrc() const { return mRoomNumberSrc; } - int getBuildingIdDst() const { return mBuildingIdDst; } - int getRoomNumberDst() const { return mRoomNumberDst; } - int getDuration() const { return mDuration_s; } - int getLineType() const { return mLineType; } + const osg::Vec3d& getShooterPos() const + { + return mShooterPos; + } - const osg::Vec4& getColor() const { return mColor; } - int32_t getId() const { return mId; } + const osg::Vec3d& getTargetPos() const + { + return mTargetPos; + } -private: - NGL::INGLLogger &m_logger; - int32_t mId; - osg::Vec3d mShooterPos; - osg::Vec3d mTargetPos; - int mBuildingIdSrc; - int mRoomNumberSrc; - int mBuildingIdDst; - int mRoomNumberDst; - int mLineType; - osg::Vec4 mColor; - unsigned int mDuration_s, m_DurationMax_s; - double mSimTimeCreated; + int getBuildingIdSrc() const + { + return mBuildingIdSrc; + } + + double getSimeTimeCreated() const + { + return mSimTimeCreated; + } + + int getRoomNumberSrc() const + { + return mRoomNumberSrc; + } + + int getBuildingIdDst() const + { + return mBuildingIdDst; + } + + int getRoomNumberDst() const + { + return mRoomNumberDst; + } + + int getDuration() const + { + return mDuration_s; + } + + int getLineType() const + { + return mLineType; + } + + const osg::Vec4& getColor() const + { + return mColor; + } + + int32_t getId() const + { + return mId; + } + + private: + NGL::INGLLogger& m_logger; + int32_t mId; + osg::Vec3d mShooterPos; + osg::Vec3d mTargetPos; + int mBuildingIdSrc; + int mRoomNumberSrc; + int mBuildingIdDst; + int mRoomNumberDst; + int mLineType; + osg::Vec4 mColor; + unsigned int mDuration_s, m_DurationMax_s; + double mSimTimeCreated; }; - struct ShotDisplay { - Shot *mShot = nullptr; - osg::ref_ptr mGeode; + Shot* mShot = nullptr; + osg::ref_ptr mGeode; }; - struct Building; - - - class OrthoMotionModelComponent; struct BuildingDisplay -{ - - unsigned int mContextId = 0; +{ - - dtEntity::EntityId mAttachPointId = 0; + unsigned int mContextId = 0; - - std::vector mLevels; + dtEntity::EntityId mAttachPointId = 0; - - osg::BoundingBox mWorldBounds; + std::vector mLevels; - - osg::BoundingBox mLocalBounds; + osg::BoundingBox mWorldBounds; - - dtEntity::EntityId mCameraId = 0; + osg::BoundingBox mLocalBounds; - - dtEntity::EntityId mMotionModelId = 0; - OrthoMotionModelComponent *pMotion = nullptr; + dtEntity::EntityId mCameraId = 0; - - dtEntity::EntityId mLightId = 0; + dtEntity::EntityId mMotionModelId = 0; + OrthoMotionModelComponent* pMotion = nullptr; - - PlayerDisplayMode mPlayerDisplayMode = PlayerDisplayMode::Icons; + dtEntity::EntityId mLightId = 0; - - ViewMode mViewMode = ViewMode::ISOMETRIC; + PlayerDisplayMode mPlayerDisplayMode = PlayerDisplayMode::Icons; - - std::vector mPlayers; + ViewMode mViewMode = ViewMode::ISOMETRIC; - - std::vector mShotDisplays; + std::vector mPlayers; - - std::vector mDeviceDisplays; + std::vector mShotDisplays; - - std::vector mNameDisplays; + std::vector mDeviceDisplays; - - bool mLockRotation = false; + std::vector mNameDisplays; - - bool mNameMode = false; + bool mLockRotation = false; - - bool mLineMode = false; + bool mNameMode = false; - BuildingDisplay() = default; + bool mLineMode = false; - BuildingDisplay(unsigned int contextid, ViewMode vm) - : mContextId(contextid) - , mViewMode(vm) - { - } + BuildingDisplay() = default; + + BuildingDisplay(unsigned int contextid, ViewMode vm) : mContextId(contextid), mViewMode(vm) {} }; - struct Building { - - dtEntity::EntityId mWorldBuildingId = 0; - - std::vector mDisplays; + dtEntity::EntityId mWorldBuildingId = 0; - - osg::Matrix mWorldToLocal; + std::vector mDisplays; - - osg::Matrix mLocalToWorld; + osg::Matrix mWorldToLocal; - - std::string mNavMeshGrpName; + osg::Matrix mLocalToWorld; - - std::vector mShots; + std::string mNavMeshGrpName; - - std::vector mDevices; + std::vector mShots; - - std::string mBuildingDisplayName; + std::vector mDevices; - - std::vector mNames; + std::string mBuildingDisplayName; - - std::string mFeatureId; + std::vector mNames; + + std::string mFeatureId; }; - class BuildingManager { -public: + public: + explicit BuildingManager(dtEntity::EntityManager& em); + ~BuildingManager(); - explicit BuildingManager(dtEntity::EntityManager &em); - ~BuildingManager(); + void addBuilding(dtEntity::EntityId buildingid, const std::string& featureId); + void deleteAllBuildings(); - void addBuilding(dtEntity::EntityId buildingid, const std::string &featureId); - void deleteAllBuildings(); + BuildingDisplay* getBuildingDisplay(unsigned int contextid); + void applyViewModeToBuildingParts(const Building& bldg, BuildingDisplay& dspl) const; - BuildingDisplay *getBuildingDisplay(unsigned int contextid); - void applyViewModeToBuildingParts(const Building &bldg, BuildingDisplay &dspl) const; + bool displayBuilding(const std::string& featureId, unsigned int contextid, dtEntity::EntityId buildingid, + const osg::Vec4& bgcolor, ViewMode viewmode, bool exactPos); + bool displayBuilding(unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4& bgcolor, + ViewMode viewmode, bool exactPos); - bool displayBuilding(const std::string& featureId, unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4 &bgcolor, ViewMode viewmode, bool exactPos); - bool displayBuilding(unsigned int contextid, dtEntity::EntityId buildingid, const osg::Vec4 &bgcolor, ViewMode viewmode, bool exactPos); + bool setCameraPosition(unsigned int contextid, const BuildingViewer::CameraViewPosition& pos); + bool getCameraPosition(unsigned int contextid, BuildingViewer::CameraViewPosition& pos); + bool setDefaultCameraPosition(unsigned int contextid); - bool setCameraPosition(unsigned int contextid, const BuildingViewer::CameraViewPosition& pos); - bool getCameraPosition(unsigned int contextid, BuildingViewer::CameraViewPosition& pos); - bool setDefaultCameraPosition(unsigned int contextid); + void closeBuildingDisplay(unsigned int contextid); + void changeViewMode(unsigned int contextId, ViewMode viewmode, bool useOriginViewPos = true); + void changeLineMode(unsigned int contextId, bool line); + void changeNameMode(unsigned int contextId, bool name); - void closeBuildingDisplay(unsigned int contextid); - void changeViewMode(unsigned int contextId, ViewMode viewmode, bool useOriginViewPos = true); - void changeLineMode(unsigned int contextId, bool line); - void changeNameMode(unsigned int contextId, bool name); + void applyMapRotation(const Building& bd, BuildingDisplay& dspl); + void lockViewRotationToMapRotation(unsigned int contextId, bool lock); + void setPlayerDisplayMode(unsigned int contextId, PlayerDisplayMode mode); + void setWallTransparency(unsigned int contextId, float value); - void applyMapRotation(const Building &bd, BuildingDisplay &dspl); - void lockViewRotationToMapRotation(unsigned int contextId, bool lock); - void setPlayerDisplayMode(unsigned int contextId, PlayerDisplayMode mode); - void setWallTransparency(unsigned int contextId, float value); + float getMapRotation() const; + void setMapRotation(float angle); - float getMapRotation() const; - void setMapRotation(float angle); + void openOverview(unsigned int contextid); - void openOverview(unsigned int contextid); + void addPlayerToBuildings(const std::string& navmeshgrpname, dtEntity::EntityId eid, const osg::Vec4& color, + const std::string& symbol, const osg::Vec3d& pos, bool visible); + void removePlayerFromBuilding(const std::string& navmeshgrpname, dtEntity::EntityId eid, + const std::string& roomname); + void updatePlayerPosition(const std::string& navmeshgrpname, dtEntity::EntityId eid, const osg::Vec3d& pos, + int roomNumber); - void addPlayerToBuildings(const std::string &navmeshgrpname, dtEntity::EntityId eid, - const osg::Vec4 &color, const std::string &symbol, - const osg::Vec3d &pos, bool visible); - void removePlayerFromBuilding(const std::string &navmeshgrpname, dtEntity::EntityId eid, const std::string &roomname); - void updatePlayerPosition(const std::string &navmeshgrpname, dtEntity::EntityId eid, - const osg::Vec3d &pos, int roomNumber); + osg::Vec3d remapPosition(const Building& bd, const BuildingDisplay& dspl, const osg::Vec3d& world, + int roomNumber = -1); - osg::Vec3d remapPosition(const Building &bd, const BuildingDisplay &dspl, const osg::Vec3d &world, int roomNumber = -1); + void setPlayerColor(dtEntity::EntityId eid, const osg::Vec4& color); + void setPlayerIcon(dtEntity::EntityId eid, const std::string& path); + void reloadPlayerIcons(); + void updatePlayerPartyColor(dtEntity::EntityId eid, const VCtrl::Color& col); + void setShowPlayerSelection(dtEntity::EntityId eid, bool show); + void setShowDisplayNamesSelection(dtEntity::EntityId eid, bool show); + void setShowHidePlayer(dtEntity::EntityId eid, bool show); + void setShowHideDisplayNames(dtEntity::EntityId eid, unsigned int contextId, bool show); + void setRoomDestructionValue(dtEntity::EntityId eid, const std::string& roomname, float value); + void setBuildingDestructionValue(dtEntity::EntityId eid, float value); + void setBuildingDisplayName(const std::string& featureId, dtEntity::EntityId eid, + const std::string& strDisplayName); + void setBuildingDisplayName(dtEntity::EntityId eid, const std::string& strDisplayName); + void setRoomDisplayName(const std::string& featureId, dtEntity::EntityId eid, const std::string& roomname, + const std::string& strDisplayName); + void setRoomDisplayName(Building* building, const std::string& roomname, const std::string& strDisplayName); - void setPlayerColor(dtEntity::EntityId eid, const osg::Vec4 &color); - void setPlayerIcon(dtEntity::EntityId eid, const std::string &path); - void reloadPlayerIcons(); - void updatePlayerPartyColor(dtEntity::EntityId eid, const VCtrl::Color& col); - void setShowPlayerSelection(dtEntity::EntityId eid, bool show); - void setShowDisplayNamesSelection(dtEntity::EntityId eid, bool show); - void setShowHidePlayer(dtEntity::EntityId eid, bool show); - void setShowHideDisplayNames(dtEntity::EntityId eid, unsigned int contextId, bool show); - void setRoomDestructionValue(dtEntity::EntityId eid, const std::string &roomname, float value); - void setBuildingDestructionValue(dtEntity::EntityId eid, float value); - void setBuildingDisplayName(const std::string& featureId, dtEntity::EntityId eid, const std::string& strDisplayName); - void setBuildingDisplayName(dtEntity::EntityId eid, const std::string& strDisplayName); - void setRoomDisplayName(const std::string& featureId, dtEntity::EntityId eid, const std::string& roomname, const std::string& strDisplayName); - void setRoomDisplayName(Building *building, const std::string &roomname, const std::string& strDisplayName); + void removeShoot(int32_t id); + void showShoot(int32_t id, dtEntity::EntityId shooter, dtEntity::EntityId target, const dtEntity::Vec3d& shooterPos, + const dtEntity::Vec3d& targetPos, int buildingIdSrc, int roomNumberSrc, int buildingIdDst, + int roomNumberDst, int lineType, float duration, double simTimeCreated); - void removeShoot(int32_t id); - void showShoot(int32_t id, dtEntity::EntityId shooter, dtEntity::EntityId target, - const dtEntity::Vec3d &shooterPos, const dtEntity::Vec3d &targetPos, int buildingIdSrc, int roomNumberSrc, - int buildingIdDst, int roomNumberDst, int lineType, float duration, double simTimeCreated); + dtEntity::EntityId getWorldPlayerIdFromLocalPlayer(dtEntity::EntityId local) const; + dtEntity::EntityId getWorldNameIdFromLocalName(dtEntity::EntityId local, std::string& buildingName, + std::string& room) const; - dtEntity::EntityId getWorldPlayerIdFromLocalPlayer(dtEntity::EntityId local) const; - dtEntity::EntityId getWorldNameIdFromLocalName(dtEntity::EntityId local, std::string &buildingName, std::string &room) const; + void addDeviceToBuilding(dtEntity::EntityId iconmainid, dtEntity::EntityId buildingid, const osg::Vec3d& pos, + const std::string& iconpath); + void removeDeviceFromBuilding(dtEntity::EntityId iconmainid); - void addDeviceToBuilding(dtEntity::EntityId iconmainid, dtEntity::EntityId buildingid, - const osg::Vec3d &pos, const std::string &iconpath); - void removeDeviceFromBuilding(dtEntity::EntityId iconmainid); + bool AddRoomOBBs(const BuildingData&); + const std::map& GetRoomOBBs() const + { + return mRooms; + } - - bool AddRoomOBBs(const BuildingData &); - const std::map &GetRoomOBBs() const { return mRooms; } + bool getRoomBounds(const std::string& bldgname, const std::string& roomname, VCtrl::OBB& obb) const; - - bool getRoomBounds(const std::string &bldgname, const std::string &roomname, VCtrl::OBB &obb) const; + bool LoadBuildings(const std::string& path, std::vector&); + size_t getNumBuildings() const; + void getBuildingIds(std::vector& toFill) const; + dtEntity::EntityId getNextBuilding(const osg::Vec3d& pos, float& distance, std::string& featureId) const; + Building getBuildingFromFeatureId(const std::string& bldname) const; - bool LoadBuildings(const std::string &path, std::vector &); + using RoomPlayers = std::vector; - size_t getNumBuildings() const; - void getBuildingIds(std::vector &toFill) const; - dtEntity::EntityId getNextBuilding(const osg::Vec3d &pos, float &distance, std::string &featureId) const; - Building getBuildingFromFeatureId(const std::string &bldname) const; + osg::Vec2d AddRoomUsages(const std::string& bldgname, const std::string& roomname, VCtrl::PlayerPosition& playPos); - - using RoomPlayers = std::vector; - - osg::Vec2d AddRoomUsages(const std::string& bldgname, const std::string& roomname, VCtrl::PlayerPosition& playPos); - const std::map &GetRoomUsages() const { return mUsedRooms; } - - void deleteRoomUsagePlayer(const std::string& bldgname, const std::string& roomname, dtEntity::EntityId playerId); - void SetExactPos(bool exactPos) { mExactPos = exactPos; } - bool GetExactPos() const { return mExactPos; } - void updateShotDuration(unsigned int newDuration_s); - using CallbackCamPosChanged = std::function; - void setCallbackCamPosChanged(const CallbackCamPosChanged &cb); + const std::map& GetRoomUsages() const + { + return mUsedRooms; + } -private: - NGL::INGLLogger &m_logger; - void updateShots(const Building &bd, BuildingDisplay &dspl); - void updateDevices(const Building &bd, BuildingDisplay &dspl); - void createRoomNames(dtEntity::EntityId buildingid, Building& building); - void updateNames(const Building& bd, BuildingDisplay& dspl); - void repositionCamera(const Building &bd, const BuildingDisplay &dspl, bool useOriginViewPos = true); - void updatePlayerPositions(const Building &bd, BuildingDisplay &dspl); - void addPlayerToBuilding(const Building &bd, BuildingDisplay &dspl, dtEntity::EntityId eid, - const osg::Vec4 &color, const std::string &symbol, const osg::Vec3d &pos, - bool visible); - static osg::Vec2d shiftPosition(const VCtrl::OBB& obb, const osg::Vec2d& pos, double& shiftValue); - void cameraViewPositionChanged(unsigned int contextId, const BuildingViewer::CameraViewPosition &viewPos); + void deleteRoomUsagePlayer(const std::string& bldgname, const std::string& roomname, dtEntity::EntityId playerId); - std::set m_setInitialCameraPositionSet; + void SetExactPos(bool exactPos) + { + mExactPos = exactPos; + } - std::map> m_mapBuildingRoomNames; - std::map m_mapBuildingDisplayNames; - dtEntity::EntityManager *mEntityManager; + bool GetExactPos() const + { + return mExactPos; + } - std::vector mBuildings; - QMutex m_mutexShots; + void updateShotDuration(unsigned int newDuration_s); + using CallbackCamPosChanged = std::function; + void setCallbackCamPosChanged(const CallbackCamPosChanged& cb); - bool mShotOverview; - bool mExactPos; - float mMapRotation; - dtEntity::MessageFunctor mTickFunctor; + private: + NGL::INGLLogger& m_logger; + void updateShots(const Building& bd, BuildingDisplay& dspl); + void updateDevices(const Building& bd, BuildingDisplay& dspl); + void createRoomNames(dtEntity::EntityId buildingid, Building& building); + void updateNames(const Building& bd, BuildingDisplay& dspl); + void repositionCamera(const Building& bd, const BuildingDisplay& dspl, bool useOriginViewPos = true); + void updatePlayerPositions(const Building& bd, BuildingDisplay& dspl); + void addPlayerToBuilding(const Building& bd, BuildingDisplay& dspl, dtEntity::EntityId eid, const osg::Vec4& color, + const std::string& symbol, const osg::Vec3d& pos, bool visible); + static osg::Vec2d shiftPosition(const VCtrl::OBB& obb, const osg::Vec2d& pos, double& shiftValue); + void cameraViewPositionChanged(unsigned int contextId, const BuildingViewer::CameraViewPosition& viewPos); - void Tick(const dtEntity::Message &message); + std::set m_setInitialCameraPositionSet; - std::map mRooms; - std::map mUsedRooms; - CallbackCamPosChanged mCbCamPosChanged; + std::map> m_mapBuildingRoomNames; + std::map m_mapBuildingDisplayNames; + dtEntity::EntityManager* mEntityManager; - - - - - - - - - - - - - - - - bool getFloorOfRoom(const std::string &bdlgFeatureId, int roomNumber, int &floorOut) const; - - - std::map > mRoomToFloorPerBldg; + std::vector mBuildings; + QMutex m_mutexShots; + + bool mShotOverview; + bool mExactPos; + float mMapRotation; + dtEntity::MessageFunctor mTickFunctor; + + void Tick(const dtEntity::Message& message); + + std::map mRooms; + std::map mUsedRooms; + CallbackCamPosChanged mCbCamPosChanged; + + bool getFloorOfRoom(const std::string& bdlgFeatureId, int roomNumber, int& floorOut) const; + + std::map> mRoomToFloorPerBldg; }; -} +} // namespace VCtrl diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/viewerinterfaceimpl.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/viewerinterfaceimpl.h old mode 100755 new mode 100644 index 54d413045..36adc8094 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/viewerinterfaceimpl.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/BgViewer/viewerCtrl/viewerinterfaceimpl.h @@ -1,41 +1,39 @@ #pragma once +#include "buildingmanager.h" +#include "exccommands.h" +#include "logger.h" #include "viewerinterface.h" #include "viewwidgetcontainer.h" -#include -#include -#include -#include +#include "viewwidgetstate.h" #include #include - -#include -#include +#include #include +#include +#include #include #include #include #include -#include #include +#include #include +#include +#include #include #include #include -#include #include -#include "buildingmanager.h" -#include "exccommands.h" -#include "viewwidgetstate.h" -#include "logger.h" +#include namespace dtEntity { class EntityManager; class MapSystem; class Message; -} +} // namespace dtEntity namespace VCtrl { @@ -48,354 +46,247 @@ class CtrlMainWindow; class CtrlImpl : public QObject, public ViewerInterface { - Q_OBJECT -public: + Q_OBJECT + public: + CtrlImpl(dtEntity::EntityManager& em, QWidget* parentWidget); + ~CtrlImpl(); - CtrlImpl(dtEntity::EntityManager &em, QWidget *parentWidget); - ~CtrlImpl(); + void SetViewerCallback(ViewerCallback*) override; + void RemoveViewerCallback() override; - void SetViewerCallback(ViewerCallback *) override; - void RemoveViewerCallback() override; + void SetProjectDataPaths(const std::vector& paths) override; - + QWidget* getMainWindow() override; + quintptr requestMainWindowHandle() override; - void SetProjectDataPaths(const std::vector &paths) override; + void openViews(const std::vector& bldIds, bool exactPos) override; + bool isViewOpen(const std::string& strBldId) const override; - QWidget* getMainWindow() override; - quintptr requestMainWindowHandle() override; + void closeViews(const std::vector& vecFeatureIDs) override; + void closeAllViews(); + void UseExactPositioning(bool exactPos) override; - void openViews(const std::vector &bldIds, bool exactPos) override; - bool isViewOpen(const std::string &strBldId) const override; + bool OpenView(const std::string& buildingid, const std::string& windowtitle, const Color& col, ViewMode viewmode, + int screennum, bool fullscreen, int x, int y, int w, int h, unsigned int& contextid, + bool exactPos = true) override; - void closeViews(const std::vector &vecFeatureIDs) override; - void closeAllViews(); + void CloseView(unsigned int contextid) override; - void UseExactPositioning(bool exactPos) override; + void ChangeViewMode(unsigned int contextId, ViewMode viewmode) override; - + void LockViewRotationToMapRotation(unsigned int contextId, bool lock) override; - bool OpenView(const std::string &buildingid, const std::string &windowtitle, const Color &col, - ViewMode viewmode, int screennum, - bool fullscreen, int x, int y, int w, int h, unsigned int &contextid, bool exactPos = true) override; + void SetPlayerDisplayMode(unsigned int contextId, PlayerDisplayMode mode) override; + void SetWallTransparency(unsigned int contextId, float transparency) override; - + float GetMapRotation() const override; - void CloseView(unsigned int contextid) override; + void SetMapRotation(float angle) override; - + void OpenOverview() override; - void ChangeViewMode(unsigned int contextId, ViewMode viewmode) override; + bool LoadBuildingPositionMap(const std::string& path, bool loadAllAvailableBuildings) override; - + void LoadAllBuildings(); - void LockViewRotationToMapRotation(unsigned int contextId, bool lock) override; + void CreatePlayer(const std::string& id, const std::string& iconpath, const Color& color) override; - + void DeletePlayer(const std::string& id, float seconds = 0) override; - void SetPlayerDisplayMode(unsigned int contextId, PlayerDisplayMode mode) override; + void SetPlayerColor(const std::string& id, const Color& color) override; - + void SetPlayerIcon(const std::string& id, const std::string& path) override; - void SetWallTransparency(unsigned int contextId, float transparency) override; + void reloadPlayerIcons() override; - + void UpdatePlayerPartyColors(const std::map& mapPlayerColors) override; - float GetMapRotation() const override; + size_t GetNumPlayers() const override; - + void GetPlayerIds(std::vector& toFill) override; - void SetMapRotation(float angle) override; + void SetPlayerShown(const std::string& id, bool show, double when = -1) override; - + size_t GetNumBuildings() const override; - void OpenOverview() override; + void GetBuildingIds(std::vector& toFill) const override; + void SetShowSelectionBox(const std::string& id, bool show, float duration = -1) override; - + void Shoot(const int32_t id, const std::string& shooter, const std::string& target, const Vec3d& shooterPos, + const Vec3d& targetPos, int buildingIdSrc, int roomNumberSrc, int buildingIdDst, int roomNumberDst, + int lineType, double when) override; + void Shoot(const int32_t id, const std::string& shooter, const std::string& targetBuildingId, + const std::string& targetRoomId, const Vec3d& shooterPos, int lineType, double when) override; - bool LoadBuildingPositionMap(const std::string &path, bool loadAllAvailableBuildings) override; + void removeShoot(const int32_t id) override; + void Teleport(const std::string& id, double when, const Vec3d& target, const std::string& bldgname, int roomNumber, + const std::string& roomname, ZValue zval) override; - void LoadAllBuildings(); + void GetRoomNames(const std::string& id, std::vector& names) override; - + bool SetRoomDestructionValue(const std::string& id, const std::string& roomname, float value) override; - void CreatePlayer(const std::string &id, const std::string &iconpath, const Color &color) override; + bool SetBuildingDestructionValue(const std::string& id, float value) override; - + void GetDeviceNames(const std::string& buildingId, std::vector& names) override; - void DeletePlayer(const std::string &id, float seconds = 0) override; + bool ShowDeviceIcon(const std::string& id, const std::string& buildingid, const std::string& devicename, + const std::string& iconpath) override; - + bool ShowDeviceIcon(const std::string& id, const std::string& buildingid, const Vec3d& position, + const std::string& iconpath) override; - void SetPlayerColor(const std::string &id, const Color &color) override; + void ChangeLineMode(unsigned int contextId, bool line) override; + void ChangeNameMode(unsigned int contextId, bool name) override; - + bool SetDisplayName(const std::string& buildingid, const std::string& roomname, + const std::string& strDisplayName) override; + void ShowDisplayNames(const std::string& buildingid, bool show) override; + void SetShowDisplayNamesSelectionBox(const std::string& buildingid, const std::string& id, bool show, + float duration = -1) override; + void setHitLineDuration(uint32_t durationSec) override; + void setMountingPointAsset(const MountingPointDescription& asset) override; + std::vector getBuildingState() const override; - void SetPlayerIcon(const std::string &id, const std::string &path) override; + bool HideDeviceIcon(const std::string& id) override; + float GetTimeScale() const override; - void reloadPlayerIcons() override; + void SetTimeScale(float scale) override; - void UpdatePlayerPartyColors(const std::map& mapPlayerColors) override; + void SetSimulationTime(double t) override; - + double GetSimulationTime() const override; - size_t GetNumPlayers() const override; + void SetPaused(bool) override; - + bool GetPaused() const override; - void GetPlayerIds(std::vector &toFill) override; + void FastForwardSimulationTo(double t) override; - + void DeleteQueuedCommands() override; - void SetPlayerShown(const std::string &id, bool show, double when = -1) override; + void SetNonRealtimeMode(bool on) override; - + bool GetNonRealtimeMode() const override; - size_t GetNumBuildings() const override; + bool StartVideoRecording(unsigned int contextid, const std::string& path, int w, int h, int framerate, + int quality) override; + bool StartVideoRecording(const std::string& buildingId, const std::string& path, int w, int h, int framerate, + int quality) override; - + bool StopVideoRecording(unsigned int contextid) override; + bool StopVideoRecording(const std::string& buildingId) override; - void GetBuildingIds(std::vector &toFill) const override; + void setTransparency(double percent) override; + void setViewMode(ViewMode m) override; + void setDisplayMode(PlayerDisplayMode m) override; - - - void SetShowSelectionBox(const std::string &id, - bool show, - float duration = -1) override; - - - - void Shoot(const int32_t id, - const std::string &shooter, - const std::string &target, - const Vec3d &shooterPos, - const Vec3d &targetPos, - int buildingIdSrc, int roomNumberSrc, int buildingIdDst, int roomNumberDst, - int lineType, - double when) override; - void Shoot(const int32_t id, - const std::string &shooter, - const std::string &targetBuildingId, - const std::string &targetRoomId, - const Vec3d &shooterPos, int lineType, - double when) override; - - void removeShoot(const int32_t id) override; - - - - void Teleport(const std::string &id, - double when, - const Vec3d &target, - const std::string &bldgname, - int roomNumber, - const std::string &roomname, - ZValue zval) override; - - - - void GetRoomNames(const std::string &id, std::vector &names) override; - - - - bool SetRoomDestructionValue(const std::string &id, - const std::string &roomname, - float value) override; - - - - bool SetBuildingDestructionValue(const std::string &id, float value) override; - - - - void GetDeviceNames(const std::string &buildingId, std::vector &names) override; - - - - bool ShowDeviceIcon(const std::string &id, const std::string &buildingid, - const std::string &devicename, const std::string &iconpath) override; - - - - bool ShowDeviceIcon(const std::string &id, const std::string &buildingid, - const Vec3d &position, const std::string &iconpath) override; - - void ChangeLineMode(unsigned int contextId, bool line) override; - void ChangeNameMode(unsigned int contextId, bool name) override; - - bool SetDisplayName(const std::string& buildingid, const std::string& roomname, const std::string& strDisplayName) override; - void ShowDisplayNames(const std::string& buildingid, bool show) override; - void SetShowDisplayNamesSelectionBox(const std::string& buildingid, const std::string& id, bool show, float duration = -1) override; - void setHitLineDuration(uint32_t durationSec) override; - void setMountingPointAsset(const MountingPointDescription &asset) override; - std::vector getBuildingState() const override; - - - - bool HideDeviceIcon(const std::string &id) override; - - - - float GetTimeScale() const override; - - - - void SetTimeScale(float scale) override; - - - - void SetSimulationTime(double t) override; - - - - double GetSimulationTime() const override; - - - - void SetPaused(bool) override; - - - - bool GetPaused() const override; - - - - void FastForwardSimulationTo(double t) override; - - - - void DeleteQueuedCommands() override; - - - - void SetNonRealtimeMode(bool on) override; - - - - bool GetNonRealtimeMode() const override; - - - - bool StartVideoRecording(unsigned int contextid, const std::string &path, - int w, int h, int framerate, int quality) override; - bool StartVideoRecording(const std::string &buildingId, const std::string &path, - int w, int h, int framerate, int quality) override; - - - - bool StopVideoRecording(unsigned int contextid) override; - bool StopVideoRecording(const std::string &buildingId) override; - - void setTransparency(double percent) override; - void setViewMode(ViewMode m) override; - void setDisplayMode(PlayerDisplayMode m) override; - - int GetFrameRate() const { return mFrameRate; } - void OnShowMsgBox(const std::string &strText); - - bool allViewWindowsExposed() const - { - for (auto *vw : m_openedViewWidgets.getViewWidgets()) + int GetFrameRate() const { - if (!vw->isOpenGlWindowExposed()) - return false; + return mFrameRate; } - return !m_openedViewWidgets.getViewWidgets().empty(); - } -private: + void OnShowMsgBox(const std::string& strText); -NGL::INGLLogger &m_logger; - bool open(const std::string& strFeatureID, bool exactPos); - bool open(const std::vector &vecFeatureIDs, bool exactPos); - bool openAll(bool exactPos); + bool allViewWindowsExposed() const + { + for (auto* vw : m_openedViewWidgets.getViewWidgets()) + { + if (!vw->isOpenGlWindowExposed()) + return false; + } + return !m_openedViewWidgets.getViewWidgets().empty(); + } - void onEXCOpen(const QString& strIDs, bool exactPos); - void onEXCClose(const QString& strIDs); - void convertAssetsToPngFiles(); + private: + NGL::INGLLogger& m_logger; + bool open(const std::string& strFeatureID, bool exactPos); + bool open(const std::vector& vecFeatureIDs, bool exactPos); + bool openAll(bool exactPos); - void OnTransformSend(const dtEntity::Message &m); - void OnMapLoaded(const dtEntity::Message &m); - void OnMapUnloaded(const dtEntity::Message &m); - void OnNavMeshGroupChanged(const dtEntity::Message &m); - void OnPlayerPicked(const dtEntity::Message &m); - void OnHideSelection(const dtEntity::Message &m); - - void OnShoot(const dtEntity::Message &m); - void OnShowHidePlayer(const dtEntity::Message &m); - void OnDisplayNameClicked(const dtEntity::Message& m); + void onEXCOpen(const QString& strIDs, bool exactPos); + void onEXCClose(const QString& strIDs); + void convertAssetsToPngFiles(); - bool SpawnBuilding(const BuildingData &b, bool useStaticMeshesFolder = true); - void LoadBuilding(BuildingData& bd, bool useStaticMeshesFolder); - void deleteAllBuildings(); + void OnTransformSend(const dtEntity::Message& m); + void OnMapLoaded(const dtEntity::Message& m); + void OnMapUnloaded(const dtEntity::Message& m); + void OnNavMeshGroupChanged(const dtEntity::Message& m); + void OnPlayerPicked(const dtEntity::Message& m); + void OnHideSelection(const dtEntity::Message& m); - bool getBuildingString(const std::string &strFeatureID, std::string *strBuildingNameID); + void OnShoot(const dtEntity::Message& m); + void OnShowHidePlayer(const dtEntity::Message& m); + void OnDisplayNameClicked(const dtEntity::Message& m); - bool OpenView(unsigned int contextId); - bool CreateView(dtEntity::EntityId bid, const std::string &windowtitle, const Color &col, ViewMode viewmode, - int screennum, bool fullscreen, int x, int y, int w, int h, - unsigned int &contextid, bool exactPos); + bool SpawnBuilding(const BuildingData& b, bool useStaticMeshesFolder = true); + void LoadBuilding(BuildingData& bd, bool useStaticMeshesFolder); + void deleteAllBuildings(); - QPointer m_pMainWindow; + bool getBuildingString(const std::string& strFeatureID, std::string* strBuildingNameID); - dtEntity::EntityManager *mEntityManager; - ViewerCallback *mViewerCallback; - LogHandler* mLogHandler = nullptr; - dtEntity::MapSystem *mMapSystem; - PlayerSystem *mPlayerSystem; - BuildingManager *mBuildingManager; + bool OpenView(unsigned int contextId); + bool CreateView(dtEntity::EntityId bid, const std::string& windowtitle, const Color& col, ViewMode viewmode, + int screennum, bool fullscreen, int x, int y, int w, int h, unsigned int& contextid, bool exactPos); - float mTimeScale; - double mSimTime; - bool mPaused; - bool mNonRealtimeMode; - int mFrameRate; - std::map mViewWidgets; + QPointer m_pMainWindow; + dtEntity::EntityManager* mEntityManager; + ViewerCallback* mViewerCallback; + LogHandler* mLogHandler = nullptr; + dtEntity::MapSystem* mMapSystem; + PlayerSystem* mPlayerSystem; + BuildingManager* mBuildingManager; - ViewWidget *GetViewWidget(unsigned int contextid); - void storeWidget(ViewWidget *pWidget, const std::string &strBuildingNameID, unsigned int contextid, VCtrl::ViewMode vmode, VCtrl::PlayerDisplayMode displayMode); + float mTimeScale; + double mSimTime; + bool mPaused; + bool mNonRealtimeMode; + int mFrameRate; + std::map mViewWidgets; + ViewWidget* GetViewWidget(unsigned int contextid); + void storeWidget(ViewWidget* pWidget, const std::string& strBuildingNameID, unsigned int contextid, + VCtrl::ViewMode vmode, VCtrl::PlayerDisplayMode displayMode); - const std::size_t m_maxParallelViewWidgets = 8; - - unsigned int m_hitlineDuration_s = 10; - double m_desiredTransparencyValue = 0.75; - bool m_showHitLines = true; - ViewWidget *CreateMainWindowView(dtEntity::EntityId bid, const std::string &featureId, unsigned int &contextid, bool exactPos); + const std::size_t m_maxParallelViewWidgets = 8; + unsigned int m_hitlineDuration_s = 10; + double m_desiredTransparencyValue = 0.75; + bool m_showHitLines = true; + ViewWidget* CreateMainWindowView(dtEntity::EntityId bid, const std::string& featureId, unsigned int& contextid, + bool exactPos); - std::unordered_map m_loadedBuildings; + std::unordered_map m_loadedBuildings; - ViewWidgetContainer m_openedViewWidgets; - bool m_isInFullscreenMode = false; + ViewWidgetContainer m_openedViewWidgets; + bool m_isInFullscreenMode = false; - - ViewMode m_desiredViewMode = ViewMode::ORTHOGRAPHIC; - VCtrl::PlayerDisplayMode m_desiredPlayerDisplayMode = VCtrl::PlayerDisplayMode::Icons; + ViewMode m_desiredViewMode = ViewMode::ORTHOGRAPHIC; + VCtrl::PlayerDisplayMode m_desiredPlayerDisplayMode = VCtrl::PlayerDisplayMode::Icons; - void CloseView(ViewWidget *pWidget); + void CloseView(ViewWidget* pWidget); - void onExcRestoreViewState(const std::string &strFeatureID); - void restoreViewWidgetStates(const std::vector &vecStates); - void restoreViewWidgetStateDeferred(ViewWidget *pViewWidget); - std::unordered_map m_deferredViewStates; + void onExcRestoreViewState(const std::string& strFeatureID); + void restoreViewWidgetStates(const std::vector& vecStates); + void restoreViewWidgetStateDeferred(ViewWidget* pViewWidget); + std::unordered_map m_deferredViewStates; - QJsonValue getViewState() const override; - void setViewState(const QJsonValue &val) override; - void highlightView(const std::string &buildingId) override; - void setBuildingDisplayName(const std::string &buildingId, const std::string &displayName) override; - + QJsonValue getViewState() const override; + void setViewState(const QJsonValue& val) override; + void highlightView(const std::string& buildingId) override; + void setBuildingDisplayName(const std::string& buildingId, const std::string& displayName) override; -private slots: - void onViewWidget_MaximizeRequest(ViewWidget *pWidget); - void onViewWidget_MinimizeRequest(ViewWidget *pWidget); - void onViewWidget_CloseRequest(ViewWidget *pWidget); - void onViewWidget_FocusRequest(ViewWidget *pWidget); - void onViewWidget_Zoom(ViewWidget *pWidget, bool zoomIn); + private slots: + void onViewWidget_MaximizeRequest(ViewWidget* pWidget); + void onViewWidget_MinimizeRequest(ViewWidget* pWidget); + void onViewWidget_CloseRequest(ViewWidget* pWidget); + void onViewWidget_FocusRequest(ViewWidget* pWidget); + void onViewWidget_Zoom(ViewWidget* pWidget, bool zoomIn); }; -} +} // namespace VCtrl diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.cpp old mode 100755 new mode 100644 index 80962c68b..20a7d9e87 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.cpp @@ -1,647 +1,605 @@ #include "bdv_communication_interface_internal.h" -#include + +#include #include #include -#include +#include namespace BuildingViewer { -static const char PLAYER_PREFIX[] = "player_"; -static const char ROOM_PREFIX[] = ""; +static const char PLAYER_PREFIX[] = "player_"; +static const char ROOM_PREFIX[] = ""; static const char BUILDING_PREFIX[] = "House_"; - static inline std::string createPlayerIdString(int playerId) { - return PLAYER_PREFIX + std::to_string(playerId); + return PLAYER_PREFIX + std::to_string(playerId); } static inline std::string createBuildingIdString(int buildingId) { - return BUILDING_PREFIX + std::to_string(buildingId); + return BUILDING_PREFIX + std::to_string(buildingId); } static inline std::string createRoomNumberString(int roomNumber) { - return ROOM_PREFIX + std::to_string(roomNumber); + return ROOM_PREFIX + std::to_string(roomNumber); } CommunicationInterfaceInternal::CommunicationInterfaceInternal(VCtrl::ViewerInterface* pviewerInterface) - : m_pviewerInterface(pviewerInterface) + : m_pviewerInterface(pviewerInterface) { - assert(m_pviewerInterface); + assert(m_pviewerInterface); } -void CommunicationInterfaceInternal::playerCreate(int playerID, int partyID, const QString &strPathToSymbolFile, - const LtsUtils::QPoint3D &pos, int buildingID, int roomNumber, Core::PositionReportingSource reportingSource) +void CommunicationInterfaceInternal::playerCreate(int playerID, int partyID, const QString& strPathToSymbolFile, + const LtsUtils::QPoint3D& pos, int buildingID, int roomNumber, + Core::PositionReportingSource reportingSource) { - std::string playerIdStr = createPlayerIdString(playerID); - VCtrl::Color partyColor = m_teamMap.value(partyID).color; - m_pviewerInterface->CreatePlayer(playerIdStr, strPathToSymbolFile.toStdString(), partyColor); + std::string playerIdStr = createPlayerIdString(playerID); + VCtrl::Color partyColor = m_teamMap.value(partyID).color; + m_pviewerInterface->CreatePlayer(playerIdStr, strPathToSymbolFile.toStdString(), partyColor); - std::string buildingIdStr, roomNumberStr; - if (buildingID > 0) - { - buildingIdStr = createBuildingIdString(buildingID); - } - if (roomNumber > 0) - { - roomNumberStr = createRoomNumberString(roomNumber); - } + std::string buildingIdStr, roomNumberStr; + if (buildingID > 0) + { + buildingIdStr = createBuildingIdString(buildingID); + } + if (roomNumber > 0) + { + roomNumberStr = createRoomNumberString(roomNumber); + } - const VCtrl::Vec3d tgt(pos.x(), pos.y(), pos.z()); - m_pviewerInterface->Teleport(playerIdStr, 0, tgt, buildingIdStr, roomNumber, roomNumberStr, - (reportingSource == Core::PositionReportingSource::Wls - ? VCtrl::ZValue::AboveMsl - : VCtrl::ZValue::RelativeBuildings)); - m_pviewerInterface->SetPlayerShown(playerIdStr, true, 0); + const VCtrl::Vec3d tgt(pos.x(), pos.y(), pos.z()); + m_pviewerInterface->Teleport(playerIdStr, 0, tgt, buildingIdStr, roomNumber, roomNumberStr, + (reportingSource == Core::PositionReportingSource::Wls + ? VCtrl::ZValue::AboveMsl + : VCtrl::ZValue::RelativeBuildings)); + m_pviewerInterface->SetPlayerShown(playerIdStr, true, 0); - m_playerId2String[playerID] = playerIdStr; - m_string2PlayerId[playerIdStr] = playerID; - m_player2TeamMap[playerID] = partyID; + m_playerId2String[playerID] = playerIdStr; + m_string2PlayerId[playerIdStr] = playerID; + m_player2TeamMap[playerID] = partyID; } - -void CommunicationInterfaceInternal::playerPlace(int playerID, const LtsUtils::QPoint3D &pos, - int buildingID, int roomNumber, Core::PositionReportingSource reportingSource) +void CommunicationInterfaceInternal::playerPlace(int playerID, const LtsUtils::QPoint3D& pos, int buildingID, + int roomNumber, Core::PositionReportingSource reportingSource) { - auto it = m_playerId2String.find(playerID); - if (it == m_playerId2String.end()) - { - WARNING_LOG(m_logger) << "Trying to set player position for unknown (=not created) player with id " << playerID; - return; - } + auto it = m_playerId2String.find(playerID); + if (it == m_playerId2String.end()) + { + WARNING_LOG(m_logger) << "Trying to set player position for unknown (=not created) player with id " << playerID; + return; + } - const std::string &playerIdStr = it.value(); + const std::string& playerIdStr = it.value(); - std::string buildingIdStr, roomNumberStr; - if (buildingID > 0 ) - { - buildingIdStr = createBuildingIdString(buildingID); - } - if ( roomNumber > 0) - { - roomNumberStr = createRoomNumberString(roomNumber); - } + std::string buildingIdStr, roomNumberStr; + if (buildingID > 0) + { + buildingIdStr = createBuildingIdString(buildingID); + } + if (roomNumber > 0) + { + roomNumberStr = createRoomNumberString(roomNumber); + } - const VCtrl::Vec3d tgt(pos.x(), pos.y(), pos.z()); - m_pviewerInterface->Teleport(playerIdStr, 0, tgt, buildingIdStr, roomNumber, roomNumberStr, - (reportingSource == Core::PositionReportingSource::Wls - ? VCtrl::ZValue::AboveMsl - : VCtrl::ZValue::RelativeBuildings)); + const VCtrl::Vec3d tgt(pos.x(), pos.y(), pos.z()); + m_pviewerInterface->Teleport(playerIdStr, 0, tgt, buildingIdStr, roomNumber, roomNumberStr, + (reportingSource == Core::PositionReportingSource::Wls + ? VCtrl::ZValue::AboveMsl + : VCtrl::ZValue::RelativeBuildings)); } - void CommunicationInterfaceInternal::playerDelete(int playerID) { - if (playerID <= 0) - return; - std::string playerIdStr = createPlayerIdString(playerID); - m_pviewerInterface->DeletePlayer(playerIdStr); + if (playerID <= 0) + return; + std::string playerIdStr = createPlayerIdString(playerID); + m_pviewerInterface->DeletePlayer(playerIdStr); - m_playerId2String.remove(playerID); - m_string2PlayerId.remove(playerIdStr); - m_player2TeamMap.remove(playerID); + m_playerId2String.remove(playerID); + m_string2PlayerId.remove(playerIdStr); + m_player2TeamMap.remove(playerID); } - void CommunicationInterfaceInternal::setPlayerVisible(int playerID, bool bVisible) { - if (playerID <= 0) - return; - std::string playerIdStr = createPlayerIdString(playerID); - m_pviewerInterface->SetPlayerShown(playerIdStr, bVisible); + if (playerID <= 0) + return; + std::string playerIdStr = createPlayerIdString(playerID); + m_pviewerInterface->SetPlayerShown(playerIdStr, bVisible); } - void CommunicationInterfaceInternal::playerClear() { - const auto string2PlayerId_Copy = m_string2PlayerId; - for (const int playerId : string2PlayerId_Copy) - playerDelete(playerId); + const auto string2PlayerId_Copy = m_string2PlayerId; + for (const int playerId : string2PlayerId_Copy) + playerDelete(playerId); - m_player2TeamMap.clear(); - m_playerId2String.clear(); - m_string2PlayerId.clear(); + m_player2TeamMap.clear(); + m_playerId2String.clear(); + m_string2PlayerId.clear(); } - void CommunicationInterfaceInternal::playerUpdateSymbols() { - m_pviewerInterface->reloadPlayerIcons(); + m_pviewerInterface->reloadPlayerIcons(); } - -void CommunicationInterfaceInternal::playerUpdatePlayerSymbol(int playerID, const QString &strPathToSymbolFile) -{ - std::string playerIdStr = createPlayerIdString(playerID); - m_pviewerInterface->SetPlayerIcon(playerIdStr, strPathToSymbolFile.toStdString()); +void CommunicationInterfaceInternal::playerUpdatePlayerSymbol(int playerID, const QString& strPathToSymbolFile) +{ + std::string playerIdStr = createPlayerIdString(playerID); + m_pviewerInterface->SetPlayerIcon(playerIdStr, strPathToSymbolFile.toStdString()); } - - - void CommunicationInterfaceInternal::playerHit(const int32_t id, int playerIdSrc, int playerIdDst, - const LtsUtils::QPoint3D &posSrc, const LtsUtils::QPoint3D &posDst, - int buildingIdSrc, int roomNumberSrc, int buildingIdDst, int roomNumberDst, - int lineType, int64_t time) + const LtsUtils::QPoint3D& posSrc, const LtsUtils::QPoint3D& posDst, + int buildingIdSrc, int roomNumberSrc, int buildingIdDst, + int roomNumberDst, int lineType, int64_t time) { - DEBUG_LOG(m_logger) << "playerHit id= " << id; - const std::string playerIdStrDst = m_playerId2String.value(playerIdDst); - const std::string playerIdStrSrc = m_playerId2String.value(playerIdSrc); - const VCtrl::Vec3d src(posSrc.x(), posSrc.y(), posSrc.z()); - const VCtrl::Vec3d dst(posDst.x(), posDst.y(), posDst.z()); - m_pviewerInterface->Shoot(id, playerIdStrSrc, playerIdStrDst, - src, dst, - buildingIdSrc, roomNumberSrc, buildingIdDst, roomNumberDst, - lineType, time / 1000.); + DEBUG_LOG(m_logger) << "playerHit id= " << id; + const std::string playerIdStrDst = m_playerId2String.value(playerIdDst); + const std::string playerIdStrSrc = m_playerId2String.value(playerIdSrc); + const VCtrl::Vec3d src(posSrc.x(), posSrc.y(), posSrc.z()); + const VCtrl::Vec3d dst(posDst.x(), posDst.y(), posDst.z()); + m_pviewerInterface->Shoot(id, playerIdStrSrc, playerIdStrDst, src, dst, buildingIdSrc, roomNumberSrc, buildingIdDst, + roomNumberDst, lineType, time / 1000.); } - -void CommunicationInterfaceInternal::buildingHit(const int32_t id, int buildingId, int damagePercent, const QMap& mapRoomDestructions) +void CommunicationInterfaceInternal::buildingHit(const int32_t id, int buildingId, int damagePercent, + const QMap& mapRoomDestructions) { - DEBUG_LOG(m_logger) << "buildingHit for building " << buildingId - << " id=" << id - << " damagePercent " << damagePercent - << " roomlist size: " << mapRoomDestructions.size(); + DEBUG_LOG(m_logger) << "buildingHit for building " << buildingId << " id=" << id << " damagePercent " + << damagePercent << " roomlist size: " << mapRoomDestructions.size(); - const std::string buildingIdStr = createBuildingIdString(buildingId); + const std::string buildingIdStr = createBuildingIdString(buildingId); - - if (damagePercent <= 0 || damagePercent >= 80) - { - if (damagePercent >= 80) - damagePercent = 100; - m_pviewerInterface->SetBuildingDestructionValue(buildingIdStr, damagePercent / 100.f); - } - else - { - for (auto it = mapRoomDestructions.begin(); it != mapRoomDestructions.end(); ++it) + if (damagePercent <= 0 || damagePercent >= 80) { - const int roomNumber = it.key(); - DEBUG_LOG(m_logger) << "BuildingId " << buildingId - << ", room: "<< roomNumber - << ", destruction: " << it.value(); - std::string roomNumberStr = createRoomNumberString(roomNumber); - if (!m_pviewerInterface->SetRoomDestructionValue(buildingIdStr, roomNumberStr,it.value() / 100.f)) - ERROR_LOG(m_logger) << "SetRoomDestructionValue failed for room "<< roomNumber; + if (damagePercent >= 80) + damagePercent = 100; + m_pviewerInterface->SetBuildingDestructionValue(buildingIdStr, damagePercent / 100.f); + } + else + { + for (auto it = mapRoomDestructions.begin(); it != mapRoomDestructions.end(); ++it) + { + const int roomNumber = it.key(); + DEBUG_LOG(m_logger) << "BuildingId " << buildingId << ", room: " << roomNumber + << ", destruction: " << it.value(); + std::string roomNumberStr = createRoomNumberString(roomNumber); + if (!m_pviewerInterface->SetRoomDestructionValue(buildingIdStr, roomNumberStr, it.value() / 100.f)) + ERROR_LOG(m_logger) << "SetRoomDestructionValue failed for room " << roomNumber; + } } - } } -void CommunicationInterfaceInternal::roomHit(const int32_t id, int playerIdSrc, int buildingId, int roomNumber, const LtsUtils::QPoint3D &posSrc, int lineType, int64_t time) +void CommunicationInterfaceInternal::roomHit(const int32_t id, int playerIdSrc, int buildingId, int roomNumber, + const LtsUtils::QPoint3D& posSrc, int lineType, int64_t time) { - + const std::string playerIdStrSrc = m_playerId2String.value(playerIdSrc); + const std::string buildingIdStrDst = createBuildingIdString(buildingId); + const std::string roomNumberStrDst = createRoomNumberString(roomNumber); + const VCtrl::Vec3d src(posSrc.x(), posSrc.y(), posSrc.z()); - const std::string playerIdStrSrc = m_playerId2String.value(playerIdSrc); - const std::string buildingIdStrDst = createBuildingIdString(buildingId); - const std::string roomNumberStrDst = createRoomNumberString(roomNumber); - const VCtrl::Vec3d src(posSrc.x(), posSrc.y(), posSrc.z()); + DEBUG_LOG(m_logger) << "roomHit for building palyer " << playerIdStrSrc << " building " << buildingIdStrDst + << " room " << roomNumberStrDst << " id=" << id; - DEBUG_LOG(m_logger) << "roomHit for building palyer " << playerIdStrSrc - << " building " << buildingIdStrDst - << " room " << roomNumberStrDst - << " id=" << id; - - - m_pviewerInterface->Shoot(id, playerIdStrSrc, buildingIdStrDst, roomNumberStrDst, src, lineType, time / 1000.); + m_pviewerInterface->Shoot(id, playerIdStrSrc, buildingIdStrDst, roomNumberStrDst, src, lineType, time / 1000.); } void CommunicationInterfaceInternal::removeRoomHit(const int32_t id) { - DEBUG_LOG(m_logger) << "removeRoomHit id=" << id; - m_pviewerInterface->removeShoot(id); + DEBUG_LOG(m_logger) << "removeRoomHit id=" << id; + m_pviewerInterface->removeShoot(id); } -void CommunicationInterfaceInternal::setTeamConfiguration(const QMap &parties) +void CommunicationInterfaceInternal::setTeamConfiguration(const QMap& parties) { - for (const ParticipantManagement::Party &party : parties) - { - BdvParty bdvParty; - bdvParty.id = party.id(); - bdvParty.name = ParticipantManagement::trPartyName(party.name()); + for (const ParticipantManagement::Party& party : parties) + { + BdvParty bdvParty; + bdvParty.id = party.id(); + bdvParty.name = ParticipantManagement::trPartyName(party.name()); - const uint32_t argb = party.color(); - bdvParty.color.w = ( ( ( argb >> 24 ) & 0xff ) / 255.); - bdvParty.color.x = ( ( ( argb >> 16 ) & 0xff ) / 255.); - bdvParty.color.y = ( ( ( argb >> 8 ) & 0xff ) / 255.); - bdvParty.color.z = ( ( ( argb >> 0 ) & 0xff ) / 255.); - m_teamMap[bdvParty.id] = bdvParty; - } + const uint32_t argb = party.color(); + bdvParty.color.w = (((argb >> 24) & 0xff) / 255.); + bdvParty.color.x = (((argb >> 16) & 0xff) / 255.); + bdvParty.color.y = (((argb >> 8) & 0xff) / 255.); + bdvParty.color.z = (((argb >> 0) & 0xff) / 255.); + m_teamMap[bdvParty.id] = bdvParty; + } - std::map mapPlayerColors; - for (auto it = m_player2TeamMap.cbegin(); it != m_player2TeamMap.cend(); ++it) - { - const auto itParty = m_teamMap.constFind(it.value()); - if (itParty == m_teamMap.cend()) - continue; - mapPlayerColors.emplace(std::make_pair(createPlayerIdString(it.key()), - itParty.value().color)); - } - m_pviewerInterface->UpdatePlayerPartyColors(mapPlayerColors); + std::map mapPlayerColors; + for (auto it = m_player2TeamMap.cbegin(); it != m_player2TeamMap.cend(); ++it) + { + const auto itParty = m_teamMap.constFind(it.value()); + if (itParty == m_teamMap.cend()) + continue; + mapPlayerColors.emplace(std::make_pair(createPlayerIdString(it.key()), itParty.value().color)); + } + m_pviewerInterface->UpdatePlayerPartyColors(mapPlayerColors); } - void CommunicationInterfaceInternal::systemSetSimulationTime(qint64 time) { - double tSimTime = time / 1000; - double tCurSimTime = m_pviewerInterface->GetSimulationTime(); - if(fabs(tCurSimTime - tSimTime) < 0.5) - return; - m_pviewerInterface->SetSimulationTime(tSimTime); + double tSimTime = time / 1000; + double tCurSimTime = m_pviewerInterface->GetSimulationTime(); + if (fabs(tCurSimTime - tSimTime) < 0.5) + return; + m_pviewerInterface->SetSimulationTime(tSimTime); } void CommunicationInterfaceInternal::setSimuationPace(double pace) { - m_pviewerInterface->SetTimeScale(pace); + m_pviewerInterface->SetTimeScale(pace); } - void CommunicationInterfaceInternal::systemDisconnect() { - playerClear(); - clearCameras(); - systemSetPaused(true); + playerClear(); + clearCameras(); + systemSetPaused(true); } void CommunicationInterfaceInternal::systemSetPaused(bool bPaused) { - m_pviewerInterface->SetPaused(bPaused); + m_pviewerInterface->SetPaused(bPaused); } - -void CommunicationInterfaceInternal::systemSetMountingPoint(const InfrastructureManagement::MountingPoint &data, const QString &filename, bool show) +void CommunicationInterfaceInternal::systemSetMountingPoint(const InfrastructureManagement::MountingPoint& data, + const QString& filename, bool show) { - int buildingId = data.buildingId(); - const QString &mountingPointName = filename; - double x = data.relPosition().offsetX(); - double y = data.relPosition().offsetY(); - double z = data.relPosition().offsetZ(); + int buildingId = data.buildingId(); + const QString& mountingPointName = filename; + double x = data.relPosition().offsetX(); + double y = data.relPosition().offsetY(); + double z = data.relPosition().offsetZ(); - const std::string buildingIdStr = createBuildingIdString(buildingId); + const std::string buildingIdStr = createBuildingIdString(buildingId); - if(!show) - { - DEBUG_LOG(m_logger) << "Hiding mounting point \"" << mountingPointName<< "\""; - m_pviewerInterface->HideDeviceIcon(mountingPointName.toStdString()); - return; - } + if (!show) + { + DEBUG_LOG(m_logger) << "Hiding mounting point \"" << mountingPointName << "\""; + m_pviewerInterface->HideDeviceIcon(mountingPointName.toStdString()); + return; + } - if(m_deviceMap.contains(mountingPointName)) - { - WARNING_LOG(m_logger) << "Trying to add a mounting point which was already added - trying to re-add"; - - m_pviewerInterface->HideDeviceIcon(mountingPointName.toStdString()); - } + if (m_deviceMap.contains(mountingPointName)) + { + WARNING_LOG(m_logger) << "Trying to add a mounting point which was already added - trying to re-add"; - const VCtrl::Vec3d position(x,y,z); - if(m_pviewerInterface->ShowDeviceIcon(mountingPointName.toStdString(), buildingIdStr, position, filename.toStdString())) { - DEBUG_LOG(m_logger) << "Added mounting point to scene: " << mountingPointName; - m_deviceMap[mountingPointName] = DeviceInfo(buildingId, mountingPointName); - } + m_pviewerInterface->HideDeviceIcon(mountingPointName.toStdString()); + } + + const VCtrl::Vec3d position(x, y, z); + if (m_pviewerInterface->ShowDeviceIcon(mountingPointName.toStdString(), buildingIdStr, position, + filename.toStdString())) + { + DEBUG_LOG(m_logger) << "Added mounting point to scene: " << mountingPointName; + m_deviceMap[mountingPointName] = DeviceInfo(buildingId, mountingPointName); + } } - -void CommunicationInterfaceInternal::excStartRecording(const QString& strPathOutputFolder, const QString &buildingId, int w, int h, int framerate, int quality) +void CommunicationInterfaceInternal::excStartRecording(const QString& strPathOutputFolder, const QString& buildingId, + int w, int h, int framerate, int quality) { - m_pviewerInterface->StartVideoRecording(buildingId.toStdString(), strPathOutputFolder.toStdString(), w, h, framerate, quality); + m_pviewerInterface->StartVideoRecording(buildingId.toStdString(), strPathOutputFolder.toStdString(), w, h, + framerate, quality); } - -void CommunicationInterfaceInternal::excStopRecording(const QString &buildingId) +void CommunicationInterfaceInternal::excStopRecording(const QString& buildingId) { - m_pviewerInterface->StopVideoRecording(buildingId.toStdString()); + m_pviewerInterface->StopVideoRecording(buildingId.toStdString()); } - -void CommunicationInterfaceInternal::excConnect(const std::vector &paths, const QString &strXMLFile) +void CommunicationInterfaceInternal::excConnect(const std::vector& paths, const QString& strXMLFile) { - m_pviewerInterface->SetProjectDataPaths(paths); - m_pviewerInterface->LoadBuildingPositionMap(strXMLFile.toStdString(), (strXMLFile.size() ? false : true)); - emit signalBgViewerInitFinished(); + m_pviewerInterface->SetProjectDataPaths(paths); + m_pviewerInterface->LoadBuildingPositionMap(strXMLFile.toStdString(), (strXMLFile.size() ? false : true)); + emit signalBgViewerInitFinished(); } - void CommunicationInterfaceInternal::excDeleteBuildingList() { - m_pviewerInterface->LoadBuildingPositionMap(std::string(), false); + m_pviewerInterface->LoadBuildingPositionMap(std::string(), false); } - void CommunicationInterfaceInternal::excSetHitlineDuration(uint32_t duration_s) { - DEBUG_LOG(m_logger) << "excSetHitlineDuration=" << duration_s; - m_pviewerInterface->setHitLineDuration(duration_s); + DEBUG_LOG(m_logger) << "excSetHitlineDuration=" << duration_s; + m_pviewerInterface->setHitLineDuration(duration_s); } - void CommunicationInterfaceInternal::excUseExactPositioning(bool useExactPositioning) { - m_useExactPositioning = useExactPositioning; - m_pviewerInterface->UseExactPositioning(useExactPositioning); + m_useExactPositioning = useExactPositioning; + m_pviewerInterface->UseExactPositioning(useExactPositioning); } - -void CommunicationInterfaceInternal::excOpenView(const std::vector &bldIds) +void CommunicationInterfaceInternal::excOpenView(const std::vector& bldIds) { - m_pviewerInterface->openViews(bldIds, m_useExactPositioning); + m_pviewerInterface->openViews(bldIds, m_useExactPositioning); } - -void CommunicationInterfaceInternal::excCloseView(const std::vector &bldIds) +void CommunicationInterfaceInternal::excCloseView(const std::vector& bldIds) { - m_pviewerInterface->closeViews(bldIds); + m_pviewerInterface->closeViews(bldIds); } - void CommunicationInterfaceInternal::excCloseAllViews() { - m_pviewerInterface->closeViews({"all"}); + m_pviewerInterface->closeViews({"all"}); } - -void CommunicationInterfaceInternal::excHighlightView(const QString &buildingId) +void CommunicationInterfaceInternal::excHighlightView(const QString& buildingId) { - m_pviewerInterface->highlightView(buildingId.toStdString()); + m_pviewerInterface->highlightView(buildingId.toStdString()); } - void CommunicationInterfaceInternal::excGetBuildingList() { - const auto states = m_pviewerInterface->getBuildingState(); - QVector tplStates; - BuildingTuple tpl; - tplStates.reserve(states.size()); - for (const auto &state : states) - { - tpl.buildingId = QString::fromStdString(state.buildingId); - tpl.description = QString::fromStdString(state.description); - tpl.entityId = state.entityId; - tpl.isShown = state.isShown; - tplStates += tpl; - } - emit signalReceivedBuildingList(tplStates); + const auto states = m_pviewerInterface->getBuildingState(); + QVector tplStates; + BuildingTuple tpl; + tplStates.reserve(states.size()); + for (const auto& state : states) + { + tpl.buildingId = QString::fromStdString(state.buildingId); + tpl.description = QString::fromStdString(state.description); + tpl.entityId = state.entityId; + tpl.isShown = state.isShown; + tplStates += tpl; + } + emit signalReceivedBuildingList(tplStates); } - void CommunicationInterfaceInternal::excSetGlobalTransparency(double transparency) { - m_pviewerInterface->setTransparency(transparency / 100.0); + m_pviewerInterface->setTransparency(transparency / 100.0); } - void CommunicationInterfaceInternal::excSetGlobalViewMode(bool useOrtho) { - m_pviewerInterface->setViewMode(useOrtho ? VCtrl::ViewMode::ORTHOGRAPHIC : VCtrl::ViewMode::ISOMETRIC); + m_pviewerInterface->setViewMode(useOrtho ? VCtrl::ViewMode::ORTHOGRAPHIC : VCtrl::ViewMode::ISOMETRIC); } - void CommunicationInterfaceInternal::excSetGlobalDotsMode(bool useDots) { - m_pviewerInterface->setDisplayMode(useDots ? VCtrl::PlayerDisplayMode::Dots : VCtrl::PlayerDisplayMode::Icons); + m_pviewerInterface->setDisplayMode(useDots ? VCtrl::PlayerDisplayMode::Dots : VCtrl::PlayerDisplayMode::Icons); } - -void CommunicationInterfaceInternal::excRestoreViewState(const QJsonValue &val) +void CommunicationInterfaceInternal::excRestoreViewState(const QJsonValue& val) { - m_pviewerInterface->setViewState(val); + m_pviewerInterface->setViewState(val); } - void CommunicationInterfaceInternal::excGetViewState() { - const auto state = m_pviewerInterface->getViewState(); - emit signalReceivedViewState(state); + const auto state = m_pviewerInterface->getViewState(); + emit signalReceivedViewState(state); } -void CommunicationInterfaceInternal::excSetBuildingDisplayName(const QString &buildingId, const QString &strBuildingDisplayName) +void CommunicationInterfaceInternal::excSetBuildingDisplayName(const QString& buildingId, + const QString& strBuildingDisplayName) { - m_pviewerInterface->setBuildingDisplayName(buildingId.toStdString(), strBuildingDisplayName.toStdString()); + m_pviewerInterface->setBuildingDisplayName(buildingId.toStdString(), strBuildingDisplayName.toStdString()); } -void CommunicationInterfaceInternal::excSetRoomDisplayName(const QString &strFeatureID, const QString &strRoomName, const QString &strRoomDisplayName) +void CommunicationInterfaceInternal::excSetRoomDisplayName(const QString& strFeatureID, const QString& strRoomName, + const QString& strRoomDisplayName) { - m_pviewerInterface->SetDisplayName(strFeatureID.toStdString(), strRoomName.toStdString(), strRoomDisplayName.toStdString()); + m_pviewerInterface->SetDisplayName(strFeatureID.toStdString(), strRoomName.toStdString(), + strRoomDisplayName.toStdString()); } - -void CommunicationInterfaceInternal::extSetMountingPointAsset(const QString &strFeatureID, const QString &strMountingPointId, - const QVector3D& position, BuildingViewer::AssetTypes assetType) +void CommunicationInterfaceInternal::extSetMountingPointAsset(const QString& strFeatureID, + const QString& strMountingPointId, + const QVector3D& position, + BuildingViewer::AssetTypes assetType) { - m_pviewerInterface->setMountingPointAsset({strFeatureID.toStdString(), - strMountingPointId.toStdString(), - {position.x(), position.y(), position.z()}, - assetType}); + m_pviewerInterface->setMountingPointAsset({strFeatureID.toStdString(), + strMountingPointId.toStdString(), + {position.x(), position.y(), position.z()}, + assetType}); } - -void CommunicationInterfaceInternal::extHideMountingPointAsset(const QString &strMountingPointId) +void CommunicationInterfaceInternal::extHideMountingPointAsset(const QString& strMountingPointId) { - m_pviewerInterface->HideDeviceIcon(strMountingPointId.toStdString()); + m_pviewerInterface->HideDeviceIcon(strMountingPointId.toStdString()); } - void CommunicationInterfaceInternal::clearCameras() { - for (const DeviceInfo &di : std::as_const(m_deviceMap)) - { - if (!di.deviceName.startsWith(QLatin1String("Camera"))) - continue; - if (!m_pviewerInterface->HideDeviceIcon(di.deviceName.toStdString())) - ERROR_LOG(m_logger) << "Could not remove camera with id " << di.deviceName; - } - m_deviceMap.clear(); -} - - - -void CommunicationInterfaceInternal::SystemReady() -{ - -} - - -void CommunicationInterfaceInternal::TransformChanged(const std::string &id, const VCtrl::Vec3d &pos, const VCtrl::Quat &attitude) -{ - Q_UNUSED(id); - Q_UNUSED(pos); - Q_UNUSED(attitude); -} - - -void CommunicationInterfaceInternal::NavMeshGroupChanged(const std::string &id, const std::string &grpname) -{ - Q_UNUSED(id); - Q_UNUSED(grpname); -} - - -static inline bool isPlayerId(const std::string &playerIdString, int *playerId) -{ - const QString playerIdQString(QString::fromStdString(playerIdString)); - bool bOk = false; - if (playerIdQString.startsWith(QLatin1String(PLAYER_PREFIX))) - *playerId = playerIdQString.midRef(QLatin1String(PLAYER_PREFIX).size()).toInt(&bOk); - return bOk; -} - -void CommunicationInterfaceInternal::PlayerPicked(const std::string &strId) -{ - int playerId = 0; - if (isPlayerId(strId, &playerId)) { - emit signalPlayerPicked(playerId); - } else { - - QString str = QString::fromStdString(strId); - int structureElementId = str.remove(0, str.lastIndexOf(QStringLiteral("_")) + 1).toInt(); - INFO_LOG(m_logger) << "Picked mounting point with id " << strId - << " mountingPointId=" << structureElementId; - if(structureElementId < 0) { - WARNING_LOG(m_logger) << "Picked mounting point with id " << strId; - return; + for (const DeviceInfo& di : std::as_const(m_deviceMap)) + { + if (!di.deviceName.startsWith(QLatin1String("Camera"))) + continue; + if (!m_pviewerInterface->HideDeviceIcon(di.deviceName.toStdString())) + ERROR_LOG(m_logger) << "Could not remove camera with id " << di.deviceName; } - - emit signalAssetPicked(structureElementId); - } + m_deviceMap.clear(); } +void CommunicationInterfaceInternal::SystemReady() {} -void CommunicationInterfaceInternal::DisplayNamePicked(const std::string &buildingid, const std::string &roomname) +void CommunicationInterfaceInternal::TransformChanged(const std::string& id, const VCtrl::Vec3d& pos, + const VCtrl::Quat& attitude) { - - Q_UNUSED(buildingid); - Q_UNUSED(roomname); + Q_UNUSED(id); + Q_UNUSED(pos); + Q_UNUSED(attitude); } +void CommunicationInterfaceInternal::NavMeshGroupChanged(const std::string& id, const std::string& grpname) +{ + Q_UNUSED(id); + Q_UNUSED(grpname); +} + +static inline bool isPlayerId(const std::string& playerIdString, int* playerId) +{ + const QString playerIdQString(QString::fromStdString(playerIdString)); + bool bOk = false; + if (playerIdQString.startsWith(QLatin1String(PLAYER_PREFIX))) + *playerId = playerIdQString.midRef(QLatin1String(PLAYER_PREFIX).size()).toInt(&bOk); + return bOk; +} + +void CommunicationInterfaceInternal::PlayerPicked(const std::string& strId) +{ + int playerId = 0; + if (isPlayerId(strId, &playerId)) + { + emit signalPlayerPicked(playerId); + } + else + { + + QString str = QString::fromStdString(strId); + int structureElementId = str.remove(0, str.lastIndexOf(QStringLiteral("_")) + 1).toInt(); + INFO_LOG(m_logger) << "Picked mounting point with id " << strId << " mountingPointId=" << structureElementId; + if (structureElementId < 0) + { + WARNING_LOG(m_logger) << "Picked mounting point with id " << strId; + return; + } + + emit signalAssetPicked(structureElementId); + } +} + +void CommunicationInterfaceInternal::DisplayNamePicked(const std::string& buildingid, const std::string& roomname) +{ + + Q_UNUSED(buildingid); + Q_UNUSED(roomname); +} void CommunicationInterfaceInternal::ViewCreated(unsigned int contextId, VCtrl::ViewMode viewmode) { - Q_UNUSED(contextId); - Q_UNUSED(viewmode); + Q_UNUSED(contextId); + Q_UNUSED(viewmode); } void CommunicationInterfaceInternal::ViewModeChanged(unsigned int contextId, VCtrl::ViewMode viewmode) { - Q_UNUSED(contextId); - Q_UNUSED(viewmode); - emit signalViewerEventButton(); - + Q_UNUSED(contextId); + Q_UNUSED(viewmode); + emit signalViewerEventButton(); } - void CommunicationInterfaceInternal::ViewLineModeChanged(unsigned int contextId, bool line) { - Q_UNUSED(contextId); - Q_UNUSED(line); - emit signalViewerEventButton(); + Q_UNUSED(contextId); + Q_UNUSED(line); + emit signalViewerEventButton(); } - void CommunicationInterfaceInternal::ViewNameModeChanged(unsigned int contextId, bool name) { - Q_UNUSED(contextId); - Q_UNUSED(name); - emit signalViewerEventButton(); + Q_UNUSED(contextId); + Q_UNUSED(name); + emit signalViewerEventButton(); } - void CommunicationInterfaceInternal::ViewLockRotationChanged(unsigned int contextId, bool lock) { - Q_UNUSED(contextId); - Q_UNUSED(lock); - emit signalViewerEventButton(); - + Q_UNUSED(contextId); + Q_UNUSED(lock); + emit signalViewerEventButton(); } void CommunicationInterfaceInternal::ViewTransparencyChanged() { - emit signalViewerEventButton(); + emit signalViewerEventButton(); } void CommunicationInterfaceInternal::PlayerDisplayModeChanged(unsigned int contextId, VCtrl::PlayerDisplayMode mode) { - Q_UNUSED(contextId); - Q_UNUSED(mode); - emit signalViewerEventButton(); + Q_UNUSED(contextId); + Q_UNUSED(mode); + emit signalViewerEventButton(); } void CommunicationInterfaceInternal::ViewClosed(unsigned int contextId) { - Q_UNUSED(contextId); + Q_UNUSED(contextId); } - -void CommunicationInterfaceInternal::HandleViewerEvent(BgViewerEvents event, const std::vector &args) +void CommunicationInterfaceInternal::HandleViewerEvent(BgViewerEvents event, const std::vector& args) { - if (args.size() < 1) - { - Q_ASSERT(false); - return; - } - - const QString featureID = QString::fromStdString(args[0]); - switch (event) - { - case BuildingViewer::BgViewerEvents::WidgetClosed: - emit signalViewerEventWidgetClosed(featureID); - break; - case BuildingViewer::BgViewerEvents::WidgetMaximized: - emit signalViewerEventWidgetMaximized(featureID); - break; - case BuildingViewer::BgViewerEvents::WidgetMinimized: - emit signalViewerEventWidgetMinimized(featureID); - break; - case BuildingViewer::BgViewerEvents::WidgetGotFocus: - emit signalViewerEventWidgetFocused(featureID); - break; - case BuildingViewer::BgViewerEvents::RoomNameClicked: - { - if (args.size() >= 2) + if (args.size() < 1) { - const QString roomID = QString::fromStdString(args[1]); - emit signalViewerEventRoomNameClicked(featureID, roomID); + Q_ASSERT(false); + return; + } + + const QString featureID = QString::fromStdString(args[0]); + switch (event) + { + case BuildingViewer::BgViewerEvents::WidgetClosed: + emit signalViewerEventWidgetClosed(featureID); + break; + case BuildingViewer::BgViewerEvents::WidgetMaximized: + emit signalViewerEventWidgetMaximized(featureID); + break; + case BuildingViewer::BgViewerEvents::WidgetMinimized: + emit signalViewerEventWidgetMinimized(featureID); + break; + case BuildingViewer::BgViewerEvents::WidgetGotFocus: + emit signalViewerEventWidgetFocused(featureID); + break; + case BuildingViewer::BgViewerEvents::RoomNameClicked: { + if (args.size() >= 2) + { + const QString roomID = QString::fromStdString(args[1]); + emit signalViewerEventRoomNameClicked(featureID, roomID); + } + break; + } } - break; - } - } } -void CommunicationInterfaceInternal::ViewZoomChanged(const std::string &buildingId, double top, double left, double bottom, double right) +void CommunicationInterfaceInternal::ViewZoomChanged(const std::string& buildingId, double top, double left, + double bottom, double right) { - emit signalViewerZoomChanged(QString::fromStdString(buildingId), top, left, bottom, right); + emit signalViewerZoomChanged(QString::fromStdString(buildingId), top, left, bottom, right); } -void CommunicationInterfaceInternal::LogMessage(Severity &severity, const std::string &filename, const std::string &methodname, int linenumber, const std::string &msg) +void CommunicationInterfaceInternal::LogMessage(Severity& severity, const std::string& filename, + const std::string& methodname, int linenumber, const std::string& msg) { - auto logLevel = NGL::LogLevel::Info; - bool logAlways = false; - switch (severity) - { - case Severity::Always: - logAlways = true; - logLevel = NGL::LogLevel::Info; - break; - case Severity::Debug: - logLevel = NGL::LogLevel::Debug; - break; - case Severity::Info: - logLevel = NGL::LogLevel::Info; - break; - case Severity::Warning: - logLevel = NGL::LogLevel::Warning; - break; - case Severity::Error: - logLevel = NGL::LogLevel::Error; - break; - case Severity::Fatal: - logLevel = NGL::LogLevel::Fatal; - break; - } - if (logAlways || m_logger.isLevelEnabled(logLevel)) - NGL::LogStreamHelper(m_logger, logLevel, filename.c_str(), linenumber, methodname.c_str()) << msg; + auto logLevel = NGL::LogLevel::Info; + bool logAlways = false; + switch (severity) + { + case Severity::Always: + logAlways = true; + logLevel = NGL::LogLevel::Info; + break; + case Severity::Debug: + logLevel = NGL::LogLevel::Debug; + break; + case Severity::Info: + logLevel = NGL::LogLevel::Info; + break; + case Severity::Warning: + logLevel = NGL::LogLevel::Warning; + break; + case Severity::Error: + logLevel = NGL::LogLevel::Error; + break; + case Severity::Fatal: + logLevel = NGL::LogLevel::Fatal; + break; + } + if (logAlways || m_logger.isLevelEnabled(logLevel)) + NGL::LogStreamHelper(m_logger, logLevel, filename.c_str(), linenumber, methodname.c_str()) << msg; } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.h old mode 100755 new mode 100644 index a4af78bf7..8118ee775 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_communication_interface_internal.h @@ -1,29 +1,25 @@ - #pragma once - -#include #include "BgViewer/viewerCtrl/viewerinterface.h" #include "bdv_helper.h" +#include "buildingviewercommon_export.h" +#include "logger.h" +#include +#include +#include +#include #include #include #include #include #include #include -#include #include - -#include "logger.h" -#include "buildingviewercommon_export.h" -#include -#include -#include -#include - +#include +#include namespace VCtrl { @@ -34,130 +30,124 @@ namespace BuildingViewer { struct DeviceInfo { - QString deviceName; - int buildingId = 0; + QString deviceName; + int buildingId = 0; - DeviceInfo() = default; - DeviceInfo(int _buildingId, const QString &_deviceName) - : deviceName(_deviceName) - , buildingId(_buildingId) - {} + DeviceInfo() = default; + + DeviceInfo(int _buildingId, const QString& _deviceName) : deviceName(_deviceName), buildingId(_buildingId) {} }; - - class BUILDINGVIEWERCOMMON_EXPORT CommunicationInterfaceInternal final : public QObject, public VCtrl::ViewerCallback { - Q_OBJECT -public: - explicit CommunicationInterfaceInternal(VCtrl::ViewerInterface* pviewerInterface); + Q_OBJECT + public: + explicit CommunicationInterfaceInternal(VCtrl::ViewerInterface* pviewerInterface); - void playerCreate(int playerID, int partyID, const QString &strPathToSymbolFile, - const LtsUtils::QPoint3D &pos, int buildingID , int roomNumber, Core::PositionReportingSource reportingSource); - void playerPlace(int playerID, const LtsUtils::QPoint3D &pos, - int buildingID, int roomNumber, Core::PositionReportingSource reportingSource); - void playerDelete(int playerID); - void setPlayerVisible(int playerID, bool bVisible); - void playerClear(); - void playerUpdateSymbols(); - void playerUpdatePlayerSymbol(int playerID, const QString &strPathToSymbolFile); - void playerHit(const int32_t id, int playerIdSrc, int playerIdDst, - const LtsUtils::QPoint3D &posSrc, const LtsUtils::QPoint3D &posDst, - int buildingIdSrc, int roomNumberSrc, int buildingIdDst, int roomNumberDst, int lineType, - int64_t time); - void buildingHit(const int32_t id, int buildingId, int damagePercent, const QMap &mapRoomDestructions); - void roomHit(const int32_t id, int playerIdSrc, int buildingId, int roomNumber, const LtsUtils::QPoint3D &posSrc, int lineType, int64_t time); - void removeRoomHit(const int32_t id); + void playerCreate(int playerID, int partyID, const QString& strPathToSymbolFile, const LtsUtils::QPoint3D& pos, + int buildingID, int roomNumber, Core::PositionReportingSource reportingSource); + void playerPlace(int playerID, const LtsUtils::QPoint3D& pos, int buildingID, int roomNumber, + Core::PositionReportingSource reportingSource); + void playerDelete(int playerID); + void setPlayerVisible(int playerID, bool bVisible); + void playerClear(); + void playerUpdateSymbols(); + void playerUpdatePlayerSymbol(int playerID, const QString& strPathToSymbolFile); + void playerHit(const int32_t id, int playerIdSrc, int playerIdDst, const LtsUtils::QPoint3D& posSrc, + const LtsUtils::QPoint3D& posDst, int buildingIdSrc, int roomNumberSrc, int buildingIdDst, + int roomNumberDst, int lineType, int64_t time); + void buildingHit(const int32_t id, int buildingId, int damagePercent, const QMap& mapRoomDestructions); + void roomHit(const int32_t id, int playerIdSrc, int buildingId, int roomNumber, const LtsUtils::QPoint3D& posSrc, + int lineType, int64_t time); + void removeRoomHit(const int32_t id); - void setTeamConfiguration(const QMap& parties); + void setTeamConfiguration(const QMap& parties); - void systemSetSimulationTime(qint64 time); - void setSimuationPace(double pace); - void systemDisconnect(); - void systemSetPaused(bool bPaused); - void systemSetMountingPoint(const InfrastructureManagement::MountingPoint &data, const QString &filename, bool show); + void systemSetSimulationTime(qint64 time); + void setSimuationPace(double pace); + void systemDisconnect(); + void systemSetPaused(bool bPaused); + void systemSetMountingPoint(const InfrastructureManagement::MountingPoint& data, const QString& filename, + bool show); - void excConnect(const std::vector &paths, const QString &strXMLFile = QString()); - void excDeleteBuildingList(); - void excSetHitlineDuration(uint32_t duration_s); - void excUseExactPositioning(bool useExactPositioning); - void excOpenView(const std::vector &bldIds); - void excCloseView(const std::vector &bldIds); - void excCloseAllViews(); - void excStartRecording(const QString &strPathOutputFolder, const QString &buildingId = QStringLiteral("all"), - int w = 800, int h = 600, int framerate = 20, int quality = 100); - void excStopRecording(const QString &buildingId = QStringLiteral("all")); - void excHighlightView(const QString &buildingId); - void excSetGlobalTransparency(double transparency); - void excSetGlobalViewMode(bool useOrtho); - void excSetGlobalDotsMode(bool useDots); - void excGetBuildingList(); - void excRestoreViewState(const QJsonValue &val); - void excGetViewState(); - void excSetRoomDisplayName(const QString &strFeatureID, const QString &strRoomName, const QString &strRoomDisplayName); - void excSetBuildingDisplayName(const QString &buildingId, const QString &strBuildingDisplayName); - void extSetMountingPointAsset(const QString &strFeatureID, const QString &strMountingPointId, const QVector3D &position, BuildingViewer::AssetTypes assetType); - void extHideMountingPointAsset(const QString &strMountingPointId); + void excConnect(const std::vector& paths, const QString& strXMLFile = QString()); + void excDeleteBuildingList(); + void excSetHitlineDuration(uint32_t duration_s); + void excUseExactPositioning(bool useExactPositioning); + void excOpenView(const std::vector& bldIds); + void excCloseView(const std::vector& bldIds); + void excCloseAllViews(); + void excStartRecording(const QString& strPathOutputFolder, const QString& buildingId = QStringLiteral("all"), + int w = 800, int h = 600, int framerate = 20, int quality = 100); + void excStopRecording(const QString& buildingId = QStringLiteral("all")); + void excHighlightView(const QString& buildingId); + void excSetGlobalTransparency(double transparency); + void excSetGlobalViewMode(bool useOrtho); + void excSetGlobalDotsMode(bool useDots); + void excGetBuildingList(); + void excRestoreViewState(const QJsonValue& val); + void excGetViewState(); + void excSetRoomDisplayName(const QString& strFeatureID, const QString& strRoomName, + const QString& strRoomDisplayName); + void excSetBuildingDisplayName(const QString& buildingId, const QString& strBuildingDisplayName); + void extSetMountingPointAsset(const QString& strFeatureID, const QString& strMountingPointId, + const QVector3D& position, BuildingViewer::AssetTypes assetType); + void extHideMountingPointAsset(const QString& strMountingPointId); + void SystemReady() override; + void TransformChanged(const std::string& id, const VCtrl::Vec3d& pos, const VCtrl::Quat& attitude) override; + void NavMeshGroupChanged(const std::string& id, const std::string& grpname) override; + void PlayerPicked(const std::string& strId) override; + void DisplayNamePicked(const std::string& buildingid, const std::string& roomname) override; + void ViewCreated(unsigned int contextId, VCtrl::ViewMode viewmode) override; + void ViewModeChanged(unsigned int contextId, VCtrl::ViewMode viewmode) override; + void ViewLineModeChanged(unsigned int contextId, bool line) override; + void ViewNameModeChanged(unsigned int contextId, bool name) override; + void ViewLockRotationChanged(unsigned int contextId, bool lock) override; + void ViewTransparencyChanged() override; + void PlayerDisplayModeChanged(unsigned int contextId, VCtrl::PlayerDisplayMode mode) override; + void ViewClosed(unsigned int contextId) override; + void HandleViewerEvent(BuildingViewer::BgViewerEvents event, const std::vector& args) override; + void ViewZoomChanged(const std::string& buildingId, double top, double left, double bottom, double right) override; + void LogMessage(Severity& severity, const std::string& filename, const std::string& methodname, int linenumber, + const std::string& msg) override; - void SystemReady() override; - void TransformChanged(const std::string &id, const VCtrl::Vec3d &pos, const VCtrl::Quat &attitude) override; - void NavMeshGroupChanged(const std::string &id, const std::string &grpname) override; - void PlayerPicked(const std::string &strId) override; - void DisplayNamePicked(const std::string &buildingid, const std::string &roomname) override; - void ViewCreated(unsigned int contextId, VCtrl::ViewMode viewmode) override; - void ViewModeChanged(unsigned int contextId, VCtrl::ViewMode viewmode) override; - void ViewLineModeChanged(unsigned int contextId, bool line) override; - void ViewNameModeChanged(unsigned int contextId, bool name) override; - void ViewLockRotationChanged(unsigned int contextId, bool lock) override; - void ViewTransparencyChanged() override; - void PlayerDisplayModeChanged(unsigned int contextId, VCtrl::PlayerDisplayMode mode) override; - void ViewClosed(unsigned int contextId) override; - void HandleViewerEvent(BuildingViewer::BgViewerEvents event, - const std::vector &args) override; - void ViewZoomChanged(const std::string &buildingId, double top, double left, double bottom, double right) override; - void LogMessage(Severity &severity, const std::string &filename, const std::string &methodname, - int linenumber, const std::string &msg) override; + Q_SIGNALS: + void signalBgViewerInitFinished(); + void signalReceivedBuildingList(const QVector& states); + void signalReceivedViewState(const QJsonValue& state); -Q_SIGNALS: - void signalBgViewerInitFinished(); - void signalReceivedBuildingList(const QVector &states); - void signalReceivedViewState(const QJsonValue &state); + void signalPlayerPicked(int playerId); + void signalAssetPicked(int structureElementId); + void signalViewerEventWidgetClosed(const QString& featureID); + void signalViewerEventWidgetMaximized(const QString& featureID); + void signalViewerEventWidgetMinimized(const QString& featureID); + void signalViewerEventWidgetFocused(const QString& featureID); + void signalViewerEventButton(); - void signalPlayerPicked(int playerId); - void signalAssetPicked(int structureElementId); - void signalViewerEventWidgetClosed(const QString &featureID); - void signalViewerEventWidgetMaximized(const QString &featureID); - void signalViewerEventWidgetMinimized(const QString &featureID); - void signalViewerEventWidgetFocused(const QString &featureID); - void signalViewerEventButton(); + void signalViewerEventRoomNameClicked(const QString& featureID, const QString& roomID); + void signalViewerZoomChanged(const QString& featureId, double top, double left, double bottom, double right); - void signalViewerEventRoomNameClicked(const QString &featureID, const QString &roomID); - void signalViewerZoomChanged(const QString &featureId, double top, double left, double bottom, double right); + private: + NGL::INGLLogger& m_logger; + void clearCameras(); + QHash m_deviceMap; -private: - + struct BdvParty + { + QString name; + VCtrl::Color color; + int id = 0; + }; -NGL::INGLLogger &m_logger; - void clearCameras(); - QHash m_deviceMap; + QHash m_teamMap; - - struct BdvParty - { - QString name; - VCtrl::Color color; - int id = 0; - }; - QHash m_teamMap; + QHash m_player2TeamMap; + QHash m_playerId2String; + QMap m_string2PlayerId; - - QHash m_player2TeamMap; - QHash m_playerId2String; - QMap m_string2PlayerId; - - VCtrl::ViewerInterface *m_pviewerInterface = nullptr; - bool m_useExactPositioning = true; + VCtrl::ViewerInterface* m_pviewerInterface = nullptr; + bool m_useExactPositioning = true; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.cpp old mode 100755 new mode 100644 index bbe2d53bf..9e856c4a6 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.cpp @@ -1,430 +1,400 @@  - #include "bdv_controller.h" -#include -#include "bdv_dds_controller.h" -#include "bdv_bgviewer_widget_container.h" +#include "bdv_bgviewer_widget_container.h" +#include "bdv_dds_controller.h" + +#include +#include #include #include #include -#include -#include -#include - #include #include +#include +#include namespace BuildingViewer { static int argc_dummy = 1; -static char *argv_dummy[] = { (char*)"Dummy" }; +static char* argv_dummy[] = {(char*)"Dummy"}; -BgViewerController::BgViewerController(QObject *parent) - : QObject(parent) - , m_mainloop(argc_dummy, argv_dummy, nullptr) - , m_widgetStolen(false) - , m_comIfc(nullptr) - , m_pBgViewerDDSController(nullptr) - , m_bgvApp(nullptr) - , m_tickTimer(new QTimer(this)) +BgViewerController::BgViewerController(QObject* parent) + : QObject(parent), m_mainloop(argc_dummy, argv_dummy, nullptr), m_widgetStolen(false), m_comIfc(nullptr), + m_pBgViewerDDSController(nullptr), m_bgvApp(nullptr), m_tickTimer(new QTimer(this)) { - m_tickTimer->setInterval(1000 / 25); - connect(m_tickTimer, &QTimer::timeout, this, [this]() { m_mainloop.tick(); }); + m_tickTimer->setInterval(1000 / 25); + connect(m_tickTimer, &QTimer::timeout, this, [this]() { m_mainloop.tick(); }); - m_mainloop.getViewerInterface()->getMainWindow()->setMinimumSize(200, 200); + m_mainloop.getViewerInterface()->getMainWindow()->setMinimumSize(200, 200); - m_viewerInterface = m_mainloop.getViewerInterface(); - m_comIfc = new CommunicationInterfaceInternal(m_viewerInterface); - m_viewerInterface->SetViewerCallback(m_comIfc); + m_viewerInterface = m_mainloop.getViewerInterface(); + m_comIfc = new CommunicationInterfaceInternal(m_viewerInterface); + m_viewerInterface->SetViewerCallback(m_comIfc); - m_pBgViewerDDSController = new BuildingViewerDdsController(m_comIfc, m_viewerInterface); + m_pBgViewerDDSController = new BuildingViewerDdsController(m_comIfc, m_viewerInterface); - connect(m_pBgViewerDDSController, &BuildingViewerDdsController::signalDdsInitFinished, this, [this]() { - m_initExerciseWasSuccessful = true; - }); - - connect(m_comIfc, &CommunicationInterfaceInternal::signalBgViewerInitFinished, - this, &BgViewerController::signalBgViewerInitFinished); - connect(m_comIfc, &CommunicationInterfaceInternal::signalReceivedBuildingList, - this, &BgViewerController::signalReceivedBuildingList); - connect(m_comIfc, &CommunicationInterfaceInternal::signalReceivedViewState, - this, &BgViewerController::signalReceivedViewState); - connect(m_comIfc, &CommunicationInterfaceInternal::signalPlayerPicked, - this, &BgViewerController::signalPlayerPicked); - connect(m_comIfc, &CommunicationInterfaceInternal::signalAssetPicked, - this, &BgViewerController::signalAssetPicked); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetClosed, - this, &BgViewerController::signalViewerEventWidgetClosed); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetMaximized, - this, &BgViewerController::signalViewerEventWidgetMaximized); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetMinimized, - this, &BgViewerController::signalViewerEventWidgetMinimized); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetFocused, - this, &BgViewerController::signalViewerEventWidgetFocused); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventRoomNameClicked, - this, &BgViewerController::signalViewerEventRoomNameClicked); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerZoomChanged, - this, &BgViewerController::signalViewerZoomChanged); - connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventButton, - this, &BgViewerController::signalViewerEventButton); + connect(m_pBgViewerDDSController, &BuildingViewerDdsController::signalDdsInitFinished, this, + [this]() { m_initExerciseWasSuccessful = true; }); + connect(m_comIfc, &CommunicationInterfaceInternal::signalBgViewerInitFinished, this, + &BgViewerController::signalBgViewerInitFinished); + connect(m_comIfc, &CommunicationInterfaceInternal::signalReceivedBuildingList, this, + &BgViewerController::signalReceivedBuildingList); + connect(m_comIfc, &CommunicationInterfaceInternal::signalReceivedViewState, this, + &BgViewerController::signalReceivedViewState); + connect(m_comIfc, &CommunicationInterfaceInternal::signalPlayerPicked, this, + &BgViewerController::signalPlayerPicked); + connect(m_comIfc, &CommunicationInterfaceInternal::signalAssetPicked, this, &BgViewerController::signalAssetPicked); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetClosed, this, + &BgViewerController::signalViewerEventWidgetClosed); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetMaximized, this, + &BgViewerController::signalViewerEventWidgetMaximized); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetMinimized, this, + &BgViewerController::signalViewerEventWidgetMinimized); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventWidgetFocused, this, + &BgViewerController::signalViewerEventWidgetFocused); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventRoomNameClicked, this, + &BgViewerController::signalViewerEventRoomNameClicked); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerZoomChanged, this, + &BgViewerController::signalViewerZoomChanged); + connect(m_comIfc, &CommunicationInterfaceInternal::signalViewerEventButton, this, + &BgViewerController::signalViewerEventButton); } - BgViewerController::~BgViewerController() { - delete m_tickTimer; + delete m_tickTimer; - if (m_bgvApp != nullptr) - { - m_bgvApp->disconnect(); - delete m_bgvApp; - } + if (m_bgvApp != nullptr) + { + m_bgvApp->disconnect(); + delete m_bgvApp; + } - delete m_pBgViewerDDSController; - delete m_comIfc; + delete m_pBgViewerDDSController; + delete m_comIfc; - m_bgvApp = nullptr; - m_comIfc = nullptr; - m_pBgViewerDDSController = nullptr; + m_bgvApp = nullptr; + m_comIfc = nullptr; + m_pBgViewerDDSController = nullptr; } - -void BgViewerController::excConnect(const std::vector &paths, const QString &strXMLFile) +void BgViewerController::excConnect(const std::vector& paths, const QString& strXMLFile) { - if (m_comIfc) - m_comIfc->excConnect(paths, strXMLFile); + if (m_comIfc) + m_comIfc->excConnect(paths, strXMLFile); } void BgViewerController::excGetBuildingList() { - if (m_comIfc) - m_comIfc->excGetBuildingList(); + if (m_comIfc) + m_comIfc->excGetBuildingList(); } void BgViewerController::excGetViewState() { - if (m_comIfc) - m_comIfc->excGetViewState(); + if (m_comIfc) + m_comIfc->excGetViewState(); } -void BgViewerController::excHighlightView(const QString &strFeatureID) +void BgViewerController::excHighlightView(const QString& strFeatureID) { - if (m_comIfc) - m_comIfc->excHighlightView(strFeatureID); + if (m_comIfc) + m_comIfc->excHighlightView(strFeatureID); } -void BgViewerController::excRestoreViewState(const QJsonValue &state) +void BgViewerController::excRestoreViewState(const QJsonValue& state) { - if (m_comIfc) - { - m_comIfc->excRestoreViewState(state); - m_comIfc->excGetBuildingList(); - } + if (m_comIfc) + { + m_comIfc->excRestoreViewState(state); + m_comIfc->excGetBuildingList(); + } } void BgViewerController::excSetGlobalDotsMode(bool useDots) { - if (m_comIfc) - m_comIfc->excSetGlobalDotsMode(useDots); + if (m_comIfc) + m_comIfc->excSetGlobalDotsMode(useDots); } void BgViewerController::excSetGlobalTransparency(double transparency) { - if (m_comIfc) - m_comIfc->excSetGlobalTransparency(transparency); + if (m_comIfc) + m_comIfc->excSetGlobalTransparency(transparency); } void BgViewerController::excSetGlobalViewMode(bool useOrtho) { - if (m_comIfc) - m_comIfc->excSetGlobalViewMode(useOrtho); + if (m_comIfc) + m_comIfc->excSetGlobalViewMode(useOrtho); } void BgViewerController::excSetHitlineDuration(uint32_t duration_s) { - if (m_comIfc) - m_comIfc->excSetHitlineDuration(duration_s); + if (m_comIfc) + m_comIfc->excSetHitlineDuration(duration_s); } -void BgViewerController::excStartRecording(const QString &strPathOutputFolder, - const QString &strFeatureID, - int w, int h, int framerate, int quality) +void BgViewerController::excStartRecording(const QString& strPathOutputFolder, const QString& strFeatureID, int w, + int h, int framerate, int quality) { - if (m_comIfc) - m_comIfc->excStartRecording(strPathOutputFolder, strFeatureID, w, h, framerate, quality); + if (m_comIfc) + m_comIfc->excStartRecording(strPathOutputFolder, strFeatureID, w, h, framerate, quality); } -void BgViewerController::excStopRecording(const QString &strFeatureID) +void BgViewerController::excStopRecording(const QString& strFeatureID) { - if (m_comIfc) - m_comIfc->excStopRecording(strFeatureID); + if (m_comIfc) + m_comIfc->excStopRecording(strFeatureID); } QString BgViewerController::buildingModelPath() { - QVector directoriesToSearch = NGL::directories(NGL::FileType::ConfigFile); + QVector directoriesToSearch = NGL::directories(NGL::FileType::ConfigFile); #ifndef WIN32 - directoriesToSearch += QStringLiteral("/opt"); + directoriesToSearch += QStringLiteral("/opt"); #endif - for (const QString &d : std::as_const(directoriesToSearch)) - { - const QDir dir(d + QStringLiteral("/BuildingModels/StaticMeshes/")); - if (dir.exists() && dir.isReadable()) - return dir.absolutePath(); - INFO_LOG(getLogger("BgViewerController")) << "Map path '" << dir.absolutePath() << "' either does not exist or is not readable - skipping"; - } - return QString(); + for (const QString& d : std::as_const(directoriesToSearch)) + { + const QDir dir(d + QStringLiteral("/BuildingModels/StaticMeshes/")); + if (dir.exists() && dir.isReadable()) + return dir.absolutePath(); + INFO_LOG(getLogger("BgViewerController")) + << "Map path '" << dir.absolutePath() << "' either does not exist or is not readable - skipping"; + } + return QString(); } -void BgViewerController::clearInterfaces(const LtsSession::DdsConnectionParams &conParams) +void BgViewerController::clearInterfaces(const LtsSession::DdsConnectionParams& conParams) { - DEBUG_LOG(m_logger) << "BgViewerControllerSingleton::clearInterfaces()"; - if (m_pBgViewerDDSController && m_currentDdsConnParams == conParams) - { - m_pBgViewerDDSController->uninitialize(); - m_currentDdsConnParams = LtsSession::DdsConnectionParams(); - } -} - - -void BgViewerController::hideLiveVideo() -{ - - - + DEBUG_LOG(m_logger) << "BgViewerControllerSingleton::clearInterfaces()"; + if (m_pBgViewerDDSController && m_currentDdsConnParams == conParams) + { + m_pBgViewerDDSController->uninitialize(); + m_currentDdsConnParams = LtsSession::DdsConnectionParams(); + } } +void BgViewerController::hideLiveVideo() {} bool BgViewerController::isBgViewerApplicationRunning() const { - return (m_bgvApp != nullptr); + return (m_bgvApp != nullptr); } - LtsSession::DdsConnectionParams BgViewerController::currentDdsConnParams() const { - return m_currentDdsConnParams; + return m_currentDdsConnParams; } - -PluginProvider *BgViewerController::activeSession() const +PluginProvider* BgViewerController::activeSession() const { - return m_pBgViewerDDSController->activeSession(); + return m_pBgViewerDDSController->activeSession(); } - -bool BgViewerController::init(PluginProvider *pSession, bool bStartRendering, const QString &modelPath) +bool BgViewerController::init(PluginProvider* pSession, bool bStartRendering, const QString& modelPath) { - DEBUG_LOG(m_logger) << "getDdsController init: " << pSession->toString(); + DEBUG_LOG(m_logger) << "getDdsController init: " << pSession->toString(); - if (m_currentDdsConnParams == pSession->connParams()) - { - if (m_initExerciseWasSuccessful) + if (m_currentDdsConnParams == pSession->connParams()) { - DEBUG_LOG(m_logger) << "BgViewerControllerSingleton::init Already initialized"; - slotLoadBuilding(); + if (m_initExerciseWasSuccessful) + { + DEBUG_LOG(m_logger) << "BgViewerControllerSingleton::init Already initialized"; + slotLoadBuilding(); + } + return true; + } - - + m_currentDdsConnParams = pSession->connParams(); + m_initExerciseWasSuccessful = false; + if (!m_pBgViewerDDSController->init(m_bgViewerBaseLayoutWidget, modelPath, pSession)) + return false; + if (bStartRendering) + { + m_bgvAppIsInitialized = true; + m_tickTimer->start(); } return true; - } - - m_currentDdsConnParams = pSession->connParams(); - m_initExerciseWasSuccessful = false; - if (!m_pBgViewerDDSController->init(m_bgViewerBaseLayoutWidget, modelPath, pSession)) - return false; - if (bStartRendering) - { - m_bgvAppIsInitialized = true; - m_tickTimer->start(); - } - return true; } -bool BgViewerController::forceInit(PluginProvider *pSession) +bool BgViewerController::forceInit(PluginProvider* pSession) { - delete m_pBgViewerDDSController; - m_pBgViewerDDSController = new BuildingViewerDdsController(m_comIfc, m_viewerInterface); - - DEBUG_LOG(m_logger) << "FORCE INIT! with " << pSession; - return (m_pBgViewerDDSController->init(m_bgViewerBaseLayoutWidget, buildingModelPath(), pSession)); + delete m_pBgViewerDDSController; + m_pBgViewerDDSController = new BuildingViewerDdsController(m_comIfc, m_viewerInterface); + DEBUG_LOG(m_logger) << "FORCE INIT! with " << pSession; + return (m_pBgViewerDDSController->init(m_bgViewerBaseLayoutWidget, buildingModelPath(), pSession)); } void BgViewerController::showBgViewerInfoMessageBox() { - static bool showMsgBox = true; + static bool showMsgBox = true; - if (!showMsgBox) - return; + if (!showMsgBox) + return; - QMessageBox msgbox; - msgbox.setText(tr("BuildingViewer is currently used by another application.\nPlease close the corresponding application.")); - msgbox.setIcon(QMessageBox::Information); - msgbox.addButton(QMessageBox::Ok); + QMessageBox msgbox; + msgbox.setText( + tr("BuildingViewer is currently used by another application.\nPlease close the corresponding application.")); + msgbox.setIcon(QMessageBox::Information); + msgbox.addButton(QMessageBox::Ok); - QCheckBox *cb = new QCheckBox(tr("Do not show this message again.")); - msgbox.setCheckBox(cb); + QCheckBox* cb = new QCheckBox(tr("Do not show this message again.")); + msgbox.setCheckBox(cb); - connect(cb, &QCheckBox::stateChanged, [](int state) { - showMsgBox = state != Qt::Checked; - }); + connect(cb, &QCheckBox::stateChanged, [](int state) { showMsgBox = state != Qt::Checked; }); - msgbox.exec(); + msgbox.exec(); } - bool BgViewerController::startBgViewerAppInSession(PluginProvider* pStartingSession) { - DEBUG_LOG(m_logger) << std::hex << this << " startBgViewerAppInSession " << (m_currentDdsConnParams == pStartingSession->connParams()); + DEBUG_LOG(m_logger) << std::hex << this << " startBgViewerAppInSession " + << (m_currentDdsConnParams == pStartingSession->connParams()); - if (m_bgvApp && (m_currentDdsConnParams == pStartingSession->connParams())) - { - INFO_LOG(m_logger) << std::hex << this << " BuildingViewer already opened. Doing nothing..."; - return true; - } + if (m_bgvApp && (m_currentDdsConnParams == pStartingSession->connParams())) + { + INFO_LOG(m_logger) << std::hex << this << " BuildingViewer already opened. Doing nothing..."; + return true; + } - - if (!m_bgvApp && m_widgetStolen) - { - showBgViewerInfoMessageBox(); - return false; - } + if (!m_bgvApp && m_widgetStolen) + { + showBgViewerInfoMessageBox(); + return false; + } - if (m_bgvApp) - { - DEBUG_LOG(m_logger) << std::hex << this << " Releasing m_bgvApp"; - delete m_bgvApp; - m_bgvApp = nullptr; - - clearInterfaces(m_currentDdsConnParams); - m_comIfc->excCloseAllViews(); - } - - m_bgvAppIsInitialized = false; - m_bgvApp = LtsAppManager::LtsAppManager::getInstance()->createApp(LtsAppDescriptor::App::BuildingViewer, pStartingSession->connParams()); - if (!m_bgvApp || !m_bgvApp->sessions().size()) - { - ERROR_LOG(m_logger) << std::hex << this << " m_bgvApp is nullptr or has no associated session!"; - return false; - } - - connect(m_bgvApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, - this, [this, pStartingSession]() - { - m_tickTimer->start(); - m_bgvAppIsInitialized = true; - - QWidget *w = nullptr; if (m_bgvApp) { - LtsSession::LtsSession *session = m_bgvApp->getSession(pStartingSession->connParams().partitionType, pStartingSession->connParams().partitionId); - w = session->baseLayoutWidget(); + DEBUG_LOG(m_logger) << std::hex << this << " Releasing m_bgvApp"; + delete m_bgvApp; + m_bgvApp = nullptr; + + clearInterfaces(m_currentDdsConnParams); + m_comIfc->excCloseAllViews(); } - m_bgViewerBaseLayoutWidget = w; - slotLoadBuilding(); - emit bgvAppIsInitialized(); - }); - - connect(m_bgvApp, &LtsPluginManager::LtsPluginManager::destroyed, - this, [this]() - { - DEBUG_LOG(m_logger) << std::hex << this << " LtsPluginManager destroyed m_bgvApp"; - m_tickTimer->stop(); - clearInterfaces(m_currentDdsConnParams); - m_comIfc->excCloseAllViews(); m_bgvAppIsInitialized = false; - m_bgvApp = nullptr; - m_bgViewerBaseLayoutWidget = nullptr; - }); + m_bgvApp = LtsAppManager::LtsAppManager::getInstance()->createApp(LtsAppDescriptor::App::BuildingViewer, + pStartingSession->connParams()); + if (!m_bgvApp || !m_bgvApp->sessions().size()) + { + ERROR_LOG(m_logger) << std::hex << this << " m_bgvApp is nullptr or has no associated session!"; + return false; + } - return true; + connect(m_bgvApp, &LtsPluginManager::LtsPluginManager::signalInitializationFinished, this, + [this, pStartingSession]() { + m_tickTimer->start(); + m_bgvAppIsInitialized = true; + + QWidget* w = nullptr; + if (m_bgvApp) + { + LtsSession::LtsSession* session = m_bgvApp->getSession(pStartingSession->connParams().partitionType, + pStartingSession->connParams().partitionId); + w = session->baseLayoutWidget(); + } + m_bgViewerBaseLayoutWidget = w; + + slotLoadBuilding(); + emit bgvAppIsInitialized(); + }); + + connect(m_bgvApp, &LtsPluginManager::LtsPluginManager::destroyed, this, [this]() { + DEBUG_LOG(m_logger) << std::hex << this << " LtsPluginManager destroyed m_bgvApp"; + m_tickTimer->stop(); + clearInterfaces(m_currentDdsConnParams); + m_comIfc->excCloseAllViews(); + m_bgvAppIsInitialized = false; + m_bgvApp = nullptr; + m_bgViewerBaseLayoutWidget = nullptr; + }); + + return true; } - -QWidget *BgViewerController::getBgViewerWidget() +QWidget* BgViewerController::getBgViewerWidget() { - if (m_widgetStolen) - { - showBgViewerInfoMessageBox(); - return nullptr; - } + if (m_widgetStolen) + { + showBgViewerInfoMessageBox(); + return nullptr; + } - BgViewerWidgetContainer *pDummy = new BgViewerWidgetContainer(m_mainloop.getViewerInterface()->getMainWindow()); + BgViewerWidgetContainer* pDummy = new BgViewerWidgetContainer(m_mainloop.getViewerInterface()->getMainWindow()); - m_widgetStolen = true; - connect(pDummy, &BgViewerWidgetContainer::signalWidgetReleased, this, &BgViewerController::slotWidgetReleased); - return pDummy; + m_widgetStolen = true; + connect(pDummy, &BgViewerWidgetContainer::signalWidgetReleased, this, &BgViewerController::slotWidgetReleased); + return pDummy; } void BgViewerController::slotWidgetReleased() { - m_widgetStolen = false; + m_widgetStolen = false; } -void BgViewerController::openBuilding(const QString &strBuildingFeatureId) +void BgViewerController::openBuilding(const QString& strBuildingFeatureId) { - m_buildingsToShow.push_back(strBuildingFeatureId.toStdString()); - slotLoadBuilding(); + m_buildingsToShow.push_back(strBuildingFeatureId.toStdString()); + slotLoadBuilding(); } -void BgViewerController::closeBuilding(const QString &strBuildingFeatureId) +void BgViewerController::closeBuilding(const QString& strBuildingFeatureId) { - if (!strBuildingFeatureId.isEmpty()) - { - const std::string s = strBuildingFeatureId.toStdString(); - m_buildingsToShow.erase(std::remove_if(m_buildingsToShow.begin(), m_buildingsToShow.end(), - [s](const std::string &str) { return s == str;}), m_buildingsToShow.end()); - } - else - m_buildingsToShow.clear(); - - if (m_comIfc) - { - if (strBuildingFeatureId.isEmpty()) - m_comIfc->excCloseAllViews(); + if (!strBuildingFeatureId.isEmpty()) + { + const std::string s = strBuildingFeatureId.toStdString(); + m_buildingsToShow.erase(std::remove_if(m_buildingsToShow.begin(), m_buildingsToShow.end(), + [s](const std::string& str) { return s == str; }), + m_buildingsToShow.end()); + } else - m_comIfc->excCloseView({strBuildingFeatureId.toStdString()}); - m_comIfc->excGetBuildingList(); - } + m_buildingsToShow.clear(); + + if (m_comIfc) + { + if (strBuildingFeatureId.isEmpty()) + m_comIfc->excCloseAllViews(); + else + m_comIfc->excCloseView({strBuildingFeatureId.toStdString()}); + m_comIfc->excGetBuildingList(); + } } void BgViewerController::updatePlayerSymbols(int size) { - m_pBgViewerDDSController->updatePlayerSymbols(size); + m_pBgViewerDDSController->updatePlayerSymbols(size); } void BgViewerController::closeAll() { - m_bgvApp->deleteLater(); + m_bgvApp->deleteLater(); } - - void BgViewerController::slotLoadBuilding() { - if (!m_bgvAppIsInitialized) - return; - m_comIfc->excOpenView(m_buildingsToShow); - m_comIfc->excGetBuildingList(); - m_buildingsToShow.clear(); + if (!m_bgvAppIsInitialized) + return; + m_comIfc->excOpenView(m_buildingsToShow); + m_comIfc->excGetBuildingList(); + m_buildingsToShow.clear(); } -void BgViewerController::slotStartRecording(const QString &strFolderPath, const QJsonValue &state) +void BgViewerController::slotStartRecording(const QString& strFolderPath, const QJsonValue& state) { - excRestoreViewState(state); - excStartRecording(strFolderPath, QStringLiteral("all"), 800, 600, 15, 40); + excRestoreViewState(state); + excStartRecording(strFolderPath, QStringLiteral("all"), 800, 600, 15, 40); } void BgViewerController::slotStopRecording() { - excStopRecording(); + excStopRecording(); } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.h old mode 100755 new mode 100644 index 6b210c18a..c9f2f7deb --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_controller.h @@ -1,30 +1,27 @@ - #pragma once - -#include -#include -#include - -#include "buildingviewercommon_export.h" -#include -#include -#include -#include -#include "logger.h" -#include "bdv_helper.h" #include "BgViewer/viewerCtrl/mainloop.h" +#include "bdv_helper.h" +#include "buildingviewercommon_export.h" +#include "logger.h" + +#include +#include +#include +#include +#include +#include +#include class QWidget; + namespace LtsPluginManager { class LtsPluginManager; } - - namespace BuildingViewer { class CommunicationInterfaceInternal; @@ -33,96 +30,93 @@ class PluginProvider; class BUILDINGVIEWERCOMMON_EXPORT BgViewerController : public QObject { - Q_OBJECT -public: - explicit BgViewerController(QObject *parent = nullptr); - ~BgViewerController(); + Q_OBJECT + public: + explicit BgViewerController(QObject* parent = nullptr); + ~BgViewerController(); - void clearInterfaces(const LtsSession::DdsConnectionParams &conParams); + void clearInterfaces(const LtsSession::DdsConnectionParams& conParams); - bool isBgViewerApplicationRunning() const; - LtsSession::DdsConnectionParams currentDdsConnParams() const; + bool isBgViewerApplicationRunning() const; + LtsSession::DdsConnectionParams currentDdsConnParams() const; - bool startBgViewerAppInSession(PluginProvider *pStartingSession); - void openBuilding(const QString &strBuildingFeatureId); - void closeBuilding(const QString &strBuildingFeatureId = QString()); - bool forceInit(PluginProvider *pSession); - void updatePlayerSymbols(int size); - void closeAll(); - - QWidget *getBgViewerWidget(); - bool init(PluginProvider *pSession, bool bStartRendering = false, const QString &modelPath = buildingModelPath()); - PluginProvider *activeSession() const; + bool startBgViewerAppInSession(PluginProvider* pStartingSession); + void openBuilding(const QString& strBuildingFeatureId); + void closeBuilding(const QString& strBuildingFeatureId = QString()); + bool forceInit(PluginProvider* pSession); + void updatePlayerSymbols(int size); + void closeAll(); - - void excConnect(const std::vector &paths, const QString &strXMLFile = QString()); - void excGetBuildingList(); - void excGetViewState(); - void excHighlightView(const QString &strFeatureID); - void excRestoreViewState(const QJsonValue &state); - void excSetGlobalDotsMode(bool useDots); - void excSetGlobalTransparency(double transparency); - void excSetGlobalViewMode(bool useOrtho); - void excSetHitlineDuration(uint32_t duration_s); - void excStartRecording(const QString &strPathOutputFolder, - const QString &strFeatureID = QStringLiteral("all"), - int w = 800, int h = 600, - int framerate = 20, int quality = 100); - void excStopRecording(const QString &strFeatureID = QStringLiteral("all")); + QWidget* getBgViewerWidget(); + bool init(PluginProvider* pSession, bool bStartRendering = false, const QString& modelPath = buildingModelPath()); + PluginProvider* activeSession() const; - static QString buildingModelPath(); + void excConnect(const std::vector& paths, const QString& strXMLFile = QString()); + void excGetBuildingList(); + void excGetViewState(); + void excHighlightView(const QString& strFeatureID); + void excRestoreViewState(const QJsonValue& state); + void excSetGlobalDotsMode(bool useDots); + void excSetGlobalTransparency(double transparency); + void excSetGlobalViewMode(bool useOrtho); + void excSetHitlineDuration(uint32_t duration_s); + void excStartRecording(const QString& strPathOutputFolder, const QString& strFeatureID = QStringLiteral("all"), + int w = 800, int h = 600, int framerate = 20, int quality = 100); + void excStopRecording(const QString& strFeatureID = QStringLiteral("all")); - LtsPluginManager::LtsPluginManager *app() { return m_bgvApp; } + static QString buildingModelPath(); -Q_SIGNALS: - void bgvAppIsInitialized(); + LtsPluginManager::LtsPluginManager* app() + { + return m_bgvApp; + } - - void signalBgViewerInitFinished(); - void signalReceivedBuildingList(const QVector &list); - void signalReceivedViewState(const QJsonValue &state); + Q_SIGNALS: + void bgvAppIsInitialized(); - void signalViewerEventButton(); - void signalPlayerPicked(int playerId); - void signalAssetPicked(int structureElementId); - void signalViewerEventWidgetClosed(const QString &featureID); - void signalViewerEventWidgetMaximized(const QString &featureID); - void signalViewerEventWidgetMinimized(const QString &featureID); - void signalViewerEventWidgetFocused(const QString &featureID); - void signalViewerEventRoomNameClicked(const QString &featureID, const QString &roomID); - void signalViewerZoomChanged(const QString &featureId, double top, double left, double bottom, double right); + void signalBgViewerInitFinished(); + void signalReceivedBuildingList(const QVector& list); + void signalReceivedViewState(const QJsonValue& state); -public slots: - void slotStartRecording(const QString &strFolderPath, const QJsonValue &state); - void slotStopRecording(); - void hideLiveVideo(); + void signalViewerEventButton(); + void signalPlayerPicked(int playerId); + void signalAssetPicked(int structureElementId); + void signalViewerEventWidgetClosed(const QString& featureID); + void signalViewerEventWidgetMaximized(const QString& featureID); + void signalViewerEventWidgetMinimized(const QString& featureID); + void signalViewerEventWidgetFocused(const QString& featureID); + void signalViewerEventRoomNameClicked(const QString& featureID, const QString& roomID); + void signalViewerZoomChanged(const QString& featureId, double top, double left, double bottom, double right); -private slots: - void slotLoadBuilding(); - void slotWidgetReleased(); + public slots: + void slotStartRecording(const QString& strFolderPath, const QJsonValue& state); + void slotStopRecording(); + void hideLiveVideo(); -private: + private slots: + void slotLoadBuilding(); + void slotWidgetReleased(); -NGL::INGLLogger &m_logger; - void showBgViewerInfoMessageBox(); + private: + NGL::INGLLogger& m_logger; + void showBgViewerInfoMessageBox(); -private: - VCtrl::MainLoop m_mainloop; - bool m_widgetStolen; + private: + VCtrl::MainLoop m_mainloop; + bool m_widgetStolen; - std::vector m_buildingsToShow; - CommunicationInterfaceInternal *m_comIfc{nullptr}; - VCtrl::ViewerInterface *m_viewerInterface{nullptr}; - BuildingViewerDdsController *m_pBgViewerDDSController; + std::vector m_buildingsToShow; + CommunicationInterfaceInternal* m_comIfc{nullptr}; + VCtrl::ViewerInterface* m_viewerInterface{nullptr}; + BuildingViewerDdsController* m_pBgViewerDDSController; - bool m_initExerciseWasSuccessful{false}; - LtsSession::DdsConnectionParams m_currentDdsConnParams; - LtsPluginManager::LtsPluginManager *m_bgvApp; + bool m_initExerciseWasSuccessful{false}; + LtsSession::DdsConnectionParams m_currentDdsConnParams; + LtsPluginManager::LtsPluginManager* m_bgvApp; - bool m_bgvAppIsInitialized{false}; + bool m_bgvAppIsInitialized{false}; - QTimer *m_tickTimer{nullptr}; - QWidget *m_bgViewerBaseLayoutWidget{nullptr}; + QTimer* m_tickTimer{nullptr}; + QWidget* m_bgViewerBaseLayoutWidget{nullptr}; }; -} - +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.cpp old mode 100755 new mode 100644 index 1bebf5e9f..c3a7bc99b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.cpp @@ -1,22 +1,19 @@ - #include "bdv_dds_controller.h" -#include -#include -#include -#include -#include -#include -#include -#include +#include "bdv_communication_interface_internal.h" +#include "bdv_controller.h" #include "bdv_helper.h" #include "bdv_plugin_provider.h" -#include "bdv_controller.h" #include "logger.h" -#include "bdv_communication_interface_internal.h" +#include +#include +#include +#include +#include +#include #include #include #include @@ -27,1663 +24,1585 @@ #include #include #include +#include +#include namespace BuildingViewer { static inline QString gStrSymbolFolderPath() { - return QDir::tempPath() + QStringLiteral("/excon_bgviewer_symbols/"); + return QDir::tempPath() + QStringLiteral("/excon_bgviewer_symbols/"); } -BuildingViewerDdsController::BuildingViewerDdsController(CommunicationInterfaceInternal *connection, VCtrl::ViewerInterface* viewerInterface) : m_connection(connection) - , m_viewerInterface(viewerInterface), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} - +BuildingViewerDdsController::BuildingViewerDdsController(CommunicationInterfaceInternal* connection, + VCtrl::ViewerInterface* viewerInterface) + : m_connection(connection), m_viewerInterface(viewerInterface), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} BuildingViewerDdsController::~BuildingViewerDdsController() { - stopAndClearTimer(); - QDir dir(gStrSymbolFolderPath()); - dir.removeRecursively(); - QFile::remove(getBuildingConfigurationXml()); + stopAndClearTimer(); + QDir dir(gStrSymbolFolderPath()); + dir.removeRecursively(); + QFile::remove(getBuildingConfigurationXml()); } - -bool BuildingViewerDdsController::init(QWidget *irreplacableWidget, const QString &modelPath, PluginProvider *session) +bool BuildingViewerDdsController::init(QWidget* irreplacableWidget, const QString& modelPath, PluginProvider* session) { - DEBUG_LOG(m_logger) << "BDV:: init"; - m_session = session; - m_irreplacableWidget = irreplacableWidget; - + DEBUG_LOG(m_logger) << "BDV:: init"; + m_session = session; + m_irreplacableWidget = irreplacableWidget; - m_buildingHeight.clear(); + m_buildingHeight.clear(); - if (!m_session) - { - ERROR_LOG(m_logger) << "No m_session for BuildingViewerController!"; - return false; - } - - connect(m_session, &PluginProvider::destroyed, this, [this]() - { - if (static_cast(m_session) == sender()) + if (!m_session) { - - m_session = nullptr; - DEBUG_LOG(m_logger) << getSessionInfo() << "BDV:: BuildingViewerDdsController: m_session has been destroyed!"; - stopAndClearTimer(); - uninitialize(); + ERROR_LOG(m_logger) << "No m_session for BuildingViewerController!"; + return false; } - }); - - m_asbIfc = session->asbIfc(); - if (!m_asbIfc) - { - ERROR_LOG(m_logger) << "Fetching 'm_asbIfc' failed!"; - return false; - } - m_bldDtc = session->bldDtc(); - if (!m_bldDtc) - { - ERROR_LOG(m_logger) << "Fetching 'm_bldDtc' failed!"; - return false; - } + connect(m_session, &PluginProvider::destroyed, this, [this]() { + if (static_cast(m_session) == sender()) + { - m_ismDtc = session->ismDtc(); - if (!m_ismDtc) - { - ERROR_LOG(m_logger) << "Fetching 'm_ismDtc' failed!"; - return false; - } + m_session = nullptr; + DEBUG_LOG(m_logger) << getSessionInfo() + << "BDV:: BuildingViewerDdsController: m_session has been destroyed!"; + stopAndClearTimer(); + uninitialize(); + } + }); - m_pdmDtc = session->pdmDtc(); - if (!m_pdmDtc) - { - ERROR_LOG(m_logger) << "Fetching 'm_pdmDtc' failed!"; - return false; - } - - m_ismIfc = session->ismDataIfc(); - if (!m_ismIfc) - { - WARNING_LOG(m_logger) << "Fetching 'm_ismIfc' failed!"; - return false; - } - connect(m_ismIfc.get(), &InfrastructureManagement::ForeignDataInterface::mountingPointChanged, - this, &BuildingViewerDdsController::onMountingPointChanged); - - - m_avmIfc = session->avmDataIfc(); - m_blgGuiIfc = session->bldInfoIfc(); - m_ppmGuiIfc = session->ppmParticipantInfoIfc(); - m_aesDtc = session->aesDtc(); - m_ppmDtc = session->ppmDtc(); - m_srpDtc = session->srpDtc(); - - - - m_exerciseId = m_session->exerciseId(); - - - QDir dir(gStrSymbolFolderPath()); - dir.removeRecursively(); - - if (!dir.mkpath(QStringLiteral("."))) - { - ERROR_LOG(m_logger) << getSessionInfo() << "Could not create path \"" << gStrSymbolFolderPath() << "\" which is required to store BgViewer symbol files!"; - return false; - } - - connect(m_connection, &CommunicationInterfaceInternal::signalPlayerPicked, this, &BuildingViewerDdsController::onPlayerPicked, Qt::UniqueConnection); - connect(m_connection, &CommunicationInterfaceInternal::signalAssetPicked, this, &BuildingViewerDdsController::onAssetPicked, Qt::UniqueConnection); - connect(m_connection, &CommunicationInterfaceInternal::signalBgViewerInitFinished, this, &BuildingViewerDdsController::onBgViewerInitFinished, Qt::UniqueConnection); - - INFO_LOG(m_logger) << getSessionInfo() << "BuildingViewerDdsController::init: The order of the following output must be [1],[2],[3],[4],[5],[6]"; - - - - setCurrentTrainingAreaMap(modelPath); - - if (m_session->isReplayPartition()) - { - if (m_reCheckTimer) + m_asbIfc = session->asbIfc(); + if (!m_asbIfc) { - m_reCheckTimer->stop(); - delete m_reCheckTimer; - m_reCheckTimer = nullptr; + ERROR_LOG(m_logger) << "Fetching 'm_asbIfc' failed!"; + return false; } - m_reCheckTimer = new QTimer(this); - connect(m_reCheckTimer, &QTimer::timeout, this, &BuildingViewerDdsController::reCheckHitLine); - m_reCheckTimer->start(5000); - - }else - { - m_connection->setSimuationPace(1.0); - } - return true; + m_bldDtc = session->bldDtc(); + if (!m_bldDtc) + { + ERROR_LOG(m_logger) << "Fetching 'm_bldDtc' failed!"; + return false; + } + + m_ismDtc = session->ismDtc(); + if (!m_ismDtc) + { + ERROR_LOG(m_logger) << "Fetching 'm_ismDtc' failed!"; + return false; + } + + m_pdmDtc = session->pdmDtc(); + if (!m_pdmDtc) + { + ERROR_LOG(m_logger) << "Fetching 'm_pdmDtc' failed!"; + return false; + } + + m_ismIfc = session->ismDataIfc(); + if (!m_ismIfc) + { + WARNING_LOG(m_logger) << "Fetching 'm_ismIfc' failed!"; + return false; + } + connect(m_ismIfc.get(), &InfrastructureManagement::ForeignDataInterface::mountingPointChanged, this, + &BuildingViewerDdsController::onMountingPointChanged); + + m_avmIfc = session->avmDataIfc(); + m_blgGuiIfc = session->bldInfoIfc(); + m_ppmGuiIfc = session->ppmParticipantInfoIfc(); + m_aesDtc = session->aesDtc(); + m_ppmDtc = session->ppmDtc(); + m_srpDtc = session->srpDtc(); + + m_exerciseId = m_session->exerciseId(); + + QDir dir(gStrSymbolFolderPath()); + dir.removeRecursively(); + + if (!dir.mkpath(QStringLiteral("."))) + { + ERROR_LOG(m_logger) << getSessionInfo() << "Could not create path \"" << gStrSymbolFolderPath() + << "\" which is required to store BgViewer symbol files!"; + return false; + } + + connect(m_connection, &CommunicationInterfaceInternal::signalPlayerPicked, this, + &BuildingViewerDdsController::onPlayerPicked, Qt::UniqueConnection); + connect(m_connection, &CommunicationInterfaceInternal::signalAssetPicked, this, + &BuildingViewerDdsController::onAssetPicked, Qt::UniqueConnection); + connect(m_connection, &CommunicationInterfaceInternal::signalBgViewerInitFinished, this, + &BuildingViewerDdsController::onBgViewerInitFinished, Qt::UniqueConnection); + + INFO_LOG(m_logger) + << getSessionInfo() + << "BuildingViewerDdsController::init: The order of the following output must be [1],[2],[3],[4],[5],[6]"; + + setCurrentTrainingAreaMap(modelPath); + + if (m_session->isReplayPartition()) + { + if (m_reCheckTimer) + { + m_reCheckTimer->stop(); + delete m_reCheckTimer; + m_reCheckTimer = nullptr; + } + m_reCheckTimer = new QTimer(this); + connect(m_reCheckTimer, &QTimer::timeout, this, &BuildingViewerDdsController::reCheckHitLine); + m_reCheckTimer->start(5000); + } + else + { + m_connection->setSimuationPace(1.0); + } + + return true; } - void BuildingViewerDdsController::onBgViewerInitFinished() { - DEBUG_LOG(m_logger) << "onBgViewerInitFinished"; + DEBUG_LOG(m_logger) << "onBgViewerInitFinished"; - INFO_LOG(m_logger) << getSessionInfo() << "[2] Training area initialization acknowledged by BgViewer"; - INFO_LOG(m_logger) << getSessionInfo() << "[3] Sending mounting points, teams, ..., to BgViewer"; + INFO_LOG(m_logger) << getSessionInfo() << "[2] Training area initialization acknowledged by BgViewer"; + INFO_LOG(m_logger) << getSessionInfo() << "[3] Sending mounting points, teams, ..., to BgViewer"; - if (!m_pSimTimeSyncTimer) - { - m_pSimTimeSyncTimer = new QTimer(this); - m_pSimTimeSyncTimer->setInterval(m_bgviewer_simSyncTimeInterval_ms); - connect(m_pSimTimeSyncTimer, &QTimer::timeout, this, &BuildingViewerDdsController::onSynchronizeSimulationTime); - } - m_pSimTimeSyncTimer->start(); - onSynchronizeSimulationTime(); - - syncTeams(); - setPaused(false); - - sendAssets(); - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool useExactPositioning = ps->value(QStringLiteral("bld"), QStringLiteral("useExactPositioning")).toBool(); - m_connection->excUseExactPositioning(useExactPositioning); - - INFO_LOG(m_logger) << getSessionInfo() << "[4] Getting building DDS data ('mainStructureElements')"; - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, - this, &BuildingViewerDdsController::onMainStructureElementChanged); - - m_ismDtc->mainStructureElements([this](const InfrastructureManagement::MainStructureElement & data) - { - onMainStructureElementChanged(data, DataModification::eAdded); - }); - INFO_LOG(m_logger) << getSessionInfo() << "\t[4.1] Done"; - - INFO_LOG(m_logger) << getSessionInfo() << "[5] Creating participants"; - - createParticipants(); - INFO_LOG(m_logger) << getSessionInfo() << "\t[5.1] Done"; - INFO_LOG(m_logger) << getSessionInfo() << "[5] Creating Booby Trap"; - createBoobyTraps(); - INFO_LOG(m_logger) << getSessionInfo() << "\t[5.2] Done"; - - INFO_LOG(m_logger) << getSessionInfo() << "[6] Getting building DDS data ('buildingStates')"; - connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, - this, &BuildingViewerDdsController::onBuildingStateChanged, Qt::UniqueConnection); - m_bldDtc->buildingStates([this](const Buildings::BuildingState & data) - { - onBuildingStateChanged(data, DataModification::eAdded); - }); - connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingHitLineInfoChanged, - this, &BuildingViewerDdsController::onBuildingHitLineInfoChanged, Qt::UniqueConnection); - INFO_LOG(m_logger) << getSessionInfo() << "\t[6.1] Done"; - - - m_connection->excSetGlobalTransparency(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("GlobalTransparency"), 75).toInt() ); - m_connection->excSetGlobalViewMode(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("UseIsoMode"), false).toBool()); - m_connection->excSetGlobalDotsMode(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("UseDotsMode"), false).toBool() ); - m_hitlineDuration_ms = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("maxHitlineDurationTime_s"), 10).toInt() * 1000; - if (m_hitlineDuration_ms < 0) - m_hitlineDuration_ms = 0; - m_connection->excSetHitlineDuration(m_hitlineDuration_ms / 1000); - - - if (!m_pFireEventFlashTimer) - { - m_pFireEventFlashTimer = new QTimer(this); - m_pFireEventFlashTimer->setInterval(1000); - connect(m_pFireEventFlashTimer, &QTimer::timeout, this, &BuildingViewerDdsController::onFireEventFlashTimer); - } - m_pFireEventFlashTimer->start(); - - if (m_srpDtc) - { - connect(m_srpDtc.get(), &SituationReplay::Interface::Dtc::sitReplayChanged, this, &BuildingViewerDdsController::onReplayChanged, Qt::UniqueConnection); - if (m_srpDtc && m_srpDtc->isSitReplayEnabled()) + if (!m_pSimTimeSyncTimer) { - m_srpDtc->sitReplays([this](const SituationReplay::SitReplay &srp) - { - onReplayChanged(srp, DataModification::eAdded); - }); + m_pSimTimeSyncTimer = new QTimer(this); + m_pSimTimeSyncTimer->setInterval(m_bgviewer_simSyncTimeInterval_ms); + connect(m_pSimTimeSyncTimer, &QTimer::timeout, this, &BuildingViewerDdsController::onSynchronizeSimulationTime); } - } + m_pSimTimeSyncTimer->start(); + onSynchronizeSimulationTime(); - if (!m_pBuildingHitlineCleanupTimer) - { - m_pBuildingHitlineCleanupTimer = new QTimer(this); - m_pBuildingHitlineCleanupTimer->setInterval(1000 * 60 * 5); - connect(m_pBuildingHitlineCleanupTimer, &QTimer::timeout, this, &BuildingViewerDdsController::onCleanupBuildingHitlines); - } - m_pBuildingHitlineCleanupTimer->start(); + syncTeams(); + setPaused(false); - INFO_LOG(m_logger) << getSessionInfo() << "[7] Emitting 'signalDdsInitFinished'"; - m_ddsInitFinished = true; - emit signalDdsInitFinished(); - onSynchronizeSimulationTime(); + sendAssets(); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool useExactPositioning = ps->value(QStringLiteral("bld"), QStringLiteral("useExactPositioning")).toBool(); + m_connection->excUseExactPositioning(useExactPositioning); + + INFO_LOG(m_logger) << getSessionInfo() << "[4] Getting building DDS data ('mainStructureElements')"; + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + &BuildingViewerDdsController::onMainStructureElementChanged); + + m_ismDtc->mainStructureElements([this](const InfrastructureManagement::MainStructureElement& data) { + onMainStructureElementChanged(data, DataModification::eAdded); + }); + INFO_LOG(m_logger) << getSessionInfo() << "\t[4.1] Done"; + + INFO_LOG(m_logger) << getSessionInfo() << "[5] Creating participants"; + + createParticipants(); + INFO_LOG(m_logger) << getSessionInfo() << "\t[5.1] Done"; + INFO_LOG(m_logger) << getSessionInfo() << "[5] Creating Booby Trap"; + createBoobyTraps(); + INFO_LOG(m_logger) << getSessionInfo() << "\t[5.2] Done"; + + INFO_LOG(m_logger) << getSessionInfo() << "[6] Getting building DDS data ('buildingStates')"; + connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, this, + &BuildingViewerDdsController::onBuildingStateChanged, Qt::UniqueConnection); + m_bldDtc->buildingStates( + [this](const Buildings::BuildingState& data) { onBuildingStateChanged(data, DataModification::eAdded); }); + connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingHitLineInfoChanged, this, + &BuildingViewerDdsController::onBuildingHitLineInfoChanged, Qt::UniqueConnection); + INFO_LOG(m_logger) << getSessionInfo() << "\t[6.1] Done"; + + m_connection->excSetGlobalTransparency( + LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("GlobalTransparency"), 75) + .toInt()); + m_connection->excSetGlobalViewMode(LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("UseIsoMode"), false) + .toBool()); + m_connection->excSetGlobalDotsMode(LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("UseDotsMode"), false) + .toBool()); + m_hitlineDuration_ms = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("maxHitlineDurationTime_s"), 10) + .toInt() * + 1000; + if (m_hitlineDuration_ms < 0) + m_hitlineDuration_ms = 0; + m_connection->excSetHitlineDuration(m_hitlineDuration_ms / 1000); + + if (!m_pFireEventFlashTimer) + { + m_pFireEventFlashTimer = new QTimer(this); + m_pFireEventFlashTimer->setInterval(1000); + connect(m_pFireEventFlashTimer, &QTimer::timeout, this, &BuildingViewerDdsController::onFireEventFlashTimer); + } + m_pFireEventFlashTimer->start(); + + if (m_srpDtc) + { + connect(m_srpDtc.get(), &SituationReplay::Interface::Dtc::sitReplayChanged, this, + &BuildingViewerDdsController::onReplayChanged, Qt::UniqueConnection); + if (m_srpDtc && m_srpDtc->isSitReplayEnabled()) + { + m_srpDtc->sitReplays( + [this](const SituationReplay::SitReplay& srp) { onReplayChanged(srp, DataModification::eAdded); }); + } + } + + if (!m_pBuildingHitlineCleanupTimer) + { + m_pBuildingHitlineCleanupTimer = new QTimer(this); + m_pBuildingHitlineCleanupTimer->setInterval(1000 * 60 * 5); + connect(m_pBuildingHitlineCleanupTimer, &QTimer::timeout, this, + &BuildingViewerDdsController::onCleanupBuildingHitlines); + } + m_pBuildingHitlineCleanupTimer->start(); + + INFO_LOG(m_logger) << getSessionInfo() << "[7] Emitting 'signalDdsInitFinished'"; + m_ddsInitFinished = true; + emit signalDdsInitFinished(); + onSynchronizeSimulationTime(); } - void BuildingViewerDdsController::stopAndClearTimer() { - DEBUG_LOG(m_logger) << "stopAndClearTimer"; + DEBUG_LOG(m_logger) << "stopAndClearTimer"; - if (m_pFireEventFlashTimer) - m_pFireEventFlashTimer->stop(); + if (m_pFireEventFlashTimer) + m_pFireEventFlashTimer->stop(); - if (m_pBuildingHitlineCleanupTimer) - m_pBuildingHitlineCleanupTimer->stop(); + if (m_pBuildingHitlineCleanupTimer) + m_pBuildingHitlineCleanupTimer->stop(); - if (m_pSimTimeSyncTimer) - m_pSimTimeSyncTimer->stop(); + if (m_pSimTimeSyncTimer) + m_pSimTimeSyncTimer->stop(); } - void BuildingViewerDdsController::uninitialize() { - DEBUG_LOG(m_logger) << "uninitialize"; - if (!m_bldDtc) - return; - + DEBUG_LOG(m_logger) << "uninitialize"; + if (!m_bldDtc) + return; - if (m_ddsInitFinished) - DEBUG_LOG(m_logger) << "Flag 'm_ddsInitFinished' set which means that initialization had been finished completely"; - else - WARNING_LOG(m_logger) << "Flag 'm_ddsInitFinished' has not been set within timeout value, forcing quit!"; + if (m_ddsInitFinished) + DEBUG_LOG(m_logger) + << "Flag 'm_ddsInitFinished' set which means that initialization had been finished completely"; + else + WARNING_LOG(m_logger) << "Flag 'm_ddsInitFinished' has not been set within timeout value, forcing quit!"; - stopAndClearTimer(); + stopAndClearTimer(); - m_connection->disconnect(this); - m_connection->systemDisconnect(); + m_connection->disconnect(this); + m_connection->systemDisconnect(); - - m_aesDtc->disconnect(this); - m_ppmDtc->disconnect(this); - m_ismDtc->disconnect(this); - m_ismIfc->disconnect(this); - m_bldDtc->disconnect(this); + m_aesDtc->disconnect(this); + m_ppmDtc->disconnect(this); + m_ismDtc->disconnect(this); + m_ismIfc->disconnect(this); + m_bldDtc->disconnect(this); + m_avmIfc = nullptr; + m_asbIfc = nullptr; + m_aesDtc = nullptr; + m_ppmDtc = nullptr; + m_ppmGuiIfc = nullptr; + m_ismDtc = nullptr; + m_ismIfc = nullptr; + m_bldDtc = nullptr; + m_blgGuiIfc = nullptr; - - m_avmIfc = nullptr; - m_asbIfc = nullptr; - m_aesDtc = nullptr; - m_ppmDtc = nullptr; - m_ppmGuiIfc = nullptr; - m_ismDtc = nullptr; - m_ismIfc = nullptr; - m_bldDtc = nullptr; - m_blgGuiIfc = nullptr; + m_ddsInitFinished = false; + m_buildingHeight.clear(); - m_ddsInitFinished = false; - m_buildingHeight.clear(); - - DEBUG_LOG(m_logger) << "BuildingViewerDdsController::uninitialize() finished"; + DEBUG_LOG(m_logger) << "BuildingViewerDdsController::uninitialize() finished"; } -QPointF BuildingViewerDdsController::toRelativePosition(const Core::GeoPosition &geoPos) const +QPointF BuildingViewerDdsController::toRelativePosition(const Core::GeoPosition& geoPos) const { - if (std::isnan(geoPos.lon()) || std::isnan(geoPos.lat()) || - qIsNull(geoPos.lon()) || qIsNull(geoPos.lat())) - return {}; + if (std::isnan(geoPos.lon()) || std::isnan(geoPos.lat()) || qIsNull(geoPos.lon()) || qIsNull(geoPos.lat())) + return {}; - LtsCoordTrans::UtmCoordinate coord(LtsCoordTrans::UtmCoordinate::fromGeographic(geoPos.lon(), geoPos.lat(), m_baseCoordinate.zone)); - return coord.relativeTo(m_baseCoordinate); + LtsCoordTrans::UtmCoordinate coord( + LtsCoordTrans::UtmCoordinate::fromGeographic(geoPos.lon(), geoPos.lat(), m_baseCoordinate.zone)); + return coord.relativeTo(m_baseCoordinate); } -LtsUtils::QPoint3D BuildingViewerDdsController::toRelative3D(const Core::GeoPosition &geoPos) const +LtsUtils::QPoint3D BuildingViewerDdsController::toRelative3D(const Core::GeoPosition& geoPos) const { - const auto ret = toRelativePosition(geoPos); - if (ret.isNull()) - return {}; - return LtsUtils::QPoint3D(ret.x(), ret.y(), geoPos.z()); + const auto ret = toRelativePosition(geoPos); + if (ret.isNull()) + return {}; + return LtsUtils::QPoint3D(ret.x(), ret.y(), geoPos.z()); } bool BuildingViewerDdsController::clear() { - DEBUG_LOG(m_logger) << "clear m_connection->playerClear();"; - m_connection->playerClear(); - return true; + DEBUG_LOG(m_logger) << "clear m_connection->playerClear();"; + m_connection->playerClear(); + return true; } - bool BuildingViewerDdsController::syncTeams() { - if (!m_ppmDtc) - return false; - INFO_LOG(m_logger) << "BuildingViewerDdsController::syncTeams"; + if (!m_ppmDtc) + return false; + INFO_LOG(m_logger) << "BuildingViewerDdsController::syncTeams"; - m_connection->setTeamConfiguration(m_ppmDtc->partys()); - return true; + m_connection->setTeamConfiguration(m_ppmDtc->partys()); + return true; } - bool BuildingViewerDdsController::setPaused(bool bPaused) { - m_connection->systemSetPaused(bPaused); - return true; + m_connection->systemSetPaused(bPaused); + return true; } -bool BuildingViewerDdsController::calcBaseCoordinate(const QMap &mseMap) +bool BuildingViewerDdsController::calcBaseCoordinate( + const QMap& mseMap) { - bool bAtLeasOneFound = false; - Core::GeoPosition geoPosition; - for (const auto &mse : mseMap) - { + bool bAtLeasOneFound = false; + Core::GeoPosition geoPosition; + for (const auto& mse : mseMap) + { + if (!bAtLeasOneFound) + { + bAtLeasOneFound = true; + geoPosition = mse.geoPosition(); + } + else + { + geoPosition.lat() = std::min(geoPosition.lat(), mse.geoPosition().lat()); + geoPosition.lon() = std::min(geoPosition.lon(), mse.geoPosition().lon()); + } + } if (!bAtLeasOneFound) { - bAtLeasOneFound = true; - geoPosition = mse.geoPosition(); + WARNING_LOG(m_logger) << "No building available in exercise " << m_exerciseId; + return false; } - else - { - geoPosition.lat() = std::min(geoPosition.lat(), mse.geoPosition().lat()); - geoPosition.lon() = std::min(geoPosition.lon(), mse.geoPosition().lon()); - } - } - if (!bAtLeasOneFound) - { - WARNING_LOG(m_logger) << "No building available in exercise " << m_exerciseId; - return false; - } - m_baseCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(geoPosition.lon(), geoPosition.lat()); - return true; + m_baseCoordinate = LtsCoordTrans::UtmCoordinate::fromGeographic(geoPosition.lon(), geoPosition.lat()); + return true; } bool BuildingViewerDdsController::isOutdatedPosition(qint64 sampleTime) const { - if (m_session == nullptr) - return true; - return LtsUtils::isPositionTimeOutdated(m_session->partitionTime(), sampleTime); + if (m_session == nullptr) + return true; + return LtsUtils::isPositionTimeOutdated(m_session->partitionTime(), sampleTime); } -bool BuildingViewerDdsController::writeBuildingDataToXML(const QString &modelPath) +bool BuildingViewerDdsController::writeBuildingDataToXML(const QString& modelPath) { - QFile f(getBuildingConfigurationXml()); - if (!f.open(QIODevice::WriteOnly)) - { - WARNING_LOG(m_logger) << "Can not open file " << f.fileName() << " for writing: " << f.errorString(); - return false; - } - m_knownBuildings.clear(); - - QMap mseMap; - - QFile jsonConfig(modelPath + QStringLiteral("/buildings.json")); - if (!jsonConfig.exists()) - jsonConfig.setFileName(modelPath + QStringLiteral("/../buildings.json")); - - DEBUG_LOG(m_logger) << "jsonConfig:" << jsonConfig.fileName(); - if (jsonConfig.exists() && jsonConfig.open(QIODevice::ReadOnly)) - { - m_ismDtc->disconnect(this); - InfrastructureManagement::MainStructureElement mse; - const QJsonArray arr = QJsonDocument::fromJson(jsonConfig.readAll()).array(); - for (const auto &ele : arr) + QFile f(getBuildingConfigurationXml()); + if (!f.open(QIODevice::WriteOnly)) { - const auto bi = BuildingInfo::fromJson(ele.toObject()); - if (!bi.isValid()) - continue; - mse.id(bi.id); - mse.angle(bi.angleDegree); - mse.geoPosition(Core::GeoPosition(bi.position.x(), bi.position.y(), bi.position.z())); - mse.name(bi.name.toStdString()); - mseMap.insert(mse.id(), mse); + WARNING_LOG(m_logger) << "Can not open file " << f.fileName() << " for writing: " << f.errorString(); + return false; } - } - else - { - m_ismDtc->waitForHistoricalDataMainStructureElement(m_dtc_timeout_ms); - const auto mMap = m_ismDtc->mainStructureElements(); - for (const auto &mse : mMap) + m_knownBuildings.clear(); + + QMap mseMap; + + QFile jsonConfig(modelPath + QStringLiteral("/buildings.json")); + if (!jsonConfig.exists()) + jsonConfig.setFileName(modelPath + QStringLiteral("/../buildings.json")); + + DEBUG_LOG(m_logger) << "jsonConfig:" << jsonConfig.fileName(); + if (jsonConfig.exists() && jsonConfig.open(QIODevice::ReadOnly)) { - if (mse.modelId() == 0) - continue; - if (!m_ismDtc->isElementAssignedToExercise(mse, m_exerciseId)) - { - DEBUG_LOG(m_logger) << "Not writing mse with id " << mse.id() << " to building xml file since it is not assigned to the current exercise which has id " << m_exerciseId; - continue; - } - mseMap.insert(mse.id(), mse); + m_ismDtc->disconnect(this); + InfrastructureManagement::MainStructureElement mse; + const QJsonArray arr = QJsonDocument::fromJson(jsonConfig.readAll()).array(); + for (const auto& ele : arr) + { + const auto bi = BuildingInfo::fromJson(ele.toObject()); + if (!bi.isValid()) + continue; + mse.id(bi.id); + mse.angle(bi.angleDegree); + mse.geoPosition(Core::GeoPosition(bi.position.x(), bi.position.y(), bi.position.z())); + mse.name(bi.name.toStdString()); + mseMap.insert(mse.id(), mse); + } } - } - INFO_LOG(m_logger) << getSessionInfo() << "writeBuildingDataToXML(): Identified Main Structure Elements: " << mseMap.size(); - - if (!calcBaseCoordinate(mseMap)) - { - WARNING_LOG(m_logger) << "failed to calc base coordinate"; - return false; - } - - QXmlStreamWriter sw(&f); - sw.setAutoFormatting(true); - sw.setAutoFormattingIndent(2); - sw.setCodec("UTF-8"); - sw.writeStartDocument(QStringLiteral("1.0"), true); - sw.writeStartElement(QStringLiteral("MetaData")); - { - sw.writeStartElement(QStringLiteral("Origin")); + else { - - const auto geo = m_baseCoordinate.geographic(); - sw.writeAttribute(QStringLiteral("Longitude"), QString::number(geo.x() * 180 / M_PI, 'f', 13)); - sw.writeAttribute(QStringLiteral("Latitude"), QString::number(geo.y() * 180 / M_PI, 'f', 13)); + m_ismDtc->waitForHistoricalDataMainStructureElement(m_dtc_timeout_ms); + const auto mMap = m_ismDtc->mainStructureElements(); + for (const auto& mse : mMap) + { + if (mse.modelId() == 0) + continue; + if (!m_ismDtc->isElementAssignedToExercise(mse, m_exerciseId)) + { + DEBUG_LOG(m_logger) + << "Not writing mse with id " << mse.id() + << " to building xml file since it is not assigned to the current exercise which has id " + << m_exerciseId; + continue; + } + mseMap.insert(mse.id(), mse); + } + } + INFO_LOG(m_logger) << getSessionInfo() + << "writeBuildingDataToXML(): Identified Main Structure Elements: " << mseMap.size(); + + if (!calcBaseCoordinate(mseMap)) + { + WARNING_LOG(m_logger) << "failed to calc base coordinate"; + return false; + } + + QXmlStreamWriter sw(&f); + sw.setAutoFormatting(true); + sw.setAutoFormattingIndent(2); + sw.setCodec("UTF-8"); + sw.writeStartDocument(QStringLiteral("1.0"), true); + sw.writeStartElement(QStringLiteral("MetaData")); + { + sw.writeStartElement(QStringLiteral("Origin")); + { + + const auto geo = m_baseCoordinate.geographic(); + sw.writeAttribute(QStringLiteral("Longitude"), QString::number(geo.x() * 180 / M_PI, 'f', 13)); + sw.writeAttribute(QStringLiteral("Latitude"), QString::number(geo.y() * 180 / M_PI, 'f', 13)); + } + sw.writeEndElement(); + + sw.writeStartElement(QStringLiteral("Tag")); + sw.writeStartElement(QStringLiteral("Group")); + + for (const InfrastructureManagement::MainStructureElement& mse : std::as_const(mseMap)) + { + m_knownBuildings += mse.id(); + + sw.writeStartElement(QStringLiteral("Model")); + sw.writeAttribute(QStringLiteral("Type"), QStringLiteral("House")); + { + const QString name(QString::fromStdString(mse.name())); + sw.writeStartElement(QStringLiteral("Description")); + sw.writeAttribute(QStringLiteral("Name"), name); + sw.writeEndElement(); + sw.writeStartElement(QStringLiteral("Feature")); + sw.writeAttribute(QStringLiteral("Id"), BuildingViewer::databaseId2FeatureId(mse.id())); + sw.writeEndElement(); + sw.writeStartElement(QStringLiteral("Orientation")); + + sw.writeAttribute(QStringLiteral("Angle"), QString::number(360 - mse.angle())); + sw.writeEndElement(); + + const QPointF offset(toRelativePosition(mse.geoPosition())); + sw.writeStartElement(QStringLiteral("Position")); + sw.writeAttribute(QStringLiteral("X"), QString::number(offset.x(), 'f', 13)); + sw.writeAttribute(QStringLiteral("Y"), QString::number(offset.y(), 'f', 13)); + sw.writeAttribute(QStringLiteral("Z"), QString::number(mse.geoPosition().z(), 'f', 13)); + sw.writeEndElement(); + sw.writeStartElement(QStringLiteral("File")); + sw.writeAttribute(QStringLiteral("Name"), name + QStringLiteral(".flt")); + sw.writeEndElement(); + sw.writeStartElement(QStringLiteral("STREIF")); + sw.writeAttribute(QStringLiteral("Name"), name + QStringLiteral(".flt.xml")); + sw.writeEndElement(); + } + sw.writeEndElement(); + } + sw.writeEndElement(); + sw.writeEndElement(); } sw.writeEndElement(); + sw.writeEndDocument(); + f.close(); - sw.writeStartElement(QStringLiteral("Tag")); - sw.writeStartElement(QStringLiteral("Group")); - - for (const InfrastructureManagement::MainStructureElement &mse : std::as_const(mseMap)) - { - m_knownBuildings += mse.id(); - - sw.writeStartElement(QStringLiteral("Model")); - sw.writeAttribute(QStringLiteral("Type"), QStringLiteral("House")); - { - const QString name(QString::fromStdString(mse.name())); - sw.writeStartElement(QStringLiteral("Description")); - sw.writeAttribute(QStringLiteral("Name"), name); - sw.writeEndElement(); - sw.writeStartElement(QStringLiteral("Feature")); - sw.writeAttribute(QStringLiteral("Id"), BuildingViewer::databaseId2FeatureId(mse.id())); - sw.writeEndElement(); - sw.writeStartElement(QStringLiteral("Orientation")); - - sw.writeAttribute(QStringLiteral("Angle"), QString::number(360 - mse.angle())); - sw.writeEndElement(); - - const QPointF offset(toRelativePosition(mse.geoPosition())); - sw.writeStartElement(QStringLiteral("Position")); - sw.writeAttribute(QStringLiteral("X"), QString::number(offset.x(), 'f', 13)); - sw.writeAttribute(QStringLiteral("Y"), QString::number(offset.y(), 'f', 13)); - sw.writeAttribute(QStringLiteral("Z"), QString::number(mse.geoPosition().z(), 'f', 13)); - sw.writeEndElement(); - sw.writeStartElement(QStringLiteral("File")); - sw.writeAttribute(QStringLiteral("Name"), name + QStringLiteral(".flt")); - sw.writeEndElement(); - sw.writeStartElement(QStringLiteral("STREIF")); - sw.writeAttribute(QStringLiteral("Name"), name + QStringLiteral(".flt.xml")); - sw.writeEndElement(); - } - sw.writeEndElement(); - } - sw.writeEndElement(); - sw.writeEndElement(); - } - sw.writeEndElement(); - sw.writeEndDocument(); - f.close(); - - std::sort(m_knownBuildings.begin(), m_knownBuildings.end()); - return true; + std::sort(m_knownBuildings.begin(), m_knownBuildings.end()); + return true; } - QString BuildingViewerDdsController::getBuildingConfigurationXml() const { - return QDir::tempPath() + QStringLiteral("/buildings_%1.xml").arg(m_exerciseId); + return QDir::tempPath() + QStringLiteral("/buildings_%1.xml").arg(m_exerciseId); } void BuildingViewerDdsController::clearAssets() { - INFO_LOG(m_logger) << "clearAssets: Removing " << m_knownAssetsInBgViewer.size() << " assets"; + INFO_LOG(m_logger) << "clearAssets: Removing " << m_knownAssetsInBgViewer.size() << " assets"; - for (const auto &strUniqueAsset : std::as_const(m_knownAssetsInBgViewer)) - m_connection->extHideMountingPointAsset(strUniqueAsset); + for (const auto& strUniqueAsset : std::as_const(m_knownAssetsInBgViewer)) + m_connection->extHideMountingPointAsset(strUniqueAsset); - m_mountingPointId2AssetType.clear(); - m_knownAssetsInBgViewer.clear(); + m_mountingPointId2AssetType.clear(); + m_knownAssetsInBgViewer.clear(); } - void BuildingViewerDdsController::sendAssets() { - clearAssets(); + clearAssets(); - std::function cb = [this](const InfrastructureManagement::MountingPoint &mp) - { - handleMountingPoint(mp, DataModification::eAdded); - }; - m_ismIfc->mountingPoints(cb); + std::function cb = + [this](const InfrastructureManagement::MountingPoint& mp) { + handleMountingPoint(mp, DataModification::eAdded); + }; + m_ismIfc->mountingPoints(cb); } -void BuildingViewerDdsController::onReplayChanged(const SituationReplay::SitReplay &srp, DataModification modType) +void BuildingViewerDdsController::onReplayChanged(const SituationReplay::SitReplay& srp, DataModification modType) { - Q_UNUSED(modType) + Q_UNUSED(modType) - switch (srp.state().underlying()) { - case SituationReplay::SrpState::Stopped: - m_connection->setSimuationPace(1.0); - - break; - case SituationReplay::SrpState::Started: - case SituationReplay::SrpState::Resumed: - m_connection->setSimuationPace(srp.pace()); - - break; - case SituationReplay::SrpState::Paused: - m_connection->setSimuationPace(0.0); - - break; - default: - break; - } - -} - -void BuildingViewerDdsController::handleMountingPoint(const InfrastructureManagement::MountingPoint &mp, DataModification modType) -{ - if (!isBuildingKnown(mp.buildingId())) - return; - if (m_session->isReplayPartition()) - return; - - const int mountingPointId = mp.id(); - - auto itMp = m_knownAssetsInBgViewer.find(mountingPointId); - if (itMp != m_knownAssetsInBgViewer.end()) - { - if (modType == DataModification::eRemoved || !mp.hasAssociatedAsset()) + switch (srp.state().underlying()) { - m_connection->extHideMountingPointAsset(itMp.value()); - m_knownAssetsInBgViewer.erase(itMp); + case SituationReplay::SrpState::Stopped: + m_connection->setSimuationPace(1.0); + + break; + case SituationReplay::SrpState::Started: + case SituationReplay::SrpState::Resumed: + m_connection->setSimuationPace(srp.pace()); + + break; + case SituationReplay::SrpState::Paused: + m_connection->setSimuationPace(0.0); + + break; + default: + break; + } +} + +void BuildingViewerDdsController::handleMountingPoint(const InfrastructureManagement::MountingPoint& mp, + DataModification modType) +{ + if (!isBuildingKnown(mp.buildingId())) + return; + if (m_session->isReplayPartition()) + return; + + const int mountingPointId = mp.id(); + + auto itMp = m_knownAssetsInBgViewer.find(mountingPointId); + if (itMp != m_knownAssetsInBgViewer.end()) + { + if (modType == DataModification::eRemoved || !mp.hasAssociatedAsset()) + { + m_connection->extHideMountingPointAsset(itMp.value()); + m_knownAssetsInBgViewer.erase(itMp); + } + + m_mountingPointId2AssetType.remove(mountingPointId); + if (modType == DataModification::eRemoved) + return; } - m_mountingPointId2AssetType.remove(mountingPointId); - if (modType == DataModification::eRemoved) - return; - } + if (!mp.hasAssociatedAsset()) + return; - if (!mp.hasAssociatedAsset()) - return; - - BuildingViewer::AssetTypes assetType; - QString strAssetType; - switch (mp.type().underlying()) - { - case InfrastructureManagement::MountingPointType_def::AnnouncementUnit: - assetType = BuildingViewer::AssetTypes::AnnouncementUnit; - strAssetType = QStringLiteral("AnnouncementUnit"); - break; - case InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit: - assetType = BuildingViewer::AssetTypes::EffectGenerationUnit; - strAssetType = QStringLiteral("EffectGenerationControlUnit"); - break; - case InfrastructureManagement::MountingPointType_def::IndoorCamera: - { - bool hasSpeaker = false; - QJsonParseError jError; - const QJsonDocument doc(QJsonDocument::fromJson(mp.properties(), &jError)); - if (jError.error == QJsonParseError::NoError) + BuildingViewer::AssetTypes assetType; + QString strAssetType; + switch (mp.type().underlying()) { - const QJsonObject obj(doc.object()); - hasSpeaker = obj[QStringLiteral("hasSpeaker")].toBool(); + case InfrastructureManagement::MountingPointType_def::AnnouncementUnit: + assetType = BuildingViewer::AssetTypes::AnnouncementUnit; + strAssetType = QStringLiteral("AnnouncementUnit"); + break; + case InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit: + assetType = BuildingViewer::AssetTypes::EffectGenerationUnit; + strAssetType = QStringLiteral("EffectGenerationControlUnit"); + break; + case InfrastructureManagement::MountingPointType_def::IndoorCamera: { + bool hasSpeaker = false; + QJsonParseError jError; + const QJsonDocument doc(QJsonDocument::fromJson(mp.properties(), &jError)); + if (jError.error == QJsonParseError::NoError) + { + const QJsonObject obj(doc.object()); + hasSpeaker = obj[QStringLiteral("hasSpeaker")].toBool(); + } + assetType = hasSpeaker ? BuildingViewer::AssetTypes::IndoorCameraWithSpeaker + : BuildingViewer::AssetTypes::IndoorCamera; + strAssetType = hasSpeaker ? QStringLiteral("IndoorCameraWithSpeaker") : QStringLiteral("IndoorCamera"); + break; + } + default: + return; } - assetType = hasSpeaker ? BuildingViewer::AssetTypes::IndoorCameraWithSpeaker : BuildingViewer::AssetTypes::IndoorCamera; - strAssetType = hasSpeaker ? QStringLiteral("IndoorCameraWithSpeaker") : QStringLiteral("IndoorCamera"); - break; - } - default: - return; - } - QVector3D position(mp.relPosition().offsetX(),mp.relPosition().offsetY(),mp.relPosition().offsetZ()); - QString strfeatureID = BuildingViewer::databaseId2FeatureId(mp.buildingId()); - QString strMountingPointID = strfeatureID + QStringLiteral("_MountingPoint_") + QString::number(mountingPointId); + QVector3D position(mp.relPosition().offsetX(), mp.relPosition().offsetY(), mp.relPosition().offsetZ()); + QString strfeatureID = BuildingViewer::databaseId2FeatureId(mp.buildingId()); + QString strMountingPointID = strfeatureID + QStringLiteral("_MountingPoint_") + QString::number(mountingPointId); - DEBUG_LOG(m_logger) << "Sending asset for building id " << mp.buildingId() << " ("<extSetMountingPointAsset(strfeatureID, strMountingPointID, position, assetType); + m_connection->extSetMountingPointAsset(strfeatureID, strMountingPointID, position, assetType); } -void BuildingViewerDdsController::setCurrentTrainingAreaMap(const QString &modelPath) +void BuildingViewerDdsController::setCurrentTrainingAreaMap(const QString& modelPath) { - if (!m_connection) - { - WARNING_LOG(m_logger) << "BuildingViewerDdsController::setCurrentTrainingAreaMap: (!m_connection)"; - return; - } + if (!m_connection) + { + WARNING_LOG(m_logger) << "BuildingViewerDdsController::setCurrentTrainingAreaMap: (!m_connection)"; + return; + } - - m_connection->excDeleteBuildingList(); + m_connection->excDeleteBuildingList(); - INFO_LOG(m_logger) << getSessionInfo() << "[1] Initializing BgViewer with training area..."; + INFO_LOG(m_logger) << getSessionInfo() << "[1] Initializing BgViewer with training area..."; - if (modelPath.isEmpty()) - { - QString strErr = tr("Error initializing Building Viewer - can not find map directory."); - DEBUG_LOG(m_logger) << getSessionInfo() << "setCurrentTrainingAreaMap: " << strErr; - QWidget *parentWidgetx = (m_viewerInterface ? m_viewerInterface->getMainWindow() : nullptr); - LtsWidgets::LtsMessageDialog::showMessage(parentWidgetx, strErr, tr("Error")); - return; - } - INFO_LOG(m_logger) << "Map path for building viewer: " << modelPath; + if (modelPath.isEmpty()) + { + QString strErr = tr("Error initializing Building Viewer - can not find map directory."); + DEBUG_LOG(m_logger) << getSessionInfo() << "setCurrentTrainingAreaMap: " << strErr; + QWidget* parentWidgetx = (m_viewerInterface ? m_viewerInterface->getMainWindow() : nullptr); + LtsWidgets::LtsMessageDialog::showMessage(parentWidgetx, strErr, tr("Error")); + return; + } + INFO_LOG(m_logger) << "Map path for building viewer: " << modelPath; - writeBuildingDataToXML(modelPath); + writeBuildingDataToXML(modelPath); - QString pathToXml = getBuildingConfigurationXml(); + QString pathToXml = getBuildingConfigurationXml(); - QFileInfo file(pathToXml); - if (!file.exists()) - { - FATAL_LOG(m_logger) << getSessionInfo() << "setCurrentTrainingAreaMap: Required buildings xml file does not exist: \"" << pathToXml << "\", BuildingViewer initialization FAILED!"; - return; - } - - const QString shadersPath = NGL::directory(NGL::FileType::ConfigFile, QStringLiteral("BuildingViewer")); + QFileInfo file(pathToXml); + if (!file.exists()) + { + FATAL_LOG(m_logger) << getSessionInfo() + << "setCurrentTrainingAreaMap: Required buildings xml file does not exist: \"" << pathToXml + << "\", BuildingViewer initialization FAILED!"; + return; + } - QString additionalPath; - QVector directoriesToSearch = NGL::directories(NGL::FileType::ConfigFile); + const QString shadersPath = NGL::directory(NGL::FileType::ConfigFile, QStringLiteral("BuildingViewer")); + + QString additionalPath; + QVector directoriesToSearch = NGL::directories(NGL::FileType::ConfigFile); #ifndef WIN32 - directoriesToSearch += QStringLiteral("/opt"); + directoriesToSearch += QStringLiteral("/opt"); #endif - for (const QString &d : std::as_const(directoriesToSearch)) - { - const QDir dir(d + QStringLiteral("/BuildingModels/StaticMeshes/")); - if (dir.exists() && dir.isReadable()) - additionalPath = dir.absolutePath(); - INFO_LOG(getLogger("BgViewerController")) << "Map path '" << dir.absolutePath() << "' either does not exist or is not readable - skipping"; - } + for (const QString& d : std::as_const(directoriesToSearch)) + { + const QDir dir(d + QStringLiteral("/BuildingModels/StaticMeshes/")); + if (dir.exists() && dir.isReadable()) + additionalPath = dir.absolutePath(); + INFO_LOG(getLogger("BgViewerController")) + << "Map path '" << dir.absolutePath() << "' either does not exist or is not readable - skipping"; + } - std::vector paths; - paths.push_back(modelPath.toStdString()); - paths.push_back(shadersPath.toStdString()); - if (!additionalPath.isEmpty()) - { - paths.push_back(additionalPath.toStdString()); - } - m_connection->excConnect(paths, pathToXml); + std::vector paths; + paths.push_back(modelPath.toStdString()); + paths.push_back(shadersPath.toStdString()); + if (!additionalPath.isEmpty()) + { + paths.push_back(additionalPath.toStdString()); + } + m_connection->excConnect(paths, pathToXml); } - -bool BuildingViewerDdsController::isValidParticipant(const ParticipantManagement::Participant &participant) const +bool BuildingViewerDdsController::isValidParticipant(const ParticipantManagement::Participant& participant) const { - if (participant.id() == 0) - { - if (m_logger.isDebugEnabled()) - DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling invalid participant with invalid id (0)"; - return false; - } + if (participant.id() == 0) + { + if (m_logger.isDebugEnabled()) + DEBUG_LOG(m_logger) << getSessionInfo() + << "isValidParticipant: Not handling invalid participant with invalid id (0)"; + return false; + } - - if (participant.isDeleted()) - { - DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " - << participant.id() << " since it is marked as 'deleted'"; - return false; - } + if (participant.isDeleted()) + { + DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " + << participant.id() << " since it is marked as 'deleted'"; + return false; + } - if (m_session == nullptr) - return false; + if (m_session == nullptr) + return false; - - if (!m_session->isVisibleParty(participant.partyId())) - { - DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " - << participant.id() << " since it is not visible for party with id " << participant.partyId(); - return false; - } + if (!m_session->isVisibleParty(participant.partyId())) + { + DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " + << participant.id() << " since it is not visible for party with id " + << participant.partyId(); + return false; + } - if (!m_ppmDtc) - return false; + if (!m_ppmDtc) + return false; - - ParticipantManagement::TypeClass tc = m_ppmDtc->type(participant.typeId()).typeClass(); - if(tc == ParticipantManagement::TypeClass_def::SupportUnit || - tc == ParticipantManagement::TypeClass_def::Unit) - { - DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " - << participant.id() << " since its type is 'SupportUnit', 'Unit' or 'Structure'"; - return false; - } + ParticipantManagement::TypeClass tc = m_ppmDtc->type(participant.typeId()).typeClass(); + if (tc == ParticipantManagement::TypeClass_def::SupportUnit || tc == ParticipantManagement::TypeClass_def::Unit) + { + DEBUG_LOG(m_logger) << getSessionInfo() << "isValidParticipant: Not handling participant with id " + << participant.id() << " since its type is 'SupportUnit', 'Unit' or 'Structure'"; + return false; + } - return true; + return true; } void BuildingViewerDdsController::createBoobyTraps() { - if (!m_aesDtc) - return; - DEBUG_LOG(m_logger) << "BDV:: create Booby Traps: "<< m_session->exerciseId() << " is replay: " << m_session->isReplayPartition(); + if (!m_aesDtc) + return; + DEBUG_LOG(m_logger) << "BDV:: create Booby Traps: " << m_session->exerciseId() + << " is replay: " << m_session->isReplayPartition(); - m_aesDtc->enableBoobyTrap(); - - - const int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - - - auto cb = [this, sizeL] (const AreaEffectSimulation::BoobyTrap &trap) - { - createBoobyTrap(trap, sizeL); - }; - m_aesDtc->boobyTraps(cb); - - - - - - connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, - this, &BuildingViewerDdsController::onBoobyTrapChanged, Qt::UniqueConnection); + m_aesDtc->enableBoobyTrap(); + const int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + auto cb = [this, sizeL](const AreaEffectSimulation::BoobyTrap& trap) { createBoobyTrap(trap, sizeL); }; + m_aesDtc->boobyTraps(cb); + connect(m_aesDtc.get(), &AreaEffectSimulation::Interface::Dtc::boobyTrapChanged, this, + &BuildingViewerDdsController::onBoobyTrapChanged, Qt::UniqueConnection); } void BuildingViewerDdsController::createParticipants() { - if (!m_ppmDtc) - return; - DEBUG_LOG(m_logger) << "BDV:: create participants: "<< m_session->exerciseId() << " is replay: " << m_session->isReplayPartition(); + if (!m_ppmDtc) + return; + DEBUG_LOG(m_logger) << "BDV:: create participants: " << m_session->exerciseId() + << " is replay: " << m_session->isReplayPartition(); - const int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); + const int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); - const QMap positionMap = m_ppmDtc->participantPositions(); - auto cb = [this, &positionMap, sizeL] (const ParticipantManagement::Participant &part) - { - if (!isValidParticipant(part)) - return; - createParticipant(part, positionMap.value(part.id()), sizeL); - }; - m_ppmDtc->participants(cb); + const QMap positionMap = m_ppmDtc->participantPositions(); + auto cb = [this, &positionMap, sizeL](const ParticipantManagement::Participant& part) { + if (!isValidParticipant(part)) + return; + createParticipant(part, positionMap.value(part.id()), sizeL); + }; + m_ppmDtc->participants(cb); - + m_ppmDtc->enableParticipant(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, this, + &BuildingViewerDdsController::onParticipantChanged, Qt::UniqueConnection); - - m_ppmDtc->enableParticipant(); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, - this, &BuildingViewerDdsController::onParticipantChanged, Qt::UniqueConnection); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::hitLineInfoChanged, this, + &BuildingViewerDdsController::onHitLineInfoChanged, Qt::UniqueConnection); + m_ppmDtc->enableHitLineInfo(); - - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::hitLineInfoChanged, - this, &BuildingViewerDdsController::onHitLineInfoChanged, Qt::UniqueConnection); - m_ppmDtc->enableHitLineInfo(); + m_ppmDtc->enableParty(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::partyChanged, this, + &BuildingViewerDdsController::onPartyChanged, Qt::UniqueConnection); - - m_ppmDtc->enableParty(); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::partyChanged, - this, &BuildingViewerDdsController::onPartyChanged, Qt::UniqueConnection); + m_ppmDtc->enableParticipantPosition(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantPositionChanged, this, + &BuildingViewerDdsController::onPositionChanged, Qt::UniqueConnection); - - m_ppmDtc->enableParticipantPosition(); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantPositionChanged, - this, &BuildingViewerDdsController::onPositionChanged, Qt::UniqueConnection); + m_ppmDtc->enableParticipantGearEvent(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantGearEventChanged, this, + &BuildingViewerDdsController::onParticipantGearEventChanged, Qt::UniqueConnection); - - m_ppmDtc->enableParticipantGearEvent(); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantGearEventChanged, - this, &BuildingViewerDdsController::onParticipantGearEventChanged, - Qt::UniqueConnection); - - - m_ppmDtc->enableDynamicParticipantData(); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, - this, &BuildingViewerDdsController::onDynParticipantChanged, Qt::UniqueConnection); - - m_ppmDtc->participantGearEvents([this](const ParticipantManagement::ParticipantGearEvent & data) - { - onParticipantGearEventChanged(data, DataModification::eAdded); - }); + m_ppmDtc->enableDynamicParticipantData(); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, this, + &BuildingViewerDdsController::onDynParticipantChanged, Qt::UniqueConnection); + m_ppmDtc->participantGearEvents([this](const ParticipantManagement::ParticipantGearEvent& data) { + onParticipantGearEventChanged(data, DataModification::eAdded); + }); } - -void BuildingViewerDdsController::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &boobyTrap, DataModification modType) +void BuildingViewerDdsController::onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& boobyTrap, + DataModification modType) { - switch (modType) - { - case DataModification::eModified: - deleteParticipant(990000+boobyTrap.id()); - Q_FALLTHROUGH(); - case DataModification::eAdded: - { - int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - createBoobyTrap(boobyTrap, sizeL); - break; - } - case DataModification::eRemoved: - { - deleteParticipant(990000+boobyTrap.id()); - break; - } - } -} - - -void BuildingViewerDdsController::onParticipantChanged(const ParticipantManagement::Participant &participant, DataModification modType) -{ - if (!isValidParticipant(participant)) - return; - - switch (modType) - { - case DataModification::eModified: - deleteParticipant(participant.id()); - Q_FALLTHROUGH(); - case DataModification::eAdded: - { - int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - createParticipant(participant, m_ppmDtc->participantPosition(participant.id()), sizeL); - break; - } - case DataModification::eRemoved: - { - deleteParticipant(participant.id()); - break; - } - } -} - -void BuildingViewerDdsController::onDynParticipantChanged(const ParticipantManagement::DynamicParticipantData &data, DataModification modType) -{ - int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - if (m_ppmDtc) - createParticipant(m_ppmDtc->participant(data.participantId()), m_ppmDtc->participantPosition(data.participantId()), sizeL); - break; - case DataModification::eRemoved: - { - break; - } - } -} - -void BuildingViewerDdsController::onHitLineInfoChanged(const ParticipantManagement::HitLineInfo &hli, DataModification modType) -{ - DEBUG_LOG(m_logger) << "X 0000 onHitLineInfoChanged id=" << hli.id(); - - if (modType == DataModification::eRemoved) - { - DEBUG_LOG(m_logger) << "onHitLineInfoChanged removeHit id=" << hli.id(); - m_connection->removeRoomHit(hli.id()); - return; - } - - if (!m_ppmDtc) - return; - m_ppmDtc->waitForHistoricalDataParticipant(); - - const ParticipantManagement::Participant &partSrc = m_ppmDtc->participant(hli.originatorParticipantId()); - const ParticipantManagement::Participant &partDst = m_ppmDtc->participant(hli.injuryParticipantId()); - if (partSrc.id() == 0 || partDst.id() == 0) - { - ERROR_LOG(m_logger) << "no knownn part: " << partSrc.id() << " dst: " << partDst.id(); - return; - } - - const QString &strFeatureID = BuildingViewer::databaseId2FeatureId(hli.injuryBuildingId()); - if (!m_viewerInterface->isViewOpen(strFeatureID.toStdString())) - { - DEBUG_LOG(m_logger) << "building not opened: hli.buildingId()=" << hli; - return; - } - - - - - - - if (hli.injuryBuildingId() != 0) - { - auto itBuildingHit = m_buildingHits.constFind(hli.injuryBuildingId()); - if (itBuildingHit != m_buildingHits.constEnd()) + switch (modType) { - const QVector &bHits = itBuildingHit.value(); - - DEBUG_LOG(m_logger) << "Got Hit lines to add? " << bHits.size(); - for (const BuildingHit &bh : bHits) - { - - const bool testFlag = (bh.chargeTypeId == hli.chargeTypeId() && - bh.originatorParticipantId == hli.originatorParticipantId() && - hli.sampleTime() - m_hitlineDuration_ms < bh.sampleTime); - DEBUG_LOG(m_logger) << "testFlag " << testFlag; - - - if (bh.chargeTypeId == hli.chargeTypeId() && - bh.originatorParticipantId == hli.originatorParticipantId() && - hli.sampleTime() - m_hitlineDuration_ms < bh.sampleTime) - return; - } + case DataModification::eModified: + deleteParticipant(990000 + boobyTrap.id()); + Q_FALLTHROUGH(); + case DataModification::eAdded: { + int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + createBoobyTrap(boobyTrap, sizeL); + break; + } + case DataModification::eRemoved: { + deleteParticipant(990000 + boobyTrap.id()); + break; + } } - } +} - DEBUG_LOG(m_logger) << "onHitLineInfoChanged: " << hli; +void BuildingViewerDdsController::onParticipantChanged(const ParticipantManagement::Participant& participant, + DataModification modType) +{ + if (!isValidParticipant(participant)) + return; - int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - DEBUG_LOG(m_logger) << "onHitLineInfoChanged createPlayerSymbols"; - createPlayerSymbols(partDst, sizeL); + switch (modType) + { + case DataModification::eModified: + deleteParticipant(participant.id()); + Q_FALLTHROUGH(); + case DataModification::eAdded: { + int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + createParticipant(participant, m_ppmDtc->participantPosition(participant.id()), sizeL); + break; + } + case DataModification::eRemoved: { + deleteParticipant(participant.id()); + break; + } + } +} +void BuildingViewerDdsController::onDynParticipantChanged(const ParticipantManagement::DynamicParticipantData& data, + DataModification modType) +{ + int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: + if (m_ppmDtc) + createParticipant(m_ppmDtc->participant(data.participantId()), + m_ppmDtc->participantPosition(data.participantId()), sizeL); + break; + case DataModification::eRemoved: { + break; + } + } +} - - LtsUtils::QPoint3D originatorSrc = toRelative3D(hli.originatorPos()); - LtsUtils::QPoint3D injuryDest = toRelative3D(hli.injuryPos()); +void BuildingViewerDdsController::onHitLineInfoChanged(const ParticipantManagement::HitLineInfo& hli, + DataModification modType) +{ + DEBUG_LOG(m_logger) << "X 0000 onHitLineInfoChanged id=" << hli.id(); - DEBUG_LOG(m_logger) << "onHitLineInfoChanged playerHit" - << " hli.originatorPos() z=" << hli.originatorPos().z() - << " hli.injuryPos() z=" <isViewOpen(strFeatureID.toStdString())) + { + DEBUG_LOG(m_logger) << "building not opened: hli.buildingId()=" << hli; + return; + } - originatorSrc.setZ(originatorSrc.z() + zAddInjury); - injuryDest.setZ(injuryDest.z() + zAddInjury); + if (hli.injuryBuildingId() != 0) + { + auto itBuildingHit = m_buildingHits.constFind(hli.injuryBuildingId()); + if (itBuildingHit != m_buildingHits.constEnd()) + { + const QVector& bHits = itBuildingHit.value(); - DEBUG_LOG(m_logger) << "After z-correction:" - << " Src=" << originatorSrc.x() << "/" << originatorSrc.y() << "/" << originatorSrc.z() - << " Dest= " << injuryDest.x() << "/" << injuryDest.y() << "/" << injuryDest.z(); + DEBUG_LOG(m_logger) << "Got Hit lines to add? " << bHits.size(); + for (const BuildingHit& bh : bHits) + { - - - - - int buildingIdSrc = -1; - int roomNumberSrc = -1; - { - auto itId2Number = m_roomId2RoomNumber.constFind(hli.originatorBuildingId()); + const bool testFlag = (bh.chargeTypeId == hli.chargeTypeId() && + bh.originatorParticipantId == hli.originatorParticipantId() && + hli.sampleTime() - m_hitlineDuration_ms < bh.sampleTime); + DEBUG_LOG(m_logger) << "testFlag " << testFlag; + + if (bh.chargeTypeId == hli.chargeTypeId() && + bh.originatorParticipantId == hli.originatorParticipantId() && + hli.sampleTime() - m_hitlineDuration_ms < bh.sampleTime) + return; + } + } + } + + DEBUG_LOG(m_logger) << "onHitLineInfoChanged: " << hli; + + int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + DEBUG_LOG(m_logger) << "onHitLineInfoChanged createPlayerSymbols"; + createPlayerSymbols(partDst, sizeL); + + LtsUtils::QPoint3D originatorSrc = toRelative3D(hli.originatorPos()); + LtsUtils::QPoint3D injuryDest = toRelative3D(hli.injuryPos()); + + DEBUG_LOG(m_logger) << "onHitLineInfoChanged playerHit" + << " hli.originatorPos() z=" << hli.originatorPos().z() + << " hli.injuryPos() z=" << hli.injuryPos().z() << " Src=" << originatorSrc.x() << "/" + << originatorSrc.y() << "/" << originatorSrc.z() << " Dest= " << injuryDest.x() << "/" + << injuryDest.y() << "/" << injuryDest.z() + << " hli.originatorBuildingId=" << hli.originatorBuildingId() + << " hli.originatorRoomId=" << hli.originatorRoomId() + << " hli.injuryBuildingId=" << hli.injuryBuildingId() + << " hli.injuryRoomId=" << hli.injuryRoomId(); + + DEBUG_LOG(m_logger) << "Before z-correction:" + << " Src=" << originatorSrc.x() << "/" << originatorSrc.y() << "/" << originatorSrc.z() + << " Dest= " << injuryDest.x() << "/" << injuryDest.y() << "/" << injuryDest.z(); + + double zAddOriginator = m_buildingHeight.value(hli.originatorBuildingId(), 0); + double zAddInjury = m_buildingHeight.value(hli.injuryBuildingId(), 0); + DEBUG_LOG(m_logger) << "z-correction: zAddOriginator=" << zAddOriginator; + DEBUG_LOG(m_logger) << "z-correction: zAddInjury=" << zAddInjury; + + if (hli.originatorBuildingId() <= 0) + zAddOriginator = zAddInjury; + + if (hli.injuryBuildingId() <= 0) + zAddInjury = zAddOriginator; + + originatorSrc.setZ(originatorSrc.z() + zAddInjury); + injuryDest.setZ(injuryDest.z() + zAddInjury); + + DEBUG_LOG(m_logger) << "After z-correction:" + << " Src=" << originatorSrc.x() << "/" << originatorSrc.y() << "/" << originatorSrc.z() + << " Dest= " << injuryDest.x() << "/" << injuryDest.y() << "/" << injuryDest.z(); + + int buildingIdSrc = -1; + int roomNumberSrc = -1; + { + auto itId2Number = m_roomId2RoomNumber.constFind(hli.originatorBuildingId()); + if (itId2Number != m_roomId2RoomNumber.constEnd()) + { + const auto& mapRooms = itId2Number.value(); + const auto itRoom = mapRooms.constFind(hli.originatorRoomId()); + if (itRoom != mapRooms.constEnd()) + { + buildingIdSrc = hli.originatorBuildingId(); + roomNumberSrc = itRoom.value(); + } + else + WARNING_LOG(m_logger) << "onHitLineInfoChanged: Room id can not be mapped! Building id: " + << hli.injuryBuildingId() << ", originatorRoomId: " << hli.originatorRoomId(); + } + } + + int buildingIdDst = -1; + int roomNumberDst = -1; + { + auto itId2Number = m_roomId2RoomNumber.constFind(hli.injuryBuildingId()); + if (itId2Number != m_roomId2RoomNumber.constEnd()) + { + const auto& mapRooms = itId2Number.value(); + const auto itRoom = mapRooms.constFind(hli.injuryRoomId()); + if (itRoom != mapRooms.constEnd()) + { + buildingIdDst = hli.injuryBuildingId(); + roomNumberDst = itRoom.value(); + } + else + WARNING_LOG(m_logger) << "onHitLineInfoChanged: Room id can not be mapped! Building id: " + << hli.injuryBuildingId() << ", room id: " << hli.injuryRoomId(); + } + } + + DEBUG_LOG(m_logger) << "After translate buildingId, roomId:" + << " hli.originatorBuildingId=" << hli.originatorBuildingId() << " -> " << buildingIdSrc + << " hli.originatorRoomId=" << hli.originatorRoomId() << " -> " << roomNumberSrc + << " hli.injuryBuildingId=" << hli.injuryBuildingId() << " -> " << buildingIdDst + << " hli.injuryRoomId=" << hli.injuryBuildingId() << " -> " << roomNumberDst + << " hli.sampleTime=" << hli.sampleTime(); + int lineType = 2; + m_pdmDtc->chargeType(hli.chargeTypeId()); + + lineType = m_pdmDtc->getChargeTypeSpecialProperty(hli.chargeTypeId(), 0, 0).underlying(); + + m_connection->playerHit(hli.id(), partSrc.id(), partDst.id(), originatorSrc, injuryDest, buildingIdSrc, + roomNumberSrc, buildingIdDst, roomNumberDst, lineType, hli.sampleTime()); +} + +void BuildingViewerDdsController::onPartyChanged(const ParticipantManagement::Party& party, DataModification modType) +{ + if (modType == DataModification::eRemoved) + return; + + int sizeL = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20) + .toInt(); + updatePlayerSymbols(sizeL, party.id()); + syncTeams(); +} + +void BuildingViewerDdsController::onPositionChanged(const ParticipantManagement::ParticipantPosition& position, + DataModification modType) +{ + + if (modType == DataModification::eRemoved) + { + return; + } + + DEBUG_LOG(m_logger) << "onPositionChanged: " << position; + + int buildingID = -1; + int roomNumber = -1; + auto itId2Number = m_roomId2RoomNumber.constFind(position.buildingId()); if (itId2Number != m_roomId2RoomNumber.constEnd()) { - const auto &mapRooms = itId2Number.value(); - const auto itRoom = mapRooms.constFind(hli.originatorRoomId()); - if (itRoom != mapRooms.constEnd()) - { - buildingIdSrc = hli.originatorBuildingId(); - roomNumberSrc = itRoom.value(); - } - else - WARNING_LOG(m_logger) << "onHitLineInfoChanged: Room id can not be mapped! Building id: " << hli.injuryBuildingId()<<", originatorRoomId: "<< hli.originatorRoomId(); + const auto& mapRooms = itId2Number.value(); + const auto itRoom = mapRooms.constFind(position.roomId()); + if (itRoom != mapRooms.constEnd()) + { + buildingID = position.buildingId(); + roomNumber = itRoom.value(); + } + else + { + WARNING_LOG(m_logger) << "onPositionChanged: Room id can not be mapped! Building id: " + << position.buildingId() << ", room id: " << position.roomId(); + } } - } - int buildingIdDst = -1; - int roomNumberDst = -1; - { - auto itId2Number = m_roomId2RoomNumber.constFind(hli.injuryBuildingId()); - if (itId2Number != m_roomId2RoomNumber.constEnd()) + if ((roomNumber < 0) && (buildingID <= 0) && (position.buildingId() > 0) && + (position.reportingSource() == Core::PositionReportingSource::Ops || + position.reportingSource() == Core::PositionReportingSource::Wls)) { - const auto &mapRooms = itId2Number.value(); - const auto itRoom = mapRooms.constFind(hli.injuryRoomId()); - if (itRoom != mapRooms.constEnd()) - { - buildingIdDst = hli.injuryBuildingId(); - roomNumberDst = itRoom.value(); - } - else - WARNING_LOG(m_logger) << "onHitLineInfoChanged: Room id can not be mapped! Building id: " << hli.injuryBuildingId()<<", room id: "<< hli.injuryRoomId(); + buildingID = position.buildingId(); } - } - DEBUG_LOG(m_logger) << "After translate buildingId, roomId:" - << " hli.originatorBuildingId=" << hli.originatorBuildingId() << " -> " << buildingIdSrc - << " hli.originatorRoomId=" << hli.originatorRoomId() << " -> " << roomNumberSrc - << " hli.injuryBuildingId=" << hli.injuryBuildingId() << " -> " << buildingIdDst - << " hli.injuryRoomId=" << hli.injuryBuildingId() << " -> " << roomNumberDst - << " hli.sampleTime=" << hli.sampleTime() ; - int lineType =2; - m_pdmDtc->chargeType(hli.chargeTypeId()); - - lineType = m_pdmDtc->getChargeTypeSpecialProperty(hli.chargeTypeId(),0,0).underlying(); - - m_connection->playerHit(hli.id(), partSrc.id(), partDst.id(), - originatorSrc, injuryDest, - buildingIdSrc, roomNumberSrc, buildingIdDst, roomNumberDst, - lineType, hli.sampleTime()); - -} - - - -void BuildingViewerDdsController::onPartyChanged(const ParticipantManagement::Party &party, DataModification modType) -{ - if (modType == DataModification::eRemoved) - return; - - int sizeL = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("PlayerSymbolSize"), 20).toInt(); - updatePlayerSymbols(sizeL, party.id()); - syncTeams(); -} - - -void BuildingViewerDdsController::onPositionChanged(const ParticipantManagement::ParticipantPosition &position, DataModification modType) -{ - - - - - if (modType == DataModification::eRemoved) - { - return; - } - - DEBUG_LOG(m_logger) << "onPositionChanged: " << position; - - - - - - int buildingID = -1; - int roomNumber = -1; - auto itId2Number = m_roomId2RoomNumber.constFind(position.buildingId()); - if (itId2Number != m_roomId2RoomNumber.constEnd()) - { - const auto &mapRooms = itId2Number.value(); - const auto itRoom = mapRooms.constFind(position.roomId()); - if (itRoom != mapRooms.constEnd()) + const int playerId = position.participantId(); + auto it = m_lastPositionTime.find(playerId); + if (it == m_lastPositionTime.end()) { - buildingID = position.buildingId(); - roomNumber = itRoom.value(); + m_lastPositionTime.insert(playerId, position.sampleTime()); + if (isOutdatedPosition(position)) + m_connection->setPlayerVisible(playerId, false); } else { - WARNING_LOG(m_logger) << "onPositionChanged: Room id can not be mapped! Building id: " << position.buildingId()<<", room id: "<< position.roomId(); + if (isOutdatedPosition(it.value()) && !isOutdatedPosition(position)) + m_connection->setPlayerVisible(playerId, true); + it.value() = position.sampleTime(); } - } - - - if ((roomNumber < 0) && (buildingID <= 0) && (position.buildingId() > 0) && - (position.reportingSource() == Core::PositionReportingSource::Ops || position.reportingSource() == Core::PositionReportingSource::Wls)) - { - buildingID = position.buildingId(); - } + if (buildingID <= 0 && roomNumber <= 0) + { + m_connection->setPlayerVisible(playerId, false); + } + else + { + m_connection->setPlayerVisible(playerId, true); + } + if (!m_baseCoordinate.isValid()) + { + WARNING_LOG(m_logger) + << "not calling playerPlace as there is no base coordinate set - are there no buildings in this exercise?"; + return; + } - const int playerId = position.participantId(); - auto it = m_lastPositionTime.find(playerId); - if (it == m_lastPositionTime.end()) - { - m_lastPositionTime.insert(playerId, position.sampleTime()); - if (isOutdatedPosition(position)) - m_connection->setPlayerVisible(playerId, false); - } - else - { - if (isOutdatedPosition(it.value()) && !isOutdatedPosition(position)) - m_connection->setPlayerVisible(playerId, true); - it.value() = position.sampleTime(); - } - - if (buildingID <= 0 && roomNumber <= 0) - { - m_connection->setPlayerVisible(playerId, false); - } - else - { - m_connection->setPlayerVisible(playerId, true); - } - - if (!m_baseCoordinate.isValid()) - { - WARNING_LOG(m_logger) << "not calling playerPlace as there is no base coordinate set - are there no buildings in this exercise?"; - return; - } - - - m_connection->playerPlace(position.participantId(), toRelative3D(position.pos()), - buildingID, roomNumber, position.reportingSource()); + m_connection->playerPlace(position.participantId(), toRelative3D(position.pos()), buildingID, roomNumber, + position.reportingSource()); } - - -void BuildingViewerDdsController::onParticipantGearEventChanged(const ParticipantManagement::ParticipantGearEvent &data, DataModification modType) +void BuildingViewerDdsController::onParticipantGearEventChanged(const ParticipantManagement::ParticipantGearEvent& data, + DataModification modType) { - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - m_participantGearEvents[data.participantId()] = data.sampleTime(); - break; - } - case DataModification::eRemoved: - { - - const int playerId = data.participantId(); - m_participantGearEvents.remove(playerId); - m_connection->playerUpdatePlayerSymbol(playerId, buildPlayerSymbolFilePath(playerId, cColorSymbolId)); - break; - } - } + switch (modType) + { + case DataModification::eAdded: + case DataModification::eModified: { + m_participantGearEvents[data.participantId()] = data.sampleTime(); + break; + } + case DataModification::eRemoved: { + + const int playerId = data.participantId(); + m_participantGearEvents.remove(playerId); + m_connection->playerUpdatePlayerSymbol(playerId, buildPlayerSymbolFilePath(playerId, cColorSymbolId)); + break; + } + } } - -void BuildingViewerDdsController::createParticipant(const ParticipantManagement::Participant &participant, - const ParticipantManagement::ParticipantPosition &position, +void BuildingViewerDdsController::createParticipant(const ParticipantManagement::Participant& participant, + const ParticipantManagement::ParticipantPosition& position, int sizeL) { - if (!m_baseCoordinate.isValid()) - { - WARNING_LOG(m_logger) << "not calling playerPlace as there is no base coordinate set - are there no buildings in this exercise?"; - return; - } + if (!m_baseCoordinate.isValid()) + { + WARNING_LOG(m_logger) + << "not calling playerPlace as there is no base coordinate set - are there no buildings in this exercise?"; + return; + } - if (!isValidParticipant(participant)) - return; + if (!isValidParticipant(participant)) + return; - createPlayerSymbols(participant, sizeL); + createPlayerSymbols(participant, sizeL); - - m_connection->playerCreate(participant.id(), participant.partyId(), - buildPlayerSymbolFilePath(participant.id()), - toRelative3D(position.pos()), - position.buildingId(), m_roomId2RoomNumber.value(position.buildingId()).value(position.roomId()), - position.reportingSource()); + m_connection->playerCreate(participant.id(), participant.partyId(), buildPlayerSymbolFilePath(participant.id()), + toRelative3D(position.pos()), position.buildingId(), + m_roomId2RoomNumber.value(position.buildingId()).value(position.roomId()), + position.reportingSource()); - const bool isOutdated = isOutdatedPosition(position); - const int participantId = participant.id(); - const bool isValid = (position.buildingId() > 0 && m_roomId2RoomNumber.value(position.buildingId()).value(position.roomId()) > 0); - m_connection->setPlayerVisible(participantId, (!isOutdated && isValid)); - m_lastPositionTime.insert(participantId, position.sampleTime()); + const bool isOutdated = isOutdatedPosition(position); + const int participantId = participant.id(); + const bool isValid = + (position.buildingId() > 0 && m_roomId2RoomNumber.value(position.buildingId()).value(position.roomId()) > 0); + m_connection->setPlayerVisible(participantId, (!isOutdated && isValid)); + m_lastPositionTime.insert(participantId, position.sampleTime()); } -void BuildingViewerDdsController::createBoobyTrap(const AreaEffectSimulation::BoobyTrap &trap, int sizeL) +void BuildingViewerDdsController::createBoobyTrap(const AreaEffectSimulation::BoobyTrap& trap, int sizeL) { - if (trap.effectStateId() != AreaEffectSimulation::AesEffectState::EsActivated && - trap.effectStateId() != AreaEffectSimulation::AesEffectState::EsPrepared) - return; + if (trap.effectStateId() != AreaEffectSimulation::AesEffectState::EsActivated && + trap.effectStateId() != AreaEffectSimulation::AesEffectState::EsPrepared) + return; - ParticipantManagement::Participant participant; - if(trap.partyId().is_set()) - participant.partyId() = trap.partyId().get(); - participant.designator() = trap.name(); - participant.designator() = trap.name(); - participant.id() = trap.id()+990000; - participant.sampleTime() = trap.sampleTime(); - participant.symbol() = "AP6D|CMPL|10011500002104000000"; - - - - createPlayerSymbols(participant, sizeL); - Core::GeoPosition pos ; - pos.lat() = trap.impactPosition().lat(); - pos.lon() = trap.impactPosition().lon(); - - DEBUG_LOG(m_logger) << "Try create Booby trap with id " << trap.id() << " internal id " << participant.id(); - DEBUG_LOG(m_logger) << "Try create Booby trap with pos " << pos.lat() << " " << pos.lon(); - m_connection->playerCreate(participant.id(), participant.partyId(), - buildPlayerSymbolFilePath(participant.id()), - toRelative3D(pos), - -1, -1, - Core::PositionReportingSource::External); - m_connection->setPlayerVisible(participant.id(), true); + ParticipantManagement::Participant participant; + if (trap.partyId().is_set()) + participant.partyId() = trap.partyId().get(); + participant.designator() = trap.name(); + participant.designator() = trap.name(); + participant.id() = trap.id() + 990000; + participant.sampleTime() = trap.sampleTime(); + participant.symbol() = "AP6D|CMPL|10011500002104000000"; + createPlayerSymbols(participant, sizeL); + Core::GeoPosition pos; + pos.lat() = trap.impactPosition().lat(); + pos.lon() = trap.impactPosition().lon(); + DEBUG_LOG(m_logger) << "Try create Booby trap with id " << trap.id() << " internal id " << participant.id(); + DEBUG_LOG(m_logger) << "Try create Booby trap with pos " << pos.lat() << " " << pos.lon(); + m_connection->playerCreate(participant.id(), participant.partyId(), buildPlayerSymbolFilePath(participant.id()), + toRelative3D(pos), -1, -1, Core::PositionReportingSource::External); + m_connection->setPlayerVisible(participant.id(), true); } - - - void BuildingViewerDdsController::updatePlayerSymbols(const int sizeL, const int forParty) { - if (!m_ppmDtc) - return; - - auto cb = [this, sizeL, forParty](const ParticipantManagement::Participant &participant) - { - if (!isValidParticipant(participant)) - return; - - if (forParty == -1 || participant.partyId() == forParty) - createPlayerSymbols(participant, sizeL); - }; - m_ppmDtc->participants(cb); -} - - -void BuildingViewerDdsController::createPlayerSymbols(const ParticipantManagement::Participant &participant, const int sizeL) -{ - SymbolInfo symbolinfo; - for (int i = 0; i < m_vecFlashColors.size(); ++i) - { - Q_ASSERT(participant.id() != 0); - symbolinfo.participantId = participant.id(); - symbolinfo.strPathToSymbolFile = buildPlayerSymbolFilePath(participant.id(), i); - symbolinfo.color = m_vecFlashColors.at(i); - symbolinfo.useThisSymbolNow = !symbolinfo.color.isValid(); - createSymbolResultWatcher(participant, symbolinfo, sizeL); - } -} - - - - -void BuildingViewerDdsController::createSymbolResultWatcher(const ParticipantManagement::Participant &participant, - const SymbolInfo &symbolInfo, - const int sizeL) -{ - AdvancedSymbology::SymbolResultWatcher *pSymbolWatcher = new AdvancedSymbology::SymbolResultWatcher(this); - - bool symbolWatcherBenchmark = false; - if (symbolWatcherBenchmark) - { - pSymbolWatcher->m_et = new QElapsedTimer; - pSymbolWatcher->m_et->start(); - } - - bool writeParticipantSymbols = true; - if (writeParticipantSymbols) - { - QFile f(symbolInfo.strPathToSymbolFile); - if (!f.exists()) - { - QPixmap pm(1, 1); - pm.fill(Qt::black); - pm.save(symbolInfo.strPathToSymbolFile, "PNG"); - } - } - - - connect(pSymbolWatcher, &AdvancedSymbology::SymbolResultWatcher::resultReady, - this, [this, pSymbolWatcher, symbolInfo, writeParticipantSymbols, symbolWatcherBenchmark]() - { - std::shared_ptr symbolWatcherDeleter(nullptr, [this, pSymbolWatcher, symbolWatcherBenchmark](int *) - { - if (symbolWatcherBenchmark && pSymbolWatcher->m_et != nullptr) - DEBUG_LOG(m_logger) << "Symbol creation took " << pSymbolWatcher->m_et->elapsed() << " ms"; - - pSymbolWatcher->deleteLater(); - }); - (void)symbolWatcherDeleter; - - if (!pSymbolWatcher->symbolResult()->symbolImage().isValid()) - { - WARNING_LOG(m_logger) << getSessionInfo() << "'slot_SymbolWatcherResultReady': Symbol creation failed -> '!symbolImage.isValid()', BgViewer might not display symbol(s)!"; - return; - } - - int32_t playerID = symbolInfo.participantId; - - if (writeParticipantSymbols) - if (!pSymbolWatcher->symbolResult()->symbolImage().image().save(symbolInfo.strPathToSymbolFile)) - { - WARNING_LOG(m_logger) << getSessionInfo() << "Could not write symbol file for BgViewer: \"" << symbolInfo.strPathToSymbolFile << "\", BgViewer might not display symbol(s)!"; + if (!m_ppmDtc) return; - } - - if (symbolInfo.useThisSymbolNow) - m_connection->playerUpdatePlayerSymbol(playerID, symbolInfo.strPathToSymbolFile); - }); + auto cb = [this, sizeL, forParty](const ParticipantManagement::Participant& participant) { + if (!isValidParticipant(participant)) + return; - pSymbolWatcher->setSymbolResult(m_asbIfc->findImage(participant, sizeL, symbolInfo.color)); + if (forParty == -1 || participant.partyId() == forParty) + createPlayerSymbols(participant, sizeL); + }; + m_ppmDtc->participants(cb); +} + +void BuildingViewerDdsController::createPlayerSymbols(const ParticipantManagement::Participant& participant, + const int sizeL) +{ + SymbolInfo symbolinfo; + for (int i = 0; i < m_vecFlashColors.size(); ++i) + { + Q_ASSERT(participant.id() != 0); + symbolinfo.participantId = participant.id(); + symbolinfo.strPathToSymbolFile = buildPlayerSymbolFilePath(participant.id(), i); + symbolinfo.color = m_vecFlashColors.at(i); + symbolinfo.useThisSymbolNow = !symbolinfo.color.isValid(); + createSymbolResultWatcher(participant, symbolinfo, sizeL); + } +} + +void BuildingViewerDdsController::createSymbolResultWatcher(const ParticipantManagement::Participant& participant, + const SymbolInfo& symbolInfo, const int sizeL) +{ + AdvancedSymbology::SymbolResultWatcher* pSymbolWatcher = new AdvancedSymbology::SymbolResultWatcher(this); + + bool symbolWatcherBenchmark = false; + if (symbolWatcherBenchmark) + { + pSymbolWatcher->m_et = new QElapsedTimer; + pSymbolWatcher->m_et->start(); + } + + bool writeParticipantSymbols = true; + if (writeParticipantSymbols) + { + QFile f(symbolInfo.strPathToSymbolFile); + if (!f.exists()) + { + QPixmap pm(1, 1); + pm.fill(Qt::black); + pm.save(symbolInfo.strPathToSymbolFile, "PNG"); + } + } + + connect(pSymbolWatcher, &AdvancedSymbology::SymbolResultWatcher::resultReady, this, + [this, pSymbolWatcher, symbolInfo, writeParticipantSymbols, symbolWatcherBenchmark]() { + std::shared_ptr symbolWatcherDeleter( + nullptr, [this, pSymbolWatcher, symbolWatcherBenchmark](int*) { + if (symbolWatcherBenchmark && pSymbolWatcher->m_et != nullptr) + DEBUG_LOG(m_logger) << "Symbol creation took " << pSymbolWatcher->m_et->elapsed() << " ms"; + + pSymbolWatcher->deleteLater(); + }); + (void)symbolWatcherDeleter; + + if (!pSymbolWatcher->symbolResult()->symbolImage().isValid()) + { + WARNING_LOG(m_logger) << getSessionInfo() + << "'slot_SymbolWatcherResultReady': Symbol creation failed -> " + "'!symbolImage.isValid()', BgViewer might not display symbol(s)!"; + return; + } + + int32_t playerID = symbolInfo.participantId; + + if (writeParticipantSymbols) + if (!pSymbolWatcher->symbolResult()->symbolImage().image().save(symbolInfo.strPathToSymbolFile)) + { + WARNING_LOG(m_logger) + << getSessionInfo() << "Could not write symbol file for BgViewer: \"" + << symbolInfo.strPathToSymbolFile << "\", BgViewer might not display symbol(s)!"; + return; + } + + if (symbolInfo.useThisSymbolNow) + m_connection->playerUpdatePlayerSymbol(playerID, symbolInfo.strPathToSymbolFile); + }); + + pSymbolWatcher->setSymbolResult(m_asbIfc->findImage(participant, sizeL, symbolInfo.color)); } void BuildingViewerDdsController::reCheckHitLine() { - if (m_ppmDtc && m_ppmDtc->isHitLineInfoEnabled()) - { - m_ppmDtc->hitLineInfos([this](const ParticipantManagement::HitLineInfo &hli) + if (m_ppmDtc && m_ppmDtc->isHitLineInfoEnabled()) { - onHitLineInfoChanged(hli, DataModification::eAdded); - }); - } - - if (m_bldDtc && m_bldDtc->isBuildingHitLineInfoEnabled()) - { - QMap hitMap = m_bldDtc->buildingHitLineInfos(); - - for (const auto &hli : hitMap) - { - if (hli.sampleTime() < (m_session->partitionTime() - 3000)) - onBuildingHitLineInfoChanged(hli, DataModification::eAdded); + m_ppmDtc->hitLineInfos([this](const ParticipantManagement::HitLineInfo& hli) { + onHitLineInfoChanged(hli, DataModification::eAdded); + }); } - } + if (m_bldDtc && m_bldDtc->isBuildingHitLineInfoEnabled()) + { + QMap hitMap = m_bldDtc->buildingHitLineInfos(); + + for (const auto& hli : hitMap) + { + if (hli.sampleTime() < (m_session->partitionTime() - 3000)) + onBuildingHitLineInfoChanged(hli, DataModification::eAdded); + } + } } - QString BuildingViewerDdsController::buildPlayerSymbolFilePath(int playerID, int postfix) { - return gStrSymbolFolderPath() + QStringLiteral("symbol_player_%1_%2.png").arg(playerID).arg(postfix); + return gStrSymbolFolderPath() + QStringLiteral("symbol_player_%1_%2.png").arg(playerID).arg(postfix); } - void BuildingViewerDdsController::onSynchronizeSimulationTime() { - if (m_session != nullptr) - { - - m_connection->systemSetSimulationTime(m_session->partitionTime()); - } - else - WARNING_LOG(m_logger) << getSessionInfo() << "'slotSynchronizeSimulationTime': m_session is nullptr, could not query partitionTime!"; + if (m_session != nullptr) + { + + m_connection->systemSetSimulationTime(m_session->partitionTime()); + } + else + WARNING_LOG(m_logger) + << getSessionInfo() + << "'slotSynchronizeSimulationTime': m_session is nullptr, could not query partitionTime!"; } -void BuildingViewerDdsController::updateBuildingRoomNames(const InfrastructureManagement::MainStructureElement& building) +void BuildingViewerDdsController::updateBuildingRoomNames( + const InfrastructureManagement::MainStructureElement& building) { - - const std::vector &vecElements = building.elements(); + const std::vector& vecElements = building.elements(); - int32_t buildingDatabaseId = building.id(); - QString featureID = BuildingViewer::databaseId2FeatureId(buildingDatabaseId); - for (const auto &se : vecElements) - { - if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Building) - m_connection->excSetBuildingDisplayName(featureID, QString::fromStdString(se.displayName())); - if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Room) - m_connection->excSetRoomDisplayName(featureID, QString::number(se.mountingPointId()), QString::fromStdString(se.displayName())); - } + int32_t buildingDatabaseId = building.id(); + QString featureID = BuildingViewer::databaseId2FeatureId(buildingDatabaseId); + for (const auto& se : vecElements) + { + if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Building) + m_connection->excSetBuildingDisplayName(featureID, QString::fromStdString(se.displayName())); + if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Room) + m_connection->excSetRoomDisplayName(featureID, QString::number(se.mountingPointId()), + QString::fromStdString(se.displayName())); + } } - - void BuildingViewerDdsController::deleteParticipant(int participantId) { - m_connection->playerDelete(participantId); + m_connection->playerDelete(participantId); } - void BuildingViewerDdsController::onPlayerPicked(int playerId) { - if (m_ppmGuiIfc) - m_ppmGuiIfc->showParticipantInfoWindow(playerId, true); - else - INFO_LOG(m_logger) << "No m_ppmGuiIfc"; + if (m_ppmGuiIfc) + m_ppmGuiIfc->showParticipantInfoWindow(playerId, true); + else + INFO_LOG(m_logger) << "No m_ppmGuiIfc"; } - void BuildingViewerDdsController::effectGenerationUnitPicked(int structureElementId) { - if (m_blgGuiIfc) - m_blgGuiIfc->showEffectGenerationUnitWindow(structureElementId); - else - INFO_LOG(m_logger) << "No m_blgGuiIfc"; + if (m_blgGuiIfc) + m_blgGuiIfc->showEffectGenerationUnitWindow(structureElementId); + else + INFO_LOG(m_logger) << "No m_blgGuiIfc"; } - void BuildingViewerDdsController::onAssetPicked(int structureElementId) { - DEBUG_LOG(m_logger) << "User clicked on asset with structureElementId " << structureElementId << " from " << QString::number((quintptr)m_session->adr(), 16); + DEBUG_LOG(m_logger) << "User clicked on asset with structureElementId " << structureElementId << " from " + << QString::number((quintptr)m_session->adr(), 16); - if (m_session->isReplayPartition()) - return; - - if (strcmp(PROJECTBUILD, "guez") == 0 && LtsSessionData::LtsSessionData::getInstance()->isTablet()) - return; - auto it = m_mountingPointId2AssetType.find(structureElementId); - if (it == m_mountingPointId2AssetType.end()) - { - WARNING_LOG(m_logger) << "onAssetPicked: User clicked on asset mounted to structureElementId " << structureElementId << " which was not added beforehand?! Ignoring..."; - return; - } + if (m_session->isReplayPartition()) + return; - const BuildingViewer::AssetTypes assetType = it.value(); - switch (assetType) - { - case BuildingViewer::AssetTypes::AnnouncementUnit: - DEBUG_LOG(m_logger) << "Clicked asset is of type is AnnouncementUnit"; - if (m_avmIfc) - m_avmIfc->showAnnouncementUnit(structureElementId); - return; - - case BuildingViewer::AssetTypes::EffectGenerationUnit: - DEBUG_LOG(m_logger) << "Clicked asset is of type is EffectGenerationUnit"; - effectGenerationUnitPicked(structureElementId); - return; - - case BuildingViewer::AssetTypes::IndoorCameraWithSpeaker: - DEBUG_LOG(m_logger) << "Clicked asset is of type is IndoorCameraWithSpeaker"; - if (m_avmIfc) + if (strcmp(PROJECTBUILD, "guez") == 0 && LtsSessionData::LtsSessionData::getInstance()->isTablet()) + return; + auto it = m_mountingPointId2AssetType.find(structureElementId); + if (it == m_mountingPointId2AssetType.end()) { - m_avmIfc->showCamera(m_irreplacableWidget, structureElementId); - m_avmIfc->showAnnouncementUnit(structureElementId); + WARNING_LOG(m_logger) << "onAssetPicked: User clicked on asset mounted to structureElementId " + << structureElementId << " which was not added beforehand?! Ignoring..."; + return; } - return; - case BuildingViewer::AssetTypes::IndoorCamera: - DEBUG_LOG(m_logger) << "Clicked asset is of type is IndoorCamera"; - if (m_avmIfc) - m_avmIfc->showCamera(m_irreplacableWidget, structureElementId); - return; - } - WARNING_LOG(m_logger) << "onAssetPicked: BuildingViewer::AssetTypes is unknown: " << assetType; + const BuildingViewer::AssetTypes assetType = it.value(); + switch (assetType) + { + case BuildingViewer::AssetTypes::AnnouncementUnit: + DEBUG_LOG(m_logger) << "Clicked asset is of type is AnnouncementUnit"; + if (m_avmIfc) + m_avmIfc->showAnnouncementUnit(structureElementId); + return; + + case BuildingViewer::AssetTypes::EffectGenerationUnit: + DEBUG_LOG(m_logger) << "Clicked asset is of type is EffectGenerationUnit"; + effectGenerationUnitPicked(structureElementId); + return; + + case BuildingViewer::AssetTypes::IndoorCameraWithSpeaker: + DEBUG_LOG(m_logger) << "Clicked asset is of type is IndoorCameraWithSpeaker"; + if (m_avmIfc) + { + m_avmIfc->showCamera(m_irreplacableWidget, structureElementId); + m_avmIfc->showAnnouncementUnit(structureElementId); + } + return; + + case BuildingViewer::AssetTypes::IndoorCamera: + DEBUG_LOG(m_logger) << "Clicked asset is of type is IndoorCamera"; + if (m_avmIfc) + m_avmIfc->showCamera(m_irreplacableWidget, structureElementId); + return; + } + WARNING_LOG(m_logger) << "onAssetPicked: BuildingViewer::AssetTypes is unknown: " << assetType; } - -void BuildingViewerDdsController::onMountingPointChanged(const InfrastructureManagement::MountingPoint &data, DataModification modType) +void BuildingViewerDdsController::onMountingPointChanged(const InfrastructureManagement::MountingPoint& data, + DataModification modType) { - handleMountingPoint(data, modType); + handleMountingPoint(data, modType); } - -void BuildingViewerDdsController::onBuildingStateChanged(const Buildings::BuildingState &data, DataModification modType) +void BuildingViewerDdsController::onBuildingStateChanged(const Buildings::BuildingState& data, DataModification modType) { - if (modType != DataModification::eAdded && - modType != DataModification::eModified) - return; - - - - - - + if (modType != DataModification::eAdded && modType != DataModification::eModified) + return; - QMap roomDestructions; - for (const Buildings::RoomState &rs : data.roomStates()) - { - roomDestructions.insert(rs.mountingPointId(), rs.damagePercent()); - } - - m_connection->buildingHit(data.id(), data.id(), data.damagePercent(), roomDestructions); + QMap roomDestructions; + for (const Buildings::RoomState& rs : data.roomStates()) + { + roomDestructions.insert(rs.mountingPointId(), rs.damagePercent()); + } + + m_connection->buildingHit(data.id(), data.id(), data.damagePercent(), roomDestructions); } -void BuildingViewerDdsController::onBuildingHitLineInfoChanged(const Buildings::BuildingHitLineInfo &hli, DataModification modType) +void BuildingViewerDdsController::onBuildingHitLineInfoChanged(const Buildings::BuildingHitLineInfo& hli, + DataModification modType) { - int topidId = static_cast (hli.id()); + int topidId = static_cast(hli.id()); - DEBUG_LOG(m_logger) << "onBuildingHitLineInfoChanged: " << hli; + DEBUG_LOG(m_logger) << "onBuildingHitLineInfoChanged: " << hli; - const QString &strFeatureID = BuildingViewer::databaseId2FeatureId(hli.buildingId()); - if (!m_viewerInterface->isViewOpen(strFeatureID.toStdString())) - { - DEBUG_LOG(m_logger) << "building not opened: hli.buildingId()=" << hli.buildingId() ; - return; - } - - - - - - - const bool isRemove = (modType == DataModification::eRemoved); - DEBUG_LOG(m_logger) << "isRemove=" << isRemove; - - if (isRemove) - { - DEBUG_LOG(m_logger) << "onBuildingHitLineInfoChanged: remove "; - QVector &bhl = m_buildingHits[hli.buildingId()]; - - auto it = std::find_if(bhl.begin(), bhl.end(), [hli](const BuildingHit &bh) + const QString& strFeatureID = BuildingViewer::databaseId2FeatureId(hli.buildingId()); + if (!m_viewerInterface->isViewOpen(strFeatureID.toStdString())) { - return (bh.id == hli.id()); - }); - - if (it != bhl.end()) - { - DEBUG_LOG(m_logger) << "bhl.erase(it)"; - bhl.erase(it); + DEBUG_LOG(m_logger) << "building not opened: hli.buildingId()=" << hli.buildingId(); + return; } - m_connection->removeRoomHit(hli.id()); - return; - } - else - { - BuildingHit bh; - bh.id = hli.id(); - bh.sampleTime = hli.sampleTime(); - bh.originatorParticipantId = hli.originatorParticipantId(); - bh.chargeTypeId = hli.chargeTypeId(); - - - bool contains = false; - for (const auto &it : m_buildingHits[hli.buildingId()] ) + + const bool isRemove = (modType == DataModification::eRemoved); + DEBUG_LOG(m_logger) << "isRemove=" << isRemove; + + if (isRemove) { - if (it.id == bh.id) - contains = true; + DEBUG_LOG(m_logger) << "onBuildingHitLineInfoChanged: remove "; + QVector& bhl = m_buildingHits[hli.buildingId()]; + + auto it = std::find_if(bhl.begin(), bhl.end(), [hli](const BuildingHit& bh) { return (bh.id == hli.id()); }); + + if (it != bhl.end()) + { + DEBUG_LOG(m_logger) << "bhl.erase(it)"; + bhl.erase(it); + } + m_connection->removeRoomHit(hli.id()); + return; } - if (!contains) + else { - - m_buildingHits[hli.buildingId()].push_back(bh); + BuildingHit bh; + bh.id = hli.id(); + bh.sampleTime = hli.sampleTime(); + bh.originatorParticipantId = hli.originatorParticipantId(); + bh.chargeTypeId = hli.chargeTypeId(); + + bool contains = false; + for (const auto& it : m_buildingHits[hli.buildingId()]) + { + if (it.id == bh.id) + contains = true; + } + if (!contains) + { + + m_buildingHits[hli.buildingId()].push_back(bh); + } } - } - int lineType = 2; - - m_connection->roomHit(topidId, hli.originatorParticipantId(), hli.buildingId(), hli.hitOnRoomId(), - toRelative3D(hli.originatorPos()), lineType, isRemove ? 0 : hli.sampleTime()); + int lineType = 2; + + m_connection->roomHit(topidId, hli.originatorParticipantId(), hli.buildingId(), hli.hitOnRoomId(), + toRelative3D(hli.originatorPos()), lineType, isRemove ? 0 : hli.sampleTime()); } void BuildingViewerDdsController::onCleanupBuildingHitlines() { - DEBUG_LOG(m_logger) << "onCleanupBuildingHitlines: "; - const qint64 tNow = QDateTime::currentMSecsSinceEpoch(); - const auto isOutdated = [tNow](const BuildingHit &bh) - { - return LtsUtils::isPositionTimeOutdated(tNow, bh.sampleTime); - }; - for (auto &hitLines : m_buildingHits) - hitLines.erase(std::remove_if(hitLines.begin(), hitLines.end(), isOutdated), hitLines.end()); + DEBUG_LOG(m_logger) << "onCleanupBuildingHitlines: "; + const qint64 tNow = QDateTime::currentMSecsSinceEpoch(); + const auto isOutdated = [tNow](const BuildingHit& bh) { + return LtsUtils::isPositionTimeOutdated(tNow, bh.sampleTime); + }; + for (auto& hitLines : m_buildingHits) + hitLines.erase(std::remove_if(hitLines.begin(), hitLines.end(), isOutdated), hitLines.end()); } -void BuildingViewerDdsController::onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &mse, DataModification modType) +void BuildingViewerDdsController::onMainStructureElementChanged( + const InfrastructureManagement::MainStructureElement& mse, DataModification modType) { - if (!isBuildingKnown(mse.id())) - return; + if (!isBuildingKnown(mse.id())) + return; - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - { - if (mse.modelId() != 0 && m_ismDtc->isElementAssignedToExercise(mse, m_exerciseId)) + switch (modType) { - DEBUG_LOG(m_logger) << "m_buildingHeight.insert id=" << mse.id() << " z=" << mse.geoPosition().z(); - m_buildingHeight.insert(mse.id(), mse.geoPosition().z()); - QHash roomId2RoomNumber; - for (const InfrastructureManagement::StructureElement &se : mse.elements()) - { - if (se.structureElementTypeId() != InfrastructureManagement::StructureElementType::Room) - continue; - roomId2RoomNumber[se.id()] = se.mountingPointId(); - } - m_roomId2RoomNumber[mse.id()] = roomId2RoomNumber; + case DataModification::eAdded: + case DataModification::eModified: { + if (mse.modelId() != 0 && m_ismDtc->isElementAssignedToExercise(mse, m_exerciseId)) + { + DEBUG_LOG(m_logger) << "m_buildingHeight.insert id=" << mse.id() << " z=" << mse.geoPosition().z(); + m_buildingHeight.insert(mse.id(), mse.geoPosition().z()); + QHash roomId2RoomNumber; + for (const InfrastructureManagement::StructureElement& se : mse.elements()) + { + if (se.structureElementTypeId() != InfrastructureManagement::StructureElementType::Room) + continue; + roomId2RoomNumber[se.id()] = se.mountingPointId(); + } + m_roomId2RoomNumber[mse.id()] = roomId2RoomNumber; - updateBuildingRoomNames(mse); + updateBuildingRoomNames(mse); + } + break; + } + case DataModification::eRemoved: + m_roomId2RoomNumber.remove(mse.id()); + m_buildingHeight.remove(mse.id()); + break; } - break; - } - case DataModification::eRemoved: - m_roomId2RoomNumber.remove(mse.id()); - m_buildingHeight.remove(mse.id()); - break; - } } - QString BuildingViewerDdsController::getSessionInfo() const { - if (m_session == nullptr) - return QStringLiteral("session == nullptr: "); + if (m_session == nullptr) + return QStringLiteral("session == nullptr: "); - return m_session->toString() + QStringLiteral(": "); + return m_session->toString() + QStringLiteral(": "); } - void BuildingViewerDdsController::onFireEventFlashTimer() { - static int currFlashState = 0; + static int currFlashState = 0; - if (m_session == nullptr) - { - DEBUG_LOG(m_logger) << getSessionInfo() << "onFireEventFlashTimer: Session is not available, flashing not possible!"; - return; - } - - ++currFlashState; - - if (currFlashState >= m_vecFlashColors.size()) - currFlashState = 0; - - - qint64 currTime_ms = m_session->partitionTime(); - int gearFlashTime_ms = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("GearFlashTime_s"), 10).toInt() * 1000; - int maxGearFlashTime_ms = LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("BgViewer"), QStringLiteral("maxGearFlashTime_s"), 120).toInt() * 1000; - - auto itB = m_participantGearEvents.begin(); - while (itB != m_participantGearEvents.end()) - { - const int playerID = itB.key(); - qint64 eventStartTime_ms = itB.value(); - - qint64 diff_ms = currTime_ms - eventStartTime_ms; - - if(diff_ms > gearFlashTime_ms) + if (m_session == nullptr) { - if(diff_ms > maxGearFlashTime_ms) - itB = m_participantGearEvents.erase(itB); - else - ++itB; - - m_connection->playerUpdatePlayerSymbol(playerID, buildPlayerSymbolFilePath(playerID, cColorSymbolId)); - continue; + DEBUG_LOG(m_logger) << getSessionInfo() + << "onFireEventFlashTimer: Session is not available, flashing not possible!"; + return; } - m_connection->playerUpdatePlayerSymbol(playerID, buildPlayerSymbolFilePath(playerID, currFlashState)); - ++itB; - } + ++currFlashState; - for (auto it = m_lastPositionTime.cbegin(); it != m_lastPositionTime.cend(); ++it) - { - const int playerId = it.key(); - const qint64 sampleTime = it.value(); - if (isOutdatedPosition(sampleTime)) - m_connection->setPlayerVisible(playerId, false); - } + if (currFlashState >= m_vecFlashColors.size()) + currFlashState = 0; + + qint64 currTime_ms = m_session->partitionTime(); + int gearFlashTime_ms = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("GearFlashTime_s"), 10) + .toInt() * + 1000; + int maxGearFlashTime_ms = LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("BgViewer"), QStringLiteral("maxGearFlashTime_s"), 120) + .toInt() * + 1000; + + auto itB = m_participantGearEvents.begin(); + while (itB != m_participantGearEvents.end()) + { + const int playerID = itB.key(); + qint64 eventStartTime_ms = itB.value(); + + qint64 diff_ms = currTime_ms - eventStartTime_ms; + + if (diff_ms > gearFlashTime_ms) + { + if (diff_ms > maxGearFlashTime_ms) + itB = m_participantGearEvents.erase(itB); + else + ++itB; + + m_connection->playerUpdatePlayerSymbol(playerID, buildPlayerSymbolFilePath(playerID, cColorSymbolId)); + continue; + } + + m_connection->playerUpdatePlayerSymbol(playerID, buildPlayerSymbolFilePath(playerID, currFlashState)); + ++itB; + } + + for (auto it = m_lastPositionTime.cbegin(); it != m_lastPositionTime.cend(); ++it) + { + const int playerId = it.key(); + const qint64 sampleTime = it.value(); + if (isOutdatedPosition(sampleTime)) + m_connection->setPlayerVisible(playerId, false); + } } -} - - - +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.h old mode 100755 new mode 100644 index d1060cebe..bcea3f53d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Common/bdv_dds_controller.h @@ -1,34 +1,30 @@ - #pragma once -#include +#include "buildingviewercommon_export.h" -#include -#include -#include -#include - -#include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include -#include #include -#include -#include -#include #include +#include #include -#include -#include -#include "buildingviewercommon_export.h" -#include -#include -#include - +#include +#include +#include +#include #include +#include namespace BuildingViewer { @@ -37,141 +33,152 @@ class PluginProvider; class BuildingViewerDdsController : public QObject { - Q_OBJECT + Q_OBJECT -public: - explicit BuildingViewerDdsController(CommunicationInterfaceInternal *connection, - VCtrl::ViewerInterface* viewerInterface); - ~BuildingViewerDdsController(); - bool init(QWidget *irreplacableWidget, const QString &modelPath, PluginProvider *session); - void uninitialize(); + public: + explicit BuildingViewerDdsController(CommunicationInterfaceInternal* connection, + VCtrl::ViewerInterface* viewerInterface); + ~BuildingViewerDdsController(); + bool init(QWidget* irreplacableWidget, const QString& modelPath, PluginProvider* session); + void uninitialize(); - void updatePlayerSymbols(const int sizeL, const int forParty = -1); + void updatePlayerSymbols(const int sizeL, const int forParty = -1); - void clearAssets(); - PluginProvider *activeSession() const { return m_session; } + void clearAssets(); -signals: - void signalDdsInitFinished(); -private: -NGL::INGLLogger &m_logger; - void setCurrentTrainingAreaMap(const QString &modelPath); -private slots: - void onPartyChanged(const ParticipantManagement::Party &party, DataModification modType); - void onBgViewerInitFinished(); - void onFireEventFlashTimer(); - void onSynchronizeSimulationTime(); - void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap &boobyTrap, DataModification modType); - void onParticipantChanged(const ParticipantManagement::Participant &participant, DataModification modType); - void onDynParticipantChanged(const ParticipantManagement::DynamicParticipantData &data, DataModification modType); - void onPositionChanged(const ParticipantManagement::ParticipantPosition &position, DataModification modType); - void onHitLineInfoChanged(const ParticipantManagement::HitLineInfo &hli, DataModification modType); - void onParticipantGearEventChanged(const ParticipantManagement::ParticipantGearEvent &data, DataModification modType); + PluginProvider* activeSession() const + { + return m_session; + } - void onPlayerPicked(int playerId); - void onAssetPicked(int structureElementId); - void onMountingPointChanged(const InfrastructureManagement::MountingPoint &data, DataModification modType); - void onBuildingStateChanged(const Buildings::BuildingState &data, DataModification modType); - void onCleanupBuildingHitlines(); - void onBuildingHitLineInfoChanged(const Buildings::BuildingHitLineInfo &hli, DataModification modType); - void onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &mse, DataModification modType); + signals: + void signalDdsInitFinished(); -private: - QPointF toRelativePosition(const Core::GeoPosition &geoPos) const; - LtsUtils::QPoint3D toRelative3D(const Core::GeoPosition &geoPos) const; - bool clear(); - bool syncTeams(); - bool setPaused(bool bPaused); - bool isOutdatedPosition(qint64 sampleTime) const; - inline bool isOutdatedPosition(const ParticipantManagement::ParticipantPosition &position) const - { - return position.participantId() <= 0 || isOutdatedPosition(position.sampleTime()); - } + private: + NGL::INGLLogger& m_logger; + void setCurrentTrainingAreaMap(const QString& modelPath); + private slots: + void onPartyChanged(const ParticipantManagement::Party& party, DataModification modType); + void onBgViewerInitFinished(); + void onFireEventFlashTimer(); + void onSynchronizeSimulationTime(); + void onBoobyTrapChanged(const AreaEffectSimulation::BoobyTrap& boobyTrap, DataModification modType); + void onParticipantChanged(const ParticipantManagement::Participant& participant, DataModification modType); + void onDynParticipantChanged(const ParticipantManagement::DynamicParticipantData& data, DataModification modType); + void onPositionChanged(const ParticipantManagement::ParticipantPosition& position, DataModification modType); + void onHitLineInfoChanged(const ParticipantManagement::HitLineInfo& hli, DataModification modType); + void onParticipantGearEventChanged(const ParticipantManagement::ParticipantGearEvent& data, + DataModification modType); - bool calcBaseCoordinate(const QMap &mseMap); - void sendAssets(); - void handleMountingPoint(const InfrastructureManagement::MountingPoint &mp, DataModification modType); - void onReplayChanged(const SituationReplay::SitReplay &srp, DataModification modType); - void effectGenerationUnitPicked(int structureElementId); - QHash m_mountingPointId2AssetType; - QHash m_knownAssetsInBgViewer; + void onPlayerPicked(int playerId); + void onAssetPicked(int structureElementId); + void onMountingPointChanged(const InfrastructureManagement::MountingPoint& data, DataModification modType); + void onBuildingStateChanged(const Buildings::BuildingState& data, DataModification modType); + void onCleanupBuildingHitlines(); + void onBuildingHitLineInfoChanged(const Buildings::BuildingHitLineInfo& hli, DataModification modType); + void onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement& mse, + DataModification modType); - void createBoobyTraps(); - void createParticipants(); - bool isValidParticipant(const ParticipantManagement::Participant &participant) const; - void createParticipant(const ParticipantManagement::Participant &participant, const ParticipantManagement::ParticipantPosition &position, int sizeL); - void createBoobyTrap(const AreaEffectSimulation::BoobyTrap &trap, int sizeL); - void deleteParticipant(int participantId); - void updateBuildingRoomNames(const InfrastructureManagement::MainStructureElement& building); - bool writeBuildingDataToXML(const QString &modelPath); - QString getBuildingConfigurationXml() const; + private: + QPointF toRelativePosition(const Core::GeoPosition& geoPos) const; + LtsUtils::QPoint3D toRelative3D(const Core::GeoPosition& geoPos) const; + bool clear(); + bool syncTeams(); + bool setPaused(bool bPaused); + bool isOutdatedPosition(qint64 sampleTime) const; - static QString buildPlayerSymbolFilePath(int playerID, int postfix = 0); + inline bool isOutdatedPosition(const ParticipantManagement::ParticipantPosition& position) const + { + return position.participantId() <= 0 || isOutdatedPosition(position.sampleTime()); + } - struct SymbolInfo - { - QString strPathToSymbolFile; - QColor color; - int participantId = -1; - bool useThisSymbolNow = false; - }; + bool calcBaseCoordinate(const QMap& mseMap); + void sendAssets(); + void handleMountingPoint(const InfrastructureManagement::MountingPoint& mp, DataModification modType); + void onReplayChanged(const SituationReplay::SitReplay& srp, DataModification modType); + void effectGenerationUnitPicked(int structureElementId); + QHash m_mountingPointId2AssetType; + QHash m_knownAssetsInBgViewer; + void createBoobyTraps(); + void createParticipants(); + bool isValidParticipant(const ParticipantManagement::Participant& participant) const; + void createParticipant(const ParticipantManagement::Participant& participant, + const ParticipantManagement::ParticipantPosition& position, int sizeL); + void createBoobyTrap(const AreaEffectSimulation::BoobyTrap& trap, int sizeL); + void deleteParticipant(int participantId); + void updateBuildingRoomNames(const InfrastructureManagement::MainStructureElement& building); + bool writeBuildingDataToXML(const QString& modelPath); + QString getBuildingConfigurationXml() const; - QHash m_participantGearEvents; - QHash m_lastPositionTime; - struct BuildingHit - { - int32_t id = 0; - int64_t sampleTime = 0; - int originatorParticipantId = 0; - int chargeTypeId = 0; - }; - QHash> m_buildingHits; - QVector m_knownBuildings; - inline bool isBuildingKnown(int id) const - { - return std::find(m_knownBuildings.cbegin(), m_knownBuildings.cend(), id) != m_knownBuildings.cend(); - } + static QString buildPlayerSymbolFilePath(int playerID, int postfix = 0); - const int cColorSymbolId = 0; - const QVector m_vecFlashColors = {QColor(), Qt::white, Qt::gray}; - void createPlayerSymbols(const ParticipantManagement::Participant &participant, const int sizeL); - void createSymbolResultWatcher(const ParticipantManagement::Participant &participant, const SymbolInfo &symbolInfo, const int sizeL); - QHash m_mapActiveSymbolResultWatcher; - void reCheckHitLine(); - QString getSessionInfo() const; - PluginProvider *m_session = nullptr; - int m_exerciseId = -1; - std::shared_ptr m_avmIfc; - std::shared_ptr m_asbIfc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ppmGuiIfc; - std::shared_ptr m_ismDtc; - std::shared_ptr m_ismIfc; - std::shared_ptr m_bldDtc; - std::shared_ptr m_srpDtc; - std::shared_ptr m_blgGuiIfc; + struct SymbolInfo + { + QString strPathToSymbolFile; + QColor color; + int participantId = -1; + bool useThisSymbolNow = false; + }; - void stopAndClearTimer(); - QTimer *m_pSimTimeSyncTimer = nullptr; - QTimer *m_pFireEventFlashTimer = nullptr; - QTimer *m_pBuildingHitlineCleanupTimer = nullptr; - bool m_ddsInitFinished = false; - int m_dtc_timeout_ms = 10000; - int m_hitlineDuration_ms = 10 * 1000; - + QHash m_participantGearEvents; + QHash m_lastPositionTime; - int m_bgviewer_simSyncTimeInterval_ms = 3000; + struct BuildingHit + { + int32_t id = 0; + int64_t sampleTime = 0; + int originatorParticipantId = 0; + int chargeTypeId = 0; + }; - QHash> m_roomId2RoomNumber; - CommunicationInterfaceInternal *m_connection{nullptr}; - VCtrl::ViewerInterface* m_viewerInterface{nullptr}; - QTimer *m_reCheckTimer{nullptr}; - LtsCoordTrans::UtmCoordinate m_baseCoordinate; - QHash < int32_t, double > m_buildingHeight; - QWidget *m_irreplacableWidget {nullptr}; + QHash> m_buildingHits; + QVector m_knownBuildings; + + inline bool isBuildingKnown(int id) const + { + return std::find(m_knownBuildings.cbegin(), m_knownBuildings.cend(), id) != m_knownBuildings.cend(); + } + + const int cColorSymbolId = 0; + const QVector m_vecFlashColors = {QColor(), Qt::white, Qt::gray}; + void createPlayerSymbols(const ParticipantManagement::Participant& participant, const int sizeL); + void createSymbolResultWatcher(const ParticipantManagement::Participant& participant, const SymbolInfo& symbolInfo, + const int sizeL); + QHash m_mapActiveSymbolResultWatcher; + void reCheckHitLine(); + QString getSessionInfo() const; + PluginProvider* m_session = nullptr; + int m_exerciseId = -1; + std::shared_ptr m_avmIfc; + std::shared_ptr m_asbIfc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ppmGuiIfc; + std::shared_ptr m_ismDtc; + std::shared_ptr m_ismIfc; + std::shared_ptr m_bldDtc; + std::shared_ptr m_srpDtc; + std::shared_ptr m_blgGuiIfc; + + void stopAndClearTimer(); + QTimer* m_pSimTimeSyncTimer = nullptr; + QTimer* m_pFireEventFlashTimer = nullptr; + QTimer* m_pBuildingHitlineCleanupTimer = nullptr; + bool m_ddsInitFinished = false; + int m_dtc_timeout_ms = 10000; + int m_hitlineDuration_ms = 10 * 1000; + + int m_bgviewer_simSyncTimeInterval_ms = 3000; + + QHash> m_roomId2RoomNumber; + CommunicationInterfaceInternal* m_connection{nullptr}; + VCtrl::ViewerInterface* m_viewerInterface{nullptr}; + QTimer* m_reCheckTimer{nullptr}; + LtsCoordTrans::UtmCoordinate m_baseCoordinate; + QHash m_buildingHeight; + QWidget* m_irreplacableWidget{nullptr}; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.cpp old mode 100755 new mode 100644 index 1dd1acc9a..3cb00972a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.cpp @@ -1,338 +1,304 @@ - #include "bdv_building_edit.h" + #include "bdv_edit_item.h" #include "ui_bdv_building_edit.h" -#include -#include - -#include #include #include - +#include +#include +#include #include namespace BuildingViewer { -BuildingEdit::BuildingEdit(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::BuildingEdit) +BuildingEdit::BuildingEdit(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::BuildingEdit) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &BuildingEdit::slotEditItem); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &BuildingEdit::slotEditItem); - bool userHasRightsToEdit = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::BuildingViewerSettingsEdit); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(userHasRightsToEdit); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setVisible(userHasRightsToEdit); + bool userHasRightsToEdit = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::BuildingViewerSettingsEdit); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(userHasRightsToEdit); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setVisible(userHasRightsToEdit); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableGuiDestroyRooms = ps->value(QStringLiteral("bld"), - QStringLiteral("enableGuiDestroyRooms")).toBool(); - - auto btnDestroy = m_buttonBox->getButton(LtsWidgets::DialogButton::Add); - btnDestroy->setText(tr("Destroy")); - btnDestroy->setVisible(enableGuiDestroyRooms); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableGuiDestroyRooms = + ps->value(QStringLiteral("bld"), QStringLiteral("enableGuiDestroyRooms")).toBool(); - connect(btnDestroy, &QPushButton::pressed, this, &BuildingEdit::onDestroyElement); + auto btnDestroy = m_buttonBox->getButton(LtsWidgets::DialogButton::Add); + btnDestroy->setText(tr("Destroy")); + btnDestroy->setVisible(enableGuiDestroyRooms); + connect(btnDestroy, &QPushButton::pressed, this, &BuildingEdit::onDestroyElement); - setOnlineHelpFilename(QStringLiteral("Building_Viewer-Building_List")); + setOnlineHelpFilename(QStringLiteral("Building_Viewer-Building_List")); } - BuildingEdit::~BuildingEdit() { - delete m_ui; + delete m_ui; } - void BuildingEdit::retranslate() { - translate(m_ui, tr("Building Edit: %1").arg(m_buildingName)); + translate(m_ui, tr("Building Edit: %1").arg(m_buildingName)); } - bool BuildingEdit::init(int32_t buildingDatabaseId, - const std::shared_ptr &ismDtc, - const std::shared_ptr &ismFtc, - const std::shared_ptr &bldDtc, - const std::shared_ptr &bldFtc) + const std::shared_ptr& ismDtc, + const std::shared_ptr& ismFtc, + const std::shared_ptr& bldDtc, + const std::shared_ptr& bldFtc) { - if (m_ismDtc) - return false; - m_buildingDatabaseId = buildingDatabaseId; + if (m_ismDtc) + return false; + m_buildingDatabaseId = buildingDatabaseId; - m_ismDtc = ismDtc; - m_ismFtc = ismFtc; - m_bldDtc = bldDtc; - m_bldFtc = bldFtc; + m_ismDtc = ismDtc; + m_ismFtc = ismFtc; + m_bldDtc = bldDtc; + m_bldFtc = bldFtc; - - InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(m_buildingDatabaseId); - m_buildingId = building.id(); + InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(m_buildingDatabaseId); + m_buildingId = building.id(); - buildModel(); - m_buildingName = m_model->getBuildingName(); + buildModel(); + m_buildingName = m_model->getBuildingName(); - if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::BuildingViewerSettingsEdit)) - { - connect(m_ui->treeViewEdit, &QTreeView::clicked, this, &BuildingEdit::slotTreeViewClicked); - connect(m_ui->treeViewEdit, &QTreeView::doubleClicked, this, &BuildingEdit::slotDoubleClicked); - connect(m_model, &BuildingEditModel::signalModelDataChanged, this, &BuildingEdit::slotChangesMade); - } + if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::BuildingViewerSettingsEdit)) + { + connect(m_ui->treeViewEdit, &QTreeView::clicked, this, &BuildingEdit::slotTreeViewClicked); + connect(m_ui->treeViewEdit, &QTreeView::doubleClicked, this, &BuildingEdit::slotDoubleClicked); + connect(m_model, &BuildingEditModel::signalModelDataChanged, this, &BuildingEdit::slotChangesMade); + } - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, - this, &BuildingEdit::slotMainStructureElementChanged); + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + &BuildingEdit::slotMainStructureElementChanged); - connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, - this, &BuildingEdit::slotBuildingStateChanged); + connect(m_bldDtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, this, + &BuildingEdit::slotBuildingStateChanged); - - return true; + return true; } - void BuildingEdit::slotTreeViewClicked() { - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(selectedIndexView().isValid()); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(selectedIndexView().isValid()); } - void BuildingEdit::buildModel() { - m_model = new BuildingEditModel(this, m_ismDtc, m_bldDtc); + m_model = new BuildingEditModel(this, m_ismDtc, m_bldDtc); - - m_proxyModel = new BuildingEditProxyModel(this); - m_proxyModel->setSourceModel(m_model); + m_proxyModel = new BuildingEditProxyModel(this); + m_proxyModel->setSourceModel(m_model); - - m_ui->treeViewEdit->setModel(m_proxyModel); - m_ui->treeViewEdit->expandAll(); - m_ui->treeViewEdit->sortByColumn(BuildingEditModel::Building, Qt::AscendingOrder); + m_ui->treeViewEdit->setModel(m_proxyModel); + m_ui->treeViewEdit->expandAll(); + m_ui->treeViewEdit->sortByColumn(BuildingEditModel::Building, Qt::AscendingOrder); - - m_ui->treeViewEdit->setContextMenuPolicy(Qt::CustomContextMenu); + m_ui->treeViewEdit->setContextMenuPolicy(Qt::CustomContextMenu); - m_model->init(m_buildingDatabaseId); - m_ui->treeViewEdit->expandAll(); - m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::Building, 230); + m_model->init(m_buildingDatabaseId); + m_ui->treeViewEdit->expandAll(); + m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::Building, 230); #ifdef LTS_DEBUG - m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::Name, 150); - m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::MountingPointId, 120); - m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::StructureElementId, 80); + m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::Name, 150); + m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::MountingPointId, 120); + m_ui->treeViewEdit->setColumnWidth(BuildingEditModel::StructureElementId, 80); #else - m_ui->treeViewEdit->hideColumn(BuildingEditModel::Name); - m_ui->treeViewEdit->hideColumn(BuildingEditModel::MountingPointId); - m_ui->treeViewEdit->hideColumn(BuildingEditModel::StructureElementId); + m_ui->treeViewEdit->hideColumn(BuildingEditModel::Name); + m_ui->treeViewEdit->hideColumn(BuildingEditModel::MountingPointId); + m_ui->treeViewEdit->hideColumn(BuildingEditModel::StructureElementId); #endif } - QModelIndex BuildingEdit::selectedIndexView() const { - QItemSelectionModel *selectionModel = m_ui->treeViewEdit->selectionModel(); - QModelIndexList indexL = selectionModel->selectedRows(0); - if (indexL.size() == 0) - return QModelIndex(); + QItemSelectionModel* selectionModel = m_ui->treeViewEdit->selectionModel(); + QModelIndexList indexL = selectionModel->selectedRows(0); + if (indexL.size() == 0) + return QModelIndex(); - return m_proxyModel->mapToSource(indexL.at(0)); + return m_proxyModel->mapToSource(indexL.at(0)); } - void BuildingEdit::slotEditItem() { - QModelIndex selIndex = selectedIndexView(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexView(); + if (!selIndex.isValid()) + return; - BuildingViewer::TreeItem data = m_model->privateData(selIndex)->data().value(); + BuildingViewer::TreeItem data = m_model->privateData(selIndex)->data().value(); - ParticipantEditItemWidget *newItemDlg = new ParticipantEditItemWidget(m_buildingName, data, this); - newItemDlg->setAttribute(Qt::WA_DeleteOnClose); + ParticipantEditItemWidget* newItemDlg = new ParticipantEditItemWidget(m_buildingName, data, this); + newItemDlg->setAttribute(Qt::WA_DeleteOnClose); - connect(newItemDlg, &ParticipantEditItemWidget::signalItemUpdated, - m_model, &BuildingEditModel::slotUpdateRow); + connect(newItemDlg, &ParticipantEditItemWidget::signalItemUpdated, m_model, &BuildingEditModel::slotUpdateRow); - newItemDlg->show(); + newItemDlg->show(); } - - - bool BuildingEdit::apply() { - - const auto fortifyFactors = m_model->getRoomsWithChangedFortifyFactors(); - + const auto fortifyFactors = m_model->getRoomsWithChangedFortifyFactors(); - - DEBUG_LOG(m_logger) << "fortifyFactors.size()=" << fortifyFactors.size(); - if (fortifyFactors.size()) - { - m_requestHelper->addRequest([this, fortifyFactors]() + DEBUG_LOG(m_logger) << "fortifyFactors.size()=" << fortifyFactors.size(); + if (fortifyFactors.size()) { - Buildings::SetFortifyFactorRequest fortifyRequest; - fortifyRequest.buildingId(m_buildingDatabaseId); + m_requestHelper->addRequest([this, fortifyFactors]() { + Buildings::SetFortifyFactorRequest fortifyRequest; + fortifyRequest.buildingId(m_buildingDatabaseId); - - fortifyRequest.fortifyFactors().reserve(fortifyFactors.size()); - for (const auto &e : fortifyFactors) - { - DEBUG_LOG(m_logger) << "push_back= databaseId=" << e.structureElementId() - << " fortifyFactor=" << e.fortifyFactor(); - fortifyRequest.fortifyFactors().push_back(Buildings::FortifyFactor(e.structureElementId(), e.fortifyFactor())); - } + fortifyRequest.fortifyFactors().reserve(fortifyFactors.size()); + for (const auto& e : fortifyFactors) + { + DEBUG_LOG(m_logger) << "push_back= databaseId=" << e.structureElementId() + << " fortifyFactor=" << e.fortifyFactor(); + fortifyRequest.fortifyFactors().push_back( + Buildings::FortifyFactor(e.structureElementId(), e.fortifyFactor())); + } - return m_bldFtc->setFortifyFactorRequest(fortifyRequest, this); - }); - } - - - const auto displayNames = m_model->getRoomsWithChangedDisplayNames(); - - - - if (displayNames.size()) - { - std::vector vecModifiedRooms; - vecModifiedRooms.reserve(displayNames.size()); - InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(m_buildingDatabaseId); - - for (const auto &treeItem : displayNames) - { - - for (const auto &room : building.elements()) - { - if (room.id() == treeItem.structureElementId()) - { - auto copy = room; - copy.displayName(treeItem.displayName().toStdString()); - vecModifiedRooms.push_back(copy); - break; - } - } + return m_bldFtc->setFortifyFactorRequest(fortifyRequest, this); + }); } - m_requestHelper->addRequest([this, vecModifiedRooms]() - { - InfrastructureManagement::StructureElementModifyRequest request(m_buildingDatabaseId, vecModifiedRooms); - return m_ismFtc->structureElementModifyRequest(request, this); - }); - } - return m_requestHelper->startRequests(); -} + const auto displayNames = m_model->getRoomsWithChangedDisplayNames(); + if (displayNames.size()) + { + std::vector vecModifiedRooms; + vecModifiedRooms.reserve(displayNames.size()); + InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(m_buildingDatabaseId); + + for (const auto& treeItem : displayNames) + { + + for (const auto& room : building.elements()) + { + if (room.id() == treeItem.structureElementId()) + { + auto copy = room; + copy.displayName(treeItem.displayName().toStdString()); + vecModifiedRooms.push_back(copy); + break; + } + } + } + + m_requestHelper->addRequest([this, vecModifiedRooms]() { + InfrastructureManagement::StructureElementModifyRequest request(m_buildingDatabaseId, vecModifiedRooms); + return m_ismFtc->structureElementModifyRequest(request, this); + }); + } + return m_requestHelper->startRequests(); +} void BuildingEdit::selectRoomRow(int mountingPointId) { - QModelIndex mIndex = m_model->modelIndexByStructureElementId(mountingPointId); - m_ui->treeViewEdit->setCurrentIndex(mIndex); - m_ui->treeViewEdit->selectionModel()->setCurrentIndex(mIndex, QItemSelectionModel::ClearAndSelect); + QModelIndex mIndex = m_model->modelIndexByStructureElementId(mountingPointId); + m_ui->treeViewEdit->setCurrentIndex(mIndex); + m_ui->treeViewEdit->selectionModel()->setCurrentIndex(mIndex, QItemSelectionModel::ClearAndSelect); } - void BuildingEdit::reinitModel() { - m_model->init(m_buildingDatabaseId); - m_ui->treeViewEdit->expandAll(); + m_model->init(m_buildingDatabaseId); + m_ui->treeViewEdit->expandAll(); } - -void BuildingEdit::slotDoubleClicked(const QModelIndex &selIndex) +void BuildingEdit::slotDoubleClicked(const QModelIndex& selIndex) { - if (!selIndex.isValid()) - return; + if (!selIndex.isValid()) + return; - slotEditItem(); + slotEditItem(); } - - - -void BuildingEdit::slotMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &mse, DataModification modType) +void BuildingEdit::slotMainStructureElementChanged(const InfrastructureManagement::MainStructureElement& mse, + DataModification modType) { - if(modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - if(mse.id() == m_buildingDatabaseId) - { - - slotHandleExternalDdsChange(); - } + if (mse.id() == m_buildingDatabaseId) + { + + slotHandleExternalDdsChange(); + } } - -void BuildingEdit::slotBuildingStateChanged(const Buildings::BuildingState &state, DataModification modType) +void BuildingEdit::slotBuildingStateChanged(const Buildings::BuildingState& state, DataModification modType) { - if(modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - if(state.id() == m_buildingDatabaseId) - { - - slotHandleExternalDdsChange(); - } + if (state.id() == m_buildingDatabaseId) + { + + slotHandleExternalDdsChange(); + } } - void BuildingEdit::slotHandleExternalDdsChange() { - reinitModel(); + reinitModel(); } -bool BuildingEdit::sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState state, std::vector structureElementIds) +bool BuildingEdit::sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState state, + std::vector structureElementIds) { - - m_requestHelper->addRequest([this, state, structureElementIds]() - { - Buildings::Building building; - std::vector< Buildings::Building > buildings; - buildings.resize(1); - Buildings::SetBuildingStatesRequest requestData; - - building.buildingId(m_buildingId); - building.roomIds().set(structureElementIds); - buildings[0] = building; - requestData.buildings(buildings); - requestData.vulnerabilityState(state); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentData: " << state; + m_requestHelper->addRequest([this, state, structureElementIds]() { + Buildings::Building building; + std::vector buildings; + buildings.resize(1); + Buildings::SetBuildingStatesRequest requestData; - return m_bldFtc->setBuildingStatesRequest(requestData, this); - }); + building.buildingId(m_buildingId); + building.roomIds().set(structureElementIds); + buildings[0] = building; + requestData.buildings(buildings); + requestData.vulnerabilityState(state); - return m_requestHelper->startRequests(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentData: " << state; + + return m_bldFtc->setBuildingStatesRequest(requestData, this); + }); + + return m_requestHelper->startRequests(); } void BuildingEdit::onDestroyElement() { - QModelIndex selIndex = selectedIndexView(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexView(); + if (!selIndex.isValid()) + return; - std::vector structureElementIds; - getStructureElementIds(m_model->privateData(selIndex), structureElementIds); + std::vector structureElementIds; + getStructureElementIds(m_model->privateData(selIndex), structureElementIds); - sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState_def::CatastrophicKill, structureElementIds); + sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState_def::CatastrophicKill, structureElementIds); } -void BuildingEdit::getStructureElementIds(NGLTreeItem *item, std::vector &structureElementIds) +void BuildingEdit::getStructureElementIds(NGLTreeItem* item, std::vector& structureElementIds) { - for (NGLTreeItem *child : item->children()) - getStructureElementIds(child, structureElementIds); + for (NGLTreeItem* child : item->children()) + getStructureElementIds(child, structureElementIds); - BuildingViewer::TreeItem data = item->data().value(); - if (data.isRoom()) - structureElementIds.push_back(data.structureElementId()); + BuildingViewer::TreeItem data = item->data().value(); + if (data.isRoom()) + structureElementIds.push_back(data.structureElementId()); } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.h old mode 100755 new mode 100644 index a51765506..15c4ebdcd --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_building_edit.h @@ -1,19 +1,15 @@ - - #pragma once #include "bdv_edit_model.h" - #include +#include +#include #include #include -#include -#include - namespace Ui { class BuildingEdit; @@ -21,68 +17,80 @@ class BuildingEdit; namespace BuildingViewer { -class BuildingEdit : public LtsWidgets::LtsDialog - , protected Buildings::Interface::Ftc::SetFortifyFactorReplyHandler - , protected Buildings::Interface::Ftc::SetBuildingStatesReplyHandler - , protected InfrastructureManagement::Interface::Ftc::StructureElementModifyReplyHandler +class BuildingEdit : public LtsWidgets::LtsDialog, + protected Buildings::Interface::Ftc::SetFortifyFactorReplyHandler, + protected Buildings::Interface::Ftc::SetBuildingStatesReplyHandler, + protected InfrastructureManagement::Interface::Ftc::StructureElementModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit BuildingEdit(QWidget *parent = nullptr); - ~BuildingEdit(); + public: + explicit BuildingEdit(QWidget* parent = nullptr); + ~BuildingEdit(); - bool init(int32_t buildingDatabaseId, - const std::shared_ptr &ismDtc, - const std::shared_ptr &ismFtc, - const std::shared_ptr &bldDtc, - const std::shared_ptr &bldFtc); + bool init(int32_t buildingDatabaseId, const std::shared_ptr& ismDtc, + const std::shared_ptr& ismFtc, + const std::shared_ptr& bldDtc, + const std::shared_ptr& bldFtc); - void onSetFortifyFactorReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onSetBuildingStatesReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onStructureElementModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void selectRoomRow(int mountingPointId); + void onSetFortifyFactorReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -signals: - void signalAccept(); + void onSetBuildingStatesReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void slotEditItem(); - void slotDoubleClicked(const QModelIndex &selIndex); - void slotMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &mse, DataModification modType); - void slotBuildingStateChanged(const Buildings::BuildingState &state, DataModification modType); - void slotHandleExternalDdsChange(); - void slotTreeViewClicked(); + void onStructureElementModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - bool sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState state, std::vector structureElementId); - void onDestroyElement(); + void selectRoomRow(int mountingPointId); -protected: + signals: + void signalAccept(); -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override; + private slots: + void slotEditItem(); + void slotDoubleClicked(const QModelIndex& selIndex); + void slotMainStructureElementChanged(const InfrastructureManagement::MainStructureElement& mse, + DataModification modType); + void slotBuildingStateChanged(const Buildings::BuildingState& state, DataModification modType); + void slotHandleExternalDdsChange(); + void slotTreeViewClicked(); -private: - void getStructureElementIds(NGLTreeItem *item, std::vector &structureElementIds); - void buildModel(); - QModelIndex selectedIndexView() const; - void reinitModel(); + bool sendBuildingStateRequest(ProjectDataManagement::VulnerabilityState state, + std::vector structureElementId); + void onDestroyElement(); -private: - std::shared_ptr m_ismDtc; - std::shared_ptr m_ismFtc; - std::shared_ptr m_bldDtc; - std::shared_ptr m_bldFtc; + protected: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override; - BuildingEditModel *m_model = nullptr; - BuildingEditProxyModel *m_proxyModel = nullptr; - LtsUtils::RequestHelper *m_requestHelper = nullptr; - Ui::BuildingEdit *m_ui = nullptr; + private: + void getStructureElementIds(NGLTreeItem* item, std::vector& structureElementIds); + void buildModel(); + QModelIndex selectedIndexView() const; + void reinitModel(); - QString m_buildingName; - int32_t m_buildingDatabaseId = 0; - int32_t m_buildingId = 0; + private: + std::shared_ptr m_ismDtc; + std::shared_ptr m_ismFtc; + std::shared_ptr m_bldDtc; + std::shared_ptr m_bldFtc; + + BuildingEditModel* m_model = nullptr; + BuildingEditProxyModel* m_proxyModel = nullptr; + LtsUtils::RequestHelper* m_requestHelper = nullptr; + Ui::BuildingEdit* m_ui = nullptr; + + QString m_buildingName; + int32_t m_buildingDatabaseId = 0; + int32_t m_buildingId = 0; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.cpp old mode 100755 new mode 100644 index 34341cdfb..e958ae235 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.cpp @@ -1,297 +1,268 @@ - #include "bdv_edit_model.h" -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include +#include namespace BuildingViewer { -BuildingEditModel::BuildingEditModel(QObject *parent, - const std::shared_ptr &ismDtc, - const std::shared_ptr &bldDtc) : NGLTreeModel(parent, new NGLTreeItem(QVariant()),, - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - tr("Selected Building"), - QStringLiteral("Name (DEBUG)"), - QStringLiteral("MountingPointId (DEBUG)"), - QStringLiteral("StructureElementId (DEBUG)"), - tr("Fortify Factor"), - tr("Damage Percent")}) - , m_ismDtc(ismDtc) - , m_bldDtc(bldDtc) - , m_buildingName(QString()) -{} - -QVariant BuildingEditModel::data(const QModelIndex &index, int role) const +BuildingEditModel::BuildingEditModel(QObject* parent, + const std::shared_ptr& ismDtc, + const std::shared_ptr& bldDtc) + : NGLTreeModel(parent, new NGLTreeItem(QVariant()), , + m_logger(NGL::NGLLoggerBootstrap::getLogger()){ + tr("Selected Building"), QStringLiteral("Name (DEBUG)"), + QStringLiteral("MountingPointId (DEBUG)"), QStringLiteral("StructureElementId (DEBUG)"), + tr("Fortify Factor"), tr("Damage Percent")}), + m_ismDtc(ismDtc), m_bldDtc(bldDtc), m_buildingName(QString()) { - if (!index.isValid() || (role != Qt::BackgroundRole && role != Qt::DisplayRole)) +} + +QVariant BuildingEditModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid() || (role != Qt::BackgroundRole && role != Qt::DisplayRole)) + return {}; + + NGLTreeItem* pNGLTreeItem = privateData(index); + + if (pNGLTreeItem->data().canConvert()) + { + BuildingViewer::TreeItem item = pNGLTreeItem->data().value(); + + if (role == Qt::BackgroundRole) + { + if (item.hasDisplayNameChanged() || item.hasFortifyFactorChanged()) + return QGuiApplication::palette().color(QPalette::Highlight); + } + else if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case BuildingEditModel::Building: + return item.displayName(); + case BuildingEditModel::Name: + return item.name(); + case BuildingEditModel::MountingPointId: + if (item.hasMountingPointId()) + return item.mountingPointId(); + break; + case BuildingEditModel::StructureElementId: + return item.structureElementId(); + case BuildingEditModel::FortifyFactor: + if (item.isRoom()) + return QString::number(item.fortifyFactor(), 'f', 1); + break; + case BuildingEditModel::DamagePercent: + if (item.isRoom()) + return QString::number(item.damagePercent()); + } + } + } return {}; - - - NGLTreeItem *pNGLTreeItem = privateData(index); - - if (pNGLTreeItem->data().canConvert()) - { - BuildingViewer::TreeItem item = pNGLTreeItem->data().value(); - - if (role == Qt::BackgroundRole) - { - if (item.hasDisplayNameChanged() || item.hasFortifyFactorChanged()) - return QGuiApplication::palette().color(QPalette::Highlight); - } - else if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case BuildingEditModel::Building: - return item.displayName(); - case BuildingEditModel::Name: - return item.name(); - case BuildingEditModel::MountingPointId: - if (item.hasMountingPointId()) - return item.mountingPointId(); - break; - case BuildingEditModel::StructureElementId: - return item.structureElementId(); - case BuildingEditModel::FortifyFactor: - if (item.isRoom()) - return QString::number(item.fortifyFactor(),'f',1); - break; - case BuildingEditModel::DamagePercent: - if (item.isRoom()) - return QString::number(item.damagePercent()); - } - } - } - return {}; } - -bool BuildingEditModel::slotUpdateRow(const BuildingViewer::TreeItem &room, const bool fortifyChanged) +bool BuildingEditModel::slotUpdateRow(const BuildingViewer::TreeItem& room, const bool fortifyChanged) { - DEBUG_LOG(m_logger) << "slotUpdateRow isBuilding=" << room.isBuilding() - << " isFloor" << room.isFloor() - << " isRoom" << room.isRoom(); + DEBUG_LOG(m_logger) << "slotUpdateRow isBuilding=" << room.isBuilding() << " isFloor" << room.isFloor() << " isRoom" + << room.isRoom(); + QModelIndex idx = modelIndexByStructureElementId(room.structureElementId()); - QModelIndex idx = modelIndexByStructureElementId(room.structureElementId()); - - if (fortifyChanged && ( !room.isRoom() || !qFuzzyIsNull(room.fortifyFactor()))) - { - for (auto *item : privateData(idx)->children()) + if (fortifyChanged && (!room.isRoom() || !qFuzzyIsNull(room.fortifyFactor()))) { - TreeItem childItem = item->data().value(); - childItem.setFortifyFactor(room.fortifyFactor()); - slotUpdateRow(childItem, fortifyChanged); + for (auto* item : privateData(idx)->children()) + { + TreeItem childItem = item->data().value(); + childItem.setFortifyFactor(room.fortifyFactor()); + slotUpdateRow(childItem, fortifyChanged); + } } - } - if (room.hasDisplayNameChanged()) - m_mapRoomsWithChangedDisplayName[room.structureElementId()] = room; - if (fortifyChanged && (room.isRoom() && room.hasFortifyFactorChanged())) - m_mapRoomsWithChangedFortifyFactor[room.structureElementId()] = room; + if (room.hasDisplayNameChanged()) + m_mapRoomsWithChangedDisplayName[room.structureElementId()] = room; + if (fortifyChanged && (room.isRoom() && room.hasFortifyFactorChanged())) + m_mapRoomsWithChangedFortifyFactor[room.structureElementId()] = room; - QVariant data; - data.setValue(room); + QVariant data; + data.setValue(room); - emit signalModelDataChanged(); - return setItemData(idx, data, QIcon()); + emit signalModelDataChanged(); + return setItemData(idx, data, QIcon()); } - -bool BuildingEditModel::onInsertRow(int &row, const QModelIndex &parent, const BuildingViewer::TreeItem &folderData) +bool BuildingEditModel::onInsertRow(int& row, const QModelIndex& parent, const BuildingViewer::TreeItem& folderData) { - row = rowCount(parent); - QVariant data; - data.setValue(folderData); - NGLTreeItem *item = new NGLTreeItem(data, QIcon()); - item->setModified(true); + row = rowCount(parent); + QVariant data; + data.setValue(folderData); + NGLTreeItem* item = new NGLTreeItem(data, QIcon()); + item->setModified(true); - emit signalModelDataChanged(); + emit signalModelDataChanged(); - return NGLTreeModel::insertRow(row, parent, item); + return NGLTreeModel::insertRow(row, parent, item); } - bool BuildingEditModel::init(int32_t mseId) { - INFO_LOG(m_logger) << "init mseId=" << mseId; - NGLTreeModel::resetModel(); - m_mapRoomsWithChangedFortifyFactor.clear(); + INFO_LOG(m_logger) << "init mseId=" << mseId; + NGLTreeModel::resetModel(); + m_mapRoomsWithChangedFortifyFactor.clear(); - QMap treemap; - QMap lookupFloorId2TreeId; - QString rootName; + QMap treemap; + QMap lookupFloorId2TreeId; + QString rootName; - + InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(mseId); + int rootId = 0; + qint32 mapId = 0; - - - InfrastructureManagement::MainStructureElement building = m_ismDtc->mainStructureElement(mseId); - int rootId = 0; - qint32 mapId = 0; - - const std::vector &vecElements = building.elements(); - for (const auto &se : vecElements) - { - DEBUG_LOG(m_logger) << "se: " << se; - if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType::Building) + const std::vector& vecElements = building.elements(); + for (const auto& se : vecElements) { - BuildingViewer::TreeItem rootItemBuilding(se); - rootName =rootItemBuilding.name(); - m_buildingName = rootItemBuilding.displayName(); - mapId = rootId; - treemap[mapId++] = rootItemBuilding; - } - } - - - - - - - - - - - for (const auto &se : vecElements) - { - DEBUG_LOG(m_logger) << "se: =" << se; - if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Floor) - { - BuildingViewer::TreeItem itemRoom(se); - itemRoom.setSuperior(rootId); - - lookupFloorId2TreeId[se.id()] = mapId; - treemap[mapId++] = itemRoom; - } - } - - m_bldDtc->enableBuildingState(); - m_bldDtc->waitForHistoricalDataBuildingState(1000); - - auto bs = m_bldDtc->buildingState(mseId); - - QMap roomStates; - for (const auto &e : bs.roomStates()) - roomStates[e.id()] = e; - - - for (const auto &se : vecElements) - { - if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Room) - { - - double fortifyFactor = 1.0; - qint32 damagePercent = bs.damagePercent(); - if (roomStates.contains(se.id())) - { - fortifyFactor = roomStates[se.id()].fortifyFactor(); - damagePercent = roomStates[se.id()].damagePercent(); - } - - BuildingViewer::TreeItem itemRoom(se, fortifyFactor, damagePercent); - - try - { - - - int32_t floorID = se.path()[1]; - itemRoom.setSuperior(lookupFloorId2TreeId[floorID]); - } - catch (const std::out_of_range &e) - { - WARNING_LOG(m_logger) << "Caught exception while trying to get superior id for building " << rootName << " with room with mounting point id: " << se.mountingPointId() << ": " << e.what(); - return false; - } - - treemap[mapId++] = itemRoom; - } - } - - - QHash parentItemIndexCache; - parentItemIndexCache.insert(rootId, QModelIndex()); - - for (auto iter = treemap.constBegin(); iter != treemap.constEnd(); ++iter) - { - int itemDatabaseId = iter.key(); - const BuildingViewer::TreeItem &item = iter.value(); - - QVariant data; - data.setValue(item); - - int parentId = item.hasSuperior() ? item.getSuperior() : rootId; - if (!parentItemIndexCache.contains(parentId)) - { - ERROR_LOG(m_logger) << "Invalid building structure! Tree can not be built!"; - return false; + DEBUG_LOG(m_logger) << "se: " << se; + if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType::Building) + { + BuildingViewer::TreeItem rootItemBuilding(se); + rootName = rootItemBuilding.name(); + m_buildingName = rootItemBuilding.displayName(); + mapId = rootId; + treemap[mapId++] = rootItemBuilding; + } } - QModelIndex pIndex = parentItemIndexCache.value(parentId); - int rowPos = -1; + for (const auto& se : vecElements) + { + DEBUG_LOG(m_logger) << "se: =" << se; + if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Floor) + { + BuildingViewer::TreeItem itemRoom(se); + itemRoom.setSuperior(rootId); - onInsertRow(rowPos, pIndex, item); + lookupFloorId2TreeId[se.id()] = mapId; + treemap[mapId++] = itemRoom; + } + } - QPersistentModelIndex mIndex = index(rowPos, 0, pIndex); - m_mapModelIndices[item.structureElementId()] = mIndex; - parentItemIndexCache.insert(itemDatabaseId, mIndex); - } + m_bldDtc->enableBuildingState(); + m_bldDtc->waitForHistoricalDataBuildingState(1000); - return true; + auto bs = m_bldDtc->buildingState(mseId); + + QMap roomStates; + for (const auto& e : bs.roomStates()) + roomStates[e.id()] = e; + + for (const auto& se : vecElements) + { + if (se.structureElementTypeId() == InfrastructureManagement::StructureElementType_def::Room) + { + + double fortifyFactor = 1.0; + qint32 damagePercent = bs.damagePercent(); + if (roomStates.contains(se.id())) + { + fortifyFactor = roomStates[se.id()].fortifyFactor(); + damagePercent = roomStates[se.id()].damagePercent(); + } + + BuildingViewer::TreeItem itemRoom(se, fortifyFactor, damagePercent); + + try + { + + int32_t floorID = se.path()[1]; + itemRoom.setSuperior(lookupFloorId2TreeId[floorID]); + } + catch (const std::out_of_range& e) + { + WARNING_LOG(m_logger) << "Caught exception while trying to get superior id for building " << rootName + << " with room with mounting point id: " << se.mountingPointId() << ": " + << e.what(); + return false; + } + + treemap[mapId++] = itemRoom; + } + } + + QHash parentItemIndexCache; + parentItemIndexCache.insert(rootId, QModelIndex()); + + for (auto iter = treemap.constBegin(); iter != treemap.constEnd(); ++iter) + { + int itemDatabaseId = iter.key(); + const BuildingViewer::TreeItem& item = iter.value(); + + QVariant data; + data.setValue(item); + + int parentId = item.hasSuperior() ? item.getSuperior() : rootId; + if (!parentItemIndexCache.contains(parentId)) + { + ERROR_LOG(m_logger) << "Invalid building structure! Tree can not be built!"; + return false; + } + + QModelIndex pIndex = parentItemIndexCache.value(parentId); + int rowPos = -1; + + onInsertRow(rowPos, pIndex, item); + + QPersistentModelIndex mIndex = index(rowPos, 0, pIndex); + m_mapModelIndices[item.structureElementId()] = mIndex; + parentItemIndexCache.insert(itemDatabaseId, mIndex); + } + + return true; } QModelIndex BuildingEditModel::modelIndexByMountingPointId(int mountingPointId) const { - for(const QPersistentModelIndex &mi : std::as_const(m_mapModelIndices)) - { - if (privateData(mi)->data().value().mountingPointId() == mountingPointId) - return mi; - } - WARNING_LOG(m_logger)<<"Could not find modelindex for given room mountig point id: " << mountingPointId; - return {}; + for (const QPersistentModelIndex& mi : std::as_const(m_mapModelIndices)) + { + if (privateData(mi)->data().value().mountingPointId() == mountingPointId) + return mi; + } + WARNING_LOG(m_logger) << "Could not find modelindex for given room mountig point id: " << mountingPointId; + return {}; } - QModelIndex BuildingEditModel::modelIndexByStructureElementId(int structureElementId) const { - auto it = m_mapModelIndices.find(structureElementId); - if (it == m_mapModelIndices.end()) - { - WARNING_LOG(m_logger)<<"Could not find modelindex for given room structreElementId: " << structureElementId; - return {}; - } - return it.value(); + auto it = m_mapModelIndices.find(structureElementId); + if (it == m_mapModelIndices.end()) + { + WARNING_LOG(m_logger) << "Could not find modelindex for given room structreElementId: " << structureElementId; + return {}; + } + return it.value(); } - - -void BuildingEditProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void BuildingEditProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - QSortFilterProxyModel::setSourceModel(m_sourceModel); + m_sourceModel = qobject_cast(sourceModel); + QSortFilterProxyModel::setSourceModel(m_sourceModel); } -bool BuildingEditProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const +bool BuildingEditProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { - if (!m_sourceModel || - left.column() != 0 || right.column() != 0) + if (!m_sourceModel || left.column() != 0 || right.column() != 0) + return QSortFilterProxyModel::lessThan(left, right); + + NGLTreeItem* itemLeft = m_sourceModel->privateData(left); + NGLTreeItem* itemRight = m_sourceModel->privateData(right); + if (itemLeft && itemRight) + return (itemLeft->row() < itemRight->row()); + return QSortFilterProxyModel::lessThan(left, right); - - NGLTreeItem *itemLeft = m_sourceModel->privateData(left); - NGLTreeItem *itemRight = m_sourceModel->privateData(right); - if (itemLeft && itemRight) - return (itemLeft->row() < itemRight->row()); - - return QSortFilterProxyModel::lessThan(left, right); } - -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.h old mode 100755 new mode 100644 index e27df4005..23c3f5c5a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/BuildingEdit/bdv_edit_model.h @@ -2,13 +2,11 @@ #pragma once -#include - -#include -#include - #include "bdv_treemodel_item.h" +#include +#include +#include #include #include #include @@ -18,70 +16,75 @@ namespace BuildingViewer { class BuildingEditModel : public NGLTreeModel { - Q_OBJECT -public: - enum Columns - { - Building, - Name, - MountingPointId, - StructureElementId, - FortifyFactor, - DamagePercent, - ColumnCount, - }; + Q_OBJECT + public: + enum Columns { + Building, + Name, + MountingPointId, + StructureElementId, + FortifyFactor, + DamagePercent, + ColumnCount, + }; - BuildingEditModel(QObject *parent, - const std::shared_ptr &ismDtc, - const std::shared_ptr &bldDtc); + BuildingEditModel(QObject* parent, const std::shared_ptr& ismDtc, + const std::shared_ptr& bldDtc); - QList getRoomsWithChangedFortifyFactors() const { return m_mapRoomsWithChangedFortifyFactor.values(); } - QList getRoomsWithChangedDisplayNames() const { return m_mapRoomsWithChangedDisplayName.values(); } + QList getRoomsWithChangedFortifyFactors() const + { + return m_mapRoomsWithChangedFortifyFactor.values(); + } - bool init(int32_t buildingDatabaseId); - QModelIndex modelIndexByMountingPointId(int mountingPointId) const; - QModelIndex modelIndexByStructureElementId(int structureElementId) const; - QString getBuildingName() const {return m_buildingName;} + QList getRoomsWithChangedDisplayNames() const + { + return m_mapRoomsWithChangedDisplayName.values(); + } -public slots: - bool slotUpdateRow(const BuildingViewer::TreeItem &room, const bool fortifyChanged); + bool init(int32_t buildingDatabaseId); + QModelIndex modelIndexByMountingPointId(int mountingPointId) const; + QModelIndex modelIndexByStructureElementId(int structureElementId) const; -signals: - void signalModelDataChanged(); + QString getBuildingName() const + { + return m_buildingName; + } -private: + public slots: + bool slotUpdateRow(const BuildingViewer::TreeItem& room, const bool fortifyChanged); -NGL::INGLLogger &m_logger; - QVariant data(const QModelIndex &index, int role) const override final; - bool onInsertRow(int &row, const QModelIndex &parent, const BuildingViewer::TreeItem &folderData); + signals: + void signalModelDataChanged(); - QMap m_mapModelIndices; + private: + NGL::INGLLogger& m_logger; + QVariant data(const QModelIndex& index, int role) const override final; + bool onInsertRow(int& row, const QModelIndex& parent, const BuildingViewer::TreeItem& folderData); - - QMap m_mapRoomsWithChangedFortifyFactor; - QMap m_mapRoomsWithChangedDisplayName; + QMap m_mapModelIndices; - std::shared_ptr m_ismDtc; - std::shared_ptr m_bldDtc; + QMap m_mapRoomsWithChangedFortifyFactor; + QMap m_mapRoomsWithChangedDisplayName; - QString m_buildingName; + std::shared_ptr m_ismDtc; + std::shared_ptr m_bldDtc; + + QString m_buildingName; }; - - class BuildingEditProxyModel final : public QSortFilterProxyModel { - Q_OBJECT -public: - using QSortFilterProxyModel::QSortFilterProxyModel; + Q_OBJECT + public: + using QSortFilterProxyModel::QSortFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; - bool lessThan(const QModelIndex &left, const QModelIndex &right) const override; -private: - BuildingEditModel *m_sourceModel = nullptr; + void setSourceModel(QAbstractItemModel* sourceModel) override; + bool lessThan(const QModelIndex& left, const QModelIndex& right) const override; + + private: + BuildingEditModel* m_sourceModel = nullptr; }; -} +} // namespace BuildingViewer Q_DECLARE_METATYPE(BuildingViewer::TreeItem) - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.cpp old mode 100755 new mode 100644 index 2665c7f21..37a55a3fe --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.cpp @@ -1,88 +1,84 @@ - #include "bdv_replay_handler.h" - namespace BuildingViewer { -ReplayHandler::ReplayHandler(int buildingTopicStart_s, int buildingTopicEnd_s, const TopicReplay::Interface::SituationReplayTime &replay, QObject *parent) : QObject(parent) - , m_actualReplayStart_ms(0) - , m_actualReplayEnd_ms(0) - , m_replayDuration_ms(0) - , m_startOffset_ms(0) - , m_replayInfo(replay), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - DEBUG_LOG(m_logger) << "buildingTopicStart_s = " << buildingTopicStart_s - << ", buildingTopicEnd_s = " << buildingTopicEnd_s - << ", replay.topicStart_s = " << replay.topicStart_s - << ", replay.topicEnd_s = " << replay.topicEnd_s - << ", replay.replayStart_ms = " << replay.replayStart_ms - << ", replay.replayEnd_ms = " << replay.replayEnd_ms; +ReplayHandler::ReplayHandler(int buildingTopicStart_s, int buildingTopicEnd_s, + const TopicReplay::Interface::SituationReplayTime& replay, QObject* parent) + : QObject(parent), m_actualReplayStart_ms(0), m_actualReplayEnd_ms(0), m_replayDuration_ms(0), m_startOffset_ms(0), + m_replayInfo(replay), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + DEBUG_LOG(m_logger) << "buildingTopicStart_s = " << buildingTopicStart_s + << ", buildingTopicEnd_s = " << buildingTopicEnd_s + << ", replay.topicStart_s = " << replay.topicStart_s + << ", replay.topicEnd_s = " << replay.topicEnd_s + << ", replay.replayStart_ms = " << replay.replayStart_ms + << ", replay.replayEnd_ms = " << replay.replayEnd_ms; - - int start_diff_ms = (buildingTopicStart_s - replay.topicStart_s) * 1000; + int start_diff_ms = (buildingTopicStart_s - replay.topicStart_s) * 1000; - if (start_diff_ms >= 0) - { - + if (start_diff_ms >= 0) + { - m_actualReplayStart_ms = replay.replayStart_ms + start_diff_ms; - m_startOffset_ms = 0; - DEBUG_LOG(m_logger) << "Replay starts before Building-Topic: Shift replay starting point to m_actualReplayStart_ms = " << m_actualReplayStart_ms; - } - else - { - + m_actualReplayStart_ms = replay.replayStart_ms + start_diff_ms; + m_startOffset_ms = 0; + DEBUG_LOG(m_logger) + << "Replay starts before Building-Topic: Shift replay starting point to m_actualReplayStart_ms = " + << m_actualReplayStart_ms; + } + else + { - m_actualReplayStart_ms = replay.replayStart_ms; - m_startOffset_ms = std::abs(start_diff_ms); - DEBUG_LOG(m_logger) << "Building-Topic starts before Replay: Starting Replay after " << m_startOffset_ms << "msec"; - } + m_actualReplayStart_ms = replay.replayStart_ms; + m_startOffset_ms = std::abs(start_diff_ms); + DEBUG_LOG(m_logger) << "Building-Topic starts before Replay: Starting Replay after " << m_startOffset_ms + << "msec"; + } - - m_actualReplayEnd_ms = replay.replayEnd_ms; - - if (replay.topicEnd_s > buildingTopicEnd_s) - { - m_actualReplayEnd_ms -= (replay.topicEnd_s - buildingTopicEnd_s) * 1000; - DEBUG_LOG(m_logger) << "Replay longer than Building-Topic, cutting replay end to m_actualReplayEnd_ms = " << m_actualReplayEnd_ms; - } + m_actualReplayEnd_ms = replay.replayEnd_ms; - m_replayDuration_ms = m_actualReplayEnd_ms - m_actualReplayStart_ms; + if (replay.topicEnd_s > buildingTopicEnd_s) + { + m_actualReplayEnd_ms -= (replay.topicEnd_s - buildingTopicEnd_s) * 1000; + DEBUG_LOG(m_logger) << "Replay longer than Building-Topic, cutting replay end to m_actualReplayEnd_ms = " + << m_actualReplayEnd_ms; + } - DEBUG_LOG(m_logger) << "Replay from " << m_actualReplayStart_ms << " to " << m_actualReplayEnd_ms << " (duration = " << m_replayDuration_ms << ")"; + m_replayDuration_ms = m_actualReplayEnd_ms - m_actualReplayStart_ms; - if (m_startOffset_ms == 0) - m_startOffset_ms = -1; + DEBUG_LOG(m_logger) << "Replay from " << m_actualReplayStart_ms << " to " << m_actualReplayEnd_ms + << " (duration = " << m_replayDuration_ms << ")"; + + if (m_startOffset_ms == 0) + m_startOffset_ms = -1; } - void ReplayHandler::tick(qint64 diffSinceLastTick) { - if (isExpired()) - return; + if (isExpired()) + return; - m_replayDuration_ms -= diffSinceLastTick; - if (m_replayDuration_ms <= 0) - { - emit signalStopReplay(); - return; - } + m_replayDuration_ms -= diffSinceLastTick; + if (m_replayDuration_ms <= 0) + { + emit signalStopReplay(); + return; + } - DEBUG_LOG(m_logger) << "ReplayHandler::tick(): Remaining: " << m_replayDuration_ms << "msec"; + DEBUG_LOG(m_logger) << "ReplayHandler::tick(): Remaining: " << m_replayDuration_ms << "msec"; - if (m_startOffset_ms == -1) - { - emit signalStartReplay(m_actualReplayStart_ms, m_actualReplayEnd_ms, m_replayInfo.replaySpeedFactor); - m_startOffset_ms = 0; - } + if (m_startOffset_ms == -1) + { + emit signalStartReplay(m_actualReplayStart_ms, m_actualReplayEnd_ms, m_replayInfo.replaySpeedFactor); + m_startOffset_ms = 0; + } - if (m_startOffset_ms > 0) - { - m_startOffset_ms -= diffSinceLastTick; - if (m_startOffset_ms <= 0) - emit signalStartReplay(m_actualReplayStart_ms, m_actualReplayEnd_ms, m_replayInfo.replaySpeedFactor); - } -} + if (m_startOffset_ms > 0) + { + m_startOffset_ms -= diffSinceLastTick; + if (m_startOffset_ms <= 0) + emit signalStartReplay(m_actualReplayStart_ms, m_actualReplayEnd_ms, m_replayInfo.replaySpeedFactor); + } } +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.h old mode 100755 new mode 100644 index 43d5a38be..cc5f3a300 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_replay_handler.h @@ -1,37 +1,39 @@ - #pragma once -#include -#include -#include #include +#include +#include +#include namespace BuildingViewer { class ReplayHandler : public QObject { - Q_OBJECT -public: - ReplayHandler(int buildingTopicStart_s, int buildingTopicEnd_s, const TopicReplay::Interface::SituationReplayTime &replay, QObject *parent = nullptr); + Q_OBJECT + public: + ReplayHandler(int buildingTopicStart_s, int buildingTopicEnd_s, + const TopicReplay::Interface::SituationReplayTime& replay, QObject* parent = nullptr); - void tick(qint64 diffSinceLastTick); + void tick(qint64 diffSinceLastTick); - bool isExpired() const { return m_replayDuration_ms == 0; } + bool isExpired() const + { + return m_replayDuration_ms == 0; + } -signals: - void signalStartReplay(qint64 start, qint64 end, double speed); - void signalStopReplay(); + signals: + void signalStartReplay(qint64 start, qint64 end, double speed); + void signalStopReplay(); -private: + private: + NGL::INGLLogger& m_logger; + qint64 m_actualReplayStart_ms; + qint64 m_actualReplayEnd_ms; -NGL::INGLLogger &m_logger; - qint64 m_actualReplayStart_ms; - qint64 m_actualReplayEnd_ms; - - qint64 m_replayDuration_ms; - qint64 m_startOffset_ms; - TopicReplay::Interface::SituationReplayTime m_replayInfo; + qint64 m_replayDuration_ms; + qint64 m_startOffset_ms; + TopicReplay::Interface::SituationReplayTime m_replayInfo; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.cpp old mode 100755 new mode 100644 index fb63119f2..02d807530 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.cpp @@ -1,109 +1,106 @@ - #include "bdv_thread_video_exporter.h" -#include + #include "bdv_replay_handler.h" +#include #include #include - -#include +#include namespace BuildingViewer { -VideoExporter::VideoExporter(QObject *parent) - : QObject(parent) +VideoExporter::VideoExporter(QObject* parent) : QObject(parent) { - DEBUG_LOG(m_logger) << "ThreadVideoExporter has been created"; + DEBUG_LOG(m_logger) << "ThreadVideoExporter has been created"; } -void VideoExporter::init(const VideoInformation &videoInfo) +void VideoExporter::init(const VideoInformation& videoInfo) { - m_vecVideosToExport.push_back(videoInfo); + m_vecVideosToExport.push_back(videoInfo); } - void VideoExporter::sendAliveSignals() { - DEBUG_LOG(m_logger) << "sendAliveSignals() called"; + DEBUG_LOG(m_logger) << "sendAliveSignals() called"; - for (auto &e : std::as_const(m_vecVideosToExport)) - emit e.m_pExportNotifier->stillAlive(); + for (auto& e : std::as_const(m_vecVideosToExport)) + emit e.m_pExportNotifier->stillAlive(); - DEBUG_LOG(m_logger) << "\tSignals emitted, mutex unlocked"; + DEBUG_LOG(m_logger) << "\tSignals emitted, mutex unlocked"; } - void VideoExporter::doExport() { - while (!m_vecVideosToExport.isEmpty()) - { - if (QThread::currentThread()->isInterruptionRequested()) - break; - VideoInformation toExport = m_vecVideosToExport.takeFirst(); - DEBUG_LOG(m_logger) << "Starting export of " << toExport.m_strFolderPath; - - const auto state = toExport.m_bgViewerState.value(QStringLiteral("arrBuildingStates")); - - if (!state.isArray()) + while (!m_vecVideosToExport.isEmpty()) { - WARNING_LOG(m_logger) << "No opened buildings, nothing to export, skipping video!"; - continue; + if (QThread::currentThread()->isInterruptionRequested()) + break; + VideoInformation toExport = m_vecVideosToExport.takeFirst(); + DEBUG_LOG(m_logger) << "Starting export of " << toExport.m_strFolderPath; + + const auto state = toExport.m_bgViewerState.value(QStringLiteral("arrBuildingStates")); + + if (!state.isArray()) + { + WARNING_LOG(m_logger) << "No opened buildings, nothing to export, skipping video!"; + continue; + } + + DEBUG_LOG(m_logger) << "Emitting 'signalStartRecording'"; + emit signalStartRecording(toExport.m_strFolderPath, state); + + QSharedPointer pHandler; + + QElapsedTimer elapsedTimer; + qint64 last_tick_elapsed = 0; + qint64 elapsed_sum_ms = 0; + const qint64 record_duration_ms = toExport.m_record_duration_s * 1000; + + elapsedTimer.start(); + while (elapsed_sum_ms <= record_duration_ms) + { + const qint64 curElapsed = elapsedTimer.restart(); + elapsed_sum_ms += curElapsed; + sendAliveSignals(); + emit toExport.m_pExportNotifier->stillAlive(); + + if (!pHandler && toExport.m_vecReplayHandler.size()) + { + pHandler = toExport.m_vecReplayHandler.front(); + connect(pHandler.data(), &ReplayHandler::signalStartReplay, this, &VideoExporter::signalStartReplay); + connect(pHandler.data(), &ReplayHandler::signalStopReplay, this, &VideoExporter::signalStopReplay); + toExport.m_vecReplayHandler.pop_front(); + } + + const qint64 diff_ms = elapsed_sum_ms - last_tick_elapsed; + + if (diff_ms >= 1000) + { + last_tick_elapsed = elapsed_sum_ms; + DEBUG_LOG(m_logger) << "Export: " << elapsed_sum_ms / 1000 << "/" << record_duration_ms / 1000 + << "[s] passed"; + } + + if (pHandler) + { + pHandler->tick(curElapsed); + + if (pHandler->isExpired()) + break; + } + QThread::msleep(100); + if (QThread::currentThread()->isInterruptionRequested()) + break; + } + DEBUG_LOG(m_logger) << "Done. Emitting 'signalStopRecording'"; + emit signalStopRecording(); + + DEBUG_LOG(m_logger) << "Export done, emitting 'signalExportSuccessful'"; + toExport.m_pExportNotifier->setExportSuccessful(toExport.m_strFolderPath); + DEBUG_LOG(m_logger) << "\tsignal emitted"; } - - DEBUG_LOG(m_logger) << "Emitting 'signalStartRecording'"; - emit signalStartRecording(toExport.m_strFolderPath, state); - - QSharedPointer pHandler; - - QElapsedTimer elapsedTimer; - qint64 last_tick_elapsed = 0; - qint64 elapsed_sum_ms = 0; - const qint64 record_duration_ms = toExport.m_record_duration_s * 1000; - - elapsedTimer.start(); - while (elapsed_sum_ms <= record_duration_ms) - { - const qint64 curElapsed = elapsedTimer.restart(); - elapsed_sum_ms += curElapsed; - sendAliveSignals(); - emit toExport.m_pExportNotifier->stillAlive(); - - if (!pHandler && toExport.m_vecReplayHandler.size()) - { - pHandler = toExport.m_vecReplayHandler.front(); - connect(pHandler.data(), &ReplayHandler::signalStartReplay, this, &VideoExporter::signalStartReplay); - connect(pHandler.data(), &ReplayHandler::signalStopReplay, this, &VideoExporter::signalStopReplay); - toExport.m_vecReplayHandler.pop_front(); - } - - const qint64 diff_ms = elapsed_sum_ms - last_tick_elapsed; - - if (diff_ms >= 1000) - { - last_tick_elapsed = elapsed_sum_ms; - DEBUG_LOG(m_logger) << "Export: " << elapsed_sum_ms / 1000 << "/" << record_duration_ms / 1000 << "[s] passed"; - } - - if (pHandler) - { - pHandler->tick(curElapsed); - - if (pHandler->isExpired()) - break; - } - QThread::msleep(100); - if (QThread::currentThread()->isInterruptionRequested()) - break; - } - DEBUG_LOG(m_logger) << "Done. Emitting 'signalStopRecording'"; - emit signalStopRecording(); - - DEBUG_LOG(m_logger) <<"Export done, emitting 'signalExportSuccessful'"; - toExport.m_pExportNotifier->setExportSuccessful(toExport.m_strFolderPath); - DEBUG_LOG(m_logger) <<"\tsignal emitted"; - } } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.h old mode 100755 new mode 100644 index 6bd8f970d..86ee6a544 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_thread_video_exporter.h @@ -1,12 +1,11 @@ - #pragma once -#include #include #include #include +#include namespace BuildingViewer { @@ -14,49 +13,44 @@ class ReplayHandler; class VideoInformation { -public: - VideoInformation() = default; - VideoInformation(TopicEditorBase::ExportNotifier *pExportNotifier, - const QString &strFolderPath, - const QJsonObject &attributes, - const QVector> &vecReplayHandler, - qint64 record_duration_s) - : m_pExportNotifier(pExportNotifier) - , m_record_duration_s(record_duration_s) - , m_strFolderPath(strFolderPath) - , m_bgViewerState(attributes) - , m_vecReplayHandler(vecReplayHandler) - {} + public: + VideoInformation() = default; - TopicEditorBase::ExportNotifier *m_pExportNotifier = nullptr; - qint64 m_record_duration_s = -1; - QString m_strFolderPath; - QJsonObject m_bgViewerState; - QVector> m_vecReplayHandler; + VideoInformation(TopicEditorBase::ExportNotifier* pExportNotifier, const QString& strFolderPath, + const QJsonObject& attributes, const QVector>& vecReplayHandler, + qint64 record_duration_s) + : m_pExportNotifier(pExportNotifier), m_record_duration_s(record_duration_s), m_strFolderPath(strFolderPath), + m_bgViewerState(attributes), m_vecReplayHandler(vecReplayHandler) + { + } + + TopicEditorBase::ExportNotifier* m_pExportNotifier = nullptr; + qint64 m_record_duration_s = -1; + QString m_strFolderPath; + QJsonObject m_bgViewerState; + QVector> m_vecReplayHandler; }; - class VideoExporter : public QObject { - Q_OBJECT -public: - VideoExporter(QObject *parent = nullptr); + Q_OBJECT + public: + VideoExporter(QObject* parent = nullptr); - void init(const VideoInformation &videoInfo); - void doExport(); + void init(const VideoInformation& videoInfo); + void doExport(); -signals: - void signalStartReplay(qint64 start, qint64 end, double speed); - void signalStopReplay(); + signals: + void signalStartReplay(qint64 start, qint64 end, double speed); + void signalStopReplay(); - void signalStartRecording(const QString &strFolderPath, const QJsonValue &state); - void signalStopRecording(); + void signalStartRecording(const QString& strFolderPath, const QJsonValue& state); + void signalStopRecording(); -private: + private: + NGL::INGLLogger& m_logger; + void sendAliveSignals(); -NGL::INGLLogger &m_logger; - void sendAliveSignals(); - - QVector m_vecVideosToExport; + QVector m_vecVideosToExport; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.cpp old mode 100755 new mode 100644 index 35d9ea6ee..686afaedb --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.cpp @@ -1,23 +1,23 @@ - #include "bdv_topic_replay_interface.h" -#include -#include "bdv_viewer_gui_plugin.h" -#include "bdv_thread_video_exporter.h" + #include "bdv_replay_handler.h" +#include "bdv_thread_video_exporter.h" +#include "bdv_viewer_gui_plugin.h" + #include #include - #include #include #include +#include #ifdef EXPORT_BDV_TOPIC_AS_JSON -#include -#include -#include #include +#include +#include +#include #else #include #endif @@ -25,292 +25,273 @@ namespace BuildingViewer { - - - -TopicReplayInterface::TopicReplayInterface(BgViewerController *bgvController, LtsSession::LtsSession *session) - : m_bgvController(bgvController) - , m_session(session) +TopicReplayInterface::TopicReplayInterface(BgViewerController* bgvController, LtsSession::LtsSession* session) + : m_bgvController(bgvController), m_session(session) { - session->getForeignGuiInterface(m_replayIfc); + session->getForeignGuiInterface(m_replayIfc); } - -QWidget *TopicReplayInterface::createWidget() +QWidget* TopicReplayInterface::createWidget() { - delete m_pBgViewerWidget; - m_pBgViewerWidget = m_bgvController ? m_bgvController->getBgViewerWidget() : nullptr; - return m_pBgViewerWidget; + delete m_pBgViewerWidget; + m_pBgViewerWidget = m_bgvController ? m_bgvController->getBgViewerWidget() : nullptr; + return m_pBgViewerWidget; } - TopicReplayInterface::~TopicReplayInterface() { #ifndef EXPORT_BDV_TOPIC_AS_JSON - if (m_tveThread) - { - m_tveThread->requestInterruption(); - m_tveThread->quit(); - m_tveThread->wait(20000); - m_tveThread->terminate(); - } - delete m_tveThread; + if (m_tveThread) + { + m_tveThread->requestInterruption(); + m_tveThread->quit(); + m_tveThread->wait(20000); + m_tveThread->terminate(); + } + delete m_tveThread; #endif - - delete m_pBgViewerWidget; - m_pBgViewerWidget = nullptr; + delete m_pBgViewerWidget; + m_pBgViewerWidget = nullptr; } - -bool TopicReplayInterface::playbackInit(const QJsonObject &attributes) +bool TopicReplayInterface::playbackInit(const QJsonObject& attributes) { - if (!m_bgvController) - return false; - m_bgvController->closeBuilding(); - m_bgvController->excRestoreViewState(attributes.value(QStringLiteral("arrBuildingStates"))); + if (!m_bgvController) + return false; + m_bgvController->closeBuilding(); + m_bgvController->excRestoreViewState(attributes.value(QStringLiteral("arrBuildingStates"))); - return true; + return true; } - void TopicReplayInterface::slotStartReplay(qint64 start, qint64 end, double speed) { - if (m_replayIfc) - m_replayIfc->startReplay(start, end, speed); + if (m_replayIfc) + m_replayIfc->startReplay(start, end, speed); } void TopicReplayInterface::slotStopReplay() { - if (m_replayIfc) - m_replayIfc->stopReplay(); + if (m_replayIfc) + m_replayIfc->stopReplay(); } - -void TopicReplayInterface::setExportPlaybackTimes(qint64 startTimeSec, - qint64 durationSec, - const QVector &sitReplayTimes) +void TopicReplayInterface::setExportPlaybackTimes(qint64 startTimeSec, qint64 durationSec, + const QVector& sitReplayTimes) { - m_startTimeSec = startTimeSec; - m_durationSec = durationSec; - m_sitReplayTimes = sitReplayTimes; + m_startTimeSec = startTimeSec; + m_durationSec = durationSec; + m_sitReplayTimes = sitReplayTimes; } -bool TopicReplayInterface::exportTopic(const QJsonObject &attributes, - const QString &folderPath, - TopicEditorBase::ExportNotifier *pExportNotifier) +bool TopicReplayInterface::exportTopic(const QJsonObject& attributes, const QString& folderPath, + TopicEditorBase::ExportNotifier* pExportNotifier) { #ifdef EXPORT_BDV_TOPIC_AS_JSON - const QJsonArray states = attributes[QStringLiteral("arrBuildingStates")].toArray(); - if (states.isEmpty()) - { - INFO_LOG(m_logger) << "Nothing to export"; - emit pExportNotifier->exportSuccessful(QString()); - return true; - } - - const QString filename(QStringLiteral("buildingViewer.json")); - QFile f(folderPath + QLatin1Char('/') + filename); - if (!f.open(QIODevice::WriteOnly)) - { - WARNING_LOG(m_logger) << "Can not open file '" << f.fileName() << "' for writing!"; - pExportNotifier->setExportFailed(); - return false; - } - QJsonObject obj; - obj[QStringLiteral("attributes")] = attributes; - obj[QStringLiteral("timeInPresentation")] = timeRange(m_startTimeSec * 1000, - (m_startTimeSec + m_durationSec) * 1000); - - QJsonArray arr; - for (const SituationReplayTime &rt : std::as_const(m_sitReplayTimes)) - { - if (m_startTimeSec > rt.topicEnd_s) - continue; - const double lenReplay = rt.replayEnd_ms - rt.replayStart_ms; - const double endReplay = rt.replayStart_ms + lenReplay; - - const double maxReplay = std::min(rt.replayStart_ms + m_durationSec * 1000. * rt.replaySpeedFactor, endReplay); - arr.push_back(rt.toJson(maxReplay)); - } - obj[QStringLiteral("replays")] = arr; - f.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); - f.close(); - DEBUG_LOG(m_logger) << "BDV filename: " << f.fileName(); - - QVector buildingIds; - buildingIds.reserve(states.size()); - for (const auto &ele : states) - { - const ViewWidgetState vws(ele.toObject()); - int buildingId = featureId2DatabaseId(QString::fromStdString(vws.m_featureID)); - if (buildingId <= 0) + const QJsonArray states = attributes[QStringLiteral("arrBuildingStates")].toArray(); + if (states.isEmpty()) { - WARNING_LOG(m_logger) << "Could not retrieve building id from '" << vws.m_featureID << "' - skipping"; - continue; + INFO_LOG(m_logger) << "Nothing to export"; + emit pExportNotifier->exportSuccessful(QString()); + return true; } - buildingIds += buildingId; - } - emit pExportNotifier->stillAlive(); - if (!exportBuildings(buildingIds) || - !exportShaders()) - { - pExportNotifier->setExportFailed(); - return false; - } - - const QString outputPath(m_basePath + QStringLiteral("BuildingModels/")); - QFile fBdv(outputPath + QStringLiteral("/buildings.json")); - if (fBdv.exists()) - { - fBdv.copy(folderPath + QStringLiteral("/../buildings.json")); - } + const QString filename(QStringLiteral("buildingViewer.json")); + QFile f(folderPath + QLatin1Char('/') + filename); + if (!f.open(QIODevice::WriteOnly)) + { + WARNING_LOG(m_logger) << "Can not open file '" << f.fileName() << "' for writing!"; + pExportNotifier->setExportFailed(); + return false; + } + QJsonObject obj; + obj[QStringLiteral("attributes")] = attributes; + obj[QStringLiteral("timeInPresentation")] = + timeRange(m_startTimeSec * 1000, (m_startTimeSec + m_durationSec) * 1000); - emit pExportNotifier->exportSuccessful(filename); + QJsonArray arr; + for (const SituationReplayTime& rt : std::as_const(m_sitReplayTimes)) + { + if (m_startTimeSec > rt.topicEnd_s) + continue; + const double lenReplay = rt.replayEnd_ms - rt.replayStart_ms; + const double endReplay = rt.replayStart_ms + lenReplay; + + const double maxReplay = std::min(rt.replayStart_ms + m_durationSec * 1000. * rt.replaySpeedFactor, endReplay); + arr.push_back(rt.toJson(maxReplay)); + } + obj[QStringLiteral("replays")] = arr; + f.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); + f.close(); + DEBUG_LOG(m_logger) << "BDV filename: " << f.fileName(); + + QVector buildingIds; + buildingIds.reserve(states.size()); + for (const auto& ele : states) + { + const ViewWidgetState vws(ele.toObject()); + int buildingId = featureId2DatabaseId(QString::fromStdString(vws.m_featureID)); + if (buildingId <= 0) + { + WARNING_LOG(m_logger) << "Could not retrieve building id from '" << vws.m_featureID << "' - skipping"; + continue; + } + buildingIds += buildingId; + } + + emit pExportNotifier->stillAlive(); + if (!exportBuildings(buildingIds) || !exportShaders()) + { + pExportNotifier->setExportFailed(); + return false; + } + + const QString outputPath(m_basePath + QStringLiteral("BuildingModels/")); + QFile fBdv(outputPath + QStringLiteral("/buildings.json")); + if (fBdv.exists()) + { + fBdv.copy(folderPath + QStringLiteral("/../buildings.json")); + } + + emit pExportNotifier->exportSuccessful(filename); #else - - if (!m_replayIfc || !m_bgvController) - { - ERROR_LOG(m_logger) << "BuildingViewer exportTopic: m_replayIfc==nullptr, can not start replay, aborting export"; - emit pExportNotifier->exportFailed(); - Q_ASSERT(false); - return false; - } - playbackInit(attributes); + if (!m_replayIfc || !m_bgvController) + { + ERROR_LOG(m_logger) + << "BuildingViewer exportTopic: m_replayIfc==nullptr, can not start replay, aborting export"; + emit pExportNotifier->exportFailed(); + Q_ASSERT(false); + return false; + } - qint64 record_duration_s = m_durationSec + 2; - - QVector> vecReplayHandler; - vecReplayHandler.reserve(m_sitReplayTimes.size()); - for (const SituationReplayTime &srt : std::as_const(m_sitReplayTimes)) - vecReplayHandler.push_back(QSharedPointer(new ReplayHandler(m_startTimeSec, m_startTimeSec + m_durationSec, srt))); + playbackInit(attributes); - VideoInformation info(pExportNotifier, folderPath, attributes, vecReplayHandler, record_duration_s); + qint64 record_duration_s = m_durationSec + 2; - VideoExporter *videoExporter = new VideoExporter; - videoExporter->init(info); + QVector> vecReplayHandler; + vecReplayHandler.reserve(m_sitReplayTimes.size()); + for (const SituationReplayTime& srt : std::as_const(m_sitReplayTimes)) + vecReplayHandler.push_back( + QSharedPointer(new ReplayHandler(m_startTimeSec, m_startTimeSec + m_durationSec, srt))); - Q_ASSERT(!m_tveThread); - m_tveThread = new QThread(this); - videoExporter->moveToThread(m_tveThread); + VideoInformation info(pExportNotifier, folderPath, attributes, vecReplayHandler, record_duration_s); - connect(videoExporter, &VideoExporter::signalStartReplay, - this, &TopicReplayInterface::slotStartReplay); - connect(videoExporter, &VideoExporter::signalStopReplay, - this, &TopicReplayInterface::slotStopReplay); + VideoExporter* videoExporter = new VideoExporter; + videoExporter->init(info); - + Q_ASSERT(!m_tveThread); + m_tveThread = new QThread(this); + videoExporter->moveToThread(m_tveThread); - connect(videoExporter, &VideoExporter::signalStartRecording, - m_bgvController, &BgViewerController::slotStartRecording, Qt::BlockingQueuedConnection); - connect(videoExporter, &VideoExporter::signalStopRecording, - m_bgvController, &BgViewerController::slotStopRecording, Qt::BlockingQueuedConnection); + connect(videoExporter, &VideoExporter::signalStartReplay, this, &TopicReplayInterface::slotStartReplay); + connect(videoExporter, &VideoExporter::signalStopReplay, this, &TopicReplayInterface::slotStopReplay); - connect(m_tveThread, &QThread::started, videoExporter, &VideoExporter::doExport); - connect(m_tveThread, &QThread::finished, videoExporter, &VideoExporter::deleteLater); + connect(videoExporter, &VideoExporter::signalStartRecording, m_bgvController, + &BgViewerController::slotStartRecording, Qt::BlockingQueuedConnection); + connect(videoExporter, &VideoExporter::signalStopRecording, m_bgvController, &BgViewerController::slotStopRecording, + Qt::BlockingQueuedConnection); - m_tveThread->start(); + connect(m_tveThread, &QThread::started, videoExporter, &VideoExporter::doExport); + connect(m_tveThread, &QThread::finished, videoExporter, &VideoExporter::deleteLater); + + m_tveThread->start(); #endif - return true; + return true; } -bool TopicReplayInterface::exportBuildings(const QVector &buildingIds) const +bool TopicReplayInterface::exportBuildings(const QVector& buildingIds) const { - std::shared_ptr ismDtc; - if (!m_session->getDtc(ismDtc)) - return false; - const QString modelPath = BgViewerController::buildingModelPath(); - if (modelPath.isEmpty()) - { - WARNING_LOG(m_logger) << "Could not find path with building models - can not copy models"; - return false; - } - - const QString outputPath(m_basePath + QStringLiteral("BuildingModels/")); - QDir dir(outputPath); - if (!dir.exists() && !dir.mkpath(outputPath)) - { - WARNING_LOG(m_logger) << "Could not create path " << outputPath; - return false; - } - QFile f(outputPath + QStringLiteral("/buildings.json")); - if (!f.open(QIODevice::ReadWrite)) - { - WARNING_LOG(m_logger) << "Could not open file " << f.fileName() << " for read/write: " << f.errorString(); - return false; - } - const QJsonArray arr(QJsonDocument::fromJson(f.readAll()).array()); - QVector knownBuildings; - knownBuildings.reserve(arr.size()); - for (const auto &ele : arr) - { - const auto bi = BuildingInfo::fromJson(ele.toObject()); - if (bi.isValid()) - knownBuildings += bi; - } - - BuildingInfo bi; - for (const int buildingId : buildingIds) - { - const auto mse = ismDtc->mainStructureElement(buildingId); - if (mse.id() != buildingId) + std::shared_ptr ismDtc; + if (!m_session->getDtc(ismDtc)) + return false; + const QString modelPath = BgViewerController::buildingModelPath(); + if (modelPath.isEmpty()) { - WARNING_LOG(m_logger) << "Could not find MainStructureElement for building with id " << buildingId << " - skipping"; - continue; + WARNING_LOG(m_logger) << "Could not find path with building models - can not copy models"; + return false; } - const QString fnIve = QString::fromStdString(mse.name()) + QStringLiteral(".flt.ive"); - const QString fnXml = QString::fromStdString(mse.name()) + QStringLiteral(".flt.xml"); - if (!copyFile(fnIve, modelPath, outputPath) || - !copyFile(fnXml, modelPath, outputPath)) - return false; - bi.name = QString::fromStdString(mse.name()); - bi.position = LtsUtils::QPoint3D(mse.geoPosition().lon(), mse.geoPosition().lat(), mse.geoPosition().z()); - bi.angleDegree = mse.angle(); - bi.id = mse.id(); - knownBuildings += bi; - } + const QString outputPath(m_basePath + QStringLiteral("BuildingModels/")); + QDir dir(outputPath); + if (!dir.exists() && !dir.mkpath(outputPath)) + { + WARNING_LOG(m_logger) << "Could not create path " << outputPath; + return false; + } + QFile f(outputPath + QStringLiteral("/buildings.json")); + if (!f.open(QIODevice::ReadWrite)) + { + WARNING_LOG(m_logger) << "Could not open file " << f.fileName() << " for read/write: " << f.errorString(); + return false; + } + const QJsonArray arr(QJsonDocument::fromJson(f.readAll()).array()); + QVector knownBuildings; + knownBuildings.reserve(arr.size()); + for (const auto& ele : arr) + { + const auto bi = BuildingInfo::fromJson(ele.toObject()); + if (bi.isValid()) + knownBuildings += bi; + } - std::sort(knownBuildings.begin(), knownBuildings.end(), - [](const BuildingInfo &a, const BuildingInfo &b) - { - return a.id < b.id; - }); - knownBuildings.erase(std::unique(knownBuildings.begin(), knownBuildings.end()), knownBuildings.end()); - QJsonArray arrOut; - for (const auto &b : std::as_const(knownBuildings)) - arrOut += b.toJson(); + BuildingInfo bi; + for (const int buildingId : buildingIds) + { + const auto mse = ismDtc->mainStructureElement(buildingId); + if (mse.id() != buildingId) + { + WARNING_LOG(m_logger) << "Could not find MainStructureElement for building with id " << buildingId + << " - skipping"; + continue; + } + const QString fnIve = QString::fromStdString(mse.name()) + QStringLiteral(".flt.ive"); + const QString fnXml = QString::fromStdString(mse.name()) + QStringLiteral(".flt.xml"); + if (!copyFile(fnIve, modelPath, outputPath) || !copyFile(fnXml, modelPath, outputPath)) + return false; + bi.name = QString::fromStdString(mse.name()); + bi.position = LtsUtils::QPoint3D(mse.geoPosition().lon(), mse.geoPosition().lat(), mse.geoPosition().z()); + bi.angleDegree = mse.angle(); + bi.id = mse.id(); - f.resize(0); - f.seek(0); - f.write(QJsonDocument(arrOut).toJson()); - f.close(); - return true; + knownBuildings += bi; + } + + std::sort(knownBuildings.begin(), knownBuildings.end(), + [](const BuildingInfo& a, const BuildingInfo& b) { return a.id < b.id; }); + knownBuildings.erase(std::unique(knownBuildings.begin(), knownBuildings.end()), knownBuildings.end()); + QJsonArray arrOut; + for (const auto& b : std::as_const(knownBuildings)) + arrOut += b.toJson(); + + f.resize(0); + f.seek(0); + f.write(QJsonDocument(arrOut).toJson()); + f.close(); + return true; } bool TopicReplayInterface::exportShaders() const { - const QString shaderPath(NGL::findFile(NGL::FileType::ConfigFile, QStringLiteral("shaders"))); - const QString outputPath(m_basePath + QStringLiteral("BuildingModels/shaders/")); - DEBUG_LOG(m_logger) << "shaderPath: " << shaderPath << ", outputPath: " << outputPath; - return NGL::copyDirContentsToDir(shaderPath, outputPath); + const QString shaderPath(NGL::findFile(NGL::FileType::ConfigFile, QStringLiteral("shaders"))); + const QString outputPath(m_basePath + QStringLiteral("BuildingModels/shaders/")); + DEBUG_LOG(m_logger) << "shaderPath: " << shaderPath << ", outputPath: " << outputPath; + return NGL::copyDirContentsToDir(shaderPath, outputPath); } - -bool TopicReplayInterface::copyFile(const QString &srcFn, const QString &srcDir, const QString &dstDir) const +bool TopicReplayInterface::copyFile(const QString& srcFn, const QString& srcDir, const QString& dstDir) const { - const QString src = srcDir + QLatin1Char('/') + srcFn; - const QString dst = dstDir + QLatin1Char('/') + srcFn; - QFile f(src); - if (!f.exists() || (!QFile::exists(dst) && !f.copy(dst))) - { - WARNING_LOG(m_logger) << "Could not copy " << src << " to " << dst << ": " << f.errorString(); - return false; - } - DEBUG_LOG(m_logger) << "Copied from " << src << " to " << dst; - return true; + const QString src = srcDir + QLatin1Char('/') + srcFn; + const QString dst = dstDir + QLatin1Char('/') + srcFn; + QFile f(src); + if (!f.exists() || (!QFile::exists(dst) && !f.copy(dst))) + { + WARNING_LOG(m_logger) << "Could not copy " << src << " to " << dst << ": " << f.errorString(); + return false; + } + DEBUG_LOG(m_logger) << "Copied from " << src << " to " << dst; + return true; } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.h old mode 100755 new mode 100644 index bd0427f1d..2eba9d94c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_topic_replay_interface.h @@ -1,18 +1,18 @@ - #pragma once +#include +#include #include #include -#include -#include #include namespace NGL { class INGLLogger; } + namespace LtsSession { class LtsSession; @@ -23,45 +23,47 @@ namespace BuildingViewer class InterfaceImpl; class BgViewerController; - class TopicReplayInterface final : public QObject, public TopicReplay::Interface { - Q_OBJECT + Q_OBJECT -public: - explicit TopicReplayInterface(BgViewerController *bgvController, LtsSession::LtsSession *session); - ~TopicReplayInterface(); + public: + explicit TopicReplayInterface(BgViewerController* bgvController, LtsSession::LtsSession* session); + ~TopicReplayInterface(); - QWidget *createWidget() override; - bool playbackInit(const QJsonObject &attributes) override; - void setExportPlaybackTimes(qint64 startTimeSec, - qint64 durationSec, - const QVector &sitReplayTimes) override; - bool exportTopic(const QJsonObject &attributes, - const QString &folderPath, - TopicEditorBase::ExportNotifier *pExportNotifier) override; + QWidget* createWidget() override; + bool playbackInit(const QJsonObject& attributes) override; + void setExportPlaybackTimes(qint64 startTimeSec, qint64 durationSec, + const QVector& sitReplayTimes) override; + bool exportTopic(const QJsonObject& attributes, const QString& folderPath, + TopicEditorBase::ExportNotifier* pExportNotifier) override; - void setBasePath(const QString &basePath) override { m_basePath = basePath; } + void setBasePath(const QString& basePath) override + { + m_basePath = basePath; + } -private slots: - void slotStartReplay(qint64 start, qint64 end, double speed); - void slotStopReplay(); -private: -NGL::INGLLogger &m_logger; - bool exportBuildings(const QVector &buildingIds) const; - bool exportShaders() const; - bool copyFile(const QString &srcFn, const QString &srcDir, const QString &dstDir) const; -private: - qint64 m_startTimeSec = 0; - qint64 m_durationSec = 0; - QVector m_sitReplayTimes; - std::shared_ptr m_replayIfc; - QString m_basePath; - QWidget *m_pBgViewerWidget = nullptr; + private slots: + void slotStartReplay(qint64 start, qint64 end, double speed); + void slotStopReplay(); + + private: + NGL::INGLLogger& m_logger; + bool exportBuildings(const QVector& buildingIds) const; + bool exportShaders() const; + bool copyFile(const QString& srcFn, const QString& srcDir, const QString& dstDir) const; + + private: + qint64 m_startTimeSec = 0; + qint64 m_durationSec = 0; + QVector m_sitReplayTimes; + std::shared_ptr m_replayIfc; + QString m_basePath; + QWidget* m_pBgViewerWidget = nullptr; #ifndef EXPORT_BDV_TOPIC_AS_JSON - QThread *m_tveThread = nullptr; + QThread* m_tveThread = nullptr; #endif - BgViewerController *m_bgvController = nullptr; - LtsSession::LtsSession *m_session = nullptr; + BgViewerController* m_bgvController = nullptr; + LtsSession::LtsSession* m_session = nullptr; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_dialog.h old mode 100755 new mode 100644 index 34f2cf1c4..6abdc1498 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_dialog.h @@ -1,44 +1,43 @@ - #pragma once +#include #include #include -#include namespace Ui { class BgViewerDataViewDialog; } - namespace BuildingViewer { class BgViewerController; class BgViewerDataViewDialog : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit BgViewerDataViewDialog(QWidget *parent = nullptr); - ~BgViewerDataViewDialog(); + public: + explicit BgViewerDataViewDialog(QWidget* parent = nullptr); + ~BgViewerDataViewDialog(); - bool init(BgViewerController *pBdvController, - const std::shared_ptr &ismDtc, - bool fetchBuildingDataOnCreation); + bool init(BgViewerController* pBdvController, + const std::shared_ptr& ismDtc, + bool fetchBuildingDataOnCreation); -public Q_SLOTS: - void fetchBuildingList(); -protected: -NGL::INGLLogger &m_logger; - void retranslate() override; + public Q_SLOTS: + void fetchBuildingList(); -signals: - void signalEditBuilding(const QString &strFeatureID); + protected: + NGL::INGLLogger& m_logger; + void retranslate() override; -private: - Ui::BgViewerDataViewDialog *m_ui; + signals: + void signalEditBuilding(const QString& strFeatureID); + + private: + Ui::BgViewerDataViewDialog* m_ui; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_view.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_view.h old mode 100755 new mode 100644 index a95805c20..65d413808 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_data_view.h @@ -1,19 +1,16 @@ - #pragma once -#include -#include #include - +#include +#include namespace Ui { class BgViewerDataView; } - namespace BuildingViewer { class BgViewerDataViewModel; @@ -21,40 +18,38 @@ class BgViewerController; class BgViewerDataView final : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit BgViewerDataView(QWidget *parent = nullptr); - ~BgViewerDataView(); + public: + explicit BgViewerDataView(QWidget* parent = nullptr); + ~BgViewerDataView(); - bool init(BgViewerController *pBgvController, - const std::shared_ptr &ismDtc, - bool fetchBuildingDataOnCreation); + bool init(BgViewerController* pBgvController, + const std::shared_ptr& ismDtc, + bool fetchBuildingDataOnCreation); - bool eventFilter(QObject *object, QEvent *event) override; + bool eventFilter(QObject* object, QEvent* event) override; -public slots: - void fetchBuildingList(); - void onLtsDataView_DoubleClicked(); - void onLtsDataView_selectionChanged(); - void onLtsDataView_onEditBuilding(); + public slots: + void fetchBuildingList(); + void onLtsDataView_DoubleClicked(); + void onLtsDataView_selectionChanged(); + void onLtsDataView_onEditBuilding(); -signals: - void signalUserActionPerformend(); - void signalCurrentSelectionChanged(const QModelIndex &idx); - void signalEditBuilding(const QString &strFeatureID); + signals: + void signalUserActionPerformend(); + void signalCurrentSelectionChanged(const QModelIndex& idx); + void signalEditBuilding(const QString& strFeatureID); + public slots: + void onViewerEventWidgetMaximized(const QString& featureID); + void onViewerEventWidgetFocused(const QString& featureID); -public slots: - void onViewerEventWidgetMaximized(const QString &featureID); - void onViewerEventWidgetFocused(const QString &featureID); - -private: - -NGL::INGLLogger &m_logger; - Ui::BgViewerDataView *m_ui = nullptr; - BgViewerDataViewModel *m_pModel = nullptr; - BgViewerController *m_pBgvController = nullptr; - int m_lastSelectedRow { -1 }; + private: + NGL::INGLLogger& m_logger; + Ui::BgViewerDataView* m_ui = nullptr; + BgViewerDataViewModel* m_pModel = nullptr; + BgViewerController* m_pBgvController = nullptr; + int m_lastSelectedRow{-1}; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.cpp old mode 100755 new mode 100644 index a8c98a64e..7e7b7b645 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.cpp @@ -1,87 +1,78 @@ - #include "bdv_viewer_gui_plugin_provider.h" -#include -#include #include #include #include #include #include #include -#include +#include #include -#include #include +#include +#include +#include namespace BuildingViewer { -BdvPluginProvider::BdvPluginProvider(LtsSession::LtsSession *session, QObject *parent) : PluginProvider(parent) - , m_session(session), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) {} +BdvPluginProvider::BdvPluginProvider(LtsSession::LtsSession* session, QObject* parent) + : PluginProvider(parent), m_session(session), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} bool BdvPluginProvider::init() { - m_session->getForeignDataInterface(m_asbIfc); - m_session->getDtc(m_srpDtc); - m_session->getDtc(m_pdmDtc); - m_session->getDtc(m_aesDtc); + m_session->getForeignDataInterface(m_asbIfc); + m_session->getDtc(m_srpDtc); + m_session->getDtc(m_pdmDtc); + m_session->getDtc(m_aesDtc); - m_session->getForeignDataInterface_NEW(m_avmDataIfc); + m_session->getForeignDataInterface_NEW(m_avmDataIfc); + if (!m_session->getDtc(m_bldDtc)) + { + ERROR_LOG(m_logger) << "Fetching 'm_bldDtc' failed!"; + return false; + } + m_session->getForeignGuiInterface(m_bldInfoIfc); - if (!m_session->getDtc(m_bldDtc)) - { - ERROR_LOG(m_logger) << "Fetching 'm_bldDtc' failed!"; - return false; - } - m_session->getForeignGuiInterface(m_bldInfoIfc); - - - - - - - - - - - if (!m_session->getDtc(m_ppmDtc)) - { - ERROR_LOG(m_logger) << "Fetching 'm_ppmDtc' failed!"; - return false; - } - m_session->getForeignGuiInterface(m_ppmParticipantInfoIfc); - return true; + if (!m_session->getDtc(m_ppmDtc)) + { + ERROR_LOG(m_logger) << "Fetching 'm_ppmDtc' failed!"; + return false; + } + m_session->getForeignGuiInterface( + m_ppmParticipantInfoIfc); + return true; } QString BdvPluginProvider::toString() const { - return m_session ? m_session->toString() : QStringLiteral("????"); + return m_session ? m_session->toString() : QStringLiteral("????"); } LtsSession::DdsConnectionParams BdvPluginProvider::connParams() const { - return m_session ? m_session->connParams() : LtsSession::DdsConnectionParams(); + return m_session ? m_session->connParams() : LtsSession::DdsConnectionParams(); } std::shared_ptr BdvPluginProvider::ismDataIfc() const { - if (!m_ismDataIfc) - m_session->getForeignDataInterface(m_ismDataIfc); + if (!m_ismDataIfc) + m_session->getForeignDataInterface(m_ismDataIfc); - return m_ismDataIfc; + return m_ismDataIfc; } std::shared_ptr BdvPluginProvider::ismDtc() const { - if (!m_ismDtc) - m_session->getDtc(m_ismDtc); + if (!m_ismDtc) + m_session->getDtc(m_ismDtc); - return m_ismDtc; + return m_ismDtc; } -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.h old mode 100755 new mode 100644 index 5fbc2daec..5bd3769a7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/BuildingViewer/Gui/BuildingViewer/bdv_viewer_gui_plugin_provider.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -12,59 +11,111 @@ namespace LtsSession { class LtsSession; } + namespace BuildingViewer { class BdvPluginProvider : public PluginProvider { - Q_OBJECT -public: - explicit BdvPluginProvider(LtsSession::LtsSession *session, QObject *parent = nullptr); + Q_OBJECT + public: + explicit BdvPluginProvider(LtsSession::LtsSession* session, QObject* parent = nullptr); - bool init(); + bool init(); - QString toString() const override; + QString toString() const override; - int exerciseId() const override { return m_session ? m_session->exerciseId() : -1; } - qint64 partitionTime() const override { return m_session ? m_session->partitionTime() : 0; } - bool isReplayPartition() const override { return m_session ? m_session->isReplayPartition() : false; } - bool isVisibleParty(int partyId) const override { return LtsSessionData::LtsSessionData::getInstance()->isVisibleParty(exerciseId(), partyId); } - quintptr adr() const override {return (quintptr)m_session;} + int exerciseId() const override + { + return m_session ? m_session->exerciseId() : -1; + } - LtsSession::DdsConnectionParams connParams() const override; + qint64 partitionTime() const override + { + return m_session ? m_session->partitionTime() : 0; + } - std::shared_ptr asbIfc() const override { return m_asbIfc; } - std::shared_ptr avmDataIfc() const override { return m_avmDataIfc; } - std::shared_ptr bldDtc() const override { return m_bldDtc; } - std::shared_ptr bldInfoIfc() const override { return m_bldInfoIfc; } - std::shared_ptr ismDtc() const override; - std::shared_ptr ismDataIfc() const override; - std::shared_ptr aesDtc() const override { return m_aesDtc; } - std::shared_ptr ppmDtc() const override { return m_ppmDtc; } - std::shared_ptr pdmDtc() const override { return m_pdmDtc; } + bool isReplayPartition() const override + { + return m_session ? m_session->isReplayPartition() : false; + } - std::shared_ptr srpDtc() const override { return m_srpDtc; } + bool isVisibleParty(int partyId) const override + { + return LtsSessionData::LtsSessionData::getInstance()->isVisibleParty(exerciseId(), partyId); + } - std::shared_ptr ppmParticipantInfoIfc() const override { return m_ppmParticipantInfoIfc; } + quintptr adr() const override + { + return (quintptr)m_session; + } + LtsSession::DdsConnectionParams connParams() const override; - LtsSession::LtsSession *m_session; + std::shared_ptr asbIfc() const override + { + return m_asbIfc; + } -private: + std::shared_ptr avmDataIfc() const override + { + return m_avmDataIfc; + } -NGL::INGLLogger &m_logger; - std::shared_ptr m_asbIfc; - std::shared_ptr m_avmDataIfc; - std::shared_ptr m_bldDtc; - std::shared_ptr m_bldInfoIfc; - mutable std::shared_ptr m_ismDtc; + std::shared_ptr bldDtc() const override + { + return m_bldDtc; + } - mutable std::shared_ptr m_ismDataIfc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_srpDtc; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ppmParticipantInfoIfc; + std::shared_ptr bldInfoIfc() const override + { + return m_bldInfoIfc; + } + + std::shared_ptr ismDtc() const override; + std::shared_ptr ismDataIfc() const override; + + std::shared_ptr aesDtc() const override + { + return m_aesDtc; + } + + std::shared_ptr ppmDtc() const override + { + return m_ppmDtc; + } + + std::shared_ptr pdmDtc() const override + { + return m_pdmDtc; + } + + std::shared_ptr srpDtc() const override + { + return m_srpDtc; + } + + std::shared_ptr ppmParticipantInfoIfc() const override + { + return m_ppmParticipantInfoIfc; + } + + LtsSession::LtsSession* m_session; + + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_asbIfc; + std::shared_ptr m_avmDataIfc; + std::shared_ptr m_bldDtc; + std::shared_ptr m_bldInfoIfc; + mutable std::shared_ptr m_ismDtc; + + mutable std::shared_ptr m_ismDataIfc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_srpDtc; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ppmParticipantInfoIfc; }; -} +} // namespace BuildingViewer diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.cpp old mode 100755 new mode 100644 index d5d513eb3..31d93ea60 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.cpp @@ -1,162 +1,121 @@ - #include "bld_config_dialog.h" + #include "ui_bld_config_dialog.h" - -#include - - #include #include - - +#include #include - namespace Buildings { -BldConfigDialog::BldConfigDialog(int bldEntityId, const QString &displayName, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_bldEntityId(bldEntityId) - , m_displayName(displayName) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::BldConfigDialog) +BldConfigDialog::BldConfigDialog(int bldEntityId, const QString& displayName, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_bldEntityId(bldEntityId), + m_displayName(displayName), m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::BldConfigDialog) { - m_ui->setupUi(this); - - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Send and Close")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Send")); - connect(m_ui->cmbStatus, QOverload::of(&QComboBox::currentIndexChanged), this, - &BldConfigDialog::slotCmbStatusCurrentIndexChanged); - -} + m_ui->setupUi(this); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Send and Close")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Send")); + connect(m_ui->cmbStatus, QOverload::of(&QComboBox::currentIndexChanged), this, + &BldConfigDialog::slotCmbStatusCurrentIndexChanged); +} BldConfigDialog::~BldConfigDialog() { - delete m_ui; -} - + delete m_ui; +} void BldConfigDialog::retranslate() { - translate(m_ui, m_displayName, false, tr("Building Status")); - fillCbx(); + translate(m_ui, m_displayName, false, tr("Building Status")); + fillCbx(); } -bool BldConfigDialog::init(LtsSession::LtsSession *session) +bool BldConfigDialog::init(LtsSession::LtsSession* session) { - if (!session->getFtc(m_ftc)) - return false; - if (!session->getFtc(m_cesFtc)) - return false; + if (!session->getFtc(m_ftc)) + return false; + if (!session->getFtc(m_cesFtc)) + return false; - std::shared_ptr dtc; - if (!session->getDtc(dtc)) - return false; - if ( dtc != NULL) - m_bldState = dtc->buildingState(m_bldEntityId); + std::shared_ptr dtc; + if (!session->getDtc(dtc)) + return false; + if (dtc != NULL) + m_bldState = dtc->buildingState(m_bldEntityId); + slotChangesMade(); + const bool showBuildingOwnershp = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Buildings"), QStringLiteral("Ownership")); + if (showBuildingOwnershp == false) + { + m_ui->gbOwnership->setVisible(false); + } - - - - - - - - slotChangesMade(); - const bool showBuildingOwnershp = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Buildings"), - QStringLiteral("Ownership")); - - if ( showBuildingOwnershp == false) - { - m_ui->gbOwnership->setVisible(false); - } - - return true; -} - + return true; +} void BldConfigDialog::fillCbx() { - m_ui->cmbStatus->clear(); - m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::NoChange), - ProjectDataManagement::VulnerabilityState::NoChange); - m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::CombatReady), - ProjectDataManagement::VulnerabilityState::CombatReady); - m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::CatastrophicKill), - ProjectDataManagement::VulnerabilityState::CatastrophicKill); - m_ui->cmbStatus->setCurrentIndex(m_ui->cmbStatus->findData(m_bldState.vulnerabilityState().underlying())); - -} - + m_ui->cmbStatus->clear(); + m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::NoChange), + ProjectDataManagement::VulnerabilityState::NoChange); + m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::CombatReady), + ProjectDataManagement::VulnerabilityState::CombatReady); + m_ui->cmbStatus->addItem(toString(ProjectDataManagement::VulnerabilityState::CatastrophicKill), + ProjectDataManagement::VulnerabilityState::CatastrophicKill); + m_ui->cmbStatus->setCurrentIndex(m_ui->cmbStatus->findData(m_bldState.vulnerabilityState().underlying())); +} bool BldConfigDialog::apply() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_ui->chbOwnership->isChecked()) - { - CentralEffectSimulation::SetOwnershipRequest req(m_bldEntityId, 0); - m_requestHelper->addRequest([req, this]() + if (m_ui->chbOwnership->isChecked()) { - return m_cesFtc->setOwnershipRequest(req, this); + CentralEffectSimulation::SetOwnershipRequest req(m_bldEntityId, 0); + m_requestHelper->addRequest([req, this]() { return m_cesFtc->setOwnershipRequest(req, this); }); + } + + m_requestHelper->addRequest([this]() { + Buildings::Building building; + building.buildingId(m_bldEntityId); + + SetBuildingStatesRequest requestData; + requestData.buildings({building}); + + ProjectDataManagement::VulnerabilityState state = + static_cast(m_ui->cmbStatus->currentData().toInt()); + requestData.vulnerabilityState(state); + + requestData.resetContamination(m_ui->chbResetContamination->isChecked()); + + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentIndex: " << m_ui->cmbStatus->currentIndex(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentData: " << state; + + return m_ftc->setBuildingStatesRequest(requestData, this); }); - } - - m_requestHelper->addRequest([this]() - { - + return m_requestHelper->startRequests(); +} - - Buildings::Building building; - building.buildingId(m_bldEntityId); - - - - - - - - - - SetBuildingStatesRequest requestData; - requestData.buildings({building}); - - ProjectDataManagement::VulnerabilityState state = static_cast(m_ui->cmbStatus->currentData().toInt()); - requestData.vulnerabilityState(state); - - requestData.resetContamination(m_ui->chbResetContamination->isChecked()); - - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentIndex: " << m_ui->cmbStatus->currentIndex(); - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "currentData: " << state; - - return m_ftc->setBuildingStatesRequest(requestData, this); - }); - - return m_requestHelper->startRequests(); - -} - - -} +} // namespace Buildings void Buildings::BldConfigDialog::slotCmbStatusCurrentIndexChanged(int index) { - Q_UNUSED(index) - ProjectDataManagement::VulnerabilityState state = static_cast(m_ui->cmbStatus->currentData().toInt()); - if (state == ProjectDataManagement::VulnerabilityState_def::CatastrophicKill) - { - m_ui->chbResetContamination->setEnabled(true); - m_ui->chbResetContamination->setChecked(false); - } - else - m_ui->chbResetContamination->setEnabled(true); - + Q_UNUSED(index) + ProjectDataManagement::VulnerabilityState state = + static_cast(m_ui->cmbStatus->currentData().toInt()); + if (state == ProjectDataManagement::VulnerabilityState_def::CatastrophicKill) + { + m_ui->chbResetContamination->setEnabled(true); + m_ui->chbResetContamination->setChecked(false); + } + else + m_ui->chbResetContamination->setEnabled(true); } diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.h old mode 100755 new mode 100644 index 13681668a..f59a92a21 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_config_dialog.h @@ -1,68 +1,70 @@ - #pragma once - -#include -#include - - #include - - +#include +#include #include #include -namespace Ui { +namespace Ui +{ class BldConfigDialog; } -namespace LtsSession { + +namespace LtsSession +{ class LtsSession; } namespace Buildings { - - -class BldConfigDialog : public LtsWidgets::LtsDialog - , protected Buildings::Interface::Ftc::SetBuildingStatesReplyHandler - , protected CentralEffectSimulation::Interface::Ftc::SetOwnershipReplyHandler +class BldConfigDialog : public LtsWidgets::LtsDialog, + protected Buildings::Interface::Ftc::SetBuildingStatesReplyHandler, + protected CentralEffectSimulation::Interface::Ftc::SetOwnershipReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit BldConfigDialog(int bldEntityId, const QString &displayName, QWidget *parent = nullptr); - ~BldConfigDialog(); + public: + explicit BldConfigDialog(int bldEntityId, const QString& displayName, QWidget* parent = nullptr); + ~BldConfigDialog(); - bool init(LtsSession::LtsSession *session); + bool init(LtsSession::LtsSession* session); - void onSetBuildingStatesReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onSetOwnershipReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onSetBuildingStatesReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void slotCmbStatusCurrentIndexChanged(int index); + void onSetOwnershipReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - NGL::INGLLogger &m_logger; - void fillCbx(); + private slots: + void slotCmbStatusCurrentIndexChanged(int index); -private: - NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override final; + private: + NGL::INGLLogger& m_logger; + void fillCbx(); - int m_bldEntityId = 0; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override final; - QString m_displayName; + int m_bldEntityId = 0; - std::shared_ptr m_ftc; - std::shared_ptr m_cesFtc; + QString m_displayName; - Buildings::BuildingState m_bldState; - LtsUtils::RequestHelper *m_requestHelper = nullptr; + std::shared_ptr m_ftc; + std::shared_ptr m_cesFtc; - Ui::BldConfigDialog *m_ui = nullptr; + Buildings::BuildingState m_bldState; + LtsUtils::RequestHelper* m_requestHelper = nullptr; + + Ui::BldConfigDialog* m_ui = nullptr; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.cpp old mode 100755 new mode 100644 index 05a527cf5..531b51ac5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.cpp @@ -1,310 +1,280 @@ - #include "bld_history_dialog_model.h" -#include -#include -#include -#include #include - +#include #include +#include +#include +#include #include namespace Buildings { - - -BuildingHistoryDialogModel::BuildingHistoryDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +BuildingHistoryDialogModel::BuildingHistoryDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Time"), tr("Charge Type"), tr("Originator"), tr("Damage [%]"), tr("Contamination")}, parent), + m_mseId(-1) { - tr("Time"), - tr("Charge Type"), - tr("Originator"), - tr("Damage [%]"), - tr("Contamination") -}, -parent) -, m_mseId(-1) -{} - -bool BuildingHistoryDialogModel::initModel(int mseId, - LtsSession::LtsSession *session) -{ - std::shared_ptr dtc; - if (!session->getDtc(dtc)) - return false; - m_mseId = mseId; - - if (!session->getDtc(m_pdmDtc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - if (!session->getDtc(m_aesDtc)) - return false; - - connect(dtc.get(), &Interface::Dtc::historyStateChanged, - this, &BuildingHistoryDialogModel::onHistoryStateChanged); - - DEBUG_LOG(m_logger) << "m_mseId=" << m_mseId; - reinitModel(dtc->historyState(m_mseId).stateHistory()); - return true; } -QVariant BuildingHistoryDialogModel::data(const QModelIndex &index, int role) const +bool BuildingHistoryDialogModel::initModel(int mseId, LtsSession::LtsSession* session) { - if (!indexIsValid(index)) - return QVariant(); + std::shared_ptr dtc; + if (!session->getDtc(dtc)) + return false; + m_mseId = mseId; - if (role != Qt::DisplayRole) - return QVariant(); + if (!session->getDtc(m_pdmDtc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + if (!session->getDtc(m_aesDtc)) + return false; - const HistoryStateItemEx &data = m_vecData[index.row()]; - switch (index.column()) - { - case Time: - return QDateTime::fromMSecsSinceEpoch(data.time()); - case Charge: - return data.chargeTypeName; - case Originator: - return data.originatorName; - case Damage: - return data.damagePercent(); - case Contamination: - return getContaminations(data.contaminationStates()); - } - return QVariant(); + connect(dtc.get(), &Interface::Dtc::historyStateChanged, this, &BuildingHistoryDialogModel::onHistoryStateChanged); + + DEBUG_LOG(m_logger) << "m_mseId=" << m_mseId; + reinitModel(dtc->historyState(m_mseId).stateHistory()); + return true; } -void BuildingHistoryDialogModel::onHistoryStateChanged(const Buildings::HistoryState &data, DataModification modType) +QVariant BuildingHistoryDialogModel::data(const QModelIndex& index, int role) const { - DEBUG_LOG(m_logger) << "onHistoryStateChanged"; - if (m_mseId != data.mseId()) - return; + if (!indexIsValid(index)) + return QVariant(); - if (modType == DataModification::eRemoved) - { - beginResetModel(); - m_vecData.clear(); - endResetModel(); - return; - } - reinitModel(data.stateHistory()); + if (role != Qt::DisplayRole) + return QVariant(); + + const HistoryStateItemEx& data = m_vecData[index.row()]; + switch (index.column()) + { + case Time: + return QDateTime::fromMSecsSinceEpoch(data.time()); + case Charge: + return data.chargeTypeName; + case Originator: + return data.originatorName; + case Damage: + return data.damagePercent(); + case Contamination: + return getContaminations(data.contaminationStates()); + } + return QVariant(); +} + +void BuildingHistoryDialogModel::onHistoryStateChanged(const Buildings::HistoryState& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << "onHistoryStateChanged"; + if (m_mseId != data.mseId()) + return; + + if (modType == DataModification::eRemoved) + { + beginResetModel(); + m_vecData.clear(); + endResetModel(); + return; + } + reinitModel(data.stateHistory()); } QString BuildingHistoryDialogModel::getChargeTypeName(int chargeTypeId, bool shortName) const { - if (shortName) - return m_pdmDtc->trChargeTypeShortName(chargeTypeId); + if (shortName) + return m_pdmDtc->trChargeTypeShortName(chargeTypeId); - return m_pdmDtc->trChargeTypeName(chargeTypeId); + return m_pdmDtc->trChargeTypeName(chargeTypeId); } - -QString BuildingHistoryDialogModel::getOriginatorName(const HistoryStateItemEx &data) const +QString BuildingHistoryDialogModel::getOriginatorName(const HistoryStateItemEx& data) const { - QString originatorType(ProjectDataManagement::toString(data.originatorType())); - QString originator; - switch (data.originatorType().underlying()) - { - case ProjectDataManagement::StateChangeOriginator::Participant: - { - - if (data.originatorParticipantId() > 0) + QString originatorType(ProjectDataManagement::toString(data.originatorType())); + QString originator; + switch (data.originatorType().underlying()) { - ParticipantManagement::Participant participant = m_ppmDtc->participant(data.originatorParticipantId()); - if (participant.equipmentNumber().is_set()) - originator = QString::number(participant.equipmentNumber().get()); - } - break; - } - case ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation: - case ProjectDataManagement::StateChangeOriginator::FunctionalArea: - { - AreaEffectSimulation::AesItem aesItem; - m_aesDtc->aesItemFromId(data.aesId(), aesItem); - if (aesItem.id() > 0) - originator = QString::fromStdString(aesItem.name()); - break; - } - case ProjectDataManagement::StateChangeOriginator::ImprovisedExplosiveDevice: - case ProjectDataManagement::StateChangeOriginator::DusMine: - case ProjectDataManagement::StateChangeOriginator::ExerciseControl: - case ProjectDataManagement::StateChangeOriginator::ObserverController: - case ProjectDataManagement::StateChangeOriginator::WoundTreatmentDevice: - case ProjectDataManagement::StateChangeOriginator::MedicalTimeout: - case ProjectDataManagement::StateChangeOriginator::MaintainanceDevice: - case ProjectDataManagement::StateChangeOriginator::Initialization: - case ProjectDataManagement::StateChangeOriginator::Sanitation: - case ProjectDataManagement::StateChangeOriginator::Unknown: - return ProjectDataManagement::toString(data.originatorType()); - } + case ProjectDataManagement::StateChangeOriginator::Participant: { - QString chargeTypeShortName = getChargeTypeName(data.chargeTypeId()); - if (!originator.isEmpty() && !chargeTypeShortName.isEmpty()) - originatorType += QStringLiteral("(%1 - %2)").arg(originator, chargeTypeShortName); - else if (!originator.isEmpty()) - originatorType += QStringLiteral(" (%1)").arg(originator); - else if (!chargeTypeShortName.isEmpty()) - originatorType += QStringLiteral(" (%1)").arg(chargeTypeShortName); - return originatorType; -} - -QString BuildingHistoryDialogModel::getContaminations(const std::vector< Buildings::ContaminationState > &contaminationStates) const -{ - DEBUG_LOG(m_logger) << "BuildingHistoryDialogModel::getContaminations"; - QStringList contaminationList; - for (const auto &cs : contaminationStates) - { - AreaEffectSimulation::AesItem item; - m_aesDtc->aesItemFromId(cs.aesId(), item); - const ProjectDataManagement::GearClass &gc = m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); - DEBUG_LOG(m_logger) << "gc=" << gc; - if (gc == ProjectDataManagement::GearClass::Unknown) - continue; - QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); - gearClassName.chop(gearClassName.size() - 1); - if (!contaminationList.contains(gearClassName)) - contaminationList.append(gearClassName); - else - DEBUG_LOG(m_logger) << "contaminationList.contains(gearClassName)" << gearClassName; - } - return contaminationList.join(QStringLiteral("+")); -} - -void BuildingHistoryDialogModel::reinitModel(const std::vector &newData) -{ - DEBUG_LOG(m_logger) << "BuildingHistoryDialogModel::reinitModel size=" << newData.size(); - int indexModel = 0; - - int contaminationOffest = 0; - beginResetModel(); - - if (newData.size() == 0) - return; - m_vecData.resize(newData.size() + newData[0].contaminationStates().size()); - contaminationOffest = 0; - - for (size_t stateHistoryIndex = 0; stateHistoryIndex < newData.size(); ++stateHistoryIndex) - { - DEBUG_LOG(m_logger) << "\n\nstateHistoryIndex=" << stateHistoryIndex; - - - if (((newData.at(stateHistoryIndex).contaminationStates().size() > 0 && stateHistoryIndex == 0) - || (stateHistoryIndex > 0 && (newData.at(stateHistoryIndex).contaminationStates().size() > newData.at(stateHistoryIndex - 1).contaminationStates().size()))) - && (stateHistoryIndex > 0)) - DEBUG_LOG(m_logger) << "1. State ist Kontamination"; - else - { - DEBUG_LOG(m_logger) << "State aus StateItem nehmen: stateHistoryIndex=" << stateHistoryIndex; - auto &data = m_vecData[stateHistoryIndex]; - data = HistoryStateItemEx(newData.at(stateHistoryIndex)); - data.chargeTypeName = getChargeTypeName(data.chargeTypeId()); - QString originatorName= getOriginatorName(data); - - - - - data.originatorName = originatorName; - if (newData.at(stateHistoryIndex).contaminationStates().empty()) - data.contamination.clear(); - else - data.contamination = QStringLiteral("C"); - DEBUG_LOG(m_logger) << "indexModel=" << indexModel - << " chargeTypeId=" << data.chargeTypeId() - << " chargeTypeName=" << getChargeTypeName(data.chargeTypeId()) - << " originatorName=" << getOriginatorName(data); - indexModel++; - } - - - unsigned int contaminationIndex = 0; - - for (const auto &contaminationState : newData.at(stateHistoryIndex).contaminationStates()) - { - - AreaEffectSimulation::AesItem item; - m_aesDtc->aesItemFromId(contaminationState.aesId(), item); - DEBUG_LOG(m_logger) << "m_vecData.size=" << m_vecData.size() - << " indexModel=" << indexModel - << " newData.size()=" << newData.size() - << " contaminationOffest=" << contaminationOffest; - - - if (stateHistoryIndex > 0) - { - DEBUG_LOG(m_logger) << "stateHistoryIndex=" << stateHistoryIndex - << " contaminationIndex=" - << " newData.at(stateHistoryIndex-1).contaminationStates().size() =" << newData.at(stateHistoryIndex - 1).contaminationStates().size(); - if (contaminationIndex < newData.at(stateHistoryIndex - 1).contaminationStates().size()) - { - contaminationIndex++; - DEBUG_LOG(m_logger) << "continue"; - continue; + if (data.originatorParticipantId() > 0) + { + ParticipantManagement::Participant participant = m_ppmDtc->participant(data.originatorParticipantId()); + if (participant.equipmentNumber().is_set()) + originator = QString::number(participant.equipmentNumber().get()); + } + break; } - } - - if (m_vecData.size() < indexModel + 1) - m_vecData.resize(indexModel + 1); - auto &data = m_vecData[indexModel]; - - data = HistoryStateItemEx(newData.at(stateHistoryIndex)); - data.chargeTypeName = getChargeTypeName(item.chargeStruct().chargeTypeId()); - QString originatorName= QString::fromStdString(item.name()); - - - - - - data.originatorName = originatorName; - data.contamination = QStringLiteral("C"); - ::rti::core::int64 time = item.effectStart().get(); - data.time(time); - DEBUG_LOG(m_logger) << " indexModel=" << indexModel - << " AesId=" << contaminationState.aesId() - << " chargeTypeId=" << data.chargeTypeId() - << " chargeTypeName=" << getChargeTypeName(data.chargeTypeId()) - << " originatorName=" << getOriginatorName(data); - - indexModel++; - contaminationIndex++; + case ProjectDataManagement::StateChangeOriginator::AreaEffectSimulation: + case ProjectDataManagement::StateChangeOriginator::FunctionalArea: { + AreaEffectSimulation::AesItem aesItem; + m_aesDtc->aesItemFromId(data.aesId(), aesItem); + if (aesItem.id() > 0) + originator = QString::fromStdString(aesItem.name()); + break; + } + case ProjectDataManagement::StateChangeOriginator::ImprovisedExplosiveDevice: + case ProjectDataManagement::StateChangeOriginator::DusMine: + case ProjectDataManagement::StateChangeOriginator::ExerciseControl: + case ProjectDataManagement::StateChangeOriginator::ObserverController: + case ProjectDataManagement::StateChangeOriginator::WoundTreatmentDevice: + case ProjectDataManagement::StateChangeOriginator::MedicalTimeout: + case ProjectDataManagement::StateChangeOriginator::MaintainanceDevice: + case ProjectDataManagement::StateChangeOriginator::Initialization: + case ProjectDataManagement::StateChangeOriginator::Sanitation: + case ProjectDataManagement::StateChangeOriginator::Unknown: + return ProjectDataManagement::toString(data.originatorType()); } - } - this->sort(0); - endResetModel(); + + QString chargeTypeShortName = getChargeTypeName(data.chargeTypeId()); + if (!originator.isEmpty() && !chargeTypeShortName.isEmpty()) + originatorType += QStringLiteral("(%1 - %2)").arg(originator, chargeTypeShortName); + else if (!originator.isEmpty()) + originatorType += QStringLiteral(" (%1)").arg(originator); + else if (!chargeTypeShortName.isEmpty()) + originatorType += QStringLiteral(" (%1)").arg(chargeTypeShortName); + return originatorType; } - - - -void BuildingHistoryDialogProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +QString BuildingHistoryDialogModel::getContaminations( + const std::vector& contaminationStates) const { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + DEBUG_LOG(m_logger) << "BuildingHistoryDialogModel::getContaminations"; + QStringList contaminationList; + for (const auto& cs : contaminationStates) + { + AreaEffectSimulation::AesItem item; + m_aesDtc->aesItemFromId(cs.aesId(), item); + const ProjectDataManagement::GearClass& gc = + m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); + DEBUG_LOG(m_logger) << "gc=" << gc; + if (gc == ProjectDataManagement::GearClass::Unknown) + continue; + QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); + gearClassName.chop(gearClassName.size() - 1); + if (!contaminationList.contains(gearClassName)) + contaminationList.append(gearClassName); + else + DEBUG_LOG(m_logger) << "contaminationList.contains(gearClassName)" << gearClassName; + } + return contaminationList.join(QStringLiteral("+")); } -bool BuildingHistoryDialogProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +void BuildingHistoryDialogModel::reinitModel(const std::vector& newData) { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + DEBUG_LOG(m_logger) << "BuildingHistoryDialogModel::reinitModel size=" << newData.size(); + int indexModel = 0; + + int contaminationOffest = 0; + beginResetModel(); + + if (newData.size() == 0) + return; + m_vecData.resize(newData.size() + newData[0].contaminationStates().size()); + contaminationOffest = 0; + + for (size_t stateHistoryIndex = 0; stateHistoryIndex < newData.size(); ++stateHistoryIndex) + { + DEBUG_LOG(m_logger) << "\n\nstateHistoryIndex=" << stateHistoryIndex; + + if (((newData.at(stateHistoryIndex).contaminationStates().size() > 0 && stateHistoryIndex == 0) || + (stateHistoryIndex > 0 && (newData.at(stateHistoryIndex).contaminationStates().size() > + newData.at(stateHistoryIndex - 1).contaminationStates().size()))) && + (stateHistoryIndex > 0)) + DEBUG_LOG(m_logger) << "1. State ist Kontamination"; + else + { + DEBUG_LOG(m_logger) << "State aus StateItem nehmen: stateHistoryIndex=" << stateHistoryIndex; + auto& data = m_vecData[stateHistoryIndex]; + data = HistoryStateItemEx(newData.at(stateHistoryIndex)); + data.chargeTypeName = getChargeTypeName(data.chargeTypeId()); + QString originatorName = getOriginatorName(data); + + data.originatorName = originatorName; + if (newData.at(stateHistoryIndex).contaminationStates().empty()) + data.contamination.clear(); + else + data.contamination = QStringLiteral("C"); + DEBUG_LOG(m_logger) << "indexModel=" << indexModel << " chargeTypeId=" << data.chargeTypeId() + << " chargeTypeName=" << getChargeTypeName(data.chargeTypeId()) + << " originatorName=" << getOriginatorName(data); + indexModel++; + } + + unsigned int contaminationIndex = 0; + + for (const auto& contaminationState : newData.at(stateHistoryIndex).contaminationStates()) + { + + AreaEffectSimulation::AesItem item; + m_aesDtc->aesItemFromId(contaminationState.aesId(), item); + DEBUG_LOG(m_logger) << "m_vecData.size=" << m_vecData.size() << " indexModel=" << indexModel + << " newData.size()=" << newData.size() + << " contaminationOffest=" << contaminationOffest; + + if (stateHistoryIndex > 0) + { + DEBUG_LOG(m_logger) << "stateHistoryIndex=" << stateHistoryIndex << " contaminationIndex=" + << " newData.at(stateHistoryIndex-1).contaminationStates().size() =" + << newData.at(stateHistoryIndex - 1).contaminationStates().size(); + if (contaminationIndex < newData.at(stateHistoryIndex - 1).contaminationStates().size()) + { + contaminationIndex++; + DEBUG_LOG(m_logger) << "continue"; + continue; + } + } + + if (m_vecData.size() < indexModel + 1) + m_vecData.resize(indexModel + 1); + auto& data = m_vecData[indexModel]; + + data = HistoryStateItemEx(newData.at(stateHistoryIndex)); + data.chargeTypeName = getChargeTypeName(item.chargeStruct().chargeTypeId()); + QString originatorName = QString::fromStdString(item.name()); + + data.originatorName = originatorName; + data.contamination = QStringLiteral("C"); + ::rti::core::int64 time = item.effectStart().get(); + data.time(time); + DEBUG_LOG(m_logger) << " indexModel=" << indexModel << " AesId=" << contaminationState.aesId() + << " chargeTypeId=" << data.chargeTypeId() + << " chargeTypeName=" << getChargeTypeName(data.chargeTypeId()) + << " originatorName=" << getOriginatorName(data); + + indexModel++; + contaminationIndex++; + } + } + this->sort(0); + endResetModel(); +} + +void BuildingHistoryDialogProxyModel::setSourceModel(QAbstractItemModel* sourceModel) +{ + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); +} + +bool BuildingHistoryDialogProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const +{ + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case BuildingHistoryDialogModel::Time: + return dataLeft.time() < dataRight.time(); + case BuildingHistoryDialogModel::Charge: + case BuildingHistoryDialogModel::Originator: + case BuildingHistoryDialogModel::Damage: + case BuildingHistoryDialogModel::Contamination: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case BuildingHistoryDialogModel::Time: - return dataLeft.time() < dataRight.time(); - case BuildingHistoryDialogModel::Charge: - case BuildingHistoryDialogModel::Originator: - case BuildingHistoryDialogModel::Damage: - case BuildingHistoryDialogModel::Contamination: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.h old mode 100755 new mode 100644 index 6740727e9..c957de7df --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_history_dialog_model.h @@ -1,17 +1,14 @@ - #pragma once - +#include +#include #include #include - -#include -#include - -namespace LtsSession { +namespace LtsSession +{ class LtsSession; } @@ -21,7 +18,7 @@ namespace Interface { class Dtc; } -} +} // namespace ProjectDataManagement namespace ParticipantManagement { @@ -29,7 +26,7 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace AreaEffectSimulation { @@ -37,73 +34,63 @@ namespace Interface { class Dtc; } -} +} // namespace AreaEffectSimulation namespace Buildings { - class HistoryStateItemEx : public HistoryStateItem { -public: - QVariant chargeTypeName; - QVariant originatorName; - QVariant contamination; - HistoryStateItemEx() = default; - explicit HistoryStateItemEx(const HistoryStateItem &item) - : HistoryStateItem(item) - {} + public: + QVariant chargeTypeName; + QVariant originatorName; + QVariant contamination; + HistoryStateItemEx() = default; + + explicit HistoryStateItemEx(const HistoryStateItem& item) : HistoryStateItem(item) {} }; - - class BuildingHistoryDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Column - { - Time, - Charge, - Originator, - Damage, - Contamination - }; - explicit BuildingHistoryDialogModel(QObject *parent = nullptr); + Q_OBJECT + public: + enum Column { Time, Charge, Originator, Damage, Contamination }; - bool initModel(int mseId, - LtsSession::LtsSession *session); + explicit BuildingHistoryDialogModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool initModel(int mseId, LtsSession::LtsSession* session); -private Q_SLOTS: - void onHistoryStateChanged(const HistoryState &data, DataModification modType); + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -private: + private Q_SLOTS: + void onHistoryStateChanged(const HistoryState& data, DataModification modType); -NGL::INGLLogger &m_logger; - void reinitModel(const std::vector &newData); - QString getChargeTypeName(int chargeTypeId, bool shortName = true) const; - QString getOriginatorName(const HistoryStateItemEx &data) const; - QString getContaminations(const std::vector &contaminationStates) const; + private: + NGL::INGLLogger& m_logger; + void reinitModel(const std::vector& newData); + QString getChargeTypeName(int chargeTypeId, bool shortName = true) const; + QString getOriginatorName(const HistoryStateItemEx& data) const; + QString getContaminations(const std::vector& contaminationStates) const; - int m_mseId; + int m_mseId; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_aesDtc; - friend class BuildingHistoryDialogProxyModel; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_aesDtc; + friend class BuildingHistoryDialogProxyModel; }; class BuildingHistoryDialogProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - BuildingHistoryDialogModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + BuildingHistoryDialogModel* m_sourceModel = nullptr; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.cpp old mode 100755 new mode 100644 index bd4a97772..c07e23a8a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.cpp @@ -1,194 +1,176 @@ - #include "bld_hitline_info_dialog.h" + #include "ui_bld_hitline_info_dialog.h" -#include -#include -#include -#include -#include -#include - - - -#include -#include -#include #include #include - - +#include +#include +#include +#include +#include +#include +#include +#include #include +#include namespace Buildings { -HitLineInfoDialog::HitLineInfoDialog(int hitLineId, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_hitLineId(hitLineId) - , m_ui(new Ui::HitLineInfoDialog) +HitLineInfoDialog::HitLineInfoDialog(int hitLineId, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_hitLineId(hitLineId), + m_ui(new Ui::HitLineInfoDialog) { - m_ui->setupUi(this); - - connect(m_ui->pbOriginatorFindOnMap, &QToolButton::clicked, - this, &HitLineInfoDialog::onFindOriginatorOnMap); - connect(m_ui->pbBuildingFindOnMap, &QToolButton::clicked, - this, &HitLineInfoDialog::onFindBuildingOnMap); + m_ui->setupUi(this); + connect(m_ui->pbOriginatorFindOnMap, &QToolButton::clicked, this, &HitLineInfoDialog::onFindOriginatorOnMap); + connect(m_ui->pbBuildingFindOnMap, &QToolButton::clicked, this, &HitLineInfoDialog::onFindBuildingOnMap); #ifndef LTS_DEBUG - m_ui->lbHitLineId->hide(); - m_ui->lblHitLineId->hide(); - m_ui->lbChargeTypeId->hide(); - m_ui->lblChargeTypeId->hide(); - m_ui->lbBuildingId->hide(); - m_ui->lblBuildingId->hide(); - + m_ui->lbHitLineId->hide(); + m_ui->lblHitLineId->hide(); + m_ui->lbChargeTypeId->hide(); + m_ui->lblChargeTypeId->hide(); + m_ui->lbBuildingId->hide(); + m_ui->lblBuildingId->hide(); #endif - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Building_Hitline")); -} - + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Building_Hitline")); +} HitLineInfoDialog::~HitLineInfoDialog() { - delete m_ui; -} - + delete m_ui; +} void HitLineInfoDialog::retranslate() { - translate(m_ui, tr("Building Hit Line Info")); + translate(m_ui, tr("Building Hit Line Info")); } - -bool HitLineInfoDialog::init(LtsSession::LtsSession *session) +bool HitLineInfoDialog::init(LtsSession::LtsSession* session) { - if (!session->getDtc(m_bldDtc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - if (!session->getDtc(m_pdmDtc)) - return false; - if (!session->getDtc(m_aesDtc)) - return false; + if (!session->getDtc(m_bldDtc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + if (!session->getDtc(m_pdmDtc)) + return false; + if (!session->getDtc(m_aesDtc)) + return false; - session->getDtc(m_ismDtc); - session->getForeignGuiInterface(m_sitMapGuiIfc); + session->getDtc(m_ismDtc); + session->getForeignGuiInterface(m_sitMapGuiIfc); - - m_bldDtc->buildingHitLineInfos([this](const BuildingHitLineInfo &data) - { - if (data.id() == m_hitLineId) - { - DEBUG_LOG(m_logger) << "Found Building HitLine Id: " << data.id(); - m_hitLineInfo = data; - m_participantOriginator = m_ppmDtc->participant(data.originatorParticipantId()); - showHitLineInfos(); - } - }); - - if (!m_isInitialized) - WARNING_LOG(m_logger) << "Non Building HitLineInfo data found for id: " << m_hitLineId; - return m_isInitialized; -} + m_bldDtc->buildingHitLineInfos([this](const BuildingHitLineInfo& data) { + if (data.id() == m_hitLineId) + { + DEBUG_LOG(m_logger) << "Found Building HitLine Id: " << data.id(); + m_hitLineInfo = data; + m_participantOriginator = m_ppmDtc->participant(data.originatorParticipantId()); + showHitLineInfos(); + } + }); + if (!m_isInitialized) + WARNING_LOG(m_logger) << "Non Building HitLineInfo data found for id: " << m_hitLineId; + return m_isInitialized; +} void HitLineInfoDialog::showHitLineInfos() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id:" << m_hitLineId; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " id:" << m_hitLineId; - if (m_hitLineInfo.buildingId() <= 0 || m_hitLineInfo.originatorParticipantId() <= 0) - return; + if (m_hitLineInfo.buildingId() <= 0 || m_hitLineInfo.originatorParticipantId() <= 0) + return; - m_ui->lblHitLineId->setText(QString::number(m_hitLineId)); + m_ui->lblHitLineId->setText(QString::number(m_hitLineId)); - - m_ui->lblSampleTime->setText(DTG::toStringMSec(m_hitLineInfo.sampleTime())); + m_ui->lblSampleTime->setText(DTG::toStringMSec(m_hitLineInfo.sampleTime())); - - m_ui->lblOriginatorEquipNr->setText(QString::number(m_participantOriginator.equipmentNumber().get())); + m_ui->lblOriginatorEquipNr->setText(QString::number(m_participantOriginator.equipmentNumber().get())); - m_ui->lblOriginatorParty->setText(ParticipantManagement::trPartyName(m_ppmDtc->party(m_hitLineInfo.originatorPartyId()).name())); + m_ui->lblOriginatorParty->setText( + ParticipantManagement::trPartyName(m_ppmDtc->party(m_hitLineInfo.originatorPartyId()).name())); - m_ui->lblOriginatorDesignator->setText(QString::fromStdString(m_participantOriginator.designator())); + m_ui->lblOriginatorDesignator->setText(QString::fromStdString(m_participantOriginator.designator())); - m_ui->lblOriginatorTactIdentifier->setText(QString::fromStdString(m_participantOriginator.tacticalIdentifier())); + m_ui->lblOriginatorTactIdentifier->setText(QString::fromStdString(m_participantOriginator.tacticalIdentifier())); - m_ui->lblOriginatorType->setText(ParticipantManagement::trTypeName(m_ppmDtc->type(m_participantOriginator.typeId()).name())); + m_ui->lblOriginatorType->setText( + ParticipantManagement::trTypeName(m_ppmDtc->type(m_participantOriginator.typeId()).name())); - QString mgrs = LtsCoordTrans::mgrsFromGeographic(m_hitLineInfo.originatorPos().lon(), m_hitLineInfo.originatorPos().lat()); - if (qFuzzyIsNull(m_hitLineInfo.originatorPos().z())) - m_ui->lblOriginatorPos->setText(tr("Position: %1").arg(mgrs)); - else - m_ui->lblOriginatorPos->setText(tr("Position: %1 %2").arg(mgrs).arg(m_hitLineInfo.originatorPos().z())); + QString mgrs = + LtsCoordTrans::mgrsFromGeographic(m_hitLineInfo.originatorPos().lon(), m_hitLineInfo.originatorPos().lat()); + if (qFuzzyIsNull(m_hitLineInfo.originatorPos().z())) + m_ui->lblOriginatorPos->setText(tr("Position: %1").arg(mgrs)); + else + m_ui->lblOriginatorPos->setText(tr("Position: %1 %2").arg(mgrs).arg(m_hitLineInfo.originatorPos().z())); - - m_ui->lblBuildingId->setText(QString::number(m_hitLineInfo.buildingId())); - if (m_ismDtc) - m_ui->lblBuildingName->setText(m_ismDtc->getBuildingDisplayName(m_hitLineInfo.buildingId())); + m_ui->lblBuildingId->setText(QString::number(m_hitLineInfo.buildingId())); + if (m_ismDtc) + m_ui->lblBuildingName->setText(m_ismDtc->getBuildingDisplayName(m_hitLineInfo.buildingId())); - mgrs = LtsCoordTrans::mgrsFromGeographic(m_hitLineInfo.buildingPos().lon(), m_hitLineInfo.buildingPos().lat()); - if (qFuzzyIsNull(m_hitLineInfo.buildingPos().z())) - m_ui->lblBuildingPos->setText(tr("Position: %1").arg(mgrs)); - else - m_ui->lblBuildingPos->setText(tr("Position: %1 %2").arg(mgrs).arg(m_hitLineInfo.buildingPos().z())); + mgrs = LtsCoordTrans::mgrsFromGeographic(m_hitLineInfo.buildingPos().lon(), m_hitLineInfo.buildingPos().lat()); + if (qFuzzyIsNull(m_hitLineInfo.buildingPos().z())) + m_ui->lblBuildingPos->setText(tr("Position: %1").arg(mgrs)); + else + m_ui->lblBuildingPos->setText(tr("Position: %1 %2").arg(mgrs).arg(m_hitLineInfo.buildingPos().z())); - Buildings::BuildingState bldState = m_bldDtc->buildingState((m_hitLineInfo.buildingId())); - ProjectDataManagement::VulnerabilityState st = bldState.vulnerabilityState(); - m_ui->lblBuildingStatus->setText(toString(st)); + Buildings::BuildingState bldState = m_bldDtc->buildingState((m_hitLineInfo.buildingId())); + ProjectDataManagement::VulnerabilityState st = bldState.vulnerabilityState(); + m_ui->lblBuildingStatus->setText(toString(st)); - m_ui->lblBuildingDamagePercent->setText(QString::number(bldState.damagePercent())); + m_ui->lblBuildingDamagePercent->setText(QString::number(bldState.damagePercent())); - m_ui->lblBuildingDamageOldPercent->setText(QString::number(bldState.damagePercentOld())); + m_ui->lblBuildingDamageOldPercent->setText(QString::number(bldState.damagePercentOld())); - m_ui->lblChargeTypeId->setText(QString::number(m_hitLineInfo.chargeTypeId())); + m_ui->lblChargeTypeId->setText(QString::number(m_hitLineInfo.chargeTypeId())); - m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_hitLineInfo.chargeTypeId())); + m_ui->lblChargeType->setText(m_pdmDtc->trChargeTypeShortName(m_hitLineInfo.chargeTypeId())); - const QString contamination = getContaminations(m_hitLineInfo.contaminationStates()); - m_ui->lbContamination->setHidden(contamination.isEmpty()); - m_ui->lblContamination->setHidden(contamination.isEmpty()); - m_ui->lblContamination->setText(contamination.isEmpty() ? QStringLiteral("-") : contamination); + const QString contamination = getContaminations(m_hitLineInfo.contaminationStates()); + m_ui->lbContamination->setHidden(contamination.isEmpty()); + m_ui->lblContamination->setHidden(contamination.isEmpty()); + m_ui->lblContamination->setText(contamination.isEmpty() ? QStringLiteral("-") : contamination); - m_isInitialized = true; + m_isInitialized = true; } -QString HitLineInfoDialog::getContaminations(const std::vector< Buildings::ContaminationState > &contaminationStates) const +QString +HitLineInfoDialog::getContaminations(const std::vector& contaminationStates) const { - QStringList contaminationList; - for(const auto &cs : contaminationStates){ - AreaEffectSimulation::AesItem item; - m_aesDtc->aesItemFromId(cs.aesId(), item); - const ProjectDataManagement::GearClass &gc = m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); - if (gc == ProjectDataManagement::GearClass::Unknown) - continue; - QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); - gearClassName.chop(gearClassName.size()-1); - if (!contaminationList.contains(gearClassName)) - contaminationList.append(gearClassName); - } - return contaminationList.join(QStringLiteral("+")); + QStringList contaminationList; + for (const auto& cs : contaminationStates) + { + AreaEffectSimulation::AesItem item; + m_aesDtc->aesItemFromId(cs.aesId(), item); + const ProjectDataManagement::GearClass& gc = + m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); + if (gc == ProjectDataManagement::GearClass::Unknown) + continue; + QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); + gearClassName.chop(gearClassName.size() - 1); + if (!contaminationList.contains(gearClassName)) + contaminationList.append(gearClassName); + } + return contaminationList.join(QStringLiteral("+")); } - - void HitLineInfoDialog::onFindOriginatorOnMap() { - if (m_sitMapGuiIfc) - m_sitMapGuiIfc->centerMapToParticipant(m_participantOriginator.id()); -} - + if (m_sitMapGuiIfc) + m_sitMapGuiIfc->centerMapToParticipant(m_participantOriginator.id()); +} void HitLineInfoDialog::onFindBuildingOnMap() { - if (m_sitMapGuiIfc) - m_sitMapGuiIfc->centerMapToBuildingObject(m_hitLineInfo.buildingId()); -} + if (m_sitMapGuiIfc) + m_sitMapGuiIfc->centerMapToBuildingObject(m_hitLineInfo.buildingId()); +} - - -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.h old mode 100755 new mode 100644 index c80e68ebb..d3e53b796 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_hitline_info_dialog.h @@ -1,18 +1,12 @@ - #pragma once - -#include - - - -#include #include +#include +#include #include - namespace Ui { class HitLineInfoDialog; @@ -22,34 +16,39 @@ namespace LtsSession { class LtsSession; } + namespace ProjectDataManagement { namespace Interface { class Dtc; } -} +} // namespace ProjectDataManagement + namespace ParticipantManagement { namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement + namespace InfrastructureManagement { namespace Interface { class Dtc; } -} +} // namespace InfrastructureManagement + namespace AreaEffectSimulation { namespace Interface { class Dtc; } -} +} // namespace AreaEffectSimulation + namespace SituationMap { @@ -58,49 +57,45 @@ class ForeignGuiInterface; namespace Buildings { -namespace Interface { +namespace Interface +{ class Dtc; } - - class HitLineInfoDialog : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit HitLineInfoDialog(int hitLineId, QWidget *parent = nullptr); - ~HitLineInfoDialog(); + public: + explicit HitLineInfoDialog(int hitLineId, QWidget* parent = nullptr); + ~HitLineInfoDialog(); - bool init(LtsSession::LtsSession *session); + bool init(LtsSession::LtsSession* session); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void showHitLineInfos(); + QString getContaminations(const std::vector& contaminationStates) const; -NGL::INGLLogger &m_logger; - void retranslate() override; - void showHitLineInfos(); - QString getContaminations(const std::vector &contaminationStates) const; + private Q_SLOTS: + void onFindBuildingOnMap(); + void onFindOriginatorOnMap(); + private: + int m_hitLineId = 0; + BuildingHitLineInfo m_hitLineInfo; + ParticipantManagement::Participant m_participantOriginator; + bool m_isInitialized = false; -private Q_SLOTS: - void onFindBuildingOnMap(); - void onFindOriginatorOnMap(); + std::shared_ptr m_bldDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ismDtc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_sitMapGuiIfc; -private: - int m_hitLineId = 0; - BuildingHitLineInfo m_hitLineInfo; - ParticipantManagement::Participant m_participantOriginator; - bool m_isInitialized = false; - - std::shared_ptr m_bldDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ismDtc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_sitMapGuiIfc; - - - Ui::HitLineInfoDialog *m_ui = nullptr; + Ui::HitLineInfoDialog* m_ui = nullptr; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.cpp old mode 100755 new mode 100644 index e16a21b98..46fbe30cf --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.cpp @@ -1,1133 +1,890 @@ - - - #include "bld_info_dialog.h" -#include -#include "ui_bld_info_dialog.h" + #include "bld_history_dialog.h" #include "egcu_info_dialog.h" +#include "ui_bld_info_dialog.h" -#include - - -#include -#include - - -#include #include -#include -#include -#include #include - - +#include +#include +#include #include #include -#include #include - - +#include +#include +#include +#include #include #include -#include -#include #include +#include +#include +#include +#include #ifdef PP_TEST -#include #include +#include #endif - #include - using namespace InfrastructureManagement; using namespace ParticipantManagement; - class HtmlDelegate : public QStyledItemDelegate { -public: - HtmlDelegate(QObject *parent = nullptr) - : QStyledItemDelegate(parent) - {} - - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override - { - - - painter->save(); - QTextDocument doc; - doc.setHtml(index.data().toString()); - doc.setTextWidth(-1); - painter->translate(option.rect.topLeft()); - painter->setClipRect(0, 0, option.rect.width(), option.rect.height()); - doc.drawContents(painter); - painter->restore(); - } - - - - - - + public: + HtmlDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {} + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override + { + painter->save(); + QTextDocument doc; + doc.setHtml(index.data().toString()); + doc.setTextWidth(-1); + painter->translate(option.rect.topLeft()); + painter->setClipRect(0, 0, option.rect.width(), option.rect.height()); + doc.drawContents(painter); + painter->restore(); + } }; - namespace Buildings { -BldInfoDialog::BldInfoDialog(int bldEntityId, const QString &menuGroup, QWidget *parent) : InfoDialogBase(bldEntityId, menuGroup, QStringLiteral("BldInfoDialog"), LtsWidgets::ButtonCombination::CloseOnly, parent) - , m_ui(new Ui::BldInfoDialog), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - DEBUG_LOG(m_logger) << LOGFUNCTION << " START" << ", bldEntityId=" << bldEntityId; +BldInfoDialog::BldInfoDialog(int bldEntityId, const QString& menuGroup, QWidget* parent) + : InfoDialogBase(bldEntityId, menuGroup, QStringLiteral("BldInfoDialog"), LtsWidgets::ButtonCombination::CloseOnly, + parent), + m_ui(new Ui::BldInfoDialog), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + DEBUG_LOG(m_logger) << LOGFUNCTION << " START" << ", bldEntityId=" << bldEntityId; - m_ui->setupUi(this); + m_ui->setupUi(this); #ifndef LTS_DEBUG - m_ui->lblAssetId->hide(); - m_ui->lbAssetId->hide(); - m_ui->lblBldId->hide(); - m_ui->lbBldId->hide(); - m_ui->lblOrganisatorParticipantId->hide(); - m_ui->lbOrganisatorParticipantId->hide(); - m_ui->lblStructElementId->hide(); - m_ui->lbStructElementId->hide(); - m_ui->lbDamagePercentOld->hide(); - m_ui->lblDamagePercentOld->hide(); + m_ui->lblAssetId->hide(); + m_ui->lbAssetId->hide(); + m_ui->lblBldId->hide(); + m_ui->lbBldId->hide(); + m_ui->lblOrganisatorParticipantId->hide(); + m_ui->lbOrganisatorParticipantId->hide(); + m_ui->lblStructElementId->hide(); + m_ui->lbStructElementId->hide(); + m_ui->lbDamagePercentOld->hide(); + m_ui->lblDamagePercentOld->hide(); #endif - m_ui->lbStatus->hide(); - m_ui->lblStatus->hide(); + m_ui->lbStatus->hide(); + m_ui->lblStatus->hide(); - m_ui->pbFindOnMap->setToolTip(tr("Locate building on map")); - m_ui->pbHistory->setToolTip(tr("Show building history")); - m_ui->pbDetails->setToolTip(tr("Set building status")); - m_ui->pbBuildingViewer->setToolTip(tr("Show building in BuildingViewer")); - m_ui->pbMonitor->setToolTip(tr("Show EGCU monitor")); + m_ui->pbFindOnMap->setToolTip(tr("Locate building on map")); + m_ui->pbHistory->setToolTip(tr("Show building history")); + m_ui->pbDetails->setToolTip(tr("Set building status")); + m_ui->pbBuildingViewer->setToolTip(tr("Show building in BuildingViewer")); + m_ui->pbMonitor->setToolTip(tr("Show EGCU monitor")); - connect(m_ui->pbHistory, &QToolButton::clicked, this, &BldInfoDialog::onOpenHistory); - connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &BldInfoDialog::onFindOnMap); - connect(m_ui->pbDetails, &QToolButton::clicked, this, &BldInfoDialog::onShowDetails); - connect(m_ui->pbBuildingViewer, &QToolButton::clicked, this, &BldInfoDialog::onShowBuildingViewer); - connect(m_ui->pbMonitor, &QToolButton::clicked, this, &BldInfoDialog::onShowEgcuMonitor); + connect(m_ui->pbHistory, &QToolButton::clicked, this, &BldInfoDialog::onOpenHistory); + connect(m_ui->pbFindOnMap, &QToolButton::clicked, this, &BldInfoDialog::onFindOnMap); + connect(m_ui->pbDetails, &QToolButton::clicked, this, &BldInfoDialog::onShowDetails); + connect(m_ui->pbBuildingViewer, &QToolButton::clicked, this, &BldInfoDialog::onShowBuildingViewer); + connect(m_ui->pbMonitor, &QToolButton::clicked, this, &BldInfoDialog::onShowEgcuMonitor); - setOnlineHelpFilename(QStringLiteral("Info_Dialog-Building_Viewer")); - - DEBUG_LOG(m_logger) << LOGFUNCTION << " END" << ", bldEntityId=" << bldEntityId; -} + setOnlineHelpFilename(QStringLiteral("Info_Dialog-Building_Viewer")); + DEBUG_LOG(m_logger) << LOGFUNCTION << " END" << ", bldEntityId=" << bldEntityId; +} BldInfoDialog::~BldInfoDialog() { - delete m_ui; -} - + delete m_ui; +} void BldInfoDialog::retranslate() { - constexpr int resolution = ICON_RESOLUTION; - const QVector polyHouse = - { - QPointF(resolution / 4, resolution), - QPointF(resolution / 4 * 3, resolution), - QPointF(resolution / 4 * 3, resolution / 4 * 2), - QPointF(resolution / 4 * 3.5, resolution / 4 * 2), - QPointF(resolution / 4 * 2, resolution / 4 * 0.5), - QPointF(resolution / 4 * 0.5, resolution / 4 * 2), - QPointF(resolution / 4, resolution / 4 * 2), - QPointF(resolution / 4, resolution) - }; + constexpr int resolution = ICON_RESOLUTION; + const QVector polyHouse = {QPointF(resolution / 4, resolution), + QPointF(resolution / 4 * 3, resolution), + QPointF(resolution / 4 * 3, resolution / 4 * 2), + QPointF(resolution / 4 * 3.5, resolution / 4 * 2), + QPointF(resolution / 4 * 2, resolution / 4 * 0.5), + QPointF(resolution / 4 * 0.5, resolution / 4 * 2), + QPointF(resolution / 4, resolution / 4 * 2), + QPointF(resolution / 4, resolution)}; - QPainterPath pPath; - pPath.addPolygon(polyHouse); + QPainterPath pPath; + pPath.addPolygon(polyHouse); + QColor partyColor = Qt::red; + const auto dpr = devicePixelRatioF(); + QPixmap preIcon(QSize(ICON_RESOLUTION, ICON_RESOLUTION) * dpr); + preIcon.fill(Qt::transparent); + preIcon.setDevicePixelRatio(dpr); + m_ui->lblIcon->setPixmap(preIcon); + QImage img = m_ui->lblIcon->pixmap()->toImage(); + QPainter painter(&img); + painter.setPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); + painter.setBrush(Qt::transparent); + painter.drawPath(pPath); + painter.fillPath(pPath, partyColor); + painter.end(); + m_ui->lblIcon->setPixmap(QPixmap::fromImage(img)); - - - - - - - - - - - - - - QColor partyColor = Qt::red; - const auto dpr = devicePixelRatioF(); - QPixmap preIcon(QSize(ICON_RESOLUTION, ICON_RESOLUTION) * dpr); - preIcon.fill(Qt::transparent); - preIcon.setDevicePixelRatio(dpr); - m_ui->lblIcon->setPixmap(preIcon); - QImage img = m_ui->lblIcon->pixmap()->toImage(); - QPainter painter(&img); - painter.setPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin)); - painter.setBrush(Qt::transparent); - painter.drawPath(pPath); - painter.fillPath(pPath, partyColor); - painter.end(); - m_ui->lblIcon->setPixmap(QPixmap::fromImage(img)); - - translate(m_ui, tr("Building: %1").arg(m_ismDtc->getBuildingDisplayName(m_mse))); + translate(m_ui, tr("Building: %1").arg(m_ismDtc->getBuildingDisplayName(m_mse))); } -bool BldInfoDialog::init(LtsSession::LtsSession *session) +bool BldInfoDialog::init(LtsSession::LtsSession* session) { - if (!InfoDialogBase::init(session)) - return false; + if (!InfoDialogBase::init(session)) + return false; - connect(m_dtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, - this, &BldInfoDialog::onBuildingStateChanged); + connect(m_dtc.get(), &Buildings::Interface::Dtc::buildingStateChanged, this, + &BldInfoDialog::onBuildingStateChanged); - if (!m_session->getDtc(m_cesDtc)) - return false; - connect(m_cesDtc.get(), &CentralEffectSimulation::Interface::Dtc::buildingOwnershipChanged, - this, &BldInfoDialog::onBuildingOwnershipChanged); + if (!m_session->getDtc(m_cesDtc)) + return false; + connect(m_cesDtc.get(), &CentralEffectSimulation::Interface::Dtc::buildingOwnershipChanged, this, + &BldInfoDialog::onBuildingOwnershipChanged); + m_session->getDtc(m_aesDtc); + m_session->getDtc(m_ppmDtc); + m_session->getDtc(m_pdmDtc); - m_session->getDtc(m_aesDtc); - m_session->getDtc(m_ppmDtc); - m_session->getDtc(m_pdmDtc); + const bool isBridge = m_mse.structureElementTypeId() == InfrastructureManagement::StructureElementType::Bridge; + const bool isResourceManagerApp = m_session->app() == LtsAppDescriptor::App::ResourceManager; - const bool isBridge = m_mse.structureElementTypeId() == InfrastructureManagement::StructureElementType::Bridge; - const bool isResourceManagerApp = m_session->app() == LtsAppDescriptor::App::ResourceManager; + DEBUG_LOG(m_logger) << LOGFUNCTION << " m_mse" << m_mse << ", isBridge=" << isBridge; - DEBUG_LOG(m_logger) << LOGFUNCTION << " m_mse" << m_mse - << ", isBridge=" << isBridge; + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + &BldInfoDialog::onMainStructureElementChanged); + m_mse = m_ismDtc->mainStructureElement(m_mseId); - - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, - this, &BldInfoDialog::onMainStructureElementChanged); - m_mse = m_ismDtc->mainStructureElement(m_mseId); + m_ui->lbDamagePercent->setVisible(m_session->partitionType() != IDL::PartitionType::Global); + m_ui->lblDamagePercent->setVisible(m_session->partitionType() != IDL::PartitionType::Global); - - m_ui->lbDamagePercent->setVisible(m_session->partitionType() != IDL::PartitionType::Global); - m_ui->lblDamagePercent->setVisible(m_session->partitionType() != IDL::PartitionType::Global); + showBuildingInfos(); - showBuildingInfos(); + auto predicate = [](const InfrastructureManagement::InstrumentationAsset& a) { + return (!a.isDeleted() && + (a.mountingPointTypeId() == InfrastructureManagement::MountingPointType::EffectGenerationControlUnit)); + }; + QMap> assetsMapBuilding; + m_ismDtc->waitForHistoricalDataInstrumentationAsset(500); + m_ismDtc->getAllAssetsPerBuilding(predicate, assetsMapBuilding); - auto predicate = [](const InfrastructureManagement::InstrumentationAsset & a) - { - return (!a.isDeleted() && (a.mountingPointTypeId() == InfrastructureManagement::MountingPointType::EffectGenerationControlUnit)); - }; - QMap> assetsMapBuilding; - m_ismDtc->waitForHistoricalDataInstrumentationAsset(500); - m_ismDtc->getAllAssetsPerBuilding(predicate, assetsMapBuilding); - - QVBoxLayout *l = new QVBoxLayout(m_ui->gbSegments); - m_ui->gbSegments->setLayout(l); - if (assetsMapBuilding.contains(m_mseId)) - { - const QVector &instrumentationAssets = assetsMapBuilding[m_mseId]; - const QMap &mountingPointAssets = m_ismDtc->mountingPointAssets(); - for (const auto &instrumentationAsset : std::as_const(instrumentationAssets)) + QVBoxLayout* l = new QVBoxLayout(m_ui->gbSegments); + m_ui->gbSegments->setLayout(l); + if (assetsMapBuilding.contains(m_mseId)) { - InfrastructureManagement::MountingPointAsset mpa; - for (const auto &mpax : std::as_const(mountingPointAssets)) - { - if (mpax.assetId() == instrumentationAsset.id()) + const QVector& instrumentationAssets = + assetsMapBuilding[m_mseId]; + const QMap& mountingPointAssets = + m_ismDtc->mountingPointAssets(); + for (const auto& instrumentationAsset : std::as_const(instrumentationAssets)) { - mpa = mpax; - break; + InfrastructureManagement::MountingPointAsset mpa; + for (const auto& mpax : std::as_const(mountingPointAssets)) + { + if (mpax.assetId() == instrumentationAsset.id()) + { + mpa = mpax; + break; + } + } + if (mpa.assetId() != instrumentationAsset.id()) + continue; + + std::string name = mpa.name().empty() ? instrumentationAsset.name() : mpa.name(); + int assetId = mpa.assetId(); + QPushButton* w = new QPushButton(QString::fromStdString(name), this); + w->setProperty("assetId", assetId); + w->setProperty("assetName", QString::fromStdString(instrumentationAsset.name())); + l->addWidget(w); + connect(w, &QPushButton::clicked, this, &BldInfoDialog::onEgcuInfoDialogRequested); } - } - if (mpa.assetId() != instrumentationAsset.id()) - continue; - - std::string name = mpa.name().empty() ? instrumentationAsset.name() : mpa.name(); - int assetId = mpa.assetId(); - QPushButton *w = new QPushButton(QString::fromStdString(name), this); - w->setProperty("assetId", assetId); - w->setProperty("assetName", QString::fromStdString(instrumentationAsset.name())); - l->addWidget(w); - connect(w, &QPushButton::clicked, this, &BldInfoDialog::onEgcuInfoDialogRequested); } - } - m_ui->gbSegments->setVisible(egcuVisibility()); - bool editable = true; - m_ui->pbMonitor->setVisible(editable && egcuVisibility()); + m_ui->gbSegments->setVisible(egcuVisibility()); + bool editable = true; + m_ui->pbMonitor->setVisible(editable && egcuVisibility()); - if ((m_session->app() == LtsAppDescriptor::App::OC) || isResourceManagerApp) - { - m_ui->pbDetails->hide(); - m_ui->pbHistory->hide(); + if ((m_session->app() == LtsAppDescriptor::App::OC) || isResourceManagerApp) + { + m_ui->pbDetails->hide(); + m_ui->pbHistory->hide(); + m_ui->pbBuildingViewer->hide(); + } + + if (m_session->isReplayPartition()) + m_ui->pbDetails->hide(); m_ui->pbBuildingViewer->hide(); - } - if (m_session->isReplayPartition()) - m_ui->pbDetails->hide(); - m_ui->pbBuildingViewer->hide(); + if (LtsAppManager::LtsAppManager::getInstance()->hasApp(LtsAppDescriptor::App::BuildingViewer)) + m_ui->pbBuildingViewer->setVisible( + m_bdvGuiIfc != nullptr && + LtsAppManager::LtsAppManager::getInstance()->hasApp(LtsAppDescriptor::App::BuildingViewer)); - if (LtsAppManager::LtsAppManager::getInstance()->hasApp(LtsAppDescriptor::App::BuildingViewer)) - m_ui->pbBuildingViewer->setVisible(m_bdvGuiIfc != nullptr && LtsAppManager::LtsAppManager::getInstance()->hasApp(LtsAppDescriptor::App::BuildingViewer)); + m_ui->lblIcon->setVisible(true); + m_ui->lblIcon->setFixedSize(ICON_RESOLUTION, ICON_RESOLUTION); - m_ui->lblIcon->setVisible(true); - m_ui->lblIcon->setFixedSize(ICON_RESOLUTION, ICON_RESOLUTION); + m_ui->lblBldName->setText(buildingDisplayName()); - m_ui->lblBldName->setText(buildingDisplayName()); + const bool ownershipFunc = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Buildings"), QStringLiteral("Ownership")); - const bool ownershipFunc = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Buildings"), - QStringLiteral("Ownership")); + const bool bShowBuildingOwnership = ownershipFunc && !isResourceManagerApp && !isBridge; + m_ui->lbOwnership->setVisible(bShowBuildingOwnership); + m_ui->twOwnership->setVisible(bShowBuildingOwnership); - const bool bShowBuildingOwnership = ownershipFunc && !isResourceManagerApp && !isBridge; - m_ui->lbOwnership->setVisible(bShowBuildingOwnership); - m_ui->twOwnership->setVisible(bShowBuildingOwnership); + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mountingPointAssetChanged, this, + &BldInfoDialog::onMountingPointAssetChanged); - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mountingPointAssetChanged, - this, &BldInfoDialog::onMountingPointAssetChanged); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableFloorParticipantCount = + ps->value(QStringLiteral("bld"), QStringLiteral("enableFloorParticipantCount")).toBool(); - - - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableFloorParticipantCount = ps->value(QStringLiteral("bld"), QStringLiteral("enableFloorParticipantCount")).toBool(); - - if (enableFloorParticipantCount) - { - m_ui->twFloorParticipantCount->setItemDelegate(new HtmlDelegate); + if (enableFloorParticipantCount) + { + m_ui->twFloorParticipantCount->setItemDelegate(new HtmlDelegate); #ifdef PP_TEST #warning PP_TEST ACTIVE! - static int pid = 1; + static int pid = 1; - struct PPData - { - int roomId; - int partyId; - int dataMod; - int participantId = pid++; - QString changeDesc = {}; - }; + struct PPData + { + int roomId; + int partyId; + int dataMod; + int participantId = pid++; + QString changeDesc = {}; + }; - const auto ppDatas = QVector() << PPData{190, 1, 0} << PPData{190, 2, 0} << PPData{190, 3, 0} << PPData{190, 3, 0} << PPData{234, 1, 0} << PPData{234, 1, 0} << PPData{234, 3, 0}; + const auto ppDatas = QVector() + << PPData{190, 1, 0} << PPData{190, 2, 0} << PPData{190, 3, 0} << PPData{190, 3, 0} + << PPData{234, 1, 0} << PPData{234, 1, 0} << PPData{234, 3, 0}; + auto fn = [this](const PPData& ppData) { + ParticipantPosition pp; + pp.roomId(ppData.roomId); + pp.participantId(ppData.participantId); + pp.partyId(ppData.partyId); + pp.buildingId(m_mse.id()); + if (!ppData.changeDesc.isEmpty()) + { + m_ui->lbFloorParticipantCount->setText( + QStringLiteral("%1: %2").arg(ppData.participantId).arg(ppData.changeDesc)); + onPositionChanged(pp, ppData.dataMod == 0 ? DataModification::eAdded : DataModification::eModified); + return; + } + qWarning() << "id" << ppData.participantId; + addParticipantPosition(pp, ppData.dataMod == 0 ? DataModification::eAdded : DataModification::eModified); + }; - auto fn = [this](const PPData & ppData) - { - ParticipantPosition pp; - pp.roomId(ppData.roomId); - pp.participantId(ppData.participantId); - pp.partyId(ppData.partyId); - pp.buildingId(m_mse.id()); - if (!ppData.changeDesc.isEmpty()) - { - m_ui->lbFloorParticipantCount->setText(QStringLiteral("%1: %2").arg(ppData.participantId).arg(ppData.changeDesc)); - onPositionChanged(pp, ppData.dataMod == 0 ? DataModification::eAdded : DataModification::eModified); - return; - } - qWarning() << "id" << ppData.participantId; - addParticipantPosition(pp, ppData.dataMod == 0 ? DataModification::eAdded : DataModification::eModified); - }; + for (const PPData& ppData : ppDatas) + fn(ppData); - for (const PPData &ppData : ppDatas) - fn(ppData); + updateFloorParticipantTable(); - updateFloorParticipantTable(); + m_ui->twFloorParticipantCount->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->twFloorParticipantCount, &QWidget::customContextMenuRequested, this, [this, fn](const QPoint& p) { + QMenu* m = new QMenu(this); + m->setAttribute(Qt::WA_DeleteOnClose); + m->addAction(QStringLiteral("[next test]"), this, [fn]() { + static int step = 0; + static auto ppDatas = QVector() - m_ui->twFloorParticipantCount->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->twFloorParticipantCount, &QWidget::customContextMenuRequested, - this, [this, fn](const QPoint & p) - { - QMenu *m = new QMenu(this); - m->setAttribute(Qt::WA_DeleteOnClose); + << PPData{190, 1, 1, 1, QStringLiteral("something changed, but nothing relevant")} + << PPData{234, 2, 1, 2, QStringLiteral("changed from floor_1 to floor_2")} + << PPData{190, 2, 1, 3, QStringLiteral("changed party to 2")} + << PPData{234, 2, 1, 4, QStringLiteral("changed party to 2 AND to floor_2")} + << PPData{190, 3, 1, 1, QStringLiteral("change party to 3")} + << PPData{277, 3, 1, 5, QStringLiteral("change party to (new) floor_3")}; - m->addAction(QStringLiteral("[next test]"), this, [fn]() - { - static int step = 0; - static auto ppDatas = QVector() - - << PPData{190, 1, 1, 1, QStringLiteral("something changed, but nothing relevant")} - << PPData{234, 2, 1, 2, QStringLiteral("changed from floor_1 to floor_2")} - << PPData{190, 2, 1, 3, QStringLiteral("changed party to 2")} - << PPData{234, 2, 1, 4, QStringLiteral("changed party to 2 AND to floor_2")} - << PPData{190, 3, 1, 1, QStringLiteral("change party to 3")} - << PPData{277, 3, 1, 5, QStringLiteral("change party to (new) floor_3")} - ; + if (step >= ppDatas.count()) + return; - if (step >= ppDatas.count()) - return; + fn(ppDatas.at(step++)); + }); - fn(ppDatas.at(step++)); - }); - - m->popup(m_ui->twFloorParticipantCount->mapToGlobal(p)); - }); + m->popup(m_ui->twFloorParticipantCount->mapToGlobal(p)); + }); #else - - const QMap &participantPosition = - m_ppmDtc->participantPositions(); - for (const ParticipantPosition &pp : std::as_const(participantPosition)) - addParticipantPosition(pp, DataModification::eAdded); - updateFloorParticipantTable(); + + const QMap& participantPosition = + m_ppmDtc->participantPositions(); + for (const ParticipantPosition& pp : std::as_const(participantPosition)) + addParticipantPosition(pp, DataModification::eAdded); + updateFloorParticipantTable(); #endif + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantPositionChanged, this, + &BldInfoDialog::onPositionChanged); + } + else + { + m_ui->lbFloorParticipantCount->hide(); + m_ui->twFloorParticipantCount->hide(); + } - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantPositionChanged, - this, &BldInfoDialog::onPositionChanged); - } - else - { - m_ui->lbFloorParticipantCount->hide(); - m_ui->twFloorParticipantCount->hide(); - } - - - return true; -} - - + return true; +} QString BldInfoDialog::buildingDisplayName() const { - return m_ismDtc->getBuildingDisplayName(m_mse); + return m_ismDtc->getBuildingDisplayName(m_mse); } bool BldInfoDialog::egcuVisibility() { - if (!m_ui || !m_ui->gbSegments) - return false; + if (!m_ui || !m_ui->gbSegments) + return false; - QVBoxLayout *l = qobject_cast(m_ui->gbSegments->layout()); - if (!l) - return false; + QVBoxLayout* l = qobject_cast(m_ui->gbSegments->layout()); + if (!l) + return false; - return (l->count() > 0) && - !m_session->isReplayPartition() && - !((m_session->app() == LtsAppDescriptor::App::OC) || (m_session->app() == LtsAppDescriptor::App::ResourceManager)); + return (l->count() > 0) && !m_session->isReplayPartition() && + !((m_session->app() == LtsAppDescriptor::App::OC) || + (m_session->app() == LtsAppDescriptor::App::ResourceManager)); } - - void BldInfoDialog::showBuildingInfos() { - showBuildingInfos(m_dtc->buildingState(m_mseId)); + showBuildingInfos(m_dtc->buildingState(m_mseId)); } - - -void BldInfoDialog::onPositionChanged(const ParticipantManagement::ParticipantPosition &data, DataModification modType) +void BldInfoDialog::onPositionChanged(const ParticipantManagement::ParticipantPosition& data, DataModification modType) { - addParticipantPosition(data, modType); - updateFloorParticipantTable(); + addParticipantPosition(data, modType); + updateFloorParticipantTable(); } - - QString BldInfoDialog::getFloorName(int floorSeId) { - auto it = m_floorNames.find(floorSeId); - if (it != m_floorNames.end()) - return *it; + auto it = m_floorNames.find(floorSeId); + if (it != m_floorNames.end()) + return *it; - InfrastructureManagement::StructureElement floorSe; - if (!getRoom(floorSeId, floorSe)) - return QStringLiteral(""); - return QString::fromStdString(floorSe.displayName()); + InfrastructureManagement::StructureElement floorSe; + if (!getRoom(floorSeId, floorSe)) + return QStringLiteral(""); + return QString::fromStdString(floorSe.displayName()); } - - -bool BldInfoDialog::getRoom(int roomSeId, InfrastructureManagement::StructureElement &roomSe) +bool BldInfoDialog::getRoom(int roomSeId, InfrastructureManagement::StructureElement& roomSe) { - auto it = m_roomStructureElementCache.find(roomSeId); - if (it != m_roomStructureElementCache.end()) - { - - roomSe = *it; - return true; - } + auto it = m_roomStructureElementCache.find(roomSeId); + if (it != m_roomStructureElementCache.end()) + { - if (m_ismDtc->getStructureElementById(roomSeId, roomSe)) - { - - m_roomStructureElementCache.insert(roomSeId, roomSe); - return true; - } + roomSe = *it; + return true; + } - return false; + if (m_ismDtc->getStructureElementById(roomSeId, roomSe)) + { + + m_roomStructureElementCache.insert(roomSeId, roomSe); + return true; + } + + return false; } - - int BldInfoDialog::findFloorIdByRoomId(int roomId) noexcept(false) { - - auto roomToFloorCache = m_roomToFloorCache.constFind(roomId); - if (roomToFloorCache != m_roomToFloorCache.constEnd()) - { - - return roomToFloorCache.value(); - } - + auto roomToFloorCache = m_roomToFloorCache.constFind(roomId); + if (roomToFloorCache != m_roomToFloorCache.constEnd()) + { - StructureElement roomSe; - if (!m_ismDtc->getStructureElementById(roomId, roomSe)) - { - ERROR_LOG(m_logger) << "getStructureElementById roomId=" << roomId << " not found"; - return -1; - } + return roomToFloorCache.value(); + } - const std::vector path = roomSe.path(); + StructureElement roomSe; + if (!m_ismDtc->getStructureElementById(roomId, roomSe)) + { + ERROR_LOG(m_logger) << "getStructureElementById roomId=" << roomId << " not found"; + return -1; + } - for (const int parentSeId : path) - { - StructureElement parentSe; - if (!getRoom(parentSeId, parentSe)) - continue; - + const std::vector path = roomSe.path(); - if (parentSe.structureElementTypeId().underlying() != StructureElementType_def::Floor) - continue; + for (const int parentSeId : path) + { + StructureElement parentSe; + if (!getRoom(parentSeId, parentSe)) + continue; - + if (parentSe.structureElementTypeId().underlying() != StructureElementType_def::Floor) + continue; - m_floorNames.insert(parentSeId, QString::fromStdString(parentSe.displayName())); - m_roomToFloorCache.insert(roomId, parentSeId); - return parentSeId; - } + m_floorNames.insert(parentSeId, QString::fromStdString(parentSe.displayName())); + m_roomToFloorCache.insert(roomId, parentSeId); + return parentSeId; + } - throw QStringLiteral("findFloorId: floor id for room %1 not found").arg(roomSe.id()); + throw QStringLiteral("findFloorId: floor id for room %1 not found").arg(roomSe.id()); } - - -void BldInfoDialog::addParticipantPosition(const ParticipantManagement::ParticipantPosition &data, DataModification ) +void BldInfoDialog::addParticipantPosition(const ParticipantManagement::ParticipantPosition& data, DataModification) { - if (data.buildingId() != m_mse.id()) - { - - return; - } - - const int roomId = data.roomId(); - const int participantId = data.participantId(); - const int participantPartyId = data.partyId(); - int participantFloorId; - - participantFloorId = findFloorIdByRoomId(roomId); - if (participantFloorId < 0 ) - { - ERROR_LOG(m_logger) << "addParticipantPosition: cannot find floor id roomId=" << roomId; - return; - } - - m_rawParticipantCount.insert(participantId, QPair(participantFloorId, participantPartyId)); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + if (data.buildingId() != m_mse.id()) + { + return; + } + const int roomId = data.roomId(); + const int participantId = data.participantId(); + const int participantPartyId = data.partyId(); + int participantFloorId; + participantFloorId = findFloorIdByRoomId(roomId); + if (participantFloorId < 0) + { + ERROR_LOG(m_logger) << "addParticipantPosition: cannot find floor id roomId=" << roomId; + return; + } + m_rawParticipantCount.insert(participantId, QPair(participantFloorId, participantPartyId)); } - - void BldInfoDialog::updateFloorParticipantTable() { - - const QMap parties(m_ppmDtc->partys()); - m_ui->twFloorParticipantCount->setUpdatesEnabled(false); - m_ui->twFloorParticipantCount->clearContents(); - m_ui->twFloorParticipantCount->setRowCount(0); - int row = 0; + const QMap parties(m_ppmDtc->partys()); + m_ui->twFloorParticipantCount->setUpdatesEnabled(false); + m_ui->twFloorParticipantCount->clearContents(); + m_ui->twFloorParticipantCount->setRowCount(0); + int row = 0; - - QVector floors; - { - QMapIterator > it(m_rawParticipantCount); - while (it.hasNext()) + QVector floors; { - it.next(); - - const QPair &data = it.value(); - const int floor = data.first; + QMapIterator> it(m_rawParticipantCount); + while (it.hasNext()) + { + it.next(); - if (!floors.contains(floor)) - floors += floor; - } - } + const QPair& data = it.value(); + const int floor = data.first; - - - QMap> floorPartyPeople; - for (const int floor : std::as_const(floors)) - { - QMapIterator > it(m_rawParticipantCount); - while (it.hasNext()) - { - it.next(); - const QPair &pair = it.value(); - const int rawFloor = pair.first; - - if (floor != rawFloor) - continue; - - const int party = pair.second; - - auto it1 = floorPartyPeople.find(floor); - if (it1 == floorPartyPeople.end()) - { - QMap partyPeople; - partyPeople.insert(party, 1); - floorPartyPeople.insert(floor, partyPeople); - } - else - { - QMap &partyPeopleRef = it1.value(); - - auto it2 = partyPeopleRef.find(party); - - if (it2 == partyPeopleRef.end()) - partyPeopleRef.insert(party, 1); - else - it2.value()++; - } - } - } - - - - QMapIterator> it1(floorPartyPeople); - while (it1.hasNext()) - { - it1.next(); - const int floor = it1.key(); - - int column = 0; - m_ui->twFloorParticipantCount->insertRow(row); - QTableWidgetItem *pItem = new QTableWidgetItem(m_floorNames.value(floor, tr(""))); - m_ui->twFloorParticipantCount->setItem(row, column++, pItem); - - - - const QMap &partyPeople = it1.value(); - - QStringList floorPartyParticipantCountStrings; - QMapIterator it2(partyPeople); - while (it2.hasNext()) - { - it2.next(); - - const int party = it2.key(); - const int count = it2.value(); - - floorPartyParticipantCountStrings += QStringLiteral("%2").arg(QString::number((unsigned int)parties.value(party).color(), 16)).arg(count); - + if (!floors.contains(floor)) + floors += floor; + } } - - pItem = new QTableWidgetItem(floorPartyParticipantCountStrings.join(QStringLiteral(" "))); - m_ui->twFloorParticipantCount->setItem(row, column, pItem); + QMap> floorPartyPeople; + for (const int floor : std::as_const(floors)) + { + QMapIterator> it(m_rawParticipantCount); + while (it.hasNext()) + { + it.next(); + const QPair& pair = it.value(); + const int rawFloor = pair.first; - row++; - } + if (floor != rawFloor) + continue; + const int party = pair.second; + auto it1 = floorPartyPeople.find(floor); + if (it1 == floorPartyPeople.end()) + { + QMap partyPeople; + partyPeople.insert(party, 1); + floorPartyPeople.insert(floor, partyPeople); + } + else + { + QMap& partyPeopleRef = it1.value(); - + auto it2 = partyPeopleRef.find(party); + if (it2 == partyPeopleRef.end()) + partyPeopleRef.insert(party, 1); + else + it2.value()++; + } + } + } + QMapIterator> it1(floorPartyPeople); + while (it1.hasNext()) + { + it1.next(); + const int floor = it1.key(); + int column = 0; + m_ui->twFloorParticipantCount->insertRow(row); + QTableWidgetItem* pItem = new QTableWidgetItem(m_floorNames.value(floor, tr(""))); + m_ui->twFloorParticipantCount->setItem(row, column++, pItem); + const QMap& partyPeople = it1.value(); + QStringList floorPartyParticipantCountStrings; + QMapIterator it2(partyPeople); + while (it2.hasNext()) + { + it2.next(); + const int party = it2.key(); + const int count = it2.value(); + floorPartyParticipantCountStrings += + QStringLiteral("%2") + .arg(QString::number((unsigned int)parties.value(party).color(), 16)) + .arg(count); + } + pItem = new QTableWidgetItem(floorPartyParticipantCountStrings.join(QStringLiteral(" "))); + m_ui->twFloorParticipantCount->setItem(row, column, pItem); + row++; + } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - m_ui->twFloorParticipantCount->setUpdatesEnabled(true); + m_ui->twFloorParticipantCount->setUpdatesEnabled(true); } - - -void BldInfoDialog::showBuildingInfos(const Buildings::BuildingState &bldState) +void BldInfoDialog::showBuildingInfos(const Buildings::BuildingState& bldState) { - if (bldState.id() <= 0) - { - m_ui->lblBldId->clear(); - m_ui->lblStructElementId->clear(); - m_ui->lblAssetId->clear(); + if (bldState.id() <= 0) + { + m_ui->lblBldId->clear(); + m_ui->lblStructElementId->clear(); + m_ui->lblAssetId->clear(); + m_ui->lblOrganisatorParticipantId->clear(); + m_ui->lblDamagePercent->clear(); + m_ui->lblDamagePercentOld->clear(); + m_ui->lblStatus->clear(); + m_ui->lblContamination->clear(); + fillOwnership({}); + return; + } + + m_ui->lblBldId->setText(QString::number(bldState.id())); + m_ui->lblStructElementId->setText(QString::number(bldState.structureElementId())); + m_ui->lblAssetId->setText(QString::number(bldState.assetId())); + m_ui->lblOrganisatorParticipantId->clear(); - m_ui->lblDamagePercent->clear(); - m_ui->lblDamagePercentOld->clear(); - m_ui->lblStatus->clear(); - m_ui->lblContamination->clear(); - fillOwnership({}); - return; - } - - m_ui->lblBldId->setText(QString::number(bldState.id())); - m_ui->lblStructElementId->setText(QString::number(bldState.structureElementId())); - m_ui->lblAssetId->setText(QString::number(bldState.assetId())); - - m_ui->lblOrganisatorParticipantId->clear(); - if (bldState.originatorParticipantId()) - { - if (m_ppmDtc) + if (bldState.originatorParticipantId()) { - ParticipantManagement::Participant player = m_ppmDtc->participant(bldState.originatorParticipantId()); - if (player.equipmentNumber().is_set()) - m_ui->lblOrganisatorParticipantId->setText(QString::number(player.equipmentNumber().get())); + if (m_ppmDtc) + { + ParticipantManagement::Participant player = m_ppmDtc->participant(bldState.originatorParticipantId()); + if (player.equipmentNumber().is_set()) + m_ui->lblOrganisatorParticipantId->setText(QString::number(player.equipmentNumber().get())); + } } - } - else if (bldState.aesId()) - { - if (m_aesDtc) + else if (bldState.aesId()) { - AreaEffectSimulation::AesItem aesItem; - m_aesDtc->aesItemFromId(bldState.aesId(), aesItem); - m_ui->lblOrganisatorParticipantId->setText(QString::fromStdString(aesItem.name())); + if (m_aesDtc) + { + AreaEffectSimulation::AesItem aesItem; + m_aesDtc->aesItemFromId(bldState.aesId(), aesItem); + m_ui->lblOrganisatorParticipantId->setText(QString::fromStdString(aesItem.name())); + } } - } - else - m_ui->lblOrganisatorParticipantId->setText(tr("EXCON")); + else + m_ui->lblOrganisatorParticipantId->setText(tr("EXCON")); - m_ui->lblDamagePercent->setText(QString::number(bldState.damagePercent())); - m_ui->lblDamagePercentOld->setText(QString::number(bldState.damagePercentOld())); + m_ui->lblDamagePercent->setText(QString::number(bldState.damagePercent())); + m_ui->lblDamagePercentOld->setText(QString::number(bldState.damagePercentOld())); - QStringList contaminationList; - for (const auto &cs : bldState.contaminationStates()) - { - AreaEffectSimulation::AesItem item; - m_aesDtc->aesItemFromId(cs.aesId(), item); - const ProjectDataManagement::GearClass &gc = m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); - if (gc == ProjectDataManagement::GearClass::Unknown) - continue; - QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); - gearClassName.chop(gearClassName.size() - 1); - if (!contaminationList.contains(gearClassName)) - contaminationList.append(gearClassName); - } - m_ui->lbContamination->setHidden(contaminationList.isEmpty()); - m_ui->lblContamination->setHidden(contaminationList.isEmpty()); - m_ui->lblContamination->setText(contaminationList.join(QStringLiteral("+"))); - - ProjectDataManagement::VulnerabilityState st = bldState.vulnerabilityState(); - m_ui->lblStatus->setText(toString(st)); - - m_ui->twFloorParticipantCount->hideColumn(2); - DEBUG_LOG(m_logger) << "fillOwnership"; - fillOwnership(bldState.id()); - DEBUG_LOG(m_logger) << "Vor fillContaminationTable"; - fillContaminationTable(bldState); - DEBUG_LOG(m_logger) << "Nach fillContaminationTable"; - - -} - -void BldInfoDialog::fillContaminationTable(const Buildings::BuildingState &bldState) -{ - clearColumn(2); - bool showContaminationCol = false; - DEBUG_LOG(m_logger) << "fillContaminationTable bldState.contaminationStates().size()=" << bldState.contaminationStates().size(); - for (const auto &cs : bldState.contaminationStates()) - { - DEBUG_LOG(m_logger) << "cs.rooms().size()=" << cs.rooms().size(); - - - - for (unsigned int i = 0; i < cs.rooms().size(); i++) + QStringList contaminationList; + for (const auto& cs : bldState.contaminationStates()) { - int floorIdContamination = findFloorIdByRoomId(cs.rooms()[i]); - DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination; - if ( floorIdContamination == -1) - { - DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination << "continue"; - continue; - } - QString floorNameConatmaniation = getFloorName(floorIdContamination); - DEBUG_LOG(m_logger) << "Floor:" << floorNameConatmaniation - << " id=" << floorIdContamination - << " m_rowToFloorId=" << floorIdContamination ; - if (!m_floorIdToRow.contains(floorIdContamination)) - { - DEBUG_LOG(m_logger) << "!m_floorIdToRow.contains(" << floorIdContamination << ")"; - continue; - } - int row = m_floorIdToRow.value(floorIdContamination); - int column = 2; - DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination - << " row=" << row; - - QTableWidgetItem *pItem = m_ui->twOwnership->item(row, column); - if (pItem == nullptr) - { - DEBUG_LOG(m_logger) << "pItem == nullptr"; - pItem = new QTableWidgetItem(); - } - const QColor color = Qt::yellow; - pItem->setData(Qt::BackgroundRole, - color); - m_ui->twOwnership->setItem(row, column, pItem); - showContaminationCol = true; + AreaEffectSimulation::AesItem item; + m_aesDtc->aesItemFromId(cs.aesId(), item); + const ProjectDataManagement::GearClass& gc = + m_pdmDtc->gearClassFromChargeTypeId(item.chargeStruct().chargeTypeId()); + if (gc == ProjectDataManagement::GearClass::Unknown) + continue; + QString gearClassName = ProjectDataManagement::toString(gc).trimmed(); + gearClassName.chop(gearClassName.size() - 1); + if (!contaminationList.contains(gearClassName)) + contaminationList.append(gearClassName); } - } - if (showContaminationCol) - m_ui->twOwnership->showColumn(2); - else - m_ui->twOwnership->hideColumn(2); + m_ui->lbContamination->setHidden(contaminationList.isEmpty()); + m_ui->lblContamination->setHidden(contaminationList.isEmpty()); + m_ui->lblContamination->setText(contaminationList.join(QStringLiteral("+"))); + + ProjectDataManagement::VulnerabilityState st = bldState.vulnerabilityState(); + m_ui->lblStatus->setText(toString(st)); + + m_ui->twFloorParticipantCount->hideColumn(2); + DEBUG_LOG(m_logger) << "fillOwnership"; + fillOwnership(bldState.id()); + DEBUG_LOG(m_logger) << "Vor fillContaminationTable"; + fillContaminationTable(bldState); + DEBUG_LOG(m_logger) << "Nach fillContaminationTable"; } +void BldInfoDialog::fillContaminationTable(const Buildings::BuildingState& bldState) +{ + clearColumn(2); + bool showContaminationCol = false; + DEBUG_LOG(m_logger) << "fillContaminationTable bldState.contaminationStates().size()=" + << bldState.contaminationStates().size(); + for (const auto& cs : bldState.contaminationStates()) + { + DEBUG_LOG(m_logger) << "cs.rooms().size()=" << cs.rooms().size(); + + for (unsigned int i = 0; i < cs.rooms().size(); i++) + { + int floorIdContamination = findFloorIdByRoomId(cs.rooms()[i]); + DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination; + if (floorIdContamination == -1) + { + DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination << "continue"; + continue; + } + QString floorNameConatmaniation = getFloorName(floorIdContamination); + DEBUG_LOG(m_logger) << "Floor:" << floorNameConatmaniation << " id=" << floorIdContamination + << " m_rowToFloorId=" << floorIdContamination; + if (!m_floorIdToRow.contains(floorIdContamination)) + { + DEBUG_LOG(m_logger) << "!m_floorIdToRow.contains(" << floorIdContamination << ")"; + continue; + } + int row = m_floorIdToRow.value(floorIdContamination); + int column = 2; + DEBUG_LOG(m_logger) << "floorIdContamination=" << floorIdContamination << " row=" << row; + + QTableWidgetItem* pItem = m_ui->twOwnership->item(row, column); + if (pItem == nullptr) + { + DEBUG_LOG(m_logger) << "pItem == nullptr"; + pItem = new QTableWidgetItem(); + } + const QColor color = Qt::yellow; + pItem->setData(Qt::BackgroundRole, color); + m_ui->twOwnership->setItem(row, column, pItem); + showContaminationCol = true; + } + } + if (showContaminationCol) + m_ui->twOwnership->showColumn(2); + else + m_ui->twOwnership->hideColumn(2); +} void BldInfoDialog::fillOwnership(int buildingId) { - CentralEffectSimulation::BuildingOwnership ownership = m_cesDtc->buildingOwnership(buildingId); - if (ownership.buildingId() == buildingId) - fillOwnership(ownership); + CentralEffectSimulation::BuildingOwnership ownership = m_cesDtc->buildingOwnership(buildingId); + if (ownership.buildingId() == buildingId) + fillOwnership(ownership); } void BldInfoDialog::clearColumn(int column) { - int rowCount = m_ui->twOwnership->rowCount(); - for (int row = 0; row < rowCount; row++) - { - QTableWidgetItem *item = m_ui->twOwnership->item(row, column); - if (item != nullptr) + int rowCount = m_ui->twOwnership->rowCount(); + for (int row = 0; row < rowCount; row++) { - const QColor color = Qt::white; - item->setData(Qt::BackgroundRole, - color); - item->setData(Qt::DisplayRole, QString()); - - } - } - -} - - -void BldInfoDialog::fillOwnership(const CentralEffectSimulation::BuildingOwnership &ownership) -{ - m_ui->twOwnership->setUpdatesEnabled(false); - - clearColumn(1); - m_ui->twOwnership->setRowCount(ownership.ownerships().size()); - int row = m_ui->twOwnership->rowCount(); - - for (const auto &data : ownership.ownerships()) - { - --row; - int column = 0; - QTableWidgetItem *pItem = nullptr; - - - for (const InfrastructureManagement::StructureElement &elem : m_mse.elements()) - { - if (elem.id() == data.floorId()) - { - QString name = QString::fromStdString(elem.displayName()); - if (name.isEmpty()) - name = QString::fromStdString(elem.name()); - pItem = new QTableWidgetItem(name); - break; - } - } - if (!pItem) - pItem = new QTableWidgetItem(QString::number(data.floorId())); - m_rowToFloorId.insert(row, data.floorId()); - m_floorIdToRow.insert(data.floorId(), row); - - DEBUG_LOG(m_logger) << "m_rowToFloorId.insert" - << " row=" << row - << " column=" << column - << " data.floorId()=" << data.floorId(); - m_ui->twOwnership->setItem(row, column++, pItem); - - - pItem = new QTableWidgetItem(); - if (m_ppmDtc && data.partyId() > 0) - { - const auto &party = m_ppmDtc->party(data.partyId()); - pItem->setData(Qt::BackgroundRole, - QColor::fromRgb(QRgb(party.color()))); - pItem->setData(Qt::DisplayRole, ParticipantManagement::trPartyName(party.name())); - } - m_ui->twOwnership->setItem(row, column++, pItem); - - } - - - m_ui->twOwnership->setUpdatesEnabled(true); -} - - -void BldInfoDialog::onBuildingStateChanged(const Buildings::BuildingState &data, const DataModification &modType) -{ - if (modType == DataModification::eRemoved) - return; - DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.id(); - if (data.id() != m_mseId) - return; - - showBuildingInfos(data); -} - - -void BldInfoDialog::onBuildingOwnershipChanged( - const CentralEffectSimulation::BuildingOwnership &data, const DataModification &modType) -{ - if (modType == DataModification::eRemoved) - return; - DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.buildingId(); - if (data.buildingId() != m_mseId) - return; - - fillOwnership(data); - -} - -void BldInfoDialog::onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &data, - const DataModification &modType) -{ - if (modType == DataModification::eRemoved) - return; - DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.id(); - if (data.id() != m_mseId) - return; - - m_mse = data; - m_ui->lblBldName->setText(buildingDisplayName()); - showBuildingInfos(); -} - -void BldInfoDialog::onMountingPointAssetChanged(const InfrastructureManagement::MountingPointAsset &data, const DataModification &modType) -{ - InfrastructureManagement::StructureElement se; - m_ismDtc->getStructureElementById(data.structureElementId(), se); - if (se.mainStructureElementId() != m_mseId) - return; - - if (modType == DataModification::eAdded) - { - auto instrumentationAsset = m_ismDtc->instrumentationAsset(data.assetId()); - if (instrumentationAsset.mountingPointTypeId() != InfrastructureManagement::MountingPointType::EffectGenerationControlUnit) - return; - QString name = QString::fromStdString(data.name()); - if (name.isNull()) - name = QString::fromStdString(instrumentationAsset.hostname()); - - QVBoxLayout *l = qobject_cast(m_ui->gbSegments->layout()); - QPushButton *w = new QPushButton(name, this); - w->setProperty("assetId", data.assetId()); - l->addWidget(w); - connect(w, &QPushButton::clicked, this, &BldInfoDialog::onEgcuInfoDialogRequested); - m_ui->gbSegments->setVisible(egcuVisibility()); - bool editable = true; - m_ui->pbMonitor->setVisible(editable && egcuVisibility()); - } - else if (modType == DataModification::eRemoved) - { - const QList &list = m_ui->gbSegments->findChildren(); - for (QPushButton *pb : std::as_const(list)) - { - if (pb->property("assetId").toInt() == data.assetId()) - { - - if (m_ui->gbSegments->layout()->count() == 1) + QTableWidgetItem* item = m_ui->twOwnership->item(row, column); + if (item != nullptr) { - m_ui->gbSegments->setVisible(false); - m_ui->pbMonitor->hide(); + const QColor color = Qt::white; + item->setData(Qt::BackgroundRole, color); + item->setData(Qt::DisplayRole, QString()); } - pb->deleteLater(); - break; - } } - } - else if (modType == DataModification::eModified) - { - const QList &list = m_ui->gbSegments->findChildren(); - for (QPushButton *pb : std::as_const(list)) - { - if (pb->property("assetId").toInt() == data.assetId()) - pb->setText(data.name().empty() ? pb->property("assetName").toString() : QString::fromStdString(data.name())); - } - } } +void BldInfoDialog::fillOwnership(const CentralEffectSimulation::BuildingOwnership& ownership) +{ + m_ui->twOwnership->setUpdatesEnabled(false); + clearColumn(1); + m_ui->twOwnership->setRowCount(ownership.ownerships().size()); + int row = m_ui->twOwnership->rowCount(); + + for (const auto& data : ownership.ownerships()) + { + --row; + int column = 0; + QTableWidgetItem* pItem = nullptr; + + for (const InfrastructureManagement::StructureElement& elem : m_mse.elements()) + { + if (elem.id() == data.floorId()) + { + QString name = QString::fromStdString(elem.displayName()); + if (name.isEmpty()) + name = QString::fromStdString(elem.name()); + pItem = new QTableWidgetItem(name); + break; + } + } + if (!pItem) + pItem = new QTableWidgetItem(QString::number(data.floorId())); + m_rowToFloorId.insert(row, data.floorId()); + m_floorIdToRow.insert(data.floorId(), row); + + DEBUG_LOG(m_logger) << "m_rowToFloorId.insert" + << " row=" << row << " column=" << column << " data.floorId()=" << data.floorId(); + m_ui->twOwnership->setItem(row, column++, pItem); + + pItem = new QTableWidgetItem(); + if (m_ppmDtc && data.partyId() > 0) + { + const auto& party = m_ppmDtc->party(data.partyId()); + pItem->setData(Qt::BackgroundRole, QColor::fromRgb(QRgb(party.color()))); + pItem->setData(Qt::DisplayRole, ParticipantManagement::trPartyName(party.name())); + } + m_ui->twOwnership->setItem(row, column++, pItem); + } + + m_ui->twOwnership->setUpdatesEnabled(true); +} + +void BldInfoDialog::onBuildingStateChanged(const Buildings::BuildingState& data, const DataModification& modType) +{ + if (modType == DataModification::eRemoved) + return; + DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.id(); + if (data.id() != m_mseId) + return; + + showBuildingInfos(data); +} + +void BldInfoDialog::onBuildingOwnershipChanged(const CentralEffectSimulation::BuildingOwnership& data, + const DataModification& modType) +{ + if (modType == DataModification::eRemoved) + return; + DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.buildingId(); + if (data.buildingId() != m_mseId) + return; + + fillOwnership(data); +} + +void BldInfoDialog::onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement& data, + const DataModification& modType) +{ + if (modType == DataModification::eRemoved) + return; + DEBUG_LOG(m_logger) << LOGFUNCTION << " id:" << data.id(); + if (data.id() != m_mseId) + return; + + m_mse = data; + m_ui->lblBldName->setText(buildingDisplayName()); + showBuildingInfos(); +} + +void BldInfoDialog::onMountingPointAssetChanged(const InfrastructureManagement::MountingPointAsset& data, + const DataModification& modType) +{ + InfrastructureManagement::StructureElement se; + m_ismDtc->getStructureElementById(data.structureElementId(), se); + if (se.mainStructureElementId() != m_mseId) + return; + + if (modType == DataModification::eAdded) + { + auto instrumentationAsset = m_ismDtc->instrumentationAsset(data.assetId()); + if (instrumentationAsset.mountingPointTypeId() != + InfrastructureManagement::MountingPointType::EffectGenerationControlUnit) + return; + QString name = QString::fromStdString(data.name()); + if (name.isNull()) + name = QString::fromStdString(instrumentationAsset.hostname()); + + QVBoxLayout* l = qobject_cast(m_ui->gbSegments->layout()); + QPushButton* w = new QPushButton(name, this); + w->setProperty("assetId", data.assetId()); + l->addWidget(w); + connect(w, &QPushButton::clicked, this, &BldInfoDialog::onEgcuInfoDialogRequested); + m_ui->gbSegments->setVisible(egcuVisibility()); + bool editable = true; + m_ui->pbMonitor->setVisible(editable && egcuVisibility()); + } + else if (modType == DataModification::eRemoved) + { + const QList& list = m_ui->gbSegments->findChildren(); + for (QPushButton* pb : std::as_const(list)) + { + if (pb->property("assetId").toInt() == data.assetId()) + { + + if (m_ui->gbSegments->layout()->count() == 1) + { + m_ui->gbSegments->setVisible(false); + m_ui->pbMonitor->hide(); + } + pb->deleteLater(); + break; + } + } + } + else if (modType == DataModification::eModified) + { + const QList& list = m_ui->gbSegments->findChildren(); + for (QPushButton* pb : std::as_const(list)) + { + if (pb->property("assetId").toInt() == data.assetId()) + pb->setText(data.name().empty() ? pb->property("assetName").toString() + : QString::fromStdString(data.name())); + } + } +} void BldInfoDialog::onOpenHistory() { - BuildingHistoryDialog *diag = new BuildingHistoryDialog(buildingDisplayName(), this); - if (diag->init(m_mseId, m_session)) - addDialog(diag, m_menuGroup, QStringLiteral("BuildingHistory") + QString::number(m_mseId), LtsWidgets::LayoutArea::eDialogTab); - else - delete diag; + BuildingHistoryDialog* diag = new BuildingHistoryDialog(buildingDisplayName(), this); + if (diag->init(m_mseId, m_session)) + addDialog(diag, m_menuGroup, QStringLiteral("BuildingHistory") + QString::number(m_mseId), + LtsWidgets::LayoutArea::eDialogTab); + else + delete diag; } void BldInfoDialog::onEgcuInfoDialogRequested() { - QPushButton *sender = qobject_cast(QObject::sender()); - if (!sender) - return; + QPushButton* sender = qobject_cast(QObject::sender()); + if (!sender) + return; - QVariant temp = sender->property("assetId"); - if (temp.isNull()) - { - ERROR_LOG(m_logger) << LOGFUNCTION << " missing property , return"; - return; - } - const int assetId = temp.toInt(); + QVariant temp = sender->property("assetId"); + if (temp.isNull()) + { + ERROR_LOG(m_logger) << LOGFUNCTION << " missing property , return"; + return; + } + const int assetId = temp.toInt(); - temp = sender->property("assetName"); - if (temp.isNull()) - { - ERROR_LOG(m_logger) << LOGFUNCTION << " missing property, return"; - return; - } - const QString name = temp.toString(); + temp = sender->property("assetName"); + if (temp.isNull()) + { + ERROR_LOG(m_logger) << LOGFUNCTION << " missing property, return"; + return; + } + const QString name = temp.toString(); - if (assetId < 0 || name.isEmpty()) - { - ERROR_LOG(m_logger) << LOGFUNCTION << " missing properties, return"; - return; - } + if (assetId < 0 || name.isEmpty()) + { + ERROR_LOG(m_logger) << LOGFUNCTION << " missing properties, return"; + return; + } - EgcuInfoDialog *dialog = new EgcuInfoDialog(assetId, menuGroup()); - if (!dialog->init(m_session)) - { - delete dialog; - return; - } - m_session->addWidget(dialog, menuGroup(), name, LtsWidgets::LayoutArea::eInfoTab); + EgcuInfoDialog* dialog = new EgcuInfoDialog(assetId, menuGroup()); + if (!dialog->init(m_session)) + { + delete dialog; + return; + } + m_session->addWidget(dialog, menuGroup(), name, LtsWidgets::LayoutArea::eInfoTab); } -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.h old mode 100755 new mode 100644 index 00973d0f2..939ceccec --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bld_info_dialog.h @@ -1,139 +1,125 @@ - #pragma once #include "info_dialog_base.h" -#include - -#include -#include #include +#include +#include #include #include - - #include #include - namespace Ui { class BldInfoDialog; } + namespace CentralEffectSimulation { namespace Interface { class Dtc; } -} +} // namespace CentralEffectSimulation + namespace AreaEffectSimulation { namespace Interface { class Dtc; } -} +} // namespace AreaEffectSimulation + namespace ParticipantManagement { namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement + namespace ProjectDataManagement { namespace Interface { class Dtc; } -} +} // namespace ProjectDataManagement namespace Buildings { constexpr int ICON_RESOLUTION = 64; - - - class BldInfoDialog : public InfoDialogBase { - Q_OBJECT + Q_OBJECT -public: - explicit BldInfoDialog(int bldEntityId, const QString &menuGroup, QWidget *parent = nullptr); - ~BldInfoDialog(); + public: + explicit BldInfoDialog(int bldEntityId, const QString& menuGroup, QWidget* parent = nullptr); + ~BldInfoDialog(); - bool init(LtsSession::LtsSession *session) override; + bool init(LtsSession::LtsSession* session) override; -private: + private: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - template - static ReturnType constFinder(const Container &container, const Key &key) noexcept(false) - { - auto it = container.constFind(key); + template + static ReturnType constFinder(const Container& container, const Key& key) noexcept(false) + { + auto it = container.constFind(key); - if (it == container.constEnd()) - throw QStringLiteral("constFinder: cannot find '%1' in container").arg(keyToString(key)); + if (it == container.constEnd()) + throw QStringLiteral("constFinder: cannot find '%1' in container").arg(keyToString(key)); - return it.value(); - } + return it.value(); + } - void retranslate() override; - void showBuildingInfos() override; - void showBuildingInfos(const Buildings::BuildingState &bldState); - void fillOwnership(int buildingId); - void fillOwnership(const CentralEffectSimulation::BuildingOwnership &ownership); - void clearColumn(int column); - void fillContaminationTable(const Buildings::BuildingState &bldState); - QString buildingDisplayName() const override; - bool egcuVisibility(); + void retranslate() override; + void showBuildingInfos() override; + void showBuildingInfos(const Buildings::BuildingState& bldState); + void fillOwnership(int buildingId); + void fillOwnership(const CentralEffectSimulation::BuildingOwnership& ownership); + void clearColumn(int column); + void fillContaminationTable(const Buildings::BuildingState& bldState); + QString buildingDisplayName() const override; + bool egcuVisibility(); - - void updateFloorParticipantTable(); - bool getRoom(int roomSeId, InfrastructureManagement::StructureElement &roomSe); - QString getFloorName(int floorSeId); - int findFloorIdByRoomId(int roomId) noexcept(false); + void updateFloorParticipantTable(); + bool getRoom(int roomSeId, InfrastructureManagement::StructureElement& roomSe); + QString getFloorName(int floorSeId); + int findFloorIdByRoomId(int roomId) noexcept(false); -private slots: - void onBuildingStateChanged(const Buildings::BuildingState &data, const DataModification &modType); - void onBuildingOwnershipChanged(const CentralEffectSimulation::BuildingOwnership &data, - const DataModification &modType); - void onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement &data, - const DataModification &modType); - void onMountingPointAssetChanged(const InfrastructureManagement::MountingPointAsset &data, - const DataModification &modType); - void onOpenHistory(); - void onEgcuInfoDialogRequested(); + private slots: + void onBuildingStateChanged(const Buildings::BuildingState& data, const DataModification& modType); + void onBuildingOwnershipChanged(const CentralEffectSimulation::BuildingOwnership& data, + const DataModification& modType); + void onMainStructureElementChanged(const InfrastructureManagement::MainStructureElement& data, + const DataModification& modType); + void onMountingPointAssetChanged(const InfrastructureManagement::MountingPointAsset& data, + const DataModification& modType); + void onOpenHistory(); + void onEgcuInfoDialogRequested(); - - void onPositionChanged(const ParticipantManagement::ParticipantPosition &data, DataModification modType); - void addParticipantPosition(const ParticipantManagement::ParticipantPosition &data, DataModification modType); + void onPositionChanged(const ParticipantManagement::ParticipantPosition& data, DataModification modType); + void addParticipantPosition(const ParticipantManagement::ParticipantPosition& data, DataModification modType); -private: - Ui::BldInfoDialog *m_ui; - InfrastructureManagement::MainStructureElement m_mse; + private: + Ui::BldInfoDialog* m_ui; + InfrastructureManagement::MainStructureElement m_mse; - - - - - - - QMap m_floorNames; - QMap m_rowToFloorId; - QMap m_floorIdToRow; - QMap m_roomToFloorCache; - QMap m_roomStructureElementCache; - QMap > m_rawParticipantCount; - - std::shared_ptr m_cesDtc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_pdmDtc; + QMap m_floorNames; + QMap m_rowToFloorId; + QMap m_floorIdToRow; + QMap m_roomToFloorCache; + QMap m_roomStructureElementCache; + QMap> m_rawParticipantCount; + std::shared_ptr m_cesDtc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_pdmDtc; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bridge_history_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bridge_history_dialog_model.h old mode 100755 new mode 100644 index ed68f3a27..b10c98b8f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bridge_history_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/bridge_history_dialog_model.h @@ -1,19 +1,15 @@ - #pragma once - +#include +#include +#include #include #include - -#include -#include - -#include - -namespace LtsSession { +namespace LtsSession +{ class LtsSession; } @@ -23,7 +19,7 @@ namespace Interface { class Dtc; } -} +} // namespace ProjectDataManagement namespace ParticipantManagement { @@ -31,7 +27,7 @@ namespace Interface { class Dtc; } -} +} // namespace ParticipantManagement namespace AreaEffectSimulation { @@ -39,51 +35,45 @@ namespace Interface { class Dtc; } -} +} // namespace AreaEffectSimulation namespace Buildings { - - - class BridgeHistoryDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Column - { - Time, - State - }; - explicit BridgeHistoryDialogModel(QObject *parent = nullptr); + Q_OBJECT + public: + enum Column { Time, State }; - bool initModel(int dds_id, - LtsSession::LtsSession *session); + explicit BridgeHistoryDialogModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool initModel(int dds_id, LtsSession::LtsSession* session); -private Q_SLOTS: - void onHistoryStateChanged(const BridgeStatus &data, DataModification modType); + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -private: + private Q_SLOTS: + void onHistoryStateChanged(const BridgeStatus& data, DataModification modType); -NGL::INGLLogger &m_logger; - void reinitModel(const QMap &newData); - int m_ddsId; - std::shared_ptr m_dtc; - friend class BridgeHistoryDialogProxyModel; + private: + NGL::INGLLogger& m_logger; + void reinitModel(const QMap& newData); + int m_ddsId; + std::shared_ptr m_dtc; + friend class BridgeHistoryDialogProxyModel; }; class BridgeHistoryDialogProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - BridgeHistoryDialogModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + BridgeHistoryDialogModel* m_sourceModel = nullptr; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.cpp old mode 100755 new mode 100644 index d8b979fcc..0f22fc381 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.cpp @@ -1,113 +1,100 @@ - #include "info_dialog_base.h" + #include "bld_config_dialog.h" + +#include +#include +#include +#include #include #include -#include -#include -#include #include - - -#include -#include -#include +#include +#include namespace Buildings { -InfoDialogBase::InfoDialogBase(int bldEntityId, const QString &menuGroup, const QString& strLogger, LtsWidgets::ButtonCombination bc, QWidget *parent) - : LtsWidgets::LtsDialog(parent, bc) - , m_mseId(bldEntityId) - , m_menuGroup(menuGroup) - , m_exerciseId(0) - , m_logger(getLogger(strLogger)) +InfoDialogBase::InfoDialogBase(int bldEntityId, const QString& menuGroup, const QString& strLogger, + LtsWidgets::ButtonCombination bc, QWidget* parent) + : LtsWidgets::LtsDialog(parent, bc), m_mseId(bldEntityId), m_menuGroup(menuGroup), m_exerciseId(0), + m_logger(getLogger(strLogger)) { -} +} -bool InfoDialogBase::init(LtsSession::LtsSession *session) +bool InfoDialogBase::init(LtsSession::LtsSession* session) { - m_session = session; - m_exerciseId = session->exerciseId(); - if (!m_session->getDtc(m_dtc)) - return false; - if (!m_session->getDtc(m_ismDtc)) - return false; + m_session = session; + m_exerciseId = session->exerciseId(); + if (!m_session->getDtc(m_dtc)) + return false; + if (!m_session->getDtc(m_ismDtc)) + return false; + m_ismDtc->enableMainStructureElement(); - m_ismDtc->enableMainStructureElement(); - + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this, + [this](const InfrastructureManagement::MainStructureElement& mse, DataModification mod) { + if (mod != DataModification::eModified) + return; + QJsonObject obj = QJsonDocument::fromJson(QByteArray::fromStdString(mse.properties())).object(); + if (!obj.contains(QStringLiteral("available_in_exercise"))) + { + deleteLater(); + return; + } + int newExerciseId = obj.value(QStringLiteral("available_in_exercise")).toArray().at(0).toInt(); - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::mainStructureElementChanged, this , [this](const InfrastructureManagement::MainStructureElement & mse, DataModification mod){ - if(mod != DataModification::eModified) - return; - QJsonObject obj = QJsonDocument::fromJson(QByteArray::fromStdString(mse.properties())).object(); - if(!obj.contains(QStringLiteral("available_in_exercise"))) - { - deleteLater(); - return; - } - int newExerciseId = obj.value(QStringLiteral("available_in_exercise")).toArray().at(0).toInt(); + if (newExerciseId != m_exerciseId) + { + deleteLater(); + return; + } + }); - if(newExerciseId != m_exerciseId) - { - deleteLater(); - return; - } + m_session->getForeignGuiInterface(m_bdvGuiIfc); - }); - - - - m_session->getForeignGuiInterface(m_bdvGuiIfc); - - - m_session->getForeignGuiInterface(m_smoGuiIfc); - - return true; -} + m_session->getForeignGuiInterface(m_smoGuiIfc); + return true; +} void InfoDialogBase::onFindOnMap() { - std::shared_ptr ifc; - if (m_session->getForeignGuiInterface(ifc)) - ifc->centerMapToBuildingObject(m_mseId); - else - WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; -} - + std::shared_ptr ifc; + if (m_session->getForeignGuiInterface(ifc)) + ifc->centerMapToBuildingObject(m_mseId); + else + WARNING_LOG(m_logger) << Q_FUNC_INFO << "getForeignGuiInterface failed!"; +} void InfoDialogBase::onShowDetails() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - BldConfigDialog *dialog = new BldConfigDialog(m_mseId, buildingDisplayName(), this); - - if (dialog->init(m_session)) - addDialog(dialog, m_menuGroup, QStringLiteral("BuildingConfig %1").arg(m_mseId), LtsWidgets::LayoutArea::eDialogTab); - else - delete dialog; - -} + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + BldConfigDialog* dialog = new BldConfigDialog(m_mseId, buildingDisplayName(), this); + if (dialog->init(m_session)) + addDialog(dialog, m_menuGroup, QStringLiteral("BuildingConfig %1").arg(m_mseId), + LtsWidgets::LayoutArea::eDialogTab); + else + delete dialog; +} void InfoDialogBase::onShowBuildingViewer() { - if (!m_bdvGuiIfc) - return; - m_bdvGuiIfc->showBuildingViewer(m_session, m_mseId); -} + if (!m_bdvGuiIfc) + return; + m_bdvGuiIfc->showBuildingViewer(m_session, m_mseId); +} void InfoDialogBase::onShowEgcuMonitor() { - if (!m_smoGuiIfc) - return; - int seId = m_ismDtc->mainStructureElement(m_mseId).structureElementId(); - m_smoGuiIfc->showEgcuMonitor({seId},true); + if (!m_smoGuiIfc) + return; + int seId = m_ismDtc->mainStructureElement(m_mseId).structureElementId(); + m_smoGuiIfc->showEgcuMonitor({seId}, true); +} -} - - -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.h old mode 100755 new mode 100644 index ba8569f35..df5f38e6a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/info_dialog_base.h @@ -1,33 +1,34 @@ - #pragma once - -#include - - #include +#include #include namespace Ui { class BldInfoDialog; } + namespace InfrastructureManagement { namespace Interface { class Dtc; } -} -namespace LtsSession { +} // namespace InfrastructureManagement + +namespace LtsSession +{ class LtsSession; } + namespace BuildingViewer { class ForeignGuiInterface; } + namespace ServiceMonitor { class ForeignGuiInterface; @@ -42,35 +43,35 @@ class Dtc; class InfoDialogBase : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit InfoDialogBase(int bldEntityId, const QString &menuGroup, const QString &strLogger, LtsWidgets::ButtonCombination bc, QWidget *parent = nullptr); + public: + explicit InfoDialogBase(int bldEntityId, const QString& menuGroup, const QString& strLogger, + LtsWidgets::ButtonCombination bc, QWidget* parent = nullptr); - virtual bool init(LtsSession::LtsSession *session); + virtual bool init(LtsSession::LtsSession* session); + protected slots: + void onFindOnMap(); + void onShowDetails(); + void onShowBuildingViewer(); + void onShowEgcuMonitor(); -protected slots: - void onFindOnMap(); - void onShowDetails(); - void onShowBuildingViewer(); - void onShowEgcuMonitor(); + protected: + NGL::INGLLogger& m_logger; + virtual void showBuildingInfos() = 0; + virtual QString buildingDisplayName() const = 0; -protected: - NGL::INGLLogger &m_logger; - virtual void showBuildingInfos() = 0; - virtual QString buildingDisplayName() const = 0; + protected: + NGL::INGLLogger& m_logger; + int m_mseId = -1; + QString m_menuGroup; + int m_exerciseId; + LtsSession::LtsSession* m_session = nullptr; -protected: - NGL::INGLLogger &m_logger; - int m_mseId = -1; - QString m_menuGroup; - int m_exerciseId; - LtsSession::LtsSession *m_session = nullptr; - - std::shared_ptr m_dtc; - std::shared_ptr m_ismDtc; - std::shared_ptr m_bdvGuiIfc; - std::shared_ptr m_smoGuiIfc; + std::shared_ptr m_dtc; + std::shared_ptr m_ismDtc; + std::shared_ptr m_bdvGuiIfc; + std::shared_ptr m_smoGuiIfc; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.cpp old mode 100755 new mode 100644 index c58aba72f..84c0b2e28 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.cpp @@ -1,129 +1,131 @@ - #include "relay_info.h" + #include "ui_relay_info.h" + #include #include namespace Buildings { -RelayInfoWidget::RelayInfoWidget(int id, QWidget *parent) : QWidget(parent) - , m_id(id) - , m_state(false) - , m_ui(new Ui::RelayInfoWidget), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - DEBUG_LOG(m_logger) << "RelayInfoWidget"; - m_ui->setupUi(this); +RelayInfoWidget::RelayInfoWidget(int id, QWidget* parent) + : QWidget(parent), m_id(id), m_state(false), m_ui(new Ui::RelayInfoWidget), + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + DEBUG_LOG(m_logger) << "RelayInfoWidget"; + m_ui->setupUi(this); - m_ui->ledStatus->setAspectHint(LtsWidgets::LtsLedWidget::AspectHint::WidthIsHeight); - m_ui->ledStatus->setContentsMargins(5,5,5,5); - setOfflineColor(); - connect(m_ui->tbOn, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); - connect(m_ui->tbOff, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); - connect(m_ui->tbAuto, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); + m_ui->ledStatus->setAspectHint(LtsWidgets::LtsLedWidget::AspectHint::WidthIsHeight); + m_ui->ledStatus->setContentsMargins(5, 5, 5, 5); + setOfflineColor(); + connect(m_ui->tbOn, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); + connect(m_ui->tbOff, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); + connect(m_ui->tbAuto, &QToolButton::clicked, this, &RelayInfoWidget::onButtonClicked); } RelayInfoWidget::~RelayInfoWidget() { - delete m_ui; + delete m_ui; } QString RelayInfoWidget::name() const { - return m_ui->lblName->text(); + return m_ui->lblName->text(); } bool RelayInfoWidget::state() const { - return m_state; + return m_state; } int RelayInfoWidget::id() const { - return m_id; + return m_id; } -void RelayInfoWidget::setName(const QString &name) +void RelayInfoWidget::setName(const QString& name) { - m_ui->lblName->setText(name); + m_ui->lblName->setText(name); } void RelayInfoWidget::setState(bool state, qint64 stateTime, qint64 offlineTime) { - if ( stateTime > offlineTime) - { - m_state = state; - m_ui->ledStatus->setOnColor(state ? Qt::green : Qt::red); - m_ui->ledStatus->setToolTip(QStringLiteral("%1 - %2").arg(tr("Values from")).arg(DTG::toStringMSec(stateTime))); - m_ui->ledStatus->setStatus(true); - } - else - { - setOfflineColor(); - m_ui->ledStatus->setToolTip(QStringLiteral("%1 - %2,\nEGCU offline since: %3").arg(tr("Values from")).arg(DTG::toStringMSec(stateTime)).arg(DTG::toStringMSec(offlineTime))); - m_ui->ledStatus->setStatus(true); - } - + if (stateTime > offlineTime) + { + m_state = state; + m_ui->ledStatus->setOnColor(state ? Qt::green : Qt::red); + m_ui->ledStatus->setToolTip(QStringLiteral("%1 - %2").arg(tr("Values from")).arg(DTG::toStringMSec(stateTime))); + m_ui->ledStatus->setStatus(true); + } + else + { + setOfflineColor(); + m_ui->ledStatus->setToolTip(QStringLiteral("%1 - %2,\nEGCU offline since: %3") + .arg(tr("Values from")) + .arg(DTG::toStringMSec(stateTime)) + .arg(DTG::toStringMSec(offlineTime))); + m_ui->ledStatus->setStatus(true); + } } void RelayInfoWidget::setEffectOverride(InfrastructureManagement::EffectOverride override) { - switch(override.underlying()) - { - case InfrastructureManagement::EffectOverride_def::Automatic: - m_ui->tbAuto->setChecked(true); - break; - case InfrastructureManagement::EffectOverride_def::PermanentOn: - m_ui->tbOn->setChecked(true); - break; - case InfrastructureManagement::EffectOverride_def::PermanentOff: - m_ui->tbOff->setChecked(true); - break; - } + switch (override.underlying()) + { + case InfrastructureManagement::EffectOverride_def::Automatic: + m_ui->tbAuto->setChecked(true); + break; + case InfrastructureManagement::EffectOverride_def::PermanentOn: + m_ui->tbOn->setChecked(true); + break; + case InfrastructureManagement::EffectOverride_def::PermanentOff: + m_ui->tbOff->setChecked(true); + break; + } } void RelayInfoWidget::setEffectOverrideEnabled(InfrastructureManagement::EffectOverride override, bool enable) { - switch(override.underlying()) - { - case InfrastructureManagement::EffectOverride_def::Automatic: - m_ui->tbAuto->setEnabled(enable); - break; - case InfrastructureManagement::EffectOverride_def::PermanentOn: - m_ui->tbOn->setEnabled(enable); - break; - case InfrastructureManagement::EffectOverride_def::PermanentOff: - m_ui->tbOff->setEnabled(enable); - break; - } + switch (override.underlying()) + { + case InfrastructureManagement::EffectOverride_def::Automatic: + m_ui->tbAuto->setEnabled(enable); + break; + case InfrastructureManagement::EffectOverride_def::PermanentOn: + m_ui->tbOn->setEnabled(enable); + break; + case InfrastructureManagement::EffectOverride_def::PermanentOff: + m_ui->tbOff->setEnabled(enable); + break; + } } void RelayInfoWidget::setLedVisible(bool enable) { - m_ui->ledStatus->setVisible(enable); + m_ui->ledStatus->setVisible(enable); } void RelayInfoWidget::onButtonClicked() { - QAbstractButton *ab = qobject_cast(sender()); - if (!ab) - return; - InfrastructureManagement::EffectOverride eo = InfrastructureManagement::EffectOverride_def::Automatic; - if (ab == m_ui->tbOff) - eo = InfrastructureManagement::EffectOverride_def::PermanentOff; - else if (ab == m_ui->tbOn) - eo = InfrastructureManagement::EffectOverride_def::PermanentOn; + QAbstractButton* ab = qobject_cast(sender()); + if (!ab) + return; + InfrastructureManagement::EffectOverride eo = InfrastructureManagement::EffectOverride_def::Automatic; + if (ab == m_ui->tbOff) + eo = InfrastructureManagement::EffectOverride_def::PermanentOff; + else if (ab == m_ui->tbOn) + eo = InfrastructureManagement::EffectOverride_def::PermanentOn; - emit effectOverrideChanged(m_id, eo); + emit effectOverrideChanged(m_id, eo); } void RelayInfoWidget::setOfflineColor() { - QColor offlineColor; - offlineColor.setRgb(120,92,37); - m_ui->ledStatus->setOnColor(offlineColor); + QColor offlineColor; + offlineColor.setRgb(120, 92, 37); + m_ui->ledStatus->setOnColor(offlineColor); } -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.h old mode 100755 new mode 100644 index dea6fe4d9..7e19b575f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Buildings/Gui/BuildingInfo/relay_info.h @@ -1,54 +1,52 @@ - #pragma once -#include #include +#include #include #include -#include +#include -namespace Ui { +namespace Ui +{ class RelayInfoWidget; } - namespace Buildings { class RelayInfoWidget : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit RelayInfoWidget(int id, QWidget *parent = nullptr); - ~RelayInfoWidget(); + public: + explicit RelayInfoWidget(int id, QWidget* parent = nullptr); + ~RelayInfoWidget(); - QString name() const; - bool state() const; - int id() const; + QString name() const; + bool state() const; + int id() const; -signals: - void effectOverrideChanged(int relayId, InfrastructureManagement::EffectOverride override); + signals: + void effectOverrideChanged(int relayId, InfrastructureManagement::EffectOverride override); -public slots: - void setName(const QString &name); - void setState(bool state, qint64 stateTime, qint64 offlineTime); - void setEffectOverride(InfrastructureManagement::EffectOverride override); - void setEffectOverrideEnabled(InfrastructureManagement::EffectOverride override, bool enable = true); - void setLedVisible(bool enable = true); - void setOfflineColor(); + public slots: + void setName(const QString& name); + void setState(bool state, qint64 stateTime, qint64 offlineTime); + void setEffectOverride(InfrastructureManagement::EffectOverride override); + void setEffectOverrideEnabled(InfrastructureManagement::EffectOverride override, bool enable = true); + void setLedVisible(bool enable = true); + void setOfflineColor(); -private slots: - void onButtonClicked(); + private slots: + void onButtonClicked(); -private: - -NGL::INGLLogger &m_logger; - int m_id; - bool m_state; - Ui::RelayInfoWidget *m_ui; + private: + NGL::INGLLogger& m_logger; + int m_id; + bool m_state; + Ui::RelayInfoWidget* m_ui; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participant_move_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participant_move_dialog.cpp old mode 100755 new mode 100644 index 3b67a5d07..b93f7acd9 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participant_move_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participant_move_dialog.cpp @@ -1,526 +1,463 @@ - #include "participant_move_dialog.h" -#include "ui_participant_move_dialog.h" - -#include -#include - -#include -#include -#include -#include -#include #include "logger.h" -#include -#include -#include +#include "ui_participant_move_dialog.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include -#include #include +#include namespace CentralEffectSimulation { -static constexpr double s_msConversion = 3.6; -static constexpr int s_timeMilliConversion = 1000; +static constexpr double s_msConversion = 3.6; +static constexpr int s_timeMilliConversion = 1000; -ParticipantMoveDialog::ParticipantMoveDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ftc(nullptr) - , m_sitMapGuiIfc(nullptr) - , m_ui(new Ui::WaypointsEdit) - , m_id(0) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_polyline(QPolygonF()) +ParticipantMoveDialog::ParticipantMoveDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ftc(nullptr), + m_sitMapGuiIfc(nullptr), m_ui(new Ui::WaypointsEdit), m_id(0), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_polyline(QPolygonF()) { - m_ui->setupUi(this); - m_ui->cbJump->hide(); - m_ui->label_5->hide(); - m_ui->spSpeed->setValue(30); - m_ui->lePrefix->setText(tr("Waypoint")); - m_uiRequirements->addRequirement({m_ui->lblMoveStart, [this]() { return hasValidEffectStart(m_ui->dteStartTime); }, tr("Begin time is smaller than current time")}); - connect (this, &ParticipantMoveDialog::signalFocused, this, &ParticipantMoveDialog::onFocus); - setOnlineHelpFilename(QStringLiteral("Situation-Move_Participant_0")); -} - + m_ui->setupUi(this); + m_ui->cbJump->hide(); + m_ui->label_5->hide(); + m_ui->spSpeed->setValue(30); + m_ui->lePrefix->setText(tr("Waypoint")); + m_uiRequirements->addRequirement({m_ui->lblMoveStart, [this]() { return hasValidEffectStart(m_ui->dteStartTime); }, + tr("Begin time is smaller than current time")}); + connect(this, &ParticipantMoveDialog::signalFocused, this, &ParticipantMoveDialog::onFocus); + setOnlineHelpFilename(QStringLiteral("Situation-Move_Participant_0")); +} ParticipantMoveDialog::~ParticipantMoveDialog() { - m_sitMapGuiIfc = nullptr; - delete m_ui; - emit closeDialog(m_participantData.id()); -} - + m_sitMapGuiIfc = nullptr; + delete m_ui; + emit closeDialog(m_participantData.id()); +} void ParticipantMoveDialog::enableUiElements(bool enable) { - m_ui->pbPosition->setEnabled(enable); - m_ui->pbClear->setEnabled(enable); -} + m_ui->pbPosition->setEnabled(enable); + m_ui->pbClear->setEnabled(enable); +} - -bool ParticipantMoveDialog::init(LtsSession::LtsSessionDataDds *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &cesDtc, - const ParticipantManagement::ParticipantData &data) +bool ParticipantMoveDialog::init(LtsSession::LtsSessionDataDds* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& cesDtc, + const ParticipantManagement::ParticipantData& data) { - m_session = session; - m_participantData = data; - m_cesDtc = cesDtc; + m_session = session; + m_participantData = data; + m_cesDtc = cesDtc; - - - - + if (!m_session->getFtc(m_ftc)) + return false; - if (!m_session->getFtc(m_ftc)) - return false; + m_session->getForeignGuiInterface(m_sitMapGuiIfc); - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - - if (m_sitMapGuiIfc) - { - connect(m_ui->pbPosition, &QPushButton::clicked, this, &ParticipantMoveDialog::onGetPolyline); - connect(m_ui->pbClear, &QPushButton::clicked, this, &ParticipantMoveDialog::clearCoordinates); - } - else - { - m_ui->pbPosition->setEnabled(false); - m_ui->pbClear->setEnabled(false); - } - - m_ui->dteStartTime->setMinimumTimeMSec(m_session->partitionTime()); - m_ui->dteStartTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - m_ui->lbIdentifier->setText(QString::fromStdString(data.tacticalIdentifier())); - QString partyStr = ParticipantManagement::trPartyName(ppmDtc->party(m_participantData.partyId()).name()); - m_ui->lbParty->setText(partyStr); - QString typeStr = ParticipantManagement::trTypeName(ppmDtc->type(m_participantData.typeId()).name()); - m_ui->lbType->setText(typeStr); - - - enableUiElements(true); - - initTableHeader(); - - connect(cesDtc.get(), &CentralEffectSimulation::Interface::Dtc::simulatedMovementChanged, - this, &ParticipantMoveDialog::onSimulatedMovementChanged); - - - { - auto sm = [this](const CentralEffectSimulation::SimulatedMovement & sme) + if (m_sitMapGuiIfc) { - onSimulatedMovementChanged(sme, DataModification::eAdded); - }; - if (!m_cesDtc->simulatedMovements(sm)) - return false; - } + connect(m_ui->pbPosition, &QPushButton::clicked, this, &ParticipantMoveDialog::onGetPolyline); + connect(m_ui->pbClear, &QPushButton::clicked, this, &ParticipantMoveDialog::clearCoordinates); + } + else + { + m_ui->pbPosition->setEnabled(false); + m_ui->pbClear->setEnabled(false); + } - - m_buttonBox->connectLibraryButton(this, - &ParticipantMoveDialog::onImportButtonClicked, - &ParticipantMoveDialog::onExportButtonClicked); + m_ui->dteStartTime->setMinimumTimeMSec(m_session->partitionTime()); + m_ui->dteStartTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + m_ui->lbIdentifier->setText(QString::fromStdString(data.tacticalIdentifier())); + QString partyStr = ParticipantManagement::trPartyName(ppmDtc->party(m_participantData.partyId()).name()); + m_ui->lbParty->setText(partyStr); + QString typeStr = ParticipantManagement::trTypeName(ppmDtc->type(m_participantData.typeId()).name()); + m_ui->lbType->setText(typeStr); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + enableUiElements(true); - return true; + initTableHeader(); -} + connect(cesDtc.get(), &CentralEffectSimulation::Interface::Dtc::simulatedMovementChanged, this, + &ParticipantMoveDialog::onSimulatedMovementChanged); -void ParticipantMoveDialog::onSimulatedMovementChanged(const CentralEffectSimulation::SimulatedMovement &data, DataModification modType) + { + auto sm = [this](const CentralEffectSimulation::SimulatedMovement& sme) { + onSimulatedMovementChanged(sme, DataModification::eAdded); + }; + if (!m_cesDtc->simulatedMovements(sm)) + return false; + } + + m_buttonBox->connectLibraryButton(this, &ParticipantMoveDialog::onImportButtonClicked, + &ParticipantMoveDialog::onExportButtonClicked); + + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + + return true; +} + +void ParticipantMoveDialog::onSimulatedMovementChanged(const CentralEffectSimulation::SimulatedMovement& data, + DataModification modType) { - if (modType == DataModification::eRemoved || m_participantData.id() != data.participantId()) - return; + if (modType == DataModification::eRemoved || m_participantData.id() != data.participantId()) + return; INFO_LOG(m_logger) << "onSimulatedMovementChanged"; - - clearContent(); - - m_id = data.id(); - m_ui->lePrefix->setText(QString::fromStdString(data.name())); - m_ui->cbRepeat->setChecked(data.repeat()); - m_ui->cbJump->setChecked(data.jumpToStart()); - m_ui->dteStartTime->setMsecsSinceEpoch(data.startTime()); - m_polyline.clear(); - - for (const SimulatedMovementSegment &segment : data.segments()) - { - const Core::GeoPosition2D &pointDds = segment.position(); - insertPos(pointDds.lon(), pointDds.lat(), QString::fromStdString(segment.name()), segment.delay(), segment.speed()); - m_polyline.push_back(QPointF(pointDds.lon(), pointDds.lat())); - } - - if (this->amIFocused()) - m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); + clearContent(); + + m_id = data.id(); + m_ui->lePrefix->setText(QString::fromStdString(data.name())); + m_ui->cbRepeat->setChecked(data.repeat()); + m_ui->cbJump->setChecked(data.jumpToStart()); + m_ui->dteStartTime->setMsecsSinceEpoch(data.startTime()); + m_polyline.clear(); + + for (const SimulatedMovementSegment& segment : data.segments()) + { + const Core::GeoPosition2D& pointDds = segment.position(); + insertPos(pointDds.lon(), pointDds.lat(), QString::fromStdString(segment.name()), segment.delay(), + segment.speed()); + m_polyline.push_back(QPointF(pointDds.lon(), pointDds.lat())); + } + + if (this->amIFocused()) + m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); } void ParticipantMoveDialog::showPreview(bool show) { - if (m_sitMapGuiIfc) - { - if (show) - m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); - else - m_sitMapGuiIfc->removePreviewObject(); - } + if (m_sitMapGuiIfc) + { + if (show) + m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); + else + m_sitMapGuiIfc->removePreviewObject(); + } } - -void ParticipantMoveDialog::onSimulatedMovementRemoveReply(const Core::FunctionReplyObject &replyObject) +void ParticipantMoveDialog::onSimulatedMovementRemoveReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); - if (!replyObject.error()) - { - m_sitMapGuiIfc->cancelActiveRubberbands(); - m_sitMapGuiIfc->removePreviewObject(); - } + m_requestHelper->requestReply(replyObject); + if (!replyObject.error()) + { + m_sitMapGuiIfc->cancelActiveRubberbands(); + m_sitMapGuiIfc->removePreviewObject(); + } } -void ParticipantMoveDialog::onSimulatedMovementModifyReply(const Core::FunctionReplyObject &replyObject) +void ParticipantMoveDialog::onSimulatedMovementModifyReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); - if (!replyObject.error()) - m_sitMapGuiIfc->removePreviewObject(); + m_requestHelper->requestReply(replyObject); + if (!replyObject.error()) + m_sitMapGuiIfc->removePreviewObject(); } void ParticipantMoveDialog::retranslate() { - translate(m_ui, QString::fromStdString(m_participantData.tacticalIdentifier()), false, tr("Waypoints")); - DEBUG_LOG(m_logger) << "retranslate"; + translate(m_ui, QString::fromStdString(m_participantData.tacticalIdentifier()), false, tr("Waypoints")); + DEBUG_LOG(m_logger) << "retranslate"; } void ParticipantMoveDialog::initTableHeader() { - QStringList headers; - headers << tr("Identifier") << tr("Idle Time [s]") << tr("Speed [km/h]") << tr("Position"); - m_ui->tableWidget->setHorizontalHeaderLabels(headers); - m_ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + QStringList headers; + headers << tr("Identifier") << tr("Idle Time [s]") << tr("Speed [km/h]") << tr("Position"); + m_ui->tableWidget->setHorizontalHeaderLabels(headers); + m_ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); } - -void ParticipantMoveDialog::insertPos(const double lon, const double lat, const QString &identifier, const int idleTime, const double speed) +void ParticipantMoveDialog::insertPos(const double lon, const double lat, const QString& identifier, const int idleTime, + const double speed) { - QLineEdit *le = new QLineEdit; - QSpinBox *sbDelay = new QSpinBox; - QSpinBox *sbSpeed = new QSpinBox; - sbDelay->setMinimum(m_ui->spIdleTime->minimum()); - sbDelay->setMaximum(m_ui->spIdleTime->maximum()); - sbSpeed->setMinimum(m_ui->spSpeed->minimum()); - sbSpeed->setMaximum(m_ui->spSpeed->maximum()); - int rowCount = m_ui->tableWidget->rowCount(); + QLineEdit* le = new QLineEdit; + QSpinBox* sbDelay = new QSpinBox; + QSpinBox* sbSpeed = new QSpinBox; + sbDelay->setMinimum(m_ui->spIdleTime->minimum()); + sbDelay->setMaximum(m_ui->spIdleTime->maximum()); + sbSpeed->setMinimum(m_ui->spSpeed->minimum()); + sbSpeed->setMaximum(m_ui->spSpeed->maximum()); + int rowCount = m_ui->tableWidget->rowCount(); - LtsCoordWidget::LtsCoordWidget *wdg = new LtsCoordWidget::LtsCoordWidget(); - - wdg->setCoordinate(lon, lat); - wdg->setObjectName(QStringLiteral("positionEdit_") + QString::number(rowCount)); - m_ui->tableWidget->insertRow(rowCount); - le->setText(identifier); - m_ui->tableWidget->setCellWidget(rowCount, Name, le); - sbDelay->setValue(idleTime / s_timeMilliConversion); - m_ui->tableWidget->setCellWidget(rowCount, IdleTime, sbDelay); - sbSpeed->setValue(speed * s_msConversion); - m_ui->tableWidget->setCellWidget(rowCount, Speed, sbSpeed); - m_ui->tableWidget->setCellWidget(rowCount, Position, wdg); - wdg->setDisplayType(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS); + LtsCoordWidget::LtsCoordWidget* wdg = new LtsCoordWidget::LtsCoordWidget(); + wdg->setCoordinate(lon, lat); + wdg->setObjectName(QStringLiteral("positionEdit_") + QString::number(rowCount)); + m_ui->tableWidget->insertRow(rowCount); + le->setText(identifier); + m_ui->tableWidget->setCellWidget(rowCount, Name, le); + sbDelay->setValue(idleTime / s_timeMilliConversion); + m_ui->tableWidget->setCellWidget(rowCount, IdleTime, sbDelay); + sbSpeed->setValue(speed * s_msConversion); + m_ui->tableWidget->setCellWidget(rowCount, Speed, sbSpeed); + m_ui->tableWidget->setCellWidget(rowCount, Position, wdg); + wdg->setDisplayType(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS); } - - - - void ParticipantMoveDialog::clearContent() { - m_ui->lePrefix->clear(); - m_ui->cbRepeat->setChecked(false); - m_ui->cbJump->setChecked(false); + m_ui->lePrefix->clear(); + m_ui->cbRepeat->setChecked(false); + m_ui->cbJump->setChecked(false); - clearCoordinates(); + clearCoordinates(); } void ParticipantMoveDialog::clearCoordinates() { - if (m_ui) - { - m_ui->tableWidget->clearContents(); - m_ui->tableWidget->setRowCount(0); - } - - if ( m_sitMapGuiIfc && this->amIFocused()) - m_sitMapGuiIfc->removePreviewObject(); + if (m_ui) + { + m_ui->tableWidget->clearContents(); + m_ui->tableWidget->setRowCount(0); + } + + if (m_sitMapGuiIfc && this->amIFocused()) + m_sitMapGuiIfc->removePreviewObject(); } void ParticipantMoveDialog::onFocus() { - showPreview(true); - m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); + showPreview(true); + m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); } void ParticipantMoveDialog::onGetPolyline() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return; - } + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return; + } - QPolygonF coordinates; - int i = 0; - while (true) - { - LtsCoordWidget::LtsCoordWidget *w = findChild(QStringLiteral("positionEdit_%1").arg(i)); - if (!w) - break; - if (!w->coordinate().isNull()) - coordinates << w->coordinate(); - ++i; - } + QPolygonF coordinates; + int i = 0; + while (true) + { + LtsCoordWidget::LtsCoordWidget* w = + findChild(QStringLiteral("positionEdit_%1").arg(i)); + if (!w) + break; + if (!w->coordinate().isNull()) + coordinates << w->coordinate(); + ++i; + } - m_sitMapGuiIfc->getPolyline(this, - SLOT(onPolylineData(QPolygonF)), - nullptr, - 2, - 11, - -1, - -1, - coordinates); + m_sitMapGuiIfc->getPolyline(this, SLOT(onPolylineData(QPolygonF)), nullptr, 2, 11, -1, -1, coordinates); +} -} - - -void ParticipantMoveDialog::onPolylineData(const QPolygonF &polyline) +void ParticipantMoveDialog::onPolylineData(const QPolygonF& polyline) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " numberOfPoints: " << polyline.size(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " numberOfPoints: " << polyline.size(); - if (polyline.size() < 2) - return; + if (polyline.size() < 2) + return; - m_polyline = polyline; + m_polyline = polyline; - clearCoordinates(); - for (int i = 0; i < polyline.size(); i++) - insertPos(polyline.at(i).x(), polyline.at(i).y(), - m_ui->lePrefix->text() + QLatin1Char('_') + QString::number(i + 1), - m_ui->spIdleTime->value() * s_timeMilliConversion, - m_ui->spSpeed->value() / s_msConversion); + clearCoordinates(); + for (int i = 0; i < polyline.size(); i++) + insertPos(polyline.at(i).x(), polyline.at(i).y(), + m_ui->lePrefix->text() + QLatin1Char('_') + QString::number(i + 1), + m_ui->spIdleTime->value() * s_timeMilliConversion, m_ui->spSpeed->value() / s_msConversion); - - m_sitMapGuiIfc->displayPreviewObject(this, polyline, false); + m_sitMapGuiIfc->displayPreviewObject(this, polyline, false); +} -} - - -bool ParticipantMoveDialog::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit *dte) const +bool ParticipantMoveDialog::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit* dte) const { - - const bool bEmptyAllowed = dte->isCheckable(); - const auto ms = dte->msecsSinceEpoch(); - - if (bEmptyAllowed && ms == 0) - return true; - return ms > m_session->partitionTime(); + + const bool bEmptyAllowed = dte->isCheckable(); + const auto ms = dte->msecsSinceEpoch(); + + if (bEmptyAllowed && ms == 0) + return true; + return ms > m_session->partitionTime(); } SimulatedMovement ParticipantMoveDialog::requestContent() const { - std::string name = m_ui->lePrefix->text().toStdString(); - int32_t repeat = m_ui->cbRepeat->isChecked(); - - int32_t jumpToStart = true; - rti::core::int64 startTime = m_ui->dteStartTime->msecsSinceEpoch(); - int32_t participantId = m_participantData.id(); - int32_t nextPoint = 0; + std::string name = m_ui->lePrefix->text().toStdString(); + int32_t repeat = m_ui->cbRepeat->isChecked(); - int cntSegments = m_ui->tableWidget->rowCount(); - std::vector segments; - segments.resize(cntSegments); - for (int i = 0; i < cntSegments; i++) - { - QWidget *widget = m_ui->tableWidget->cellWidget(i, Name); - const QString nameSeg = static_cast(widget)->text(); - segments[i].name(nameSeg.toStdString()); + int32_t jumpToStart = true; + rti::core::int64 startTime = m_ui->dteStartTime->msecsSinceEpoch(); + int32_t participantId = m_participantData.id(); + int32_t nextPoint = 0; - widget = m_ui->tableWidget->cellWidget(i, IdleTime); - const int idleTime = static_cast(widget)->value() * s_timeMilliConversion; - segments[i].delay(idleTime); + int cntSegments = m_ui->tableWidget->rowCount(); + std::vector segments; + segments.resize(cntSegments); + for (int i = 0; i < cntSegments; i++) + { + QWidget* widget = m_ui->tableWidget->cellWidget(i, Name); + const QString nameSeg = static_cast(widget)->text(); + segments[i].name(nameSeg.toStdString()); - widget = m_ui->tableWidget->cellWidget(i, Speed); - const double speed = static_cast(widget)->value() / s_msConversion; + widget = m_ui->tableWidget->cellWidget(i, IdleTime); + const int idleTime = static_cast(widget)->value() * s_timeMilliConversion; + segments[i].delay(idleTime); - segments[i].speed(speed); + widget = m_ui->tableWidget->cellWidget(i, Speed); + const double speed = static_cast(widget)->value() / s_msConversion; - widget = m_ui->tableWidget->cellWidget(i, Position); - const QPointF point = static_cast(widget)->coordinate(); - const Core::GeoPosition2D pos(Core::GeoPosition2D(point.x(), point.y())); - segments[i].position(pos); - } + segments[i].speed(speed); - return SimulatedMovement(m_id, - name, - startTime, - participantId, - segments, - repeat, - jumpToStart, - nextPoint - ); + widget = m_ui->tableWidget->cellWidget(i, Position); + const QPointF point = static_cast(widget)->coordinate(); + const Core::GeoPosition2D pos(Core::GeoPosition2D(point.x(), point.y())); + segments[i].position(pos); + } + + return SimulatedMovement(m_id, name, startTime, participantId, segments, repeat, jumpToStart, nextPoint); } bool ParticipantMoveDialog::apply() { - int cntSegments = m_ui->tableWidget->rowCount(); - if (cntSegments > 0) - { - const SimulatedMovement req = requestContent(); - - INFO_LOG(m_logger) << "--- onApplyMessage() "; - - m_requestHelper->addRequest([this, req]() + int cntSegments = m_ui->tableWidget->rowCount(); + if (cntSegments > 0) { - return m_ftc->simulatedMovementModifyRequest(req, this); - }); - } - else - { - if (m_id > 0) - { - Core::RemoveElementRequest req(m_id); - m_id = 0; + const SimulatedMovement req = requestContent(); - INFO_LOG(m_logger) << "--- onApplyMessage() "; + INFO_LOG(m_logger) << "--- onApplyMessage() "; - m_requestHelper->addRequest([req, this]() - { - return m_ftc->simulatedMovementRemoveRequest(req, this); - }); + m_requestHelper->addRequest([this, req]() { return m_ftc->simulatedMovementModifyRequest(req, this); }); } - } + else + { + if (m_id > 0) + { + Core::RemoveElementRequest req(m_id); + m_id = 0; - return m_requestHelper->startRequests(); + INFO_LOG(m_logger) << "--- onApplyMessage() "; + + m_requestHelper->addRequest([req, this]() { return m_ftc->simulatedMovementRemoveRequest(req, this); }); + } + } + + return m_requestHelper->startRequests(); } - - - - QByteArray ParticipantMoveDialog::simulatedMovementToJson() const { - const SimulatedMovement req = requestContent(); - QJsonObject obj; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::CESParticipantMove); + const SimulatedMovement req = requestContent(); + QJsonObject obj; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::CESParticipantMove); - obj[QStringLiteral("id")] = req.id(); - obj[QStringLiteral("jumpToStart")] = req.jumpToStart(); - obj[QStringLiteral("name")] = QString::fromStdString(req.name()); - obj[QStringLiteral("nextPoint")] = req.nextPoint(); - obj[QStringLiteral("participantId")] = req.participantId(); - obj[QStringLiteral("repeat")] = req.repeat(); - obj[QStringLiteral("startTime")] = req.startTime(); + obj[QStringLiteral("id")] = req.id(); + obj[QStringLiteral("jumpToStart")] = req.jumpToStart(); + obj[QStringLiteral("name")] = QString::fromStdString(req.name()); + obj[QStringLiteral("nextPoint")] = req.nextPoint(); + obj[QStringLiteral("participantId")] = req.participantId(); + obj[QStringLiteral("repeat")] = req.repeat(); + obj[QStringLiteral("startTime")] = req.startTime(); - QJsonArray arr; - for (auto it = req.segments().begin(); it != req.segments().end(); ++it) - { - QJsonObject inner; - inner[QStringLiteral("delay")] = it->delay(); - inner[QStringLiteral("name")] = QString::fromStdString(it->name()); - inner[QStringLiteral("speed")] = it->speed(); - inner[QStringLiteral("lat")] = it->position().lat(); - inner[QStringLiteral("lon")] = it->position().lon(); - arr += inner; - } - obj[QStringLiteral("segments")] = arr; + QJsonArray arr; + for (auto it = req.segments().begin(); it != req.segments().end(); ++it) + { + QJsonObject inner; + inner[QStringLiteral("delay")] = it->delay(); + inner[QStringLiteral("name")] = QString::fromStdString(it->name()); + inner[QStringLiteral("speed")] = it->speed(); + inner[QStringLiteral("lat")] = it->position().lat(); + inner[QStringLiteral("lon")] = it->position().lon(); + arr += inner; + } + obj[QStringLiteral("segments")] = arr; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -SimulatedMovement ParticipantMoveDialog::jsonToSimulatedMovement(const QByteArray &content) const +SimulatedMovement ParticipantMoveDialog::jsonToSimulatedMovement(const QByteArray& content) const { - - CentralEffectSimulation::SimulatedMovement result; - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); - result.id(obj[QStringLiteral("id")].toInt()); - result.jumpToStart(obj[QStringLiteral("jumpToStart")].toInt()); - result.name(obj[QStringLiteral("name")].toString().toStdString()); - result.nextPoint(obj[QStringLiteral("nextPoint")].toInt()); - result.participantId(m_participantData.id()); - result.repeat(obj[QStringLiteral("repeat")].toInt()); - result.startTime(obj[QStringLiteral("startTime")].toDouble()); + CentralEffectSimulation::SimulatedMovement result; + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); - const QJsonArray arr(obj.value(QStringLiteral("segments")).toArray()); - auto &segments = result.segments(); - segments.resize(arr.size()); - for (int i = 0; i < arr.size(); ++i) - { - CentralEffectSimulation::SimulatedMovementSegment &segment = segments[i]; - const QJsonObject objArr(arr.at(i).toObject()); - segment.delay(objArr[QStringLiteral("delay")].toDouble()); - segment.name(objArr[QStringLiteral("name")].toString().toStdString()); + result.id(obj[QStringLiteral("id")].toInt()); + result.jumpToStart(obj[QStringLiteral("jumpToStart")].toInt()); + result.name(obj[QStringLiteral("name")].toString().toStdString()); + result.nextPoint(obj[QStringLiteral("nextPoint")].toInt()); + result.participantId(m_participantData.id()); + result.repeat(obj[QStringLiteral("repeat")].toInt()); + result.startTime(obj[QStringLiteral("startTime")].toDouble()); + const QJsonArray arr(obj.value(QStringLiteral("segments")).toArray()); + auto& segments = result.segments(); + segments.resize(arr.size()); + for (int i = 0; i < arr.size(); ++i) + { + CentralEffectSimulation::SimulatedMovementSegment& segment = segments[i]; + const QJsonObject objArr(arr.at(i).toObject()); + segment.delay(objArr[QStringLiteral("delay")].toDouble()); + segment.name(objArr[QStringLiteral("name")].toString().toStdString()); - segment.position().lat(objArr[QStringLiteral("lat")].toDouble()); - segment.position().lon(objArr[QStringLiteral("lon")].toDouble()); - segment.speed(objArr[QStringLiteral("speed")].toDouble()); - } - return result; + segment.position().lat(objArr[QStringLiteral("lat")].toDouble()); + segment.position().lon(objArr[QStringLiteral("lon")].toDouble()); + segment.speed(objArr[QStringLiteral("speed")].toDouble()); + } + return result; } void ParticipantMoveDialog::onExportButtonClicked() { - QJsonObject saveObject; - saveObject[QStringLiteral("content")] = QString(); + QJsonObject saveObject; + saveObject[QStringLiteral("content")] = QString(); - const QByteArray byteArray = simulatedMovementToJson(); + const QByteArray byteArray = simulatedMovementToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void ParticipantMoveDialog::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::CESParticipantMove)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::CESParticipantMove))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::CESParticipantMove)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - SimulatedMovement req = jsonToSimulatedMovement(content); + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::CESParticipantMove))) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + SimulatedMovement req = jsonToSimulatedMovement(content); - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; - m_requestHelper->addRequest([this, req]() - { - return m_ftc->simulatedMovementModifyRequest(req, this); - }); - m_requestHelper->startRequests(); + m_requestHelper->addRequest([this, req]() { return m_ftc->simulatedMovementModifyRequest(req, this); }); + m_requestHelper->startRequests(); + } } - } } - -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_dialog.cpp old mode 100755 new mode 100644 index 52e001e20..2f133835d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_dialog.cpp @@ -1,895 +1,846 @@  - #include "participants_move_dialog.h" -#include -#include "participants_move_model.h" -#include "ui_participants_move_dialog.h" -#include -#include -#include -#include -#include -#include -#include #include "participant_move_dialog.h" +#include "participants_move_model.h" +#include "ui_participants_move_dialog.h" -#include -#include -#include +#include +#include +#include #include #include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include -#include -#include -#include +#include namespace CentralEffectSimulation { -ParticipantsMoveDialog::ParticipantsMoveDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_participantModel(nullptr) - , m_ppmDtc(nullptr) - , m_ppmCbxIfc(nullptr) - , m_ftc(nullptr) - , m_ui(new Ui::ParticipantMoveDialog) - , m_session(nullptr) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_sitMapGuiIfc(nullptr) +ParticipantsMoveDialog::ParticipantsMoveDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_participantModel(nullptr), + m_ppmDtc(nullptr), m_ppmCbxIfc(nullptr), m_ftc(nullptr), m_ui(new Ui::ParticipantMoveDialog), m_session(nullptr), + m_menuGroup(menuGroup), m_requestHelper(new LtsUtils::RequestHelper(this)), m_sitMapGuiIfc(nullptr) { - m_ui->setupUi(this); - setUnchangeable(); + m_ui->setupUi(this); + setUnchangeable(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &ParticipantsMoveDialog::onSetSimulatedMGRSPosition); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); - m_buttonBox->setIcon(LtsWidgets::DialogButton::Save, QIcon(QStringLiteral("icon:position.svg"))); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, + &ParticipantsMoveDialog::onSetSimulatedMGRSPosition); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); + m_buttonBox->setIcon(LtsWidgets::DialogButton::Save, QIcon(QStringLiteral("icon:position.svg"))); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ParticipantsMoveDialog::onClicked); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ParticipantsMoveDialog::onClicked); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ParticipantsMoveDialog::onSetPosition); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ParticipantsMoveDialog::onSetPosition); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ParticipantsMoveDialog::onRemove); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ParticipantsMoveDialog::onRemove); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - - setOnlineHelpFilename(QStringLiteral("Situation-Move_Participant_0")); + setOnlineHelpFilename(QStringLiteral("Situation-Move_Participant_0")); } ParticipantsMoveDialog::~ParticipantsMoveDialog() { - m_sitMapGuiIfc = nullptr; - delete m_ui; + m_sitMapGuiIfc = nullptr; + delete m_ui; } static constexpr int s_maxAngleDeg = 360; static constexpr int s_maxAngleMil = 6400; -inline constexpr int mil2Deg(const int &mil) + +inline constexpr int mil2Deg(const int& mil) { - return s_maxAngleDeg * mil / s_maxAngleMil; + return s_maxAngleDeg * mil / s_maxAngleMil; } -inline constexpr int deg2Mil(const int &angleDeg) + +inline constexpr int deg2Mil(const int& angleDeg) { - return s_maxAngleMil * angleDeg / s_maxAngleDeg; + return s_maxAngleMil * angleDeg / s_maxAngleDeg; } void ParticipantsMoveDialog::retranslate() { - translate(m_ui, tr("Move Participant")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Set Simulated MGRS Position")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("Set Simulated Position")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Edit Simulation")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Remove)->setText(tr("Remove Simulation")); + translate(m_ui, tr("Move Participant")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Set Simulated MGRS Position")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("Set Simulated Position")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Edit Simulation")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Remove)->setText(tr("Remove Simulation")); } -bool ParticipantsMoveDialog::init(LtsSession::LtsSession *session, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &cesDtc, - const std::shared_ptr &ppmFtc) +bool ParticipantsMoveDialog::init(LtsSession::LtsSession* session, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& cesDtc, + const std::shared_ptr& ppmFtc) { - m_ppmDtc = ppmDtc; - m_cesDtc = cesDtc; - m_session = session; - m_ppmFtc = ppmFtc; + m_ppmDtc = ppmDtc; + m_cesDtc = cesDtc; + m_session = session; + m_ppmFtc = ppmFtc; - if (!m_ppmDtc) - return false; + if (!m_ppmDtc) + return false; - if (!m_ppmFtc) - return false; + if (!m_ppmFtc) + return false; - if (!session->getForeignGuiInterface(m_ppmCbxIfc)) - return false; + if (!session->getForeignGuiInterface(m_ppmCbxIfc)) + return false; - if (!m_session->getFtc(m_ftc)) - return false; + if (!m_session->getFtc(m_ftc)) + return false; - std::shared_ptr exmDtc; - if (!m_session->getDtc(exmDtc)) - { - ERROR_LOG(m_logger) << "failed to get exmDtc "; - return false; - } + std::shared_ptr exmDtc; + if (!m_session->getDtc(exmDtc)) + { + ERROR_LOG(m_logger) << "failed to get exmDtc "; + return false; + } - std::shared_ptr asmDtc; - if (!m_session->getDtc(asmDtc)) - { - ERROR_LOG(m_logger) << "failed to get asmDtc "; - return false; - } + std::shared_ptr asmDtc; + if (!m_session->getDtc(asmDtc)) + { + ERROR_LOG(m_logger) << "failed to get asmDtc "; + return false; + } - if (asmDtc == nullptr || exmDtc == nullptr) - return false; + if (asmDtc == nullptr || exmDtc == nullptr) + return false; - const ExerciseManagement::Exercise exc = exmDtc->exercise(m_session->exerciseId()); - AssetManagement::TrainingArea ta = asmDtc->trainingArea(exc.trainingAreaId()); - if (ta.id() != exc.trainingAreaId()) - { - ERROR_LOG(m_logger)<<" couldn't get Training Area with id: "<exercise(m_session->exerciseId()); + AssetManagement::TrainingArea ta = asmDtc->trainingArea(exc.trainingAreaId()); + if (ta.id() != exc.trainingAreaId()) + { + ERROR_LOG(m_logger) << " couldn't get Training Area with id: " << exc.trainingAreaId(); + return false; + } - if (!m_session ->getDtc(m_aesDtc)) - { - ERROR_LOG(m_logger)<<"failed to get aesDtc"; - return false; - } + if (!m_session->getDtc(m_aesDtc)) + { + ERROR_LOG(m_logger) << "failed to get aesDtc"; + return false; + } + const LtsCoordTrans::UtmCoordinate& bottomLeft = + LtsCoordTrans::UtmCoordinate::fromGeographic(ta.bottomLeft().lon(), ta.bottomLeft().lat()); + m_trainingAreaRect = QRectF(bottomLeft.geographic(0, ta.height()), bottomLeft.geographic(ta.width(), 0)); + m_ppmDtc->enableUnitPosition(); + m_ppmDtc->waitForHistoricalDataUnitPosition(1000); - - const LtsCoordTrans::UtmCoordinate &bottomLeft = LtsCoordTrans::UtmCoordinate::fromGeographic(ta.bottomLeft().lon(), ta.bottomLeft().lat()); - m_trainingAreaRect = QRectF(bottomLeft.geographic(0, ta.height()), bottomLeft.geographic(ta.width(), 0)); + std::shared_ptr asb; + session->getForeignDataInterface(asb); + m_participantModel = new ParticipantMoveModel(this, m_ppmDtc, asb); + auto proxyModel = new ParticipantManagement::ParticipantTreeFilterProxyModel(this); + proxyModel->setSourceModel(m_participantModel); + proxyModel->setRecursiveFilteringEnabled(true); + m_ui->dvParticipants->setModel(proxyModel); + m_ui->dvParticipants->setSortIndicator(0, Qt::AscendingOrder); - - m_ppmDtc->enableUnitPosition(); - m_ppmDtc->waitForHistoricalDataUnitPosition(1000); + connect(m_ui->cbParty, + static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &ParticipantsMoveDialog::changeParty); + connect(m_ui->cbAll, &QCheckBox::toggled, this, &ParticipantsMoveDialog::changeParty); - std::shared_ptr asb; - session->getForeignDataInterface(asb); - m_participantModel = new ParticipantMoveModel(this, m_ppmDtc, asb); - - auto proxyModel = new ParticipantManagement::ParticipantTreeFilterProxyModel(this); - proxyModel->setSourceModel(m_participantModel); - proxyModel->setRecursiveFilteringEnabled(true); - m_ui->dvParticipants->setModel(proxyModel); - m_ui->dvParticipants->setSortIndicator(0, Qt::AscendingOrder); + connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::selectionChanged, this, + &ParticipantsMoveDialog::onSelectionChanged); - connect(m_ui->cbParty, - static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &ParticipantsMoveDialog::changeParty); - connect(m_ui->cbAll, &QCheckBox::toggled, this, &ParticipantsMoveDialog::changeParty); + connect(m_participantModel, &ParticipantMoveModel::newData, this, &ParticipantsMoveDialog::onModelChanged); - connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::selectionChanged, - this, &ParticipantsMoveDialog::onSelectionChanged); + connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ParticipantsMoveDialog::onDoubleClicked); - connect(m_participantModel, &ParticipantMoveModel::newData, - this, &ParticipantsMoveDialog::onModelChanged); + m_ppmCbxIfc->fillPartyComboBox(m_ui->cbParty, + ParticipantManagement::ForeignGuiComboboxInterface::CbxPartyFilter::All); + changeParty(); - connect(m_ui->dvParticipants, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ParticipantsMoveDialog::onDoubleClicked); - - - m_ppmCbxIfc->fillPartyComboBox(m_ui->cbParty, ParticipantManagement::ForeignGuiComboboxInterface::CbxPartyFilter::All); - changeParty(); - - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setIcon(QIcon(QStringLiteral("icon:position.svg"))); + m_session->getForeignGuiInterface(m_sitMapGuiIfc); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setIcon(QIcon(QStringLiteral("icon:position.svg"))); #ifndef LTS_DEBUG - m_ui->dvParticipants->hideColumn(ParticipantMoveModel::ColParticipantId); + m_ui->dvParticipants->hideColumn(ParticipantMoveModel::ColParticipantId); #endif - return true; + return true; } - - void ParticipantsMoveDialog::closeDialogReceived(int32_t participantId) { - m_participantDialogMap.remove(participantId); + m_participantDialogMap.remove(participantId); } - void ParticipantsMoveDialog::onSelectionChanged() { - const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - bool isOne = (indexList.size() == 1); + const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + bool isOne = (indexList.size() == 1); - - if (!isOne) - return; + if (!isOne) + return; - const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); - DEBUG_LOG(m_logger) << "ParticipantId: " << data.id(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, data.isSimulated()); - - if (data.isSimulated() && m_participantDialogMap.contains(data.id())) - m_participantDialogMap.value(data.id())->showPreview(true); - else - { - - QMapIterator i(m_participantDialogMap); - while (i.hasNext()) - { - i.next(); - - i.value()->showPreview(false); - } - } + const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); + DEBUG_LOG(m_logger) << "ParticipantId: " << data.id(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, data.isSimulated()); - - { - bool isParticipantInUseOrAdler = participantInUse4ExplosionCluster(indexList.first()); - - if (!isParticipantInUseOrAdler) - isParticipantInUseOrAdler = (m_ppmDtc->isAdlerType(data.typeId()) && !data.name().empty()); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, isOne && !isParticipantInUseOrAdler); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, isOne && !isParticipantInUseOrAdler); - } - - if (m_ppmDtc->type(data.typeId()).typeClass() != ParticipantManagement::TypeClass_def::Unit) - { - - if (!data.equipmentNumber().is_set() || data.equipmentNumber().get() <= 0) - { - - isOne &= !(m_ppmDtc->isAdlerType(data.typeId()) && !data.name().empty()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); - } + if (data.isSimulated() && m_participantDialogMap.contains(data.id())) + m_participantDialogMap.value(data.id())->showPreview(true); else - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - } + { + QMapIterator i(m_participantDialogMap); + while (i.hasNext()) + { + i.next(); + + i.value()->showPreview(false); + } + } + + { + bool isParticipantInUseOrAdler = participantInUse4ExplosionCluster(indexList.first()); + + if (!isParticipantInUseOrAdler) + isParticipantInUseOrAdler = (m_ppmDtc->isAdlerType(data.typeId()) && !data.name().empty()); + + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, isOne && !isParticipantInUseOrAdler); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, isOne && !isParticipantInUseOrAdler); + } + + if (m_ppmDtc->type(data.typeId()).typeClass() != ParticipantManagement::TypeClass_def::Unit) + { + + if (!data.equipmentNumber().is_set() || data.equipmentNumber().get() <= 0) + { + + isOne &= !(m_ppmDtc->isAdlerType(data.typeId()) && !data.name().empty()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); + } + else + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + } } void ParticipantsMoveDialog::onModelChanged() { - m_ui->dvParticipants->expandAll(); - DEBUG_LOG(m_logger) << "onModelChanged"; + m_ui->dvParticipants->expandAll(); + DEBUG_LOG(m_logger) << "onModelChanged"; } void ParticipantsMoveDialog::onDoubleClicked() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return; - } + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return; + } - if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) - return; - const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); + if (!m_buttonBox->isButtonEnabled(LtsWidgets::DialogButton::Edit)) + return; + const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - bool isOne = (indexList.size() == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); + bool isOne = (indexList.size() == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); - if (!isOne) - return; + if (!isOne) + return; - const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); - DEBUG_LOG(m_logger) << "ParticipantId: " << data.id(); + const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); + DEBUG_LOG(m_logger) << "ParticipantId: " << data.id(); - if (!m_participantDialogMap.contains(data.id())) - { - ParticipantMoveDialog *dialog = new ParticipantMoveDialog(this); - m_participantDialogMap.insert(data.id(), dialog); - connect(dialog, &ParticipantMoveDialog::closeDialog, - this, &ParticipantsMoveDialog::closeDialogReceived); + if (!m_participantDialogMap.contains(data.id())) + { + ParticipantMoveDialog* dialog = new ParticipantMoveDialog(this); + m_participantDialogMap.insert(data.id(), dialog); + connect(dialog, &ParticipantMoveDialog::closeDialog, this, &ParticipantsMoveDialog::closeDialogReceived); - addDialog(LtsWidgets::initDialog(dialog, m_session, m_ppmDtc, m_cesDtc, data), - m_menuGroup, QStringLiteral("cesNewSimulation%1").arg(data.id()), LtsWidgets::LayoutArea::eDialogTab); - } - else - focusDialog(m_menuGroup, QStringLiteral("cesNewSimulation%1").arg(data.id()), LtsWidgets::LayoutArea::eDialogTab); + addDialog(LtsWidgets::initDialog(dialog, m_session, m_ppmDtc, m_cesDtc, data), m_menuGroup, + QStringLiteral("cesNewSimulation%1").arg(data.id()), LtsWidgets::LayoutArea::eDialogTab); + } + else + focusDialog(m_menuGroup, QStringLiteral("cesNewSimulation%1").arg(data.id()), + LtsWidgets::LayoutArea::eDialogTab); } - void ParticipantsMoveDialog::changeParty() { - if (m_ui->cbAll->isChecked()) - { - m_ui->cbParty->setEnabled(false); - m_ui->dvParticipants->setEnabled(false); - m_participantModel->resetModel(); - } - else - { - m_ui->cbParty->setEnabled(true); - m_ui->dvParticipants->setEnabled(true); - int partyId = m_ui->cbParty->currentData().toInt(); - m_participantModel->onReinitModel(partyId); - m_ui->dvParticipants->expandAll(); - } - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, m_ui->cbAll->isChecked()); + if (m_ui->cbAll->isChecked()) + { + m_ui->cbParty->setEnabled(false); + m_ui->dvParticipants->setEnabled(false); + m_participantModel->resetModel(); + } + else + { + m_ui->cbParty->setEnabled(true); + m_ui->dvParticipants->setEnabled(true); + int partyId = m_ui->cbParty->currentData().toInt(); + m_participantModel->onReinitModel(partyId); + m_ui->dvParticipants->expandAll(); + } + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, m_ui->cbAll->isChecked()); } void ParticipantsMoveDialog::onClicked() { - onDoubleClicked(); + onDoubleClicked(); } void ParticipantsMoveDialog::onRemove() { - const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); + const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - bool isOne = (indexList.size() == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + bool isOne = (indexList.size() == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - if (!isOne) - return; + if (!isOne) + return; - const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); - INFO_LOG(m_logger) << "onRemove ParticipantId: " << data.id(); + const ParticipantManagement::ParticipantData data(participantFromIndex(indexList.first())); + INFO_LOG(m_logger) << "onRemove ParticipantId: " << data.id(); - - delete m_participantDialogMap.value(data.id()); - m_participantDialogMap.remove(data.id()); + delete m_participantDialogMap.value(data.id()); + m_participantDialogMap.remove(data.id()); - removeFtc(data.id()); + removeFtc(data.id()); } - void ParticipantsMoveDialog::onSetSimulatedMGRSPosition() { - const QModelIndexList &indexList = m_ui->dvParticipants->selectedRows(); - if (indexList.size() == 1) - { - QPointF mgrsCoordinate; - m_mgrsPosEditCoordinateActive = true; - if(!participantInUse4ExplosionCluster(indexList.first())) + const QModelIndexList& indexList = m_ui->dvParticipants->selectedRows(); + if (indexList.size() == 1) { - onGetCoordinate(mgrsCoordinate); - m_mgrsPosEditCoordinateActive = false; + QPointF mgrsCoordinate; + m_mgrsPosEditCoordinateActive = true; + if (!participantInUse4ExplosionCluster(indexList.first())) + { + onGetCoordinate(mgrsCoordinate); + m_mgrsPosEditCoordinateActive = false; + } + else + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("This Participant Unit is currently in use.\nThe Parameters can't be changed!")); + } +} + +bool ParticipantsMoveDialog::participantInUse4ExplosionCluster(const QModelIndex& participantIndex) +{ + const ParticipantManagement::ParticipantData participantData(participantFromIndex(participantIndex)); + bool bret = false; + + const ParticipantManagement::Type& participantType = m_ppmDtc->type(participantData.typeId()); + bool isUnitType = (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || + (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); + + if (!isUnitType) + { + const QModelIndex parentIndex = m_participantModel->indexFromParticipantId(participantData.superiorModId()); + const ParticipantManagement::ParticipantData parentParticipantData(participantFromIndex(parentIndex)); + + const ParticipantManagement::Type& partentParticipantType = m_ppmDtc->type(parentParticipantData.typeId()); + isUnitType = (partentParticipantType.typeClass() == ParticipantManagement::TypeClass::Unit) || + (partentParticipantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); + bret = isUnitType && isParticipantInUseForExplosionCluster(parentParticipantData.id()); + ; } else - LtsWidgets::LtsMessageDialog::showMessage(this, tr("This Participant Unit is currently in use.\nThe Parameters can't be changed!")); - } + bret = isParticipantInUseForExplosionCluster(participantData.id()); + + return bret; } -bool ParticipantsMoveDialog::participantInUse4ExplosionCluster(const QModelIndex &participantIndex) +void ParticipantsMoveDialog::onSimulatedMovementRemoveByParticipantIdReply(const Core::FunctionReplyObject& replyObject) { - const ParticipantManagement::ParticipantData participantData(participantFromIndex(participantIndex)); - bool bret=false; - - const ParticipantManagement::Type &participantType = m_ppmDtc->type(participantData.typeId()); - bool isUnitType = (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || - (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); - - - if (!isUnitType) - { - const QModelIndex parentIndex = m_participantModel->indexFromParticipantId(participantData.superiorModId()); - const ParticipantManagement::ParticipantData parentParticipantData(participantFromIndex(parentIndex)); - - const ParticipantManagement::Type &partentParticipantType = m_ppmDtc->type(parentParticipantData.typeId()); - isUnitType = (partentParticipantType.typeClass() == ParticipantManagement::TypeClass::Unit) || - (partentParticipantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); - bret = isUnitType && isParticipantInUseForExplosionCluster(parentParticipantData.id());; - } - else - bret = isParticipantInUseForExplosionCluster(participantData.id()); - - return bret; + m_requestHelper->requestReply(replyObject); } -void ParticipantsMoveDialog::onSimulatedMovementRemoveByParticipantIdReply(const Core::FunctionReplyObject &replyObject) +void ParticipantsMoveDialog::onSetSimulatedPositionReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -void ParticipantsMoveDialog::onSetSimulatedPositionReply(const Core::FunctionReplyObject &replyObject) +void ParticipantsMoveDialog::onSetSimulatedPositionRelativeReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -void ParticipantsMoveDialog::onSetSimulatedPositionRelativeReply(const Core::FunctionReplyObject &replyObject) +void ParticipantsMoveDialog::onSetSimulatedParticipantFormationReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); -} - -void ParticipantsMoveDialog::onSetSimulatedParticipantFormationReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } bool ParticipantsMoveDialog::removeFtc(int32_t participantId) { - if (participantId <= 0) - return true; + if (participantId <= 0) + return true; - CentralEffectSimulation::SimulatedMovementRemoveByParticipantId req(participantId); + CentralEffectSimulation::SimulatedMovementRemoveByParticipantId req(participantId); - m_requestHelper->addRequest([req, this]() - { - return m_ftc->simulatedMovementRemoveByParticipantIdRequest(req, this); - }); - return m_requestHelper->startRequests(); + m_requestHelper->addRequest( + [req, this]() { return m_ftc->simulatedMovementRemoveByParticipantIdRequest(req, this); }); + return m_requestHelper->startRequests(); } void ParticipantsMoveDialog::onGetCoordinate(QPointF coordinate) { - const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - if (indexList.size() == 0) - return; + const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); + if (indexList.size() == 0) + return; - const ParticipantManagement::ParticipantData participantData(participantFromIndex(indexList.first())); + const ParticipantManagement::ParticipantData participantData(participantFromIndex(indexList.first())); - INFO_LOG(m_logger) << Q_FUNC_INFO << "ParticipantId=" << participantData.id() - << " EquipmentNr=" << participantData.equipmentNumber() - << " onGetCoordinate x=" << coordinate.x() << " y=" << coordinate.y(); - if (participantData.id() <= 0) - return; + INFO_LOG(m_logger) << Q_FUNC_INFO << "ParticipantId=" << participantData.id() + << " EquipmentNr=" << participantData.equipmentNumber() + << " onGetCoordinate x=" << coordinate.x() << " y=" << coordinate.y(); + if (participantData.id() <= 0) + return; - const ParticipantManagement::Type &participantType = m_ppmDtc->type(participantData.typeId()); - const bool &isUnitType = - (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || - (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); - - - - - m_formationProps.setFormation(QString::fromStdString(participantType.properties())); - const bool &withFormation = (isUnitType && m_formationProps.isArtillery); - if (withFormation || m_mgrsPosEditCoordinateActive) - setFormationAndPositioningUi(participantData, coordinate, withFormation); - else if (isUnitType) - m_shiftModifierWhileOnSetPosition ? doSetSimulatedPositionRequest(participantData, coordinate) : - doSetSimulatedPositionRelativeRequest(participantData, coordinate); - else - doSetSimulatedPositionRequest(participantData, coordinate); + const ParticipantManagement::Type& participantType = m_ppmDtc->type(participantData.typeId()); + const bool& isUnitType = (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || + (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); + m_formationProps.setFormation(QString::fromStdString(participantType.properties())); + const bool& withFormation = (isUnitType && m_formationProps.isArtillery); + if (withFormation || m_mgrsPosEditCoordinateActive) + setFormationAndPositioningUi(participantData, coordinate, withFormation); + else if (isUnitType) + m_shiftModifierWhileOnSetPosition ? doSetSimulatedPositionRequest(participantData, coordinate) + : doSetSimulatedPositionRelativeRequest(participantData, coordinate); + else + doSetSimulatedPositionRequest(participantData, coordinate); } void ParticipantsMoveDialog::onSetPosition() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return; - } - - if (!m_ui->cbAll->isChecked()) - { - const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - - bool isOne = (indexList.size() == 1); - if (!isOne) - return; - - if (participantInUse4ExplosionCluster(indexList.first())) + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("This Participant Unit is currently in use.\nThe Parameters can't be changed!")); - return; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return; } - } + if (!m_ui->cbAll->isChecked()) + { + const QModelIndexList indexList = m_ui->dvParticipants->selectedRows(); - m_shiftModifierWhileOnSetPosition = QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier); - m_sitMapGuiIfc->getCoordinate(this, SLOT(onGetCoordinate(QPointF)), nullptr); + bool isOne = (indexList.size() == 1); + if (!isOne) + return; + + if (participantInUse4ExplosionCluster(indexList.first())) + { + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("This Participant Unit is currently in use.\nThe Parameters can't be changed!")); + return; + } + } + + m_shiftModifierWhileOnSetPosition = QApplication::keyboardModifiers().testFlag(Qt::ShiftModifier); + m_sitMapGuiIfc->getCoordinate(this, SLOT(onGetCoordinate(QPointF)), nullptr); } void ParticipantsMoveDialog::setDialogEnable(bool enable) { - m_ui->dvParticipants->setEnabled(enable); - m_ui->cbParty->setEnabled(enable); - m_ui->cbAll->setEnabled(enable); - m_buttonBox->setEnabled(enable); + m_ui->dvParticipants->setEnabled(enable); + m_ui->cbParty->setEnabled(enable); + m_ui->cbAll->setEnabled(enable); + m_buttonBox->setEnabled(enable); } bool ParticipantsMoveDialog::isParticipantInUseForExplosionCluster(int id) { - if (!m_aesDtc) - { - ERROR_LOG(m_logger)<<" m_aesDTC is not setted"; - return true; - } + if (!m_aesDtc) + { + ERROR_LOG(m_logger) << " m_aesDTC is not setted"; + return true; + } - const QMap &ecMap = m_aesDtc->explosionClusters(); - for(const AreaEffectSimulation::ExplosionCluster &aes : std::as_const(ecMap)) - { - if (aes.participantId() == id && - (aes.effectStateId() == AreaEffectSimulation::AesEffectState::EsPrepared || - aes.effectStateId() == AreaEffectSimulation::AesEffectState::EsActivated)) - return true; - } - return false; + const QMap& ecMap = m_aesDtc->explosionClusters(); + for (const AreaEffectSimulation::ExplosionCluster& aes : std::as_const(ecMap)) + { + if (aes.participantId() == id && (aes.effectStateId() == AreaEffectSimulation::AesEffectState::EsPrepared || + aes.effectStateId() == AreaEffectSimulation::AesEffectState::EsActivated)) + return true; + } + return false; } void ParticipantsMoveDialog::tableColumnOrganiserSetting() { - - m_ui->dvParticipants->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->dvParticipants->setColumnsOrganiserEnabled(identifier(), true); } - - -void ParticipantsMoveDialog::setFormationAndPositioningUi(const ParticipantManagement::ParticipantData &participantData, - QPointF &mgrsCoordinate, - const bool &unitWithFormation) +void ParticipantsMoveDialog::setFormationAndPositioningUi(const ParticipantManagement::ParticipantData& participantData, + QPointF& mgrsCoordinate, const bool& unitWithFormation) { - if (!unitWithFormation && !m_mgrsPosEditCoordinateActive) - return; + if (!unitWithFormation && !m_mgrsPosEditCoordinateActive) + return; - const ParticipantManagement::Type &participantType = m_ppmDtc->type(participantData.typeId()); - const bool isUnitType = - (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || - (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); + const ParticipantManagement::Type& participantType = m_ppmDtc->type(participantData.typeId()); + const bool isUnitType = (participantType.typeClass() == ParticipantManagement::TypeClass::Unit) || + (participantType.typeClass() == ParticipantManagement::TypeClass::SupportUnit); - m_formationProps.setFormation(QString::fromStdString(participantType.properties())); + m_formationProps.setFormation(QString::fromStdString(participantType.properties())); - if (m_formationProps.hasFormationData()) - return; + if (m_formationProps.hasFormationData()) + return; + LtsWidgets::LtsFramelessDialog* dialog = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); + dialog->setFixedSize(390, 300); + dialog->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); - LtsWidgets::LtsFramelessDialog *dialog = new LtsWidgets::LtsFramelessDialog(this, LtsWidgets::Behaviour::Popup); - dialog->setFixedSize(390, 300); - dialog->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); + int row = 0; + QGridLayout* gla = new QGridLayout(dialog); - int row = 0; - QGridLayout *gla = new QGridLayout(dialog); - - { - QLabel *msgLbl = new QLabel(tr(" Following Parameter(s) must be set to proceed. "), dialog); - msgLbl->setWordWrap(true); - gla->addWidget(msgLbl, row, 0, 1, 2); - } - - - LtsCoordWidget::LtsCoordWidget *posEdit = new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog); - { - QLabel *posEditLbl = new QLabel(tr("MGRS Position:"), dialog); - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const QSize offset = QSize(ps->value(QStringLiteral("MgrsSquaresOffsets"), QStringLiteral("xOffset")).toInt(), - ps->value(QStringLiteral("MgrsSquaresOffsets"), QStringLiteral("yOffset")).toInt()); - - posEdit->setWithSurroundingMgrsSquares(true); - posEdit->setMgrsSquareEditable(true); - QVector geoCoords; - - if (LtsCoordTrans::defaultMgrsSquareWithOffsets().isEmpty()) { - const QRectF &trainingAreaWithMargin = LtsCoordTrans::addMarginToArea(m_trainingAreaRect, offset); - geoCoords = LtsCoordTrans::getMgrsSquares(trainingAreaWithMargin,false,false,true); - } - else - geoCoords = LtsCoordTrans::defaultMgrsSquareWithOffsets(); - - posEdit->setMgrsSquares(geoCoords); - if (!mgrsCoordinate.isNull()) - posEdit->setCoordinate(mgrsCoordinate, true); - - ++row; - gla->addWidget(posEditLbl, row, 0, 1, 1); - gla->addWidget(posEdit, row, 1, 1, 1); - - QFrame *line = new QFrame(dialog); - line->setObjectName(QString::fromUtf8("line")); - line->setGeometry(QRect(110, 110, 118, 3)); - line->setFrameShape(QFrame::HLine); - line->setFrameShadow(QFrame::Sunken); - - ++row; - gla->addWidget(line, row, 0, 1, 2); - } - - - QSpinBox *angleSBox = nullptr; - - { - QLabel *angleLbl = new QLabel( tr("Angle:"), dialog); - angleSBox = new QSpinBox(dialog); - angleSBox->setMinimum(0); - angleSBox->setMaximum(s_maxAngleMil); - angleSBox->setSuffix(tr(" mil")); - ++row; - gla->addWidget(angleLbl, row, 0, 1, 1); - gla->addWidget(angleSBox, row, 1, 1, 1); - - } - - - QSpinBox *distanceSBox = nullptr; - QComboBox *distanceCBox = nullptr; - { - QLabel *distanceLbl = new QLabel(tr("Distance:"), dialog); - distanceCBox = new QComboBox(dialog); - for(const auto &dis : m_formationProps.distanceSets.toStdMap()) - { - QString str; - if (dis.first == QStringLiteral("Locked")) - str = tr("Locked"); - else if (dis.first == QStringLiteral("Unlocked")) - str = tr("Unlocked"); - distanceCBox->addItem(QStringLiteral("%1 (%2m)").arg(str).arg(dis.second.toInt()), dis.second.toInt()); + QLabel* msgLbl = new QLabel(tr(" Following Parameter(s) must be set to proceed. "), dialog); + msgLbl->setWordWrap(true); + gla->addWidget(msgLbl, row, 0, 1, 2); } - ++row; - gla->addWidget(distanceLbl, row, 0, 1, 1); - gla->addWidget(distanceCBox, row, 1, 1, 1); + LtsCoordWidget::LtsCoordWidget* posEdit = + new LtsCoordWidget::LtsCoordWidget(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS, dialog); + { + QLabel* posEditLbl = new QLabel(tr("MGRS Position:"), dialog); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const QSize offset = QSize(ps->value(QStringLiteral("MgrsSquaresOffsets"), QStringLiteral("xOffset")).toInt(), + ps->value(QStringLiteral("MgrsSquaresOffsets"), QStringLiteral("yOffset")).toInt()); - } + posEdit->setWithSurroundingMgrsSquares(true); + posEdit->setMgrsSquareEditable(true); + QVector geoCoords; - - { - QScopedPointer verticalSpacer(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding)); - row++; - gla->addItem(verticalSpacer.take(), row, 0, 1, 1); - } + if (LtsCoordTrans::defaultMgrsSquareWithOffsets().isEmpty()) + { + const QRectF& trainingAreaWithMargin = LtsCoordTrans::addMarginToArea(m_trainingAreaRect, offset); + geoCoords = LtsCoordTrans::getMgrsSquares(trainingAreaWithMargin, false, false, true); + } + else + geoCoords = LtsCoordTrans::defaultMgrsSquareWithOffsets(); - - LtsWidgets::LtsDialogButtonBox *btnBox = new LtsWidgets::LtsDialogButtonBox(dialog); - btnBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Apply")); - btnBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort")); - - { - QScopedPointer horizontalSpacer(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); - row++; - gla->addItem(horizontalSpacer.take(), row, 0, 1, 1); - gla->addWidget(btnBox, row, 0, 1, 2); - } + posEdit->setMgrsSquares(geoCoords); + if (!mgrsCoordinate.isNull()) + posEdit->setCoordinate(mgrsCoordinate, true); - - auto applyData = [=]() - { - - - { - int angleMil = angleSBox->value(); - - m_formationProps.angle = std::fmod((mil2Deg(angleMil) + 90), 360); + ++row; + gla->addWidget(posEditLbl, row, 0, 1, 1); + gla->addWidget(posEdit, row, 1, 1, 1); - DEBUG_LOG(m_logger)<<" angle in deg mil: "< degree: "<< mil2Deg(angleMil)<<" final position(°): "<setObjectName(QString::fromUtf8("line")); + line->setGeometry(QRect(110, 110, 118, 3)); + line->setFrameShape(QFrame::HLine); + line->setFrameShadow(QFrame::Sunken); + + ++row; + gla->addWidget(line, row, 0, 1, 2); + } + + QSpinBox* angleSBox = nullptr; + + { + QLabel* angleLbl = new QLabel(tr("Angle:"), dialog); + angleSBox = new QSpinBox(dialog); + angleSBox->setMinimum(0); + angleSBox->setMaximum(s_maxAngleMil); + angleSBox->setSuffix(tr(" mil")); + ++row; + gla->addWidget(angleLbl, row, 0, 1, 1); + gla->addWidget(angleSBox, row, 1, 1, 1); + } + + QSpinBox* distanceSBox = nullptr; + QComboBox* distanceCBox = nullptr; + { + QLabel* distanceLbl = new QLabel(tr("Distance:"), dialog); + distanceCBox = new QComboBox(dialog); + for (const auto& dis : m_formationProps.distanceSets.toStdMap()) + { + QString str; + if (dis.first == QStringLiteral("Locked")) + str = tr("Locked"); + else if (dis.first == QStringLiteral("Unlocked")) + str = tr("Unlocked"); + distanceCBox->addItem(QStringLiteral("%1 (%2m)").arg(str).arg(dis.second.toInt()), dis.second.toInt()); + } + + ++row; + gla->addWidget(distanceLbl, row, 0, 1, 1); + gla->addWidget(distanceCBox, row, 1, 1, 1); } { - - if (distanceSBox != nullptr) - m_formationProps.distance = distanceSBox->value(); - else if(distanceCBox != nullptr) - m_formationProps.distance = distanceCBox->currentData().toInt(); + QScopedPointer verticalSpacer( + new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding)); + row++; + gla->addItem(verticalSpacer.take(), row, 0, 1, 1); } - const QPointF mgrsCoordinate = posEdit->coordinate(); - if (mgrsCoordinate.isNull()) + LtsWidgets::LtsDialogButtonBox* btnBox = new LtsWidgets::LtsDialogButtonBox(dialog); + btnBox->getButton(LtsWidgets::DialogButton::Ok)->setText(tr("Apply")); + btnBox->getButton(LtsWidgets::DialogButton::Close)->setText(tr("Abort")); + { - WARNING_LOG(m_logger)<<"MGRS Coordinates invalid!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Coordinates invalid!\nPlease check them and try again.")); - return; + QScopedPointer horizontalSpacer( + new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum)); + row++; + gla->addItem(horizontalSpacer.take(), row, 0, 1, 1); + gla->addWidget(btnBox, row, 0, 1, 2); } - if (unitWithFormation && (m_formationProps.hasFormationData() || !mgrsCoordinate.isNull())) - { - doSetSimulatedParticipantFormationRequest(participantData, mgrsCoordinate, m_formationProps.getFormationDataObjectString()); - } - else if (isUnitType) - { - - m_shiftModifierWhileOnSetPosition ? doSetSimulatedPositionRequest(participantData, mgrsCoordinate) : - doSetSimulatedPositionRelativeRequest(participantData, mgrsCoordinate); - } - else - doSetSimulatedPositionRequest(participantData, mgrsCoordinate); - setDialogEnable(true); - dialog->accept(); - }; + auto applyData = [=]() { + { + int angleMil = angleSBox->value(); - - connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, dialog, [=](){ - setDialogEnable(true); - dialog->accept(); - }); - - connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, applyData); + m_formationProps.angle = std::fmod((mil2Deg(angleMil) + 90), 360); - dialog->setLayout(gla); - dialog->show(); - setDialogEnable(false); + DEBUG_LOG(m_logger) << " angle in deg mil: " << angleMil << " -> degree: " << mil2Deg(angleMil) + << " final position(°): " << m_formationProps.angle; + } + + { + + if (distanceSBox != nullptr) + m_formationProps.distance = distanceSBox->value(); + else if (distanceCBox != nullptr) + m_formationProps.distance = distanceCBox->currentData().toInt(); + } + + const QPointF mgrsCoordinate = posEdit->coordinate(); + if (mgrsCoordinate.isNull()) + { + WARNING_LOG(m_logger) << "MGRS Coordinates invalid!"; + LtsWidgets::LtsMessageDialog::showMessage(this, + tr("Coordinates invalid!\nPlease check them and try again.")); + return; + } + if (unitWithFormation && (m_formationProps.hasFormationData() || !mgrsCoordinate.isNull())) + { + doSetSimulatedParticipantFormationRequest(participantData, mgrsCoordinate, + m_formationProps.getFormationDataObjectString()); + } + else if (isUnitType) + { + + m_shiftModifierWhileOnSetPosition ? doSetSimulatedPositionRequest(participantData, mgrsCoordinate) + : doSetSimulatedPositionRelativeRequest(participantData, mgrsCoordinate); + } + else + doSetSimulatedPositionRequest(participantData, mgrsCoordinate); + + setDialogEnable(true); + dialog->accept(); + }; + + connect(btnBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, dialog, [=]() { + setDialogEnable(true); + dialog->accept(); + }); + + connect(btnBox->getButton(LtsWidgets::DialogButton::Ok), &QPushButton::clicked, this, applyData); + + dialog->setLayout(gla); + dialog->show(); + setDialogEnable(false); } - -bool ParticipantsMoveDialog::getUnitPosition(int32_t participantId, Core::GeoPosition &unitPositionOut) +bool ParticipantsMoveDialog::getUnitPosition(int32_t participantId, Core::GeoPosition& unitPositionOut) { - - std::shared_ptr fltParticipantIfc; - m_session->getForeignGuiInterface(fltParticipantIfc); - if (!fltParticipantIfc) + std::shared_ptr fltParticipantIfc; + m_session->getForeignGuiInterface(fltParticipantIfc); + + if (!fltParticipantIfc) + return false; + + int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + QString workspaceId = m_session->workspaceId(); + + std::shared_ptr symbolAppearanceSettings = + fltParticipantIfc->symbolAppearanceForOperator(operatorId, workspaceId); + + FilterManagement::SymbolAppearanceSettings::Settings settings = symbolAppearanceSettings->settings(); + + FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition usp = settings.symbolSettings.unitSymbolPosition; + + ParticipantManagement::UnitPosition up = m_ppmDtc->unitPosition(participantId); + if (up.participantId() != participantId) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << ", unitPosition failed for participantId=" << participantId; + return false; + } + + switch (usp) + { + case FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition::Center: + unitPositionOut = up.positionCenter(); + return true; + break; + case FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition::Leader: + unitPositionOut = up.positionLeader(); + return true; + break; + } + return false; - - int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - QString workspaceId = m_session->workspaceId(); - - std::shared_ptr symbolAppearanceSettings = - fltParticipantIfc->symbolAppearanceForOperator(operatorId, workspaceId); - - FilterManagement::SymbolAppearanceSettings::Settings settings = - symbolAppearanceSettings->settings(); - - FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition usp = - settings.symbolSettings.unitSymbolPosition; - - ParticipantManagement::UnitPosition up = m_ppmDtc->unitPosition(participantId); - if (up.participantId() != participantId) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << ", unitPosition failed for participantId=" << participantId; - return false; - } - - switch (usp) - { - case FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition::Center: - unitPositionOut = up.positionCenter(); - return true; - break; - case FilterManagement::SymbolAppearanceSettings::UnitSymbolPosition::Leader: - unitPositionOut = up.positionLeader(); - return true; - break; - } - - return false; } -void ParticipantsMoveDialog::doSetSimulatedPositionRequest(const ParticipantManagement::ParticipantData &participantData, const QPointF &coordinate) +void ParticipantsMoveDialog::doSetSimulatedPositionRequest( + const ParticipantManagement::ParticipantData& participantData, const QPointF& coordinate) { - - const int participantId = participantData.id(); - if (participantId <= 0) - return; - ParticipantManagement::SetSimulatedPosition req; - bool bAll = m_ui->cbAll->isChecked(); - bool bAskOutdated = true; - if (bAll) - req.participantId(-1); - else - { - const ParticipantManagement::TypeClass tc = m_ppmDtc->type(participantData.typeId()).typeClass(); + const int participantId = participantData.id(); + if (participantId <= 0) + return; - DEBUG_LOG(m_logger) << "ParticipantId=" << participantData.id() - << " EquipmentNr=" << participantData.equipmentNumber() - << " onGetCoordinate x=" << coordinate.x() << " y=" << coordinate.y() - << ", tc=" << tc; - if (participantData.id() <= 0) - return; - req.participantId(participantData.id()); + ParticipantManagement::SetSimulatedPosition req; + bool bAll = m_ui->cbAll->isChecked(); + bool bAskOutdated = true; + if (bAll) + req.participantId(-1); + else + { + const ParticipantManagement::TypeClass tc = m_ppmDtc->type(participantData.typeId()).typeClass(); - bAskOutdated = m_ppmDtc->type(participantData.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit; - } + DEBUG_LOG(m_logger) << "ParticipantId=" << participantData.id() + << " EquipmentNr=" << participantData.equipmentNumber() + << " onGetCoordinate x=" << coordinate.x() << " y=" << coordinate.y() << ", tc=" << tc; + if (participantData.id() <= 0) + return; + req.participantId(participantData.id()); - bool bOnlyOutdated = false; - if (bAskOutdated) - { - QHash texts({{LtsWidgets::Button::Yes, tr("All")}, - {LtsWidgets::Button::No, tr("Only outdated")} - }); - auto b = LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Do you want to move all participants or only outdated ones?"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No, - texts); - if (b == LtsWidgets::Button::Cancel) - return; + bAskOutdated = + m_ppmDtc->type(participantData.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit; + } - bOnlyOutdated = (b == LtsWidgets::Button::No); - } + bool bOnlyOutdated = false; + if (bAskOutdated) + { + QHash texts( + {{LtsWidgets::Button::Yes, tr("All")}, {LtsWidgets::Button::No, tr("Only outdated")}}); + auto b = LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Do you want to move all participants or only outdated ones?"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No, texts); + if (b == LtsWidgets::Button::Cancel) + return; - req.onlyOutdatedParticipants(bOnlyOutdated); - req.position(Core::GeoPosition(coordinate.x(), coordinate.y(), 0.0)); + bOnlyOutdated = (b == LtsWidgets::Button::No); + } - m_requestHelper->startSingleRequest([req, this]() - { - return m_ppmFtc->setSimulatedPositionRequest(req, this); - }); + req.onlyOutdatedParticipants(bOnlyOutdated); + req.position(Core::GeoPosition(coordinate.x(), coordinate.y(), 0.0)); + + m_requestHelper->startSingleRequest([req, this]() { return m_ppmFtc->setSimulatedPositionRequest(req, this); }); } - -void ParticipantsMoveDialog::doSetSimulatedPositionRelativeRequest(const ParticipantManagement::ParticipantData &participantData, const QPointF &coordinate) +void ParticipantsMoveDialog::doSetSimulatedPositionRelativeRequest( + const ParticipantManagement::ParticipantData& participantData, const QPointF& coordinate) { - - const int participantId = participantData.id(); - if (participantId <= 0) - return; - Core::GeoPosition unitPositionOut; - if (!getUnitPosition(participantId, unitPositionOut)) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition failed for participantId=" << participantId; - return; - } + const int participantId = participantData.id(); + if (participantId <= 0) + return; - INFO_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition for participantId=" << participantId - << ", unitPositionOut: lon=" << unitPositionOut.lon() << " - lat=" << unitPositionOut.lat(); + Core::GeoPosition unitPositionOut; + if (!getUnitPosition(participantId, unitPositionOut)) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition failed for participantId=" << participantId; + return; + } - LtsCoordTrans::UtmCoordinate curUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(unitPositionOut.lon(), unitPositionOut.lat()); - LtsCoordTrans::UtmCoordinate desiredUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(coordinate); - QPointF offset = desiredUnitPosUtm.relativeTo(curUnitPosUtm); + INFO_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition for participantId=" << participantId + << ", unitPositionOut: lon=" << unitPositionOut.lon() << " - lat=" << unitPositionOut.lat(); - if (offset.isNull()) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << ", required offset is zero. not expected... return"; - return; - } + LtsCoordTrans::UtmCoordinate curUnitPosUtm = + LtsCoordTrans::UtmCoordinate::fromGeographic(unitPositionOut.lon(), unitPositionOut.lat()); + LtsCoordTrans::UtmCoordinate desiredUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(coordinate); + QPointF offset = desiredUnitPosUtm.relativeTo(curUnitPosUtm); - ParticipantManagement::SetSimulatedPositionRelative req; - req.participantId(participantId); - req.positionOffsetX(offset.x()); - req.positionOffsetY(offset.y()); + if (offset.isNull()) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << ", required offset is zero. not expected... return"; + return; + } - DEBUG_LOG(m_logger) << "SetSimulatedPositionRelative = " << req; + ParticipantManagement::SetSimulatedPositionRelative req; + req.participantId(participantId); + req.positionOffsetX(offset.x()); + req.positionOffsetY(offset.y()); - m_requestHelper->startSingleRequest([req, this]() - { - return m_ppmFtc->setSimulatedPositionRelativeRequest(req, this); - }); + DEBUG_LOG(m_logger) << "SetSimulatedPositionRelative = " << req; + + m_requestHelper->startSingleRequest( + [req, this]() { return m_ppmFtc->setSimulatedPositionRelativeRequest(req, this); }); } -void ParticipantsMoveDialog::doSetSimulatedParticipantFormationRequest(const ParticipantManagement::ParticipantData &participantData, const QPointF &coordinate, const QString &formationData) +void ParticipantsMoveDialog::doSetSimulatedParticipantFormationRequest( + const ParticipantManagement::ParticipantData& participantData, const QPointF& coordinate, + const QString& formationData) { - - const int participantId = participantData.id(); - if (participantId <= 0) - return; - Core::GeoPosition unitPositionOut; - if (!getUnitPosition(participantId, unitPositionOut)) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition failed for participantId=" << participantId; - return; - } + const int participantId = participantData.id(); + if (participantId <= 0) + return; - INFO_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition for participantId=" << participantId - << ", unitPositionOut: lon=" << unitPositionOut.lon() << " - lat=" << unitPositionOut.lat(); + Core::GeoPosition unitPositionOut; + if (!getUnitPosition(participantId, unitPositionOut)) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition failed for participantId=" << participantId; + return; + } - LtsCoordTrans::UtmCoordinate curUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(unitPositionOut.lon(), unitPositionOut.lat()); - LtsCoordTrans::UtmCoordinate desiredUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(coordinate); - const QPointF offset = desiredUnitPosUtm.relativeTo(curUnitPosUtm); + INFO_LOG(m_logger) << Q_FUNC_INFO << ", getUnitPosition for participantId=" << participantId + << ", unitPositionOut: lon=" << unitPositionOut.lon() << " - lat=" << unitPositionOut.lat(); - if (offset.isNull()) - { - ERROR_LOG(m_logger) << Q_FUNC_INFO << ", required offset is zero. not expected... return"; - return; - } + LtsCoordTrans::UtmCoordinate curUnitPosUtm = + LtsCoordTrans::UtmCoordinate::fromGeographic(unitPositionOut.lon(), unitPositionOut.lat()); + LtsCoordTrans::UtmCoordinate desiredUnitPosUtm = LtsCoordTrans::UtmCoordinate::fromGeographic(coordinate); + const QPointF offset = desiredUnitPosUtm.relativeTo(curUnitPosUtm); - ParticipantManagement::SetSimulatedParticipantFormation req; - req.participantId(participantId); - req.position(Core::GeoPosition(coordinate.x(), coordinate.y(), 0.0)); - req.positionOffsetX(offset.x()); - req.positionOffsetY(offset.y()); - req.formation(formationData.toStdString()); + if (offset.isNull()) + { + ERROR_LOG(m_logger) << Q_FUNC_INFO << ", required offset is zero. not expected... return"; + return; + } - m_requestHelper->startSingleRequest([req, this]() - { - return m_ppmFtc->setSimulatedParticipantFormationRequest(req, this); - }); + ParticipantManagement::SetSimulatedParticipantFormation req; + req.participantId(participantId); + req.position(Core::GeoPosition(coordinate.x(), coordinate.y(), 0.0)); + req.positionOffsetX(offset.x()); + req.positionOffsetY(offset.y()); + req.formation(formationData.toStdString()); + + m_requestHelper->startSingleRequest( + [req, this]() { return m_ppmFtc->setSimulatedParticipantFormationRequest(req, this); }); } - -ParticipantManagement::ParticipantData ParticipantsMoveDialog::participantFromIndex(const QModelIndex &idx) const +ParticipantManagement::ParticipantData ParticipantsMoveDialog::participantFromIndex(const QModelIndex& idx) const { - return m_participantModel->getParticipantData(idx); + return m_participantModel->getParticipantData(idx); } -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.cpp old mode 100755 new mode 100644 index afad18139..e1454c2a7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.cpp @@ -1,73 +1,68 @@ - #include "participants_move_model.h" #include - namespace CentralEffectSimulation { -ParticipantMoveModel::ParticipantMoveModel(QObject *parent, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &asbIfc) - : ParticipantManagement::ParticipantEditModel(parent, ppmDtc, asbIfc) +ParticipantMoveModel::ParticipantMoveModel(QObject* parent, + const std::shared_ptr& ppmDtc, + const std::shared_ptr& asbIfc) + : ParticipantManagement::ParticipantEditModel(parent, ppmDtc, asbIfc) { - m_titles += tr("Simulated"); + m_titles += tr("Simulated"); - connect(m_dtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, - this, &ParticipantMoveModel::onParticipantChanged); + connect(m_dtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, this, + &ParticipantMoveModel::onParticipantChanged); - DEBUG_LOG(m_logger) << "ParticipantMoveModel::ParticipantMoveModel"; + DEBUG_LOG(m_logger) << "ParticipantMoveModel::ParticipantMoveModel"; } - -QVariant ParticipantMoveModel::data(const QModelIndex &index, int role) const +QVariant ParticipantMoveModel::data(const QModelIndex& index, int role) const { - - if (role == Qt::DisplayRole && index.column() == columnCount() - 1) - { - bool bIsSimulated = false; - if (!isSelectableBySimulation(index, &bIsSimulated)) - return QVariant(); - return bIsSimulated ? tr("Yes") : tr("No"); - } - return ParticipantManagement::ParticipantEditModel::data(index, role); + if (role == Qt::DisplayRole && index.column() == columnCount() - 1) + { + bool bIsSimulated = false; + if (!isSelectableBySimulation(index, &bIsSimulated)) + return QVariant(); + return bIsSimulated ? tr("Yes") : tr("No"); + } + + return ParticipantManagement::ParticipantEditModel::data(index, role); } -void ParticipantMoveModel::onParticipantChanged(const ParticipantManagement::Participant &data, DataModification modType) +void ParticipantMoveModel::onParticipantChanged(const ParticipantManagement::Participant& data, + DataModification modType) { - Q_UNUSED(modType) - if (data.partyId() != m_partyId) - return; - INFO_LOG(m_logger) << "onParticipantChanged isSimulated=" << data.isSimulated(); - onReinitModel(partyId()); - emit newData(); + Q_UNUSED(modType) + if (data.partyId() != m_partyId) + return; + INFO_LOG(m_logger) << "onParticipantChanged isSimulated=" << data.isSimulated(); + onReinitModel(partyId()); + emit newData(); } -bool ParticipantMoveModel::isSelectableBySimulation(const QModelIndex &index, bool *bIsSimulated) const +bool ParticipantMoveModel::isSelectableBySimulation(const QModelIndex& index, bool* bIsSimulated) const { - bool isSimulatable = true; - const ParticipantManagement::ParticipantData data(getParticipantData(index)); + bool isSimulatable = true; + const ParticipantManagement::ParticipantData data(getParticipantData(index)); - if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || - m_dtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) - isSimulatable = false; + if ((data.equipmentNumber().is_set() && data.equipmentNumber().get() > 0) || + m_dtc->type(data.typeId()).typeClass() == ParticipantManagement::TypeClass_def::Unit) + isSimulatable = false; - DEBUG_LOG(m_logger) << "ParticipantId: " << data.id() - << " isSimulated:" << data.isSimulated() - << " equipmentNo:" << data.equipmentNumber() - << " typeId=" << data.typeId() - << " modId=" << data.modId() - << " typeClass=" << m_dtc->type(data.typeId()).typeClass() - << " isSimulatable=" << isSimulatable; + DEBUG_LOG(m_logger) << "ParticipantId: " << data.id() << " isSimulated:" << data.isSimulated() + << " equipmentNo:" << data.equipmentNumber() << " typeId=" << data.typeId() + << " modId=" << data.modId() << " typeClass=" << m_dtc->type(data.typeId()).typeClass() + << " isSimulatable=" << isSimulatable; - if (bIsSimulated) - *bIsSimulated = data.isSimulated(); + if (bIsSimulated) + *bIsSimulated = data.isSimulated(); - return isSimulatable; + return isSimulatable; } -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.h old mode 100755 new mode 100644 index eee0d476a..36c63c1c1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantMove/participants_move_model.h @@ -1,36 +1,32 @@ - #pragma once -#include -#include -#include -#include - +#include "logger.h" #include -#include "logger.h" +#include +#include +#include +#include namespace CentralEffectSimulation { class ParticipantMoveModel final : public ParticipantManagement::ParticipantEditModel { - Q_OBJECT -public: - ParticipantMoveModel(QObject *parent, - const std::shared_ptr &ppmDtc, - const std::shared_ptr &asbIfc); + Q_OBJECT + public: + ParticipantMoveModel(QObject* parent, const std::shared_ptr& ppmDtc, + const std::shared_ptr& asbIfc); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -signals: - void newData(); + signals: + void newData(); -private: - -NGL::INGLLogger &m_logger; - void onParticipantChanged(const ParticipantManagement::Participant &data, DataModification modType); - bool isSelectableBySimulation(const QModelIndex &index, bool *bIsSimulated = nullptr) const; + private: + NGL::INGLLogger& m_logger; + void onParticipantChanged(const ParticipantManagement::Participant& data, DataModification modType); + bool isSelectableBySimulation(const QModelIndex& index, bool* bIsSimulated = nullptr) const; }; -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_dialog.cpp old mode 100755 new mode 100644 index 51882f070..bc712d442 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_dialog.cpp @@ -1,334 +1,322 @@ - -#include -#include -#include -#include -#include - #include "mission_plan_dialog.h" + #include "ui_mission_plan_dialog.h" +#include +#include +#include +#include +#include + namespace CentralEffectSimulation { -MissionPlanDialog::MissionPlanDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ppmDtc(nullptr) - , m_ppmFtc(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_session(nullptr) - , m_menuGroup(menuGroup) - , m_ui(new Ui::MissionPlanDialog) +MissionPlanDialog::MissionPlanDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ppmDtc(nullptr), m_ppmFtc(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_session(nullptr), m_menuGroup(menuGroup), + m_ui(new Ui::MissionPlanDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_updateMissionTimer.setSingleShot(true); - m_updateMissionTimer.setInterval(500); - connect(&m_updateMissionTimer, &QTimer::timeout, this, &MissionPlanDialog::enaDisa); + m_updateMissionTimer.setSingleShot(true); + m_updateMissionTimer.setInterval(500); + connect(&m_updateMissionTimer, &QTimer::timeout, this, &MissionPlanDialog::enaDisa); - setOnlineHelpFilename(QStringLiteral("Situation-UAS-Mission")); + setOnlineHelpFilename(QStringLiteral("Situation-UAS-Mission")); } MissionPlanDialog::~MissionPlanDialog() { - delete m_ui; + delete m_ui; } -bool MissionPlanDialog::init(LtsSession::LtsSession *session) +bool MissionPlanDialog::init(LtsSession::LtsSession* session) { - m_session = session; + m_session = session; - if (!m_session->getDtc(m_ppmDtc)) - { - ERROR_LOG(m_logger) << " failed to get ppmDtc"; - return false; - } - if (!m_session->getFtc(m_ppmFtc)) - { - ERROR_LOG(m_logger) << " failed to get ppmFtc"; - return false; - } + if (!m_session->getDtc(m_ppmDtc)) + { + ERROR_LOG(m_logger) << " failed to get ppmDtc"; + return false; + } + if (!m_session->getFtc(m_ppmFtc)) + { + ERROR_LOG(m_logger) << " failed to get ppmFtc"; + return false; + } - m_ppmDtc->enableUnitPosition(); - m_ppmDtc->waitForHistoricalDataUnitPosition(1000); + m_ppmDtc->enableUnitPosition(); + m_ppmDtc->waitForHistoricalDataUnitPosition(1000); + delete m_missionPlanModel; + m_missionPlanModel = new MissionPlanModel(this); + m_missionPlanModel->initModel(m_ppmDtc, m_session->exerciseId()); - delete m_missionPlanModel; - m_missionPlanModel = new MissionPlanModel(this); - m_missionPlanModel->initModel(m_ppmDtc, m_session->exerciseId()); + m_missionPlanProxyModel = new MissionPlanProxyModel(this); + m_missionPlanProxyModel->setSourceModel(m_missionPlanModel); + m_ui->participantsDataView->setModel(m_missionPlanProxyModel); - m_missionPlanProxyModel = new MissionPlanProxyModel(this); - m_missionPlanProxyModel->setSourceModel(m_missionPlanModel); - m_ui->participantsDataView->setModel(m_missionPlanProxyModel); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &MissionPlanDialog::onLockModifications); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Lock")); - m_buttonBox->setIcon(LtsWidgets::DialogButton::Load, QIcon(QStringLiteral("icon:drone_remote_connection.svg"))); - - m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->hide(); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &MissionPlanDialog::onUnlockModifications); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Unlock")); - m_buttonBox->setIcon(LtsWidgets::DialogButton::Save, QIcon(QStringLiteral("icon:drone_remote_connection.svg"))); - - m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->hide(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &MissionPlanDialog::onLockModifications); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->setText(tr("Lock")); + m_buttonBox->setIcon(LtsWidgets::DialogButton::Load, QIcon(QStringLiteral("icon:drone_remote_connection.svg"))); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MissionPlanDialog::onAddMissionPlan); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); + m_buttonBox->getButton(LtsWidgets::DialogButton::Load)->hide(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MissionPlanDialog::onEditMissionPlan); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &MissionPlanDialog::onUnlockModifications); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->setText(tr("Unlock")); + m_buttonBox->setIcon(LtsWidgets::DialogButton::Save, QIcon(QStringLiteral("icon:drone_remote_connection.svg"))); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MissionPlanDialog::onRemoveMissionPlanClicked); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Save)->hide(); - connect(m_ui->participantsDataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, &MissionPlanDialog::enaDisa); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &MissionPlanDialog::onAddMissionPlan); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); - const bool &hasOperatorRightParticipantUAS = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ParticipantMove); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(hasOperatorRightParticipantUAS); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setVisible(hasOperatorRightParticipantUAS); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MissionPlanDialog::onEditMissionPlan); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, - this, &MissionPlanDialog::onMissionPlanChanged); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &MissionPlanDialog::onRemoveMissionPlanClicked); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - connect(m_ui->participantsDataView, &LtsDataView::LtsDataView::doubleClicked, this, &MissionPlanDialog::onEditMissionPlan); + connect(m_ui->participantsDataView, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &MissionPlanDialog::enaDisa); - return true; + const bool& hasOperatorRightParticipantUAS = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ParticipantMove); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setVisible(hasOperatorRightParticipantUAS); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setVisible(hasOperatorRightParticipantUAS); + + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, this, + &MissionPlanDialog::onMissionPlanChanged); + + connect(m_ui->participantsDataView, &LtsDataView::LtsDataView::doubleClicked, this, + &MissionPlanDialog::onEditMissionPlan); + + return true; } -void MissionPlanDialog::onModifyMissionPlanReply(const Core::FunctionReplyObject &replyObject) +void MissionPlanDialog::onModifyMissionPlanReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -void MissionPlanDialog::onRemoveMissionPlanReply(const Core::FunctionReplyObject &replyObject) +void MissionPlanDialog::onRemoveMissionPlanReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } void MissionPlanDialog::retranslate() { - translate(m_ui, tr("UAS Mission Plans")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Edit")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Remove)->setText(tr("Delete")); + translate(m_ui, tr("UAS Mission Plans")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Edit")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Remove)->setText(tr("Delete")); } bool MissionPlanDialog::removeMissionPlan(int32_t missionplanId) { - if (missionplanId <= 0) - return false; + if (missionplanId <= 0) + return false; - ParticipantManagement::RemoveMissionPlanRequest req(missionplanId); - - m_requestHelper->startSingleRequest([req, this]() - { - return m_ppmFtc->removeMissionPlanRequest(req, this); - }); - return m_requestHelper->startRequests(); + ParticipantManagement::RemoveMissionPlanRequest req(missionplanId); + m_requestHelper->startSingleRequest([req, this]() { return m_ppmFtc->removeMissionPlanRequest(req, this); }); + return m_requestHelper->startRequests(); } -MissionPlanDialog::WayPointsStatus MissionPlanDialog::wayPointCurrentStatus(const ParticipantManagement::MissionPlan &mp) const +MissionPlanDialog::WayPointsStatus +MissionPlanDialog::wayPointCurrentStatus(const ParticipantManagement::MissionPlan& mp) const { - WayPointsStatus state = WayPointsStatus::Undefined; - - if (mp.missionStart() > m_session->partitionTime()) - return WayPointsStatus::Prepared; - else if (mp.itemsFulfilled() != static_cast(mp.items().size())) - return WayPointsStatus::Active; - else if (mp.itemsFulfilled() == static_cast(mp.items().size())) - return WayPointsStatus::Expired; + WayPointsStatus state = WayPointsStatus::Undefined; - - WARNING_LOG(m_logger)<<" -- Status Wegpunktkette Abgebrochen muss definiert werden"; + if (mp.missionStart() > m_session->partitionTime()) + return WayPointsStatus::Prepared; + else if (mp.itemsFulfilled() != static_cast(mp.items().size())) + return WayPointsStatus::Active; + else if (mp.itemsFulfilled() == static_cast(mp.items().size())) + return WayPointsStatus::Expired; - return state; + WARNING_LOG(m_logger) << " -- Status Wegpunktkette Abgebrochen muss definiert werden"; + + return state; } bool MissionPlanDialog::canBeLocked() const { - auto missionPlan = currentMissionPlan(); - if (missionPlan.id()<= 0) + auto missionPlan = currentMissionPlan(); + if (missionPlan.id() <= 0) + return false; + + const auto wpStatus = wayPointCurrentStatus(missionPlan); + const auto uas = m_ppmDtc->getUasByParticipantId(missionPlan.participantId(), m_session->exerciseId()); + + if (uas.uasState() == ProjectDataManagement::UasState_def::Manual || wpStatus == WayPointsStatus::Active) + return true; + return false; - - const auto wpStatus = wayPointCurrentStatus(missionPlan); - const auto uas = m_ppmDtc->getUasByParticipantId(missionPlan.participantId(), m_session->exerciseId()); - - if (uas.uasState() == ProjectDataManagement::UasState_def::Manual - || wpStatus == WayPointsStatus::Active ) - return true; - - return false; } bool MissionPlanDialog::canBeUnlocked() const { - auto missionPlan = currentMissionPlan(); - if (missionPlan.id()<= 0) + auto missionPlan = currentMissionPlan(); + if (missionPlan.id() <= 0) + return false; + if (missionPlan.aborted()) + return false; + + const auto wpStatus = wayPointCurrentStatus(missionPlan); + const auto uas = m_ppmDtc->getUasByParticipantId(missionPlan.participantId(), m_session->exerciseId()); + + if (uas.uasState() == ProjectDataManagement::UasState_def::Manual || wpStatus != WayPointsStatus::Active) + return true; + return false; - if (missionPlan.aborted()) - return false; - - const auto wpStatus = wayPointCurrentStatus(missionPlan); - const auto uas = m_ppmDtc->getUasByParticipantId(missionPlan.participantId(), m_session->exerciseId()); - - if ( uas.uasState() == ProjectDataManagement::UasState_def::Manual - || wpStatus != WayPointsStatus::Active) - return true; - - return false; } -MissionPlanEdit *MissionPlanDialog::currentMissionPlanEditor() const +MissionPlanEdit* MissionPlanDialog::currentMissionPlanEditor() const { - QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - if (indexList.isEmpty()) - return nullptr; + QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + if (indexList.isEmpty()) + return nullptr; - const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); - if (mp.id() < 0) - return nullptr; + const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); + if (mp.id() < 0) + return nullptr; - return m_participantUasEditMap.value(mp.participantId(), nullptr); + return m_participantUasEditMap.value(mp.participantId(), nullptr); } ParticipantManagement::MissionPlan MissionPlanDialog::currentMissionPlan() const { - QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - if (indexList.isEmpty()) - return {}; + QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + if (indexList.isEmpty()) + return {}; - return m_missionPlanModel->getRowData(indexList.front().row()); + return m_missionPlanModel->getRowData(indexList.front().row()); } void MissionPlanDialog::tableColumnOrganiserSetting() { - - m_ui->participantsDataView->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->participantsDataView->setColumnsOrganiserEnabled(identifier(), true); } void MissionPlanDialog::enaDisa() { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - bool bOk = !indexList.isEmpty(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + bool bOk = !indexList.isEmpty(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bOk); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, bOk); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, bOk && canBeLocked()); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, bOk && canBeUnlocked()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, bOk); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, bOk); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, bOk && canBeLocked()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, bOk && canBeUnlocked()); } void MissionPlanDialog::onUnlockModifications() { - auto dialog = currentMissionPlanEditor(); - if (!dialog) - return; + auto dialog = currentMissionPlanEditor(); + if (!dialog) + return; - if (canBeUnlocked()) - dialog->setAllUiElementsEnabled(true); - else - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Cannot unlock selected Mission Plan:\n mission plan still activ")); + if (canBeUnlocked()) + dialog->setAllUiElementsEnabled(true); + else + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Cannot unlock selected Mission Plan:\n mission plan still activ")); } void MissionPlanDialog::onLockModifications() { - auto dialog = currentMissionPlanEditor(); - if (!dialog) - return; - - if (canBeLocked()) - dialog->setAllUiElementsEnabled(false); - else { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Cannot Lock selected Mission Plan.")); - } + auto dialog = currentMissionPlanEditor(); + if (!dialog) + return; + if (canBeLocked()) + dialog->setAllUiElementsEnabled(false); + else + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Cannot Lock selected Mission Plan.")); + } } - void MissionPlanDialog::onAddMissionPlan() { - static QString newMissionPlanIdentifier(QStringLiteral("NewMissionPlan")); + static QString newMissionPlanIdentifier(QStringLiteral("NewMissionPlan")); - - const QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - if (indexList.isEmpty()) - { - addDialog(LtsWidgets::initDialog(new MissionPlanEdit(this), 0, m_session), - m_menuGroup, newMissionPlanIdentifier, LtsWidgets::LayoutArea::eDialogTab); - return; - } + const QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + if (indexList.isEmpty()) + { + addDialog(LtsWidgets::initDialog(new MissionPlanEdit(this), 0, m_session), m_menuGroup, + newMissionPlanIdentifier, LtsWidgets::LayoutArea::eDialogTab); + return; + } - const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); - if (mp.id() <= 0) - { - return; - } + const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); + if (mp.id() <= 0) + { + return; + } - addDialog(LtsWidgets::initDialog(new MissionPlanEdit(this), mp.id(), m_session, true ), - m_menuGroup, newMissionPlanIdentifier, LtsWidgets::LayoutArea::eDialogTab); + addDialog(LtsWidgets::initDialog(new MissionPlanEdit(this), mp.id(), m_session, true), m_menuGroup, + newMissionPlanIdentifier, LtsWidgets::LayoutArea::eDialogTab); } void MissionPlanDialog::onRemoveMissionPlanClicked() { - const QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - const bool isOne = (indexList.size() == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + const QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + const bool isOne = (indexList.size() == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, isOne); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - if (!isOne) - return; - const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); + if (!isOne) + return; + const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); - delete m_participantUasEditMap.value(mp.id()); - m_participantUasEditMap.remove(mp.id()); - removeMissionPlan(mp.id()); + delete m_participantUasEditMap.value(mp.id()); + m_participantUasEditMap.remove(mp.id()); + removeMissionPlan(mp.id()); } void MissionPlanDialog::onEditMissionPlan() { - QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); - if (indexList.isEmpty()) - return; + QModelIndexList indexList = m_ui->participantsDataView->selectedRows(); + if (indexList.isEmpty()) + return; - const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); - if (mp.id() <= 0) - return; + const ParticipantManagement::MissionPlan mp = m_missionPlanModel->getRowData(indexList.front().row()); + if (mp.id() <= 0) + return; - const QString dialogIdentifier = QStringLiteral("Edit-MissionPlan_%1").arg(mp.id()); - - if (!m_participantUasEditMap.contains(mp.participantId())) - { - MissionPlanEdit *dialog = new MissionPlanEdit(this); - m_participantUasEditMap.insert(mp.participantId(), dialog); - connect(dialog, &MissionPlanEdit::editUasDialogClosed, this, &MissionPlanDialog::onEditDialogClosed); - addDialog(LtsWidgets::initDialog(dialog, mp.id(), m_session) - , m_menuGroup - , dialogIdentifier - , LtsWidgets::LayoutArea::eDialogTab); - } - else - focusDialog(m_menuGroup, dialogIdentifier, LtsWidgets::LayoutArea::eDialogTab); + const QString dialogIdentifier = QStringLiteral("Edit-MissionPlan_%1").arg(mp.id()); + if (!m_participantUasEditMap.contains(mp.participantId())) + { + MissionPlanEdit* dialog = new MissionPlanEdit(this); + m_participantUasEditMap.insert(mp.participantId(), dialog); + connect(dialog, &MissionPlanEdit::editUasDialogClosed, this, &MissionPlanDialog::onEditDialogClosed); + addDialog(LtsWidgets::initDialog(dialog, mp.id(), m_session), m_menuGroup, dialogIdentifier, + LtsWidgets::LayoutArea::eDialogTab); + } + else + focusDialog(m_menuGroup, dialogIdentifier, LtsWidgets::LayoutArea::eDialogTab); } void MissionPlanDialog::onEditDialogClosed(const int participantId) { - m_participantUasEditMap.remove(participantId); + m_participantUasEditMap.remove(participantId); } -void MissionPlanDialog::onMissionPlanChanged(const ParticipantManagement::MissionPlan &data, const DataModification modType) +void MissionPlanDialog::onMissionPlanChanged(const ParticipantManagement::MissionPlan& data, + const DataModification modType) { - Q_UNUSED(data) - Q_UNUSED(modType) - m_updateMissionTimer.start(); + Q_UNUSED(data) + Q_UNUSED(modType) + m_updateMissionTimer.start(); } - -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_edit.cpp old mode 100755 new mode 100644 index 9a6e02f1d..af6752882 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_edit.cpp @@ -1,820 +1,761 @@ +#include "mission_plan_edit.h" + +#include "ui_mission_plan_edit.h" -#include -#include #include +#include +#include +#include #include #include - +#include +#include #include #include -#include - -#include -#include -#include #include -#include - -#include +#include #include #include #include -#include "mission_plan_edit.h" -#include "ui_mission_plan_edit.h" +#include namespace CentralEffectSimulation { - - -MissionPlanEdit::MissionPlanEdit(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_missionPlanId(0) - , m_uiEnabled(false) - , m_sitMapGuiIfc(nullptr) - , m_ppmCbxGui(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_participantTimer(new QTimer(this)) - , m_ui(new Ui::MissionPlanEdit) +MissionPlanEdit::MissionPlanEdit(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_missionPlanId(0), + m_uiEnabled(false), m_sitMapGuiIfc(nullptr), m_ppmCbxGui(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_participantTimer(new QTimer(this)), + m_ui(new Ui::MissionPlanEdit) { - m_ui->setupUi(this); - m_ui->nameLineEdit->clear(); - m_ui->lePrefix->setText(tr("Waypoint")); - m_uiRequirements->addRequirement({m_ui->lblMoveStart, [this]() { return hasValidEffectStart(m_ui->dteStartTime); }, tr("Begin time is smaller than current time")}); - m_uiRequirements->addRequirement({m_ui->lblUASParty, [this]() {return ( !m_ui->cbParty->currentData().isNull());}}); - m_uiRequirements->addRequirement({m_ui->lblUasParticipant, [this]() {return ( !m_ui->participantCBox->currentData().isNull());}}); + m_ui->setupUi(this); + m_ui->nameLineEdit->clear(); + m_ui->lePrefix->setText(tr("Waypoint")); + m_uiRequirements->addRequirement({m_ui->lblMoveStart, [this]() { return hasValidEffectStart(m_ui->dteStartTime); }, + tr("Begin time is smaller than current time")}); + m_uiRequirements->addRequirement( + {m_ui->lblUASParty, [this]() { return (!m_ui->cbParty->currentData().isNull()); }}); + m_uiRequirements->addRequirement( + {m_ui->lblUasParticipant, [this]() { return (!m_ui->participantCBox->currentData().isNull()); }}); - if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) - { - m_uiRequirements->addRequirement({m_ui->lblParticipantStateText, [this]() { return m_participantReady; }}); - } + if (!QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier)) + { + m_uiRequirements->addRequirement({m_ui->lblParticipantStateText, [this]() { return m_participantReady; }}); + } - connect(this, &MissionPlanEdit::signalFocused, this, &MissionPlanEdit::onFocus); - m_participantTimer->setSingleShot(true); - m_participantTimer->setInterval(500); + connect(this, &MissionPlanEdit::signalFocused, this, &MissionPlanEdit::onFocus); + m_participantTimer->setSingleShot(true); + m_participantTimer->setInterval(500); - connect(m_participantTimer, &QTimer::timeout, this, &MissionPlanEdit::onParticipantTimerTimedout); + connect(m_participantTimer, &QTimer::timeout, this, &MissionPlanEdit::onParticipantTimerTimedout); - setOnlineHelpFilename(QStringLiteral("Situation-UAS-Mission-Edit")); + setOnlineHelpFilename(QStringLiteral("Situation-UAS-Mission-Edit")); } MissionPlanEdit::~MissionPlanEdit() { - m_sitMapGuiIfc = nullptr; - delete m_ui; - emit editUasDialogClosed(m_participantData.id()); + m_sitMapGuiIfc = nullptr; + delete m_ui; + emit editUasDialogClosed(m_participantData.id()); } -bool MissionPlanEdit::init(const int missionPlanId, LtsSession::LtsSessionDataDds *session, bool asCopy) +bool MissionPlanEdit::init(const int missionPlanId, LtsSession::LtsSessionDataDds* session, bool asCopy) { - m_session = session; - m_missionPlanId = missionPlanId; + m_session = session; + m_missionPlanId = missionPlanId; - if (!m_session->getDtc(m_pdmDtc)) - { - ERROR_LOG(m_logger) << " failed to get pdmDtc"; - return false; - } - if (!m_session->getDtc(m_ppmDtc)) - { - ERROR_LOG(m_logger) << " failed to get ppmDtc"; - return false; - } - if (!m_session->getFtc(m_ppmFtc)) - { - ERROR_LOG(m_logger) << " failed to get ppmFtc"; - return false; - } - if (!m_session->getForeignGuiInterface(m_ppmCbxGui)) - { - ERROR_LOG(m_logger) << " failed to get ppmCbxGui"; - return false; - } - - m_ui->cbJumpToStart->hide(); - m_ui->cbRepeat->hide(); - - - - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Start Now")); - m_buttonBox->setIcon(LtsWidgets::DialogButton::Edit, QIcon(QStringLiteral("icon:media-play.svg"))); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MissionPlanEdit::onApplyNow); - - m_missionPlan = m_ppmDtc->missionPlan(m_missionPlanId); - auto cb = [this, asCopy](const ParticipantManagement::MissionPlan &mission) - { - - - if ((((mission.participantId() == m_missionPlan.participantId()) && !asCopy ) || mission.participantId() <= 0) - && mission.missionStart() <= m_missionPlan.missionStart() && !mission.aborted()) - return; - - if (static_cast(mission.items().size()) == mission.itemsFulfilled() || mission.aborted()) - return; - - m_usedUasSet.insert(mission.participantId()); - }; - m_ppmDtc->missionPlans(cb); - - m_ppmDtc->waitForHistoricalDataParty(1000); - m_ppmDtc->waitForHistoricalDataUAS(1000); - m_ppmDtc->waitForHistoricalDataParticipant(1000); - - - connect(m_ui->participantCBox, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int ) - { - setReady(false); - const auto pId = m_ui->participantCBox->currentData().toInt(); - m_participant = m_ppmDtc->participant(pId); - const auto dpd = m_ppmDtc->dynamicParticipantData(m_participant.id()); - DEBUG_LOG(m_logger) << "idx changed! pId: " << pId << ", m_participant.id(): " << m_participant.id() << ", dpd.participantId(): " << dpd.participantId(); - - if (dpd.participantId() < 1) + if (!m_session->getDtc(m_pdmDtc)) { - ERROR_LOG(m_logger) << "no dynamic pdata yet for pId " << pId; - setReady(false); - return; + ERROR_LOG(m_logger) << " failed to get pdmDtc"; + return false; + } + if (!m_session->getDtc(m_ppmDtc)) + { + ERROR_LOG(m_logger) << " failed to get ppmDtc"; + return false; + } + if (!m_session->getFtc(m_ppmFtc)) + { + ERROR_LOG(m_logger) << " failed to get ppmFtc"; + return false; + } + if (!m_session->getForeignGuiInterface(m_ppmCbxGui)) + { + ERROR_LOG(m_logger) << " failed to get ppmCbxGui"; + return false; } - DEBUG_LOG(m_logger) << "calling onDynamicParticipantDataChanged !"; - onDynamicParticipantDataChanged(dpd, DataModification::eAdded); - }); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, - this, &MissionPlanEdit::onDynamicParticipantDataChanged); + m_ui->cbJumpToStart->hide(); + m_ui->cbRepeat->hide(); + m_session->getForeignGuiInterface(m_sitMapGuiIfc); + m_buttonBox->setText(LtsWidgets::DialogButton::Edit, tr("Start Now")); + m_buttonBox->setIcon(LtsWidgets::DialogButton::Edit, QIcon(QStringLiteral("icon:media-play.svg"))); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &MissionPlanEdit::onApplyNow); - connect(m_ui->cbParty, QOverload::of(&QComboBox::currentIndexChanged), - this, &MissionPlanEdit::onPartyChanged); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::uASChanged, - this, &MissionPlanEdit::onUasChanged); - - fillParties(); - setUASCharges(); + m_missionPlan = m_ppmDtc->missionPlan(m_missionPlanId); + auto cb = [this, asCopy](const ParticipantManagement::MissionPlan& mission) { + if ((((mission.participantId() == m_missionPlan.participantId()) && !asCopy) || mission.participantId() <= 0) && + mission.missionStart() <= m_missionPlan.missionStart() && !mission.aborted()) + return; - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, - this, &MissionPlanEdit::onMissionPlanChanged); + if (static_cast(mission.items().size()) == mission.itemsFulfilled() || mission.aborted()) + return; + m_usedUasSet.insert(mission.participantId()); + }; + m_ppmDtc->missionPlans(cb); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, - this, &MissionPlanEdit::onParticipantChanged); - if (m_sitMapGuiIfc) - { - connect(m_ui->pbPosition, &QPushButton::clicked, this, &MissionPlanEdit::onGetPolyline); - connect(m_ui->pbClear, &QPushButton::clicked, this, &MissionPlanEdit::clearCoordinates); - } - else - { - m_ui->pbPosition->setEnabled(false); - m_ui->pbClear->setEnabled(false); - } + m_ppmDtc->waitForHistoricalDataParty(1000); + m_ppmDtc->waitForHistoricalDataUAS(1000); + m_ppmDtc->waitForHistoricalDataParticipant(1000); - - setData(missionPlanId); + connect(m_ui->participantCBox, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int) { + setReady(false); + const auto pId = m_ui->participantCBox->currentData().toInt(); + m_participant = m_ppmDtc->participant(pId); + const auto dpd = m_ppmDtc->dynamicParticipantData(m_participant.id()); + DEBUG_LOG(m_logger) << "idx changed! pId: " << pId << ", m_participant.id(): " << m_participant.id() + << ", dpd.participantId(): " << dpd.participantId(); - enaDisa(); + if (dpd.participantId() < 1) + { + ERROR_LOG(m_logger) << "no dynamic pdata yet for pId " << pId; + setReady(false); + return; + } - if(m_participant.id() <= 0 ) - setReady(false); + DEBUG_LOG(m_logger) << "calling onDynamicParticipantDataChanged !"; + onDynamicParticipantDataChanged(dpd, DataModification::eAdded); + }); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::dynamicParticipantDataChanged, this, + &MissionPlanEdit::onDynamicParticipantDataChanged); - if (m_missionPlanId > 0 && m_session->partitionTime() > m_missionPlan.missionStart() && !asCopy) - { - enableUiElements(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(false); - } + connect(m_ui->cbParty, QOverload::of(&QComboBox::currentIndexChanged), this, &MissionPlanEdit::onPartyChanged); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::uASChanged, this, &MissionPlanEdit::onUasChanged); - if (asCopy) - { - m_missionPlanId = 0; - - if (m_ui->participantCBox->currentIndex()<0) - m_ui->participantCBox->setCurrentIndex(0); - } + fillParties(); + setUASCharges(); - return true; + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, this, + &MissionPlanEdit::onMissionPlanChanged); + + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::participantChanged, this, + &MissionPlanEdit::onParticipantChanged); + if (m_sitMapGuiIfc) + { + connect(m_ui->pbPosition, &QPushButton::clicked, this, &MissionPlanEdit::onGetPolyline); + connect(m_ui->pbClear, &QPushButton::clicked, this, &MissionPlanEdit::clearCoordinates); + } + else + { + m_ui->pbPosition->setEnabled(false); + m_ui->pbClear->setEnabled(false); + } + + setData(missionPlanId); + + enaDisa(); + + if (m_participant.id() <= 0) + setReady(false); + + if (m_missionPlanId > 0 && m_session->partitionTime() > m_missionPlan.missionStart() && !asCopy) + { + enableUiElements(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(false); + } + + if (asCopy) + { + m_missionPlanId = 0; + + if (m_ui->participantCBox->currentIndex() < 0) + m_ui->participantCBox->setCurrentIndex(0); + } + + return true; } void MissionPlanEdit::retranslate() { - translate(m_ui, ((m_missionPlanId <= 0) ? QString() : QString::fromStdString(m_missionPlan.name())), m_missionPlanId <= 0, tr("UAS-Waypoints")); + translate(m_ui, ((m_missionPlanId <= 0) ? QString() : QString::fromStdString(m_missionPlan.name())), + m_missionPlanId <= 0, tr("UAS-Waypoints")); } - void MissionPlanEdit::setReady(bool isReady) { - m_participantReady = isReady; - m_ui->lblParticipantState->setText(QStringLiteral("%2") - .arg(isReady ? QStringLiteral("00dd00") : QStringLiteral("dd0000")) - .arg(isReady ? tr("Ready") : tr("Not ready"))); + m_participantReady = isReady; + m_ui->lblParticipantState->setText(QStringLiteral("%2") + .arg(isReady ? QStringLiteral("00dd00") : QStringLiteral("dd0000")) + .arg(isReady ? tr("Ready") : tr("Not ready"))); } - -void MissionPlanEdit::onDynamicParticipantDataChanged(const ParticipantManagement::DynamicParticipantData &data, DataModification modType) +void MissionPlanEdit::onDynamicParticipantDataChanged(const ParticipantManagement::DynamicParticipantData& data, + DataModification modType) { - if (data.participantId() != m_participant.id() && data.participantId() != 0) - { - ERROR_LOG(m_logger) << "### " << data.participantId() << " != " << m_participant.id() << " (" << (int)modType << ")"; - return; - } - - DEBUG_LOG(m_logger) << "### " << data.participantId() << " == " << m_participant.id() << " (" << (int)modType << ") !!!"; - - - - if (modType == DataModification::eRemoved) - { - return; - } - - - if (data.stateHistory().empty()) - { - setReady(false); - return; - } - - const auto &history = data.stateHistory(); - - - - auto lastState = m_ppmDtc->youngestStateInformation(history ); - decltype(lastState) youngestState; - youngestState.stateTime(0); - for (const auto &si : history) - { - DEBUG_LOG(m_logger) << "StateInformation " - << " time=" << si.stateTime() - << " vulnerabilityBits=" << si.vulnerabilityBits() - << " vulnerabilityKindId=" << si.vulnerabilityKindId(); - if ( youngestState.stateTime() < si.stateTime()) - youngestState = si; - } - - setReady(youngestState.vulnerabilityState() == ProjectDataManagement::VulnerabilityState::CombatReady); -} - -void MissionPlanEdit::onMissionPlanChanged(const ParticipantManagement::MissionPlan &data, const DataModification modType) -{ - Q_UNUSED(modType) - if (data.id() != m_missionPlanId) - { - - if (static_cast(data.items().size()) != data.itemsFulfilled()) - return; - if (m_usedUasSet.contains(data.participantId())) + if (data.participantId() != m_participant.id() && data.participantId() != 0) { - m_usedUasSet.remove(data.participantId()); - fillParticipants(); + ERROR_LOG(m_logger) << "### " << data.participantId() << " != " << m_participant.id() << " (" << (int)modType + << ")"; + return; } - return; - } - bool enabled; - if (m_session->partitionTime() > m_missionPlan.missionStart() && !m_missionPlan.aborted()) - enabled = false; - else - enabled = true; + DEBUG_LOG(m_logger) << "### " << data.participantId() << " == " << m_participant.id() << " (" << (int)modType + << ") !!!"; - enableUiElements(enabled); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(enabled); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(enabled); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(enabled); + if (modType == DataModification::eRemoved) + { + return; + } - if (static_cast(data.items().size()) == data.itemsFulfilled() - && m_usedUasSet.remove(data.participantId())) - fillParticipants(); + if (data.stateHistory().empty()) + { + setReady(false); + return; + } + const auto& history = data.stateHistory(); + + auto lastState = m_ppmDtc->youngestStateInformation(history); + decltype(lastState) youngestState; + youngestState.stateTime(0); + for (const auto& si : history) + { + DEBUG_LOG(m_logger) << "StateInformation " + << " time=" << si.stateTime() << " vulnerabilityBits=" << si.vulnerabilityBits() + << " vulnerabilityKindId=" << si.vulnerabilityKindId(); + if (youngestState.stateTime() < si.stateTime()) + youngestState = si; + } + + setReady(youngestState.vulnerabilityState() == ProjectDataManagement::VulnerabilityState::CombatReady); } -void MissionPlanEdit::onModifyMissionPlanReply(const Core::FunctionReplyObject &replyObject) +void MissionPlanEdit::onMissionPlanChanged(const ParticipantManagement::MissionPlan& data, + const DataModification modType) { - m_requestHelper->requestReply(replyObject); - if (!replyObject.error()) - m_sitMapGuiIfc->removePreviewObject(); + Q_UNUSED(modType) + if (data.id() != m_missionPlanId) + { + + if (static_cast(data.items().size()) != data.itemsFulfilled()) + return; + if (m_usedUasSet.contains(data.participantId())) + { + m_usedUasSet.remove(data.participantId()); + fillParticipants(); + } + return; + } + + bool enabled; + if (m_session->partitionTime() > m_missionPlan.missionStart() && !m_missionPlan.aborted()) + enabled = false; + else + enabled = true; + + enableUiElements(enabled); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(enabled); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(enabled); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(enabled); + + if (static_cast(data.items().size()) == data.itemsFulfilled() && m_usedUasSet.remove(data.participantId())) + fillParticipants(); } -void MissionPlanEdit::onSetMissionActionFulfilledReply(const Core::FunctionReplyObject &replyObject) +void MissionPlanEdit::onModifyMissionPlanReply(const Core::FunctionReplyObject& replyObject) { - DEBUG_LOG(m_logger)<<" -- MissionPlanEdit - onSetMissionActionFulfilledReply: "<requestReply(replyObject); + if (!replyObject.error()) + m_sitMapGuiIfc->removePreviewObject(); +} + +void MissionPlanEdit::onSetMissionActionFulfilledReply(const Core::FunctionReplyObject& replyObject) +{ + DEBUG_LOG(m_logger) << " -- MissionPlanEdit - onSetMissionActionFulfilledReply: " << replyObject.error(); } QStringList MissionPlanEdit::tableColLabelList() const { - QStringList wayPointsHeaders; - wayPointsHeaders << tr("Identifier") - << tr("Position") - << tr("Altitude") - << tr("Idle Time [s]") - << tr("Charges"); - return wayPointsHeaders; + QStringList wayPointsHeaders; + wayPointsHeaders << tr("Identifier") << tr("Position") << tr("Altitude") << tr("Idle Time [s]") << tr("Charges"); + return wayPointsHeaders; } void MissionPlanEdit::setAllUiElementsEnabled(bool enable) { - enableUiElements(enable); + enableUiElements(enable); } ParticipantManagement::MissionPlan MissionPlanEdit::missionPlan() const { - return m_missionPlan; + return m_missionPlan; } bool MissionPlanEdit::isUiEnabled() const { - return m_uiEnabled; + return m_uiEnabled; } + void MissionPlanEdit::enaDisa() { - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0)); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled((m_ui->tableWidget->rowCount() > 0)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled((m_ui->tableWidget->rowCount() > 0)); } bool MissionPlanEdit::apply() { - - ParticipantManagement::UAS uasP = m_ppmDtc->getUasByParticipantId(m_ui->participantCBox->currentData().toInt(), m_session->exerciseId()); - if (uasP.uasState() == ProjectDataManagement::UasState_def::Manual - && uasP.participantId() != m_missionPlan.participantId()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Waypoints can't be saved!: Uas switched to %1-Mode").arg(ProjectDataManagement::toString(uasP.uasState()))); - return false; - } - ParticipantManagement::ModifyMissionPlanRequest req; - req.id(m_missionPlanId); - req.missionStart(m_ui->dteStartTime->msecsSinceEpoch()); - req.participantId(m_ui->participantCBox->currentData().toInt()); - req.jumpToStart(false); - req.repeat(false); - req.name(m_ui->nameLineEdit->text().toStdString()); - req.items(itemsRequestContent()); + ParticipantManagement::UAS uasP = + m_ppmDtc->getUasByParticipantId(m_ui->participantCBox->currentData().toInt(), m_session->exerciseId()); - return m_requestHelper->startSingleRequest([this, req]() - { - return m_ppmFtc->modifyMissionPlanRequest(req, this); - }); + if (uasP.uasState() == ProjectDataManagement::UasState_def::Manual && + uasP.participantId() != m_missionPlan.participantId()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Waypoints can't be saved!: Uas switched to %1-Mode") + .arg(ProjectDataManagement::toString(uasP.uasState()))); + return false; + } + ParticipantManagement::ModifyMissionPlanRequest req; + req.id(m_missionPlanId); + req.missionStart(m_ui->dteStartTime->msecsSinceEpoch()); + req.participantId(m_ui->participantCBox->currentData().toInt()); + req.jumpToStart(false); + req.repeat(false); + req.name(m_ui->nameLineEdit->text().toStdString()); + req.items(itemsRequestContent()); + return m_requestHelper->startSingleRequest([this, req]() { return m_ppmFtc->modifyMissionPlanRequest(req, this); }); } void MissionPlanEdit::clearCoordinates() { - if (m_ui) - { - m_ui->tableWidget->clearContents(); - m_ui->tableWidget->setRowCount(0); - enaDisa(); - } - - if ( m_sitMapGuiIfc && this->amIFocused()) - m_sitMapGuiIfc->removePreviewObject(); + if (m_ui) + { + m_ui->tableWidget->clearContents(); + m_ui->tableWidget->setRowCount(0); + enaDisa(); + } + + if (m_sitMapGuiIfc && this->amIFocused()) + m_sitMapGuiIfc->removePreviewObject(); } void MissionPlanEdit::clearContent() { - m_ui->lePrefix->clear(); - m_ui->cbRepeat->setChecked(false); - + m_ui->lePrefix->clear(); + m_ui->cbRepeat->setChecked(false); - clearCoordinates(); + clearCoordinates(); } void MissionPlanEdit::enableUiElements(bool enable) { - m_ui->tableWidget->setEnabled(enable); - m_ui->pbPosition->setEnabled(enable); - m_ui->pbClear->setEnabled(enable); - m_ui->spIdleTime->setEnabled(enable); - m_ui->dteStartTime->setEnabled(enable); - m_ui->cbParty->setEnabled(enable); - m_ui->participantCBox->setEnabled(enable); - m_ui->chargesCBox->setEnabled(enable); - m_ui->nameLineEdit->setEnabled(enable); - m_ui->lePrefix->setEnabled(enable); - m_ui->cbRepeat->setEnabled(enable); - m_ui->cbJumpToStart->setEnabled(enable); - m_ui->spAltitude->setEnabled(false); - m_uiEnabled = enable; + m_ui->tableWidget->setEnabled(enable); + m_ui->pbPosition->setEnabled(enable); + m_ui->pbClear->setEnabled(enable); + m_ui->spIdleTime->setEnabled(enable); + m_ui->dteStartTime->setEnabled(enable); + m_ui->cbParty->setEnabled(enable); + m_ui->participantCBox->setEnabled(enable); + m_ui->chargesCBox->setEnabled(enable); + m_ui->nameLineEdit->setEnabled(enable); + m_ui->lePrefix->setEnabled(enable); + m_ui->cbRepeat->setEnabled(enable); + m_ui->cbJumpToStart->setEnabled(enable); + m_ui->spAltitude->setEnabled(false); + m_uiEnabled = enable; - - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0 && !enable)); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled((m_ui->tableWidget->rowCount() > 0 && !enable)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0 && !enable)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled((m_ui->tableWidget->rowCount() > 0 && !enable)); } -bool MissionPlanEdit::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit *dte) const -{ - const bool bEmptyAllowed = dte->isCheckable(); - const auto ms = dte->msecsSinceEpoch(); - - if (bEmptyAllowed && ms == 0) - return true; - return ms > m_session->partitionTime(); +bool MissionPlanEdit::hasValidEffectStart(LtsWidgets::LtsDateTimeEdit* dte) const +{ + const bool bEmptyAllowed = dte->isCheckable(); + const auto ms = dte->msecsSinceEpoch(); + + if (bEmptyAllowed && ms == 0) + return true; + return ms > m_session->partitionTime(); } void MissionPlanEdit::initTableHeader() { - m_ui->tableWidget->setColumnCount(tableColLabelList().count()); - m_ui->tableWidget->setHorizontalHeaderLabels(tableColLabelList()); - m_ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); + m_ui->tableWidget->setColumnCount(tableColLabelList().count()); + m_ui->tableWidget->setHorizontalHeaderLabels(tableColLabelList()); + m_ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); } -void MissionPlanEdit::insertPos(const WayPointParam &wpp) +void MissionPlanEdit::insertPos(const WayPointParam& wpp) { - const int rowCount = m_ui->tableWidget->rowCount(); - - m_ui->tableWidget->insertRow(rowCount); - QLineEdit *le = new QLineEdit; - le->setText(wpp.identifier); - m_ui->tableWidget->setCellWidget(rowCount, Name, le); + const int rowCount = m_ui->tableWidget->rowCount(); - - LtsCoordWidget::LtsCoordWidget *wdg = new LtsCoordWidget::LtsCoordWidget(); - wdg->setCoordinate(wpp.lon, wpp.lat); - wdg->setObjectName(QStringLiteral("positionEdit_") + QString::number(rowCount)); - wdg->setDisplayType(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS); - m_ui->tableWidget->setCellWidget(rowCount, Position, wdg); + m_ui->tableWidget->insertRow(rowCount); + QLineEdit* le = new QLineEdit; + le->setText(wpp.identifier); + m_ui->tableWidget->setCellWidget(rowCount, Name, le); - - QSpinBox *sbAltitude = new QSpinBox; - sbAltitude->setMinimum(0); - sbAltitude->setMaximum(120); - sbAltitude->setValue(wpp.z); - m_ui->tableWidget->setCellWidget(rowCount, Altitude, sbAltitude); + LtsCoordWidget::LtsCoordWidget* wdg = new LtsCoordWidget::LtsCoordWidget(); + wdg->setCoordinate(wpp.lon, wpp.lat); + wdg->setObjectName(QStringLiteral("positionEdit_") + QString::number(rowCount)); + wdg->setDisplayType(LtsCoordWidget::LtsCoordWidget::DisplayType::MGRS); + m_ui->tableWidget->setCellWidget(rowCount, Position, wdg); - - QSpinBox *sbDelay = new QSpinBox; - sbDelay->setMinimum(m_ui->spIdleTime->minimum()); - sbDelay->setMaximum(m_ui->spIdleTime->maximum()); - sbDelay->setValue(wpp.idleTime); - m_ui->tableWidget->setCellWidget(rowCount, IdleTime, sbDelay); + QSpinBox* sbAltitude = new QSpinBox; + sbAltitude->setMinimum(0); + sbAltitude->setMaximum(120); + sbAltitude->setValue(wpp.z); + m_ui->tableWidget->setCellWidget(rowCount, Altitude, sbAltitude); - - QComboBox *ccbox = new QComboBox; + QSpinBox* sbDelay = new QSpinBox; + sbDelay->setMinimum(m_ui->spIdleTime->minimum()); + sbDelay->setMaximum(m_ui->spIdleTime->maximum()); + sbDelay->setValue(wpp.idleTime); + m_ui->tableWidget->setCellWidget(rowCount, IdleTime, sbDelay); - ccbox->insertItem(m_ui->chargesCBox->count(), tr("Undefined")); - for(const auto &c : m_uasCharges.toStdMap()) - { - ccbox->addItem(c.second, c.first); - } - int idx = ccbox->findData(QVariant::fromValue(wpp.chargeTypeId)); - ccbox->setCurrentIndex(idx > 0 ? idx : 0 ); - m_ui->tableWidget->setCellWidget(rowCount, Charges, ccbox); + QComboBox* ccbox = new QComboBox; + + ccbox->insertItem(m_ui->chargesCBox->count(), tr("Undefined")); + for (const auto& c : m_uasCharges.toStdMap()) + { + ccbox->addItem(c.second, c.first); + } + int idx = ccbox->findData(QVariant::fromValue(wpp.chargeTypeId)); + ccbox->setCurrentIndex(idx > 0 ? idx : 0); + m_ui->tableWidget->setCellWidget(rowCount, Charges, ccbox); } void MissionPlanEdit::showPreview(bool show) { - if (m_sitMapGuiIfc) - { - if (show) - m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); - else - m_sitMapGuiIfc->removePreviewObject(); - } + if (m_sitMapGuiIfc) + { + if (show) + m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); + else + m_sitMapGuiIfc->removePreviewObject(); + } } const std::vector MissionPlanEdit::itemsRequestContent() { - const int missionItemCount = m_ui->tableWidget->rowCount(); - std::vector missionItems; - using ParticipantManagement::MissionActionType; - - const QVector actiontypes{ - MissionActionType::MoveTo, MissionActionType::Loiter, MissionActionType::Attack}; - int itemNumber = 0; - for (int i = 0; i < missionItemCount; i++) - { - ParticipantManagement::MissionItem msi; - QWidget *nameWidget = m_ui->tableWidget->cellWidget(i, Name); - const QString name = static_cast(nameWidget)->text(); - - QWidget *altitudeWidget = m_ui->tableWidget->cellWidget(i, Altitude); - const int altitude = static_cast(altitudeWidget)->value(); - - QWidget *posWidget = m_ui->tableWidget->cellWidget(i, Position); - const QPointF point = static_cast(posWidget)->coordinate(); - Core::GeoPosition geoPos(point.x(), point.y(), altitude); - - - QWidget *idleTimeWidget = m_ui->tableWidget->cellWidget(i, IdleTime); - const int idleTime = static_cast(idleTimeWidget)->value(); - - QWidget *chargesWidget = m_ui->tableWidget->cellWidget(i, Charges); - const int chargeTypeId = static_cast(chargesWidget)->currentData().toInt(); - - - - - - const QString &msiName = name; - int actionNumber = 0; - const QString &msaName = QStringLiteral("%1_%2").arg(m_ui->nameLineEdit->text()).arg(name); + const int missionItemCount = m_ui->tableWidget->rowCount(); + std::vector missionItems; + using ParticipantManagement::MissionActionType; + const QVector actiontypes{MissionActionType::MoveTo, MissionActionType::Loiter, + MissionActionType::Attack}; + int itemNumber = 0; + for (int i = 0; i < missionItemCount; i++) { - ParticipantManagement::MissionAction actionMoveTo; - actionMoveTo.actionType(ParticipantManagement::MissionActionType::MoveTo); - actionMoveTo.duration(0); - actionMoveTo.actionNumber(actionNumber++); - actionMoveTo.name(msaName.toStdString()); - actionMoveTo.itemNumber(itemNumber); - actionMoveTo.planId(m_missionPlan.id()); + ParticipantManagement::MissionItem msi; + QWidget* nameWidget = m_ui->tableWidget->cellWidget(i, Name); + const QString name = static_cast(nameWidget)->text(); - QJsonObject jsoMoveTo; - jsoMoveTo.insert(QStringLiteral("location_x"), point.x()); - jsoMoveTo.insert(QStringLiteral("location_y"), point.y()); - jsoMoveTo.insert(QStringLiteral("location_z"), altitude); - const QString props = QString::fromUtf8(QJsonDocument(jsoMoveTo).toJson(QJsonDocument::Compact)); - actionMoveTo.properties(props.toStdString()); - msi.actions().push_back(actionMoveTo); + QWidget* altitudeWidget = m_ui->tableWidget->cellWidget(i, Altitude); + const int altitude = static_cast(altitudeWidget)->value(); + + QWidget* posWidget = m_ui->tableWidget->cellWidget(i, Position); + const QPointF point = static_cast(posWidget)->coordinate(); + Core::GeoPosition geoPos(point.x(), point.y(), altitude); + + QWidget* idleTimeWidget = m_ui->tableWidget->cellWidget(i, IdleTime); + const int idleTime = static_cast(idleTimeWidget)->value(); + + QWidget* chargesWidget = m_ui->tableWidget->cellWidget(i, Charges); + const int chargeTypeId = static_cast(chargesWidget)->currentData().toInt(); + + const QString& msiName = name; + int actionNumber = 0; + const QString& msaName = QStringLiteral("%1_%2").arg(m_ui->nameLineEdit->text()).arg(name); + + { + ParticipantManagement::MissionAction actionMoveTo; + actionMoveTo.actionType(ParticipantManagement::MissionActionType::MoveTo); + actionMoveTo.duration(0); + actionMoveTo.actionNumber(actionNumber++); + actionMoveTo.name(msaName.toStdString()); + actionMoveTo.itemNumber(itemNumber); + actionMoveTo.planId(m_missionPlan.id()); + + QJsonObject jsoMoveTo; + jsoMoveTo.insert(QStringLiteral("location_x"), point.x()); + jsoMoveTo.insert(QStringLiteral("location_y"), point.y()); + jsoMoveTo.insert(QStringLiteral("location_z"), altitude); + const QString props = QString::fromUtf8(QJsonDocument(jsoMoveTo).toJson(QJsonDocument::Compact)); + actionMoveTo.properties(props.toStdString()); + msi.actions().push_back(actionMoveTo); + } + + if (idleTime > 0) + { + ParticipantManagement::MissionAction actionLoiter; + actionLoiter.actionType(ParticipantManagement::MissionActionType::Loiter); + actionLoiter.duration(idleTime); + actionLoiter.actionNumber(actionNumber++); + actionLoiter.itemNumber(itemNumber); + actionLoiter.name(msaName.toStdString()); + actionLoiter.planId(m_missionPlan.id()); + msi.actions().push_back(actionLoiter); + } + + if (chargeTypeId > 0) + { + ParticipantManagement::MissionAction actionAttack; + actionAttack.actionType(ParticipantManagement::MissionActionType::Attack); + actionAttack.duration(idleTime); + actionAttack.actionNumber(actionNumber++); + actionAttack.itemNumber(itemNumber); + actionAttack.name(msaName.toStdString()); + actionAttack.planId(m_missionPlan.id()); + + QJsonObject jsoAttack; + jsoAttack.insert(QStringLiteral("location_x"), point.x()); + jsoAttack.insert(QStringLiteral("location_y"), point.y()); + jsoAttack.insert(QStringLiteral("location_z"), 0); + jsoAttack.insert(QStringLiteral("chargeTypeId"), chargeTypeId); + const QString props = QString::fromUtf8(QJsonDocument(jsoAttack).toJson(QJsonDocument::Compact)); + actionAttack.properties(props.toStdString()); + + msi.actions().push_back(actionAttack); + } + + msi.itemNumber(itemNumber++); + msi.location(geoPos); + msi.name(msiName.toStdString()); + missionItems.push_back(msi); } - - if (idleTime > 0) - { - ParticipantManagement::MissionAction actionLoiter; - actionLoiter.actionType(ParticipantManagement::MissionActionType::Loiter); - actionLoiter.duration(idleTime); - actionLoiter.actionNumber(actionNumber++); - actionLoiter.itemNumber(itemNumber); - actionLoiter.name(msaName.toStdString()); - actionLoiter.planId(m_missionPlan.id()); - msi.actions().push_back(actionLoiter); - } - - - if (chargeTypeId > 0) - { - ParticipantManagement::MissionAction actionAttack; - actionAttack.actionType(ParticipantManagement::MissionActionType::Attack); - actionAttack.duration(idleTime); - actionAttack.actionNumber(actionNumber++); - actionAttack.itemNumber(itemNumber); - actionAttack.name(msaName.toStdString()); - actionAttack.planId(m_missionPlan.id()); - - QJsonObject jsoAttack; - jsoAttack.insert(QStringLiteral("location_x"), point.x()); - jsoAttack.insert(QStringLiteral("location_y"), point.y()); - jsoAttack.insert(QStringLiteral("location_z"), 0); - jsoAttack.insert(QStringLiteral("chargeTypeId"), chargeTypeId); - const QString props = QString::fromUtf8(QJsonDocument(jsoAttack).toJson(QJsonDocument::Compact)); - actionAttack.properties(props.toStdString()); - - msi.actions().push_back(actionAttack); - } - - - msi.itemNumber(itemNumber++); - msi.location(geoPos); - msi.name(msiName.toStdString()); - missionItems.push_back(msi); - - } - - return missionItems; + return missionItems; } void MissionPlanEdit::setUASCharges() { - const auto chargesForGearClass = m_pdmDtc->chargeTypes(); - m_ui->chargesCBox->clear(); - m_ui->chargesCBox->insertItem(m_ui->chargesCBox->count(), tr("Undefined")); - for (const ProjectDataManagement::ChargeType &chargeType : std::as_const(chargesForGearClass)) - { - - if (!m_pdmDtc->isUasDroppable(chargeType.id(),0,0)) - continue; - DEBUG_LOG(m_logger) << " fillCharges" - << ", id=" << chargeType.id() - << ", name= " << chargeType.name(); + const auto chargesForGearClass = m_pdmDtc->chargeTypes(); + m_ui->chargesCBox->clear(); + m_ui->chargesCBox->insertItem(m_ui->chargesCBox->count(), tr("Undefined")); + for (const ProjectDataManagement::ChargeType& chargeType : std::as_const(chargesForGearClass)) + { - m_ui->chargesCBox->addItem(QString::fromStdString(chargeType.name()), chargeType.id()); - m_uasCharges.insert(chargeType.id(), QString::fromStdString(chargeType.name())); - } - m_ui->chargesCBox->setCurrentIndex(0); + if (!m_pdmDtc->isUasDroppable(chargeType.id(), 0, 0)) + continue; + DEBUG_LOG(m_logger) << " fillCharges" + << ", id=" << chargeType.id() << ", name= " << chargeType.name(); + + m_ui->chargesCBox->addItem(QString::fromStdString(chargeType.name()), chargeType.id()); + m_uasCharges.insert(chargeType.id(), QString::fromStdString(chargeType.name())); + } + m_ui->chargesCBox->setCurrentIndex(0); } void MissionPlanEdit::setData(int mpId) { - initTableHeader(); + initTableHeader(); - if (mpId < 0 ) - return; + if (mpId < 0) + return; - m_missionPlan = m_ppmDtc->missionPlan(mpId); - m_participantData = m_ppmDtc->participant(m_missionPlan.participantId()); - m_ui->dteStartTime->setMinimumTimeMSec(m_session->partitionTime()); - m_ui->dteStartTime->setRetrieveCurrentTimeCallback([this](){return m_session->partitionTime();}); - m_ui->dteStartTime->setMsecsSinceEpoch(m_missionPlan.missionStart()); - m_ui->nameLineEdit->setText(QString::fromStdString(m_missionPlan.name())); + m_missionPlan = m_ppmDtc->missionPlan(mpId); + m_participantData = m_ppmDtc->participant(m_missionPlan.participantId()); + m_ui->dteStartTime->setMinimumTimeMSec(m_session->partitionTime()); + m_ui->dteStartTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + m_ui->dteStartTime->setMsecsSinceEpoch(m_missionPlan.missionStart()); + m_ui->nameLineEdit->setText(QString::fromStdString(m_missionPlan.name())); - - if (m_participantData.partyId() > 0) - { - const int partyIdx = m_ui->cbParty->findData(QVariant::fromValue(m_participantData.partyId())); - m_ui->cbParty->setCurrentIndex(partyIdx); - - const int ppIdx = m_ui->participantCBox->findData(QVariant::fromValue(m_missionPlan.participantId())); - m_ui->participantCBox->setCurrentIndex(ppIdx); - } - - for (const auto &item : std::as_const(m_missionPlan.items()) ) - { - const std::vector &msaVec = item.actions(); - WayPointParam wpp; - wpp.identifier = QString::fromStdString(item.name()); - wpp.lat = item.location().lat(); - wpp.lon = item.location().lon(); - wpp.z = item.location().z(); - for (auto const &msa : msaVec) + if (m_participantData.partyId() > 0) { - if (msa.actionType() == ParticipantManagement::MissionActionType::Loiter) - wpp.idleTime = msa.duration(); + const int partyIdx = m_ui->cbParty->findData(QVariant::fromValue(m_participantData.partyId())); + m_ui->cbParty->setCurrentIndex(partyIdx); - if (msa.actionType() == ParticipantManagement::MissionActionType::Attack) - { - const QJsonObject &obj = QJsonDocument::fromJson(QByteArray::fromStdString(msa.properties())).object(); - wpp.chargeTypeId = obj.value(QLatin1String("chargeTypeId")).toInt(); - } + const int ppIdx = m_ui->participantCBox->findData(QVariant::fromValue(m_missionPlan.participantId())); + m_ui->participantCBox->setCurrentIndex(ppIdx); } - insertPos(wpp); - } + for (const auto& item : std::as_const(m_missionPlan.items())) + { + const std::vector& msaVec = item.actions(); + WayPointParam wpp; + wpp.identifier = QString::fromStdString(item.name()); + wpp.lat = item.location().lat(); + wpp.lon = item.location().lon(); + wpp.z = item.location().z(); + for (auto const& msa : msaVec) + { + if (msa.actionType() == ParticipantManagement::MissionActionType::Loiter) + wpp.idleTime = msa.duration(); - - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0)); + if (msa.actionType() == ParticipantManagement::MissionActionType::Attack) + { + const QJsonObject& obj = QJsonDocument::fromJson(QByteArray::fromStdString(msa.properties())).object(); + wpp.chargeTypeId = obj.value(QLatin1String("chargeTypeId")).toInt(); + } + } + insertPos(wpp); + } + + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled((m_ui->tableWidget->rowCount() > 0)); } void MissionPlanEdit::fillParties() { - m_ppmCbxGui->fillPartyComboBox(m_ui->cbParty); - m_ui->cbParty->setCurrentIndex(0); - fillParticipants(); + m_ppmCbxGui->fillPartyComboBox(m_ui->cbParty); + m_ui->cbParty->setCurrentIndex(0); + fillParticipants(); } void MissionPlanEdit::fillParticipants() { - QVector participants; - const int partyId = m_ui->cbParty->currentData().toInt(); - gatherUASParticipants(partyId, participants); + QVector participants; + const int partyId = m_ui->cbParty->currentData().toInt(); + gatherUASParticipants(partyId, participants); - m_ui->participantCBox->clear(); - for (const auto &participant : participants) - { - QString uasString = QStringLiteral("%1 (%2)").arg(m_ppmDtc->hierarchyFromParticipant(participant.id())); - if (uasString.isEmpty() || m_usedUasSet.contains(participant.id())) - continue; - const ParticipantManagement::UAS &uasP = m_ppmDtc->getUasByParticipantId(participant.id(), m_session->exerciseId()); - uasString = uasString.arg(ProjectDataManagement::toString(uasP.uasState())); - m_ui->participantCBox->addItem(uasString, participant.id()); - } - if (m_missionPlan.id() > 0) - m_ui->participantCBox->setCurrentIndex(m_ui->participantCBox->findData(QVariant::fromValue(m_missionPlan.participantId()))); - - if (m_ui->participantCBox->currentIndex()<0) - m_ui->participantCBox->setCurrentIndex(0); + m_ui->participantCBox->clear(); + for (const auto& participant : participants) + { + QString uasString = QStringLiteral("%1 (%2)").arg(m_ppmDtc->hierarchyFromParticipant(participant.id())); + if (uasString.isEmpty() || m_usedUasSet.contains(participant.id())) + continue; + const ParticipantManagement::UAS& uasP = + m_ppmDtc->getUasByParticipantId(participant.id(), m_session->exerciseId()); + uasString = uasString.arg(ProjectDataManagement::toString(uasP.uasState())); + m_ui->participantCBox->addItem(uasString, participant.id()); + } + if (m_missionPlan.id() > 0) + m_ui->participantCBox->setCurrentIndex( + m_ui->participantCBox->findData(QVariant::fromValue(m_missionPlan.participantId()))); + if (m_ui->participantCBox->currentIndex() < 0) + m_ui->participantCBox->setCurrentIndex(0); } -void MissionPlanEdit::gatherUASParticipants(int partyId, QVector &participant) +void MissionPlanEdit::gatherUASParticipants(int partyId, QVector& participant) { - auto cb = [this, &partyId, &participant](const ParticipantManagement::Participant &p) - { - if (p.isDeleted() || p.partyId() != partyId) - return; - const ParticipantManagement::ParticipantData &ppData = m_ppmDtc->convertParticipantToParticipantData(p); - const ParticipantManagement::Type &&ppType = m_ppmDtc->type(ppData.typeId()); - const QJsonObject typeProperties(QJsonDocument::fromJson(QByteArray::fromStdString(ppType.properties())).object()); - if (typeProperties.isEmpty() - || ppType.typeClass() != ParticipantManagement::TypeClass::Aircraft - || !typeProperties[QStringLiteral("isUAS")].toBool(false)) - return; + auto cb = [this, &partyId, &participant](const ParticipantManagement::Participant& p) { + if (p.isDeleted() || p.partyId() != partyId) + return; + const ParticipantManagement::ParticipantData& ppData = m_ppmDtc->convertParticipantToParticipantData(p); + const ParticipantManagement::Type&& ppType = m_ppmDtc->type(ppData.typeId()); + const QJsonObject typeProperties( + QJsonDocument::fromJson(QByteArray::fromStdString(ppType.properties())).object()); + if (typeProperties.isEmpty() || ppType.typeClass() != ParticipantManagement::TypeClass::Aircraft || + !typeProperties[QStringLiteral("isUAS")].toBool(false)) + return; - participant.push_back(p); - }; - m_ppmDtc->participants(cb); + participant.push_back(p); + }; + m_ppmDtc->participants(cb); } - - void MissionPlanEdit::onParticipantTimerTimedout() { - fillParticipants(); + fillParticipants(); } -void MissionPlanEdit::onParticipantChanged(const ParticipantManagement::Participant &data, DataModification modType) +void MissionPlanEdit::onParticipantChanged(const ParticipantManagement::Participant& data, DataModification modType) { - Q_UNUSED(data) - Q_UNUSED(modType) + Q_UNUSED(data) + Q_UNUSED(modType) - m_participantTimer->start(); + m_participantTimer->start(); } void MissionPlanEdit::onPartyChanged() { - m_ui->participantCBox->clear(); - fillParticipants(); + m_ui->participantCBox->clear(); + fillParticipants(); } void MissionPlanEdit::onGetPolyline() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return; - } + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return; + } - QPolygonF coordinates; - int i = 0; - while (true) - { - LtsCoordWidget::LtsCoordWidget *w = findChild(QStringLiteral("positionEdit_%1").arg(i)); - if (!w) - break; - if (!w->coordinate().isNull()) - coordinates << w->coordinate(); - ++i; - } + QPolygonF coordinates; + int i = 0; + while (true) + { + LtsCoordWidget::LtsCoordWidget* w = + findChild(QStringLiteral("positionEdit_%1").arg(i)); + if (!w) + break; + if (!w->coordinate().isNull()) + coordinates << w->coordinate(); + ++i; + } - m_sitMapGuiIfc->getPolyline(this, - SLOT(onPolylineData(QPolygonF)), - nullptr, - 2, - 11, - -1, - -1, - coordinates); + m_sitMapGuiIfc->getPolyline(this, SLOT(onPolylineData(QPolygonF)), nullptr, 2, 11, -1, -1, coordinates); } -void MissionPlanEdit::onPolylineData(const QPolygonF &polyline) +void MissionPlanEdit::onPolylineData(const QPolygonF& polyline) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " numberOfPoints: " << polyline.size(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " numberOfPoints: " << polyline.size(); - if (polyline.size() < 2) - return; + if (polyline.size() < 2) + return; - m_polyline = polyline; + m_polyline = polyline; - clearCoordinates(); + clearCoordinates(); - for (int i = 0; i < polyline.size(); i++) - { - WayPointParam wp; - wp.lon = polyline.at(i).x(); - wp.lat = polyline.at(i).y(); - wp.identifier = m_ui->lePrefix->text() + QLatin1Char('_') + QString::number(i + 1); - wp.z = m_ui->spAltitude->value(); - wp.idleTime = m_ui->spIdleTime->value(); - wp.chargeTypeId = m_ui->chargesCBox->currentIndex(); - insertPos(wp); - } - - - m_sitMapGuiIfc->displayPreviewObject(this, polyline, false); - enaDisa(); + for (int i = 0; i < polyline.size(); i++) + { + WayPointParam wp; + wp.lon = polyline.at(i).x(); + wp.lat = polyline.at(i).y(); + wp.identifier = m_ui->lePrefix->text() + QLatin1Char('_') + QString::number(i + 1); + wp.z = m_ui->spAltitude->value(); + wp.idleTime = m_ui->spIdleTime->value(); + wp.chargeTypeId = m_ui->chargesCBox->currentIndex(); + insertPos(wp); + } + m_sitMapGuiIfc->displayPreviewObject(this, polyline, false); + enaDisa(); } void MissionPlanEdit::onFocus() { - showPreview(true); - m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); + showPreview(true); + m_sitMapGuiIfc->displayPreviewObject(this, m_polyline, false); } void MissionPlanEdit::onApplyNow() { - QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(m_session->partitionTime()); - m_ui->dteStartTime->setMsecsSinceEpoch(dateTime.addSecs(10).toMSecsSinceEpoch()); - if (m_ui->tableWidget->rowCount() < 2 || !m_uiRequirements->checkRequirements()) - return; - if (apply()) - { - enableUiElements(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(false); - } + QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(m_session->partitionTime()); + m_ui->dteStartTime->setMsecsSinceEpoch(dateTime.addSecs(10).toMSecsSinceEpoch()); + if (m_ui->tableWidget->rowCount() < 2 || !m_uiRequirements->checkRequirements()) + return; + if (apply()) + { + enableUiElements(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setEnabled(false); + } } -void MissionPlanEdit::onUasChanged(const ParticipantManagement::UAS &uas) +void MissionPlanEdit::onUasChanged(const ParticipantManagement::UAS& uas) { - Q_UNUSED(uas) - const int ppId = m_ui->participantCBox->currentData().toInt(); - fillParticipants(); + Q_UNUSED(uas) + const int ppId = m_ui->participantCBox->currentData().toInt(); + fillParticipants(); - const int index = m_ui->participantCBox->findData(ppId); - if( index < 0) - return; - m_ui->participantCBox->setCurrentIndex(index); + const int index = m_ui->participantCBox->findData(ppId); + if (index < 0) + return; + m_ui->participantCBox->setCurrentIndex(index); } - - - -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_model.cpp old mode 100755 new mode 100644 index f1a552a5f..60165e259 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CentralEffectSimulation/Gui/ParticipantUAS/mission_plan_model.cpp @@ -1,205 +1,164 @@ - - -#include -#include -#include - #include "mission_plan_model.h" +#include +#include +#include namespace CentralEffectSimulation { - -MissionPlanModel::MissionPlanModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( - {tr("Name"), - tr("Mission Start"), - tr("Actions [fulfilled / Count]"), - tr("Fulfilled"), - tr("Participant"), - tr("UAS State"), - tr("Current Mission"), - tr("Aborted")}, - parent) - , m_ppmDtc(nullptr) +MissionPlanModel::MissionPlanModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Name"), tr("Mission Start"), tr("Actions [fulfilled / Count]"), tr("Fulfilled"), tr("Participant"), + tr("UAS State"), tr("Current Mission"), tr("Aborted")}, + parent), + m_ppmDtc(nullptr) { - } - -QVariant MissionPlanModel::data(const QModelIndex &index, int role) const +QVariant MissionPlanModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole || !indexIsValid(index)) - return QVariant(); + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); - const ParticipantManagement::MissionPlan &mp = m_vecData.at(index.row()); - switch (index.column()) - { - - case Columns::Name: - return QString::fromStdString(mp.name()); - case Columns::MissionStart: - return QDateTime::fromMSecsSinceEpoch(mp.missionStart()); - case Columns::Fulfilled: - return QDateTime::fromMSecsSinceEpoch(mp.fulfilled()); - case Columns::ItemsCountAndFulfilled: - { - int actionsFulfilled = 0; - int actionsCount = 0; - for (const auto &item : mp.items()) + const ParticipantManagement::MissionPlan& mp = m_vecData.at(index.row()); + switch (index.column()) { - actionsFulfilled += item.actionsFulfilled(); - actionsCount += item.actions().size(); + + case Columns::Name: + return QString::fromStdString(mp.name()); + case Columns::MissionStart: + return QDateTime::fromMSecsSinceEpoch(mp.missionStart()); + case Columns::Fulfilled: + return QDateTime::fromMSecsSinceEpoch(mp.fulfilled()); + case Columns::ItemsCountAndFulfilled: { + int actionsFulfilled = 0; + int actionsCount = 0; + for (const auto& item : mp.items()) + { + actionsFulfilled += item.actionsFulfilled(); + actionsCount += item.actions().size(); + } + return QStringLiteral("%1/%2").arg(actionsFulfilled).arg(actionsCount); + } + case Columns::Participant: { + const auto& participant = m_ppmDtc->participant(mp.participantId()); + return QString::number(mp.participantId()); + } + case Columns::UasState: { + const auto& uas = m_ppmDtc->getUasByParticipantId(mp.participantId(), m_exerciseId); + return ProjectDataManagement::toString(uas.uasState()); + } + case Columns::CurrentMission: { + return currentJob2String(mp); + } + case Columns::Aborted: { + return mp.aborted(); + } + default: + break; } - return QStringLiteral("%1/%2").arg(actionsFulfilled).arg(actionsCount); - } - case Columns::Participant: - { - const auto &participant = m_ppmDtc->participant(mp.participantId()); - return QString::number(mp.participantId()); - } - case Columns::UasState: - { - const auto &uas = m_ppmDtc->getUasByParticipantId(mp.participantId(), m_exerciseId); - return ProjectDataManagement::toString(uas.uasState()); - } - case Columns::CurrentMission: - { - return currentJob2String(mp); - } - case Columns::Aborted: - { - return mp.aborted(); - } - default: - break; - } - return QVariant(); + return QVariant(); } - - -bool MissionPlanModel::initModel(const std::shared_ptr &ppmDtc, int exerciseId) +bool MissionPlanModel::initModel(const std::shared_ptr& ppmDtc, int exerciseId) { - m_ppmDtc = ppmDtc; - m_ppmDtc->enableMissionPlan(true); + m_ppmDtc = ppmDtc; + m_ppmDtc->enableMissionPlan(true); - m_exerciseId = exerciseId; + m_exerciseId = exerciseId; - if (!m_ppmDtc->isUASEnabled()) - m_ppmDtc->enableUAS(); + if (!m_ppmDtc->isUASEnabled()) + m_ppmDtc->enableUAS(); - m_ppmDtc->waitForHistoricalDataUAS(1000); + m_ppmDtc->waitForHistoricalDataUAS(1000); - connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, - this, &MissionPlanModel::onMissionPlanChanged); + connect(m_ppmDtc.get(), &ParticipantManagement::Interface::Dtc::missionPlanChanged, this, + &MissionPlanModel::onMissionPlanChanged); - auto cb = [this](const ParticipantManagement::MissionPlan &msp) - { - onMissionPlanChanged(msp, DataModification::eAdded); - }; - m_ppmDtc->missionPlans(cb); + auto cb = [this](const ParticipantManagement::MissionPlan& msp) { + onMissionPlanChanged(msp, DataModification::eAdded); + }; + m_ppmDtc->missionPlans(cb); - return true; + return true; } -QString MissionPlanModel::currentJob2String(const ParticipantManagement::MissionPlan &missionPlan) const +QString MissionPlanModel::currentJob2String(const ParticipantManagement::MissionPlan& missionPlan) const { - - - ParticipantManagement::MissionAction currAction = m_ppmDtc->currentMissionAction(missionPlan.id()); - if (currAction.planId() == 0 || - static_cast(missionPlan.items().size()) == missionPlan.itemsFulfilled()) - return tr(" Mission Complete "); - switch (currAction.actionType().underlying()) - { - case ParticipantManagement::MissionActionType::MoveTo: - { - return tr("Move to WP %1").arg(currAction.itemNumber()+1); - } - case ParticipantManagement::MissionActionType::Loiter: - { - return tr("WP %1: Loiter %2 sec.").arg(currAction.itemNumber()+1).arg(currAction.duration()); - } - case ParticipantManagement::MissionActionType::Attack: - { - return tr("WP %1: Drop Charge").arg(currAction.itemNumber()+1); - } - default: - return tr("Unknown"); - } + ParticipantManagement::MissionAction currAction = m_ppmDtc->currentMissionAction(missionPlan.id()); + if (currAction.planId() == 0 || static_cast(missionPlan.items().size()) == missionPlan.itemsFulfilled()) + return tr(" Mission Complete "); + + switch (currAction.actionType().underlying()) + { + case ParticipantManagement::MissionActionType::MoveTo: { + return tr("Move to WP %1").arg(currAction.itemNumber() + 1); + } + case ParticipantManagement::MissionActionType::Loiter: { + return tr("WP %1: Loiter %2 sec.").arg(currAction.itemNumber() + 1).arg(currAction.duration()); + } + case ParticipantManagement::MissionActionType::Attack: { + return tr("WP %1: Drop Charge").arg(currAction.itemNumber() + 1); + } + default: + return tr("Unknown"); + } } - - -void MissionPlanModel::onMissionPlanChanged(const ParticipantManagement::MissionPlan &data, const DataModification modType) +void MissionPlanModel::onMissionPlanChanged(const ParticipantManagement::MissionPlan& data, + const DataModification modType) { - const int id = data.id(); - int row = findRowForId(id); - DEBUG_LOG(m_logger)<<"MISSION PLAN CHANGED id ( "<(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } - - void MissionPlanProxyModel::setShowExpired(bool show) { - m_showExpired = show; + m_showExpired = show; } - - -bool MissionPlanProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const +bool MissionPlanProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { - Q_UNUSED(sourceParent) - return checkFilter(sourceRow); + Q_UNUSED(sourceParent) + return checkFilter(sourceRow); } - - bool MissionPlanProxyModel::checkFilter(int sourceRow) const { - Q_UNUSED(sourceRow) - - return true; + Q_UNUSED(sourceRow) + + return true; } -} +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.cpp old mode 100755 new mode 100644 index 436ed0c3b..f6c63bb21 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.cpp @@ -1,207 +1,189 @@ - #include "cod_assign_codification_data_table.h" -#include + #include "cod_codification_data_overview_model.h" -#include #include +#include #include +#include using namespace CodificationManagement; -AssignCodificationDataTable::AssignCodificationDataTable(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_ppmDtc(nullptr) - , m_ui(new Ui::AssignCodificationDataTable) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +AssignCodificationDataTable::AssignCodificationDataTable(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_dtc(nullptr), m_ftc(nullptr), + m_ppmDtc(nullptr), m_ui(new Ui::AssignCodificationDataTable), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - - setOnlineHelpFilename(QStringLiteral("Situation-Assign_Codification_Data")); - -} + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Situation-Assign_Codification_Data")); +} AssignCodificationDataTable::~AssignCodificationDataTable() { - delete m_ui; - delete m_requestHelper; -} - + delete m_ui; + delete m_requestHelper; +} void AssignCodificationDataTable::retranslate() { - translate(m_ui, tr("Assign Codification Data")); -} + translate(m_ui, tr("Assign Codification Data")); +} - -bool AssignCodificationDataTable::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc, - LtsSession::LtsSession *session) +bool AssignCodificationDataTable::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc, + LtsSession::LtsSession* session) { - DEBUG_LOG(m_logger) << "AssignCodificationDataTable::init()"; + DEBUG_LOG(m_logger) << "AssignCodificationDataTable::init()"; - if (!dtc || !ftc || !session || !ppmDtc) - { - ERROR_LOG(m_logger) << "AssignCodificationDataTable::init() Invalid shared_ptr!"; - return false; - } - - m_dtc = dtc; - m_ftc = ftc; - m_ppmDtc = ppmDtc; - m_session = session; - - m_model = new CodificationDataOverviewModel(this); - m_model->initModel(m_dtc, m_ppmDtc); - - int i = 0; - - QMap userVisibleParties; - m_ppmDtc->visibleParties(userVisibleParties, LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_session->exerciseId())); - DEBUG_LOG(m_logger) << "Number of parties visible to the user in the exercise: " << userVisibleParties.size(); - - for (const ParticipantManagement::Party &party : std::as_const(userVisibleParties)) - { - - if (party.id() != 2 && party.id() != 3) - continue; - - - QString partyName; - if (party.id() == 2) - partyName = tr("OPFOR:"); - else if (party.id() == 3) - partyName = tr("BLUFOR:"); - else - partyName = ParticipantManagement::trPartyName(party.name()); - m_ui->partyLayout->addWidget(new QLabel(partyName, this), i, 0, 1, 1); - - LtsWidgets::LtsComboBox *cb = new LtsWidgets::LtsComboBox(this); - cb->setProperty(QLatin1String("partyId").data(), party.id()); - m_tableVec.append(cb); - cb->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); - cb->addItem(QStringLiteral("---"), 0); - for (int row = 0; row < m_model->rowCount(); ++row) + if (!dtc || !ftc || !session || !ppmDtc) { - cb->addItem(m_model->data(m_model->index(row, CodificationDataOverviewModel::Identifier), Qt::DisplayRole).toString(), - m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole)); - - DEBUG_LOG(m_logger) << "Init Combobox[" << row << "]: PartyId: " << party.id() - << " Identifier: " << m_model->data(m_model->index(row, CodificationDataOverviewModel::Identifier), Qt::DisplayRole).toString() - << " CodTabId: " << m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole).toInt(); + ERROR_LOG(m_logger) << "AssignCodificationDataTable::init() Invalid shared_ptr!"; + return false; } - cb->model()->sort(0); - - int tableId = 0; - for (int row = 0; row < m_model->rowCount(); ++row) + m_dtc = dtc; + m_ftc = ftc; + m_ppmDtc = ppmDtc; + m_session = session; + + m_model = new CodificationDataOverviewModel(this); + m_model->initModel(m_dtc, m_ppmDtc); + + int i = 0; + + QMap userVisibleParties; + m_ppmDtc->visibleParties(userVisibleParties, + LtsSessionData::LtsSessionData::getInstance()->getVisibleParties(m_session->exerciseId())); + DEBUG_LOG(m_logger) << "Number of parties visible to the user in the exercise: " << userVisibleParties.size(); + + for (const ParticipantManagement::Party& party : std::as_const(userVisibleParties)) { - tableId = 0; - int assignedPartyId = m_model->data(m_model->index(row, CodificationDataOverviewModel::PartyIdHiddenColumn), Qt::DisplayRole).toInt(); - DEBUG_LOG(m_logger) << "Assignment[" << row << "]: assignedPartyId: " << assignedPartyId; - if (party.id() == assignedPartyId) - { - tableId = m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole).toInt(); - DEBUG_LOG(m_logger) << "Assignment[" << row << "]: assignedPartyId: " << assignedPartyId - << " tableId: " << tableId; - break; - } + if (party.id() != 2 && party.id() != 3) + continue; + + QString partyName; + if (party.id() == 2) + partyName = tr("OPFOR:"); + else if (party.id() == 3) + partyName = tr("BLUFOR:"); + else + partyName = ParticipantManagement::trPartyName(party.name()); + m_ui->partyLayout->addWidget(new QLabel(partyName, this), i, 0, 1, 1); + + LtsWidgets::LtsComboBox* cb = new LtsWidgets::LtsComboBox(this); + cb->setProperty(QLatin1String("partyId").data(), party.id()); + m_tableVec.append(cb); + cb->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); + cb->addItem(QStringLiteral("---"), 0); + for (int row = 0; row < m_model->rowCount(); ++row) + { + cb->addItem(m_model->data(m_model->index(row, CodificationDataOverviewModel::Identifier), Qt::DisplayRole) + .toString(), + m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole)); + + DEBUG_LOG(m_logger) + << "Init Combobox[" << row << "]: PartyId: " << party.id() << " Identifier: " + << m_model->data(m_model->index(row, CodificationDataOverviewModel::Identifier), Qt::DisplayRole) + .toString() + << " CodTabId: " + << m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole).toInt(); + } + cb->model()->sort(0); + + int tableId = 0; + for (int row = 0; row < m_model->rowCount(); ++row) + { + tableId = 0; + int assignedPartyId = + m_model->data(m_model->index(row, CodificationDataOverviewModel::PartyIdHiddenColumn), Qt::DisplayRole) + .toInt(); + DEBUG_LOG(m_logger) << "Assignment[" << row << "]: assignedPartyId: " << assignedPartyId; + + if (party.id() == assignedPartyId) + { + tableId = + m_model->data(m_model->index(row, CodificationDataOverviewModel::Id), Qt::DisplayRole).toInt(); + DEBUG_LOG(m_logger) << "Assignment[" << row << "]: assignedPartyId: " << assignedPartyId + << " tableId: " << tableId; + break; + } + } + DEBUG_LOG(m_logger) << "Assignment currentIndex: " << cb->findData(tableId); + cb->setCurrentIndex(cb->findData(tableId)); + + m_ui->partyLayout->addWidget(cb, i, 1, 1, 1); + ++i; } - DEBUG_LOG(m_logger) << "Assignment currentIndex: " << cb->findData(tableId); - cb->setCurrentIndex(cb->findData(tableId)); - - m_ui->partyLayout->addWidget(cb, i, 1, 1, 1); - ++i; - } - m_ui->partyLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding), - i, 1); - return true; -} - + m_ui->partyLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Preferred, QSizePolicy::Expanding), i, 1); + return true; +} bool AssignCodificationDataTable::apply() { - DEBUG_LOG(m_logger) << "AssignCodificationDataTable::apply()"; + DEBUG_LOG(m_logger) << "AssignCodificationDataTable::apply()"; - removeAllAssignments(); + removeAllAssignments(); - bool bStartRequests = false; - for (LtsWidgets::LtsComboBox *cb : std::as_const(m_tableVec)) - { - int partyId = cb->property("partyId").toInt(); - int tableId = cb->currentData().toInt(); - - DEBUG_LOG(m_logger) << "Assignments: partyId: " << partyId - << " codTableId: " << tableId; - - if (tableId < 1) + bool bStartRequests = false; + for (LtsWidgets::LtsComboBox* cb : std::as_const(m_tableVec)) { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("All parties must be assigned to a valid coding table.")); - return false; + int partyId = cb->property("partyId").toInt(); + int tableId = cb->currentData().toInt(); + + DEBUG_LOG(m_logger) << "Assignments: partyId: " << partyId << " codTableId: " << tableId; + + if (tableId < 1) + { + LtsWidgets::LtsMessageDialog::showMessage(this, + tr("All parties must be assigned to a valid coding table.")); + return false; + } + + if (isTableAlreadyAssigned(tableId)) + { + LtsWidgets::LtsMessageDialog::showMessage(this, + tr("All parties must be assigned to different coding tables.")); + return false; + } + + CodificationManagement::CodificationData codDdsData = m_dtc->codificationData(tableId); + + bStartRequests = true; + codDdsData.partyId(partyId); + m_requestHelper->addRequest( + [this, codDdsData]() { return m_ftc->codificationDataModifyRequest(codDdsData, this); }); } - - - if (isTableAlreadyAssigned(tableId) ) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("All parties must be assigned to different coding tables.")); - return false; - } - - CodificationManagement::CodificationData codDdsData = m_dtc->codificationData(tableId); - - - - - bStartRequests = true; - codDdsData.partyId(partyId); - m_requestHelper->addRequest([this, codDdsData]() - { - return m_ftc->codificationDataModifyRequest(codDdsData, this); - }); - - } - if (!bStartRequests) - return true; - return m_requestHelper->startRequests(); -} - + if (!bStartRequests) + return true; + return m_requestHelper->startRequests(); +} bool AssignCodificationDataTable::removeAllAssignments() { - const QMap codMap = m_dtc->codificationDatas(); + const QMap codMap = m_dtc->codificationDatas(); - bool bStartRequests = false; - for (CodificationManagement::CodificationData codData : codMap) - { - if (codData.partyId() < 0) - continue; - - bStartRequests = true; - codData.partyId(-1); - m_requestHelper->addRequest([this, codData]() + bool bStartRequests = false; + for (CodificationManagement::CodificationData codData : codMap) { - return m_ftc->codificationDataModifyRequest(codData, this); - }); - } - if (!bStartRequests) - return true; + if (codData.partyId() < 0) + continue; - return m_requestHelper->startRequests(); -} + bStartRequests = true; + codData.partyId(-1); + m_requestHelper->addRequest([this, codData]() { return m_ftc->codificationDataModifyRequest(codData, this); }); + } + if (!bStartRequests) + return true; + return m_requestHelper->startRequests(); +} bool AssignCodificationDataTable::isTableAlreadyAssigned(int codTableId) const { - const CodificationManagement::CodificationData &codData = m_dtc->codificationData(codTableId); - return codData.partyId() > 0; -} - - - + const CodificationManagement::CodificationData& codData = m_dtc->codificationData(codTableId); + return codData.partyId() > 0; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.h old mode 100755 new mode 100644 index 3705711cd..72785b186 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_assign_codification_data_table.h @@ -1,72 +1,66 @@ - #pragma once #include "ui_cod_assign_codification_data_table.h" -#include -#include +#include #include - +#include +#include +#include +#include #include #include -#include -#include -#include namespace Ui { class AssignCodificationDataTable; } - namespace CodificationManagement { class CodificationDataOverviewModel; class AssignCodificationDataTable : public LtsWidgets::LtsDialog, - protected CodificationManagement::Interface::Ftc::CodificationDataModifyReplyHandler + protected CodificationManagement::Interface::Ftc::CodificationDataModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit AssignCodificationDataTable(QWidget *parent = nullptr); + public: + explicit AssignCodificationDataTable(QWidget* parent = nullptr); - ~AssignCodificationDataTable(); + ~AssignCodificationDataTable(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc, - LtsSession::LtsSession *session); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc, LtsSession::LtsSession* session); - - void onCodificationDataModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onCodificationDataModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } + private Q_SLOTS: -private Q_SLOTS: - + bool apply() override; - bool apply() override; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; -private: + bool removeAllAssignments(); + bool isTableAlreadyAssigned(int codTableId) const; -NGL::INGLLogger &m_logger; - void retranslate() override; + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_ppmDtc; + LtsSession::LtsSession* m_session{nullptr}; + CodificationDataOverviewModel* m_model{nullptr}; + Ui::AssignCodificationDataTable* m_ui{nullptr}; - bool removeAllAssignments(); - bool isTableAlreadyAssigned(int codTableId) const; - -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_ppmDtc; - LtsSession::LtsSession *m_session{nullptr}; - CodificationDataOverviewModel *m_model{nullptr}; - Ui::AssignCodificationDataTable *m_ui{nullptr}; - - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - QVector m_tableVec; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + QVector m_tableVec; }; -} - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.cpp old mode 100755 new mode 100644 index 44b3809fd..57b1c77d3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.cpp @@ -1,262 +1,240 @@ - - #include "cod_authentication_code_model.h" + #include #include using namespace CodificationManagement; -AuthenticationCodeModel::AuthenticationCodeModel(QObject *parent) - : QAbstractTableModel(parent) - , m_dtc(nullptr) - , m_codificationDataId(0) - , m_isEditMode(false) +AuthenticationCodeModel::AuthenticationCodeModel(QObject* parent) + : QAbstractTableModel(parent), m_dtc(nullptr), m_codificationDataId(0), m_isEditMode(false) { - memset(m_matrix, 0, sizeof m_matrix); - DEBUG_LOG(m_logger) << "ctor AuthenticationCodeModel"; + memset(m_matrix, 0, sizeof m_matrix); + DEBUG_LOG(m_logger) << "ctor AuthenticationCodeModel"; +} -} - - -bool AuthenticationCodeModel::init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode) +bool AuthenticationCodeModel::init(const std::shared_ptr& dtc, + int codificationDataId, bool isEditMode) { - DEBUG_LOG(m_logger) << "AuthenticationCodeModel::init()"; - if (!dtc) - return false; + DEBUG_LOG(m_logger) << "AuthenticationCodeModel::init()"; + if (!dtc) + return false; - DEBUG_LOG(m_logger) << "AuthenticationCodeModel::init()..."; + DEBUG_LOG(m_logger) << "AuthenticationCodeModel::init()..."; - m_dtc = dtc; - m_codificationDataId = codificationDataId; - m_isEditMode = isEditMode; + m_dtc = dtc; + m_codificationDataId = codificationDataId; + m_isEditMode = isEditMode; - - m_ColumnSelectionValues.resize(5); - for (char i = 0; i < 5; ++i) - m_ColumnSelectionValues[i] = QLatin1Char('V' + i); + m_ColumnSelectionValues.resize(5); + for (char i = 0; i < 5; ++i) + m_ColumnSelectionValues[i] = QLatin1Char('V' + i); - - m_RowSelectionValues << QLatin1Char('A') << QLatin1Char('D') << QLatin1Char('E') - << QLatin1Char('G') << QLatin1Char('H') << QLatin1Char('I') - << QLatin1Char('L') << QLatin1Char('N') << QLatin1Char('O') - << QLatin1Char('R') << QLatin1Char('S') << QLatin1Char('T') - << QLatin1Char('U') ; + m_RowSelectionValues << QLatin1Char('A') << QLatin1Char('D') << QLatin1Char('E') << QLatin1Char('G') + << QLatin1Char('H') << QLatin1Char('I') << QLatin1Char('L') << QLatin1Char('N') + << QLatin1Char('O') << QLatin1Char('R') << QLatin1Char('S') << QLatin1Char('T') + << QLatin1Char('U'); - resetMatrix(); - - if (!isEditMode) - { - connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &AuthenticationCodeModel::onCodificationDataChanged); - } - return true; -} + resetMatrix(); + if (!isEditMode) + { + connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &AuthenticationCodeModel::onCodificationDataChanged); + } + return true; +} void AuthenticationCodeModel::resetMatrix() { - for (int row = 0; row < rowCount(); ++row) - { - for (int column = 0; column < columnCount(); ++column) + for (int row = 0; row < rowCount(); ++row) { - m_matrix[row][column] = 0; + for (int column = 0; column < columnCount(); ++column) + { + m_matrix[row][column] = 0; + } } - } - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); - return ; -} + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); + return; +} - -bool AuthenticationCodeModel::setMatrixValuesCSV(const QString &csvData) +bool AuthenticationCodeModel::setMatrixValuesCSV(const QString& csvData) { - DEBUG_LOG(m_logger) << "setMatrixValuesCSV: " << csvData; + DEBUG_LOG(m_logger) << "setMatrixValuesCSV: " << csvData; - const QVector slRows = csvData.splitRef(QLatin1Char('\n')); - if (slRows.size() != rowCount()) - { - ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << rowCount() - 1 << "/" << slRows.size(); - return false; - } - - for (int row = 0; row < slRows.size(); ++row) - { - const QVector slColumns = slRows[row].split(QLatin1Char(';')); - if (slColumns.size() != columnCount()) + const QVector slRows = csvData.splitRef(QLatin1Char('\n')); + if (slRows.size() != rowCount()) { - ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << columnCount() - 1 << "/" << slColumns.size(); - return false; + ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << rowCount() - 1 << "/" << slRows.size(); + return false; } - for (int column = 0; column < columnCount(); ++column) + for (int row = 0; row < slRows.size(); ++row) { - m_matrix[row][column] = slColumns.at(column).toInt(); - } - } - return true; -} + const QVector slColumns = slRows[row].split(QLatin1Char(';')); + if (slColumns.size() != columnCount()) + { + ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << columnCount() - 1 << "/" << slColumns.size(); + return false; + } + for (int column = 0; column < columnCount(); ++column) + { + m_matrix[row][column] = slColumns.at(column).toInt(); + } + } + return true; +} QString AuthenticationCodeModel::getMatrixDataCSVString() const { - QStringList slColumns; - slColumns.reserve(columnCount()); - QStringList slRows; - slRows.reserve(rowCount() * columnCount()); - for (int row = 0; row < rowCount(); ++row) - { - slColumns.clear(); - for (int column = 0; column < columnCount(); ++column) + QStringList slColumns; + slColumns.reserve(columnCount()); + QStringList slRows; + slRows.reserve(rowCount() * columnCount()); + for (int row = 0; row < rowCount(); ++row) { - slColumns << QStringLiteral("%1").arg(m_matrix[row][column], 2, 10, QLatin1Char('0')); + slColumns.clear(); + for (int column = 0; column < columnCount(); ++column) + { + slColumns << QStringLiteral("%1").arg(m_matrix[row][column], 2, 10, QLatin1Char('0')); + } + slRows << slColumns.join(QLatin1Char(';')); } - slRows << slColumns.join(QLatin1Char(';')); - } - return slRows.join(QLatin1Char('\n')); - } - + return slRows.join(QLatin1Char('\n')); +} void AuthenticationCodeModel::setEditMode(bool isEditMode) { - m_isEditMode = isEditMode; - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); -} - + m_isEditMode = isEditMode; + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); +} bool AuthenticationCodeModel::isEditMode() const { - return m_isEditMode; -} + return m_isEditMode; +} - -int AuthenticationCodeModel::rowCount(const QModelIndex &parent) const +int AuthenticationCodeModel::rowCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 13; -} + Q_UNUSED(parent) + return 13; +} - -int AuthenticationCodeModel::columnCount(const QModelIndex &parent) const +int AuthenticationCodeModel::columnCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 5; -} - + Q_UNUSED(parent) + return 5; +} QVariant AuthenticationCodeModel::headerData(int column, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) + if (role != Qt::DisplayRole) + return QAbstractTableModel::headerData(column, orientation, role); + + if (orientation == Qt::Horizontal) + { + if (!m_ColumnSelectionValues.isEmpty()) + return m_ColumnSelectionValues.at(column); + return QChar::fromLatin1('?'); + } + if (orientation == Qt::Vertical) + { + if (!m_RowSelectionValues.isEmpty()) + return m_RowSelectionValues.at(column); + return QChar::fromLatin1('?'); + } return QAbstractTableModel::headerData(column, orientation, role); +} - if (orientation == Qt::Horizontal) - { - if (!m_ColumnSelectionValues.isEmpty()) - return m_ColumnSelectionValues.at(column); - return QChar::fromLatin1('?'); - } - if (orientation == Qt::Vertical) - { - if (!m_RowSelectionValues.isEmpty()) - return m_RowSelectionValues.at(column); - return QChar::fromLatin1('?'); - } - return QAbstractTableModel::headerData(column, orientation, role); -} - - -QVariant AuthenticationCodeModel::data(const QModelIndex &index, int role) const +QVariant AuthenticationCodeModel::data(const QModelIndex& index, int role) const { - if ((role == Qt::DisplayRole || role == Qt::EditRole)) - { + if ((role == Qt::DisplayRole || role == Qt::EditRole)) + { - return QStringLiteral("%1").arg(m_matrix[index.row()][index.column()], 2, 10, QLatin1Char('0')); - } + return QStringLiteral("%1").arg(m_matrix[index.row()][index.column()], 2, 10, QLatin1Char('0')); + } - if (role == Qt::TextAlignmentRole) - return Qt::AlignCenter; + if (role == Qt::TextAlignmentRole) + return Qt::AlignCenter; - if (role == Qt::BackgroundRole) - { - if (m_isEditMode) - - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); - else - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); - } - return QVariant(); -} + if (role == Qt::BackgroundRole) + { + if (m_isEditMode) + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); + else + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + } + return QVariant(); +} -bool AuthenticationCodeModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool AuthenticationCodeModel::setData(const QModelIndex& index, const QVariant& value, int role) { - DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " char:" << value.toString() << " int:" << value.toInt(); + DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() << " char:" << value.toString() + << " int:" << value.toInt(); - bool bOk; - int val = value.toInt(&bOk); + bool bOk; + int val = value.toInt(&bOk); - if ((!bOk) || (val < 0) || (val > 99)) - { - ERROR_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " Invalid Input! " << value.toString() << " Required input value in the range 0-99."; - return false; - } + if ((!bOk) || (val < 0) || (val > 99)) + { + ERROR_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() << " Invalid Input! " + << value.toString() << " Required input value in the range 0-99."; + return false; + } - if (role == Qt::EditRole) - { - m_matrix[index.row()][index.column()] = val; - emit dataModified(); - } - return true; -} + if (role == Qt::EditRole) + { + m_matrix[index.row()][index.column()] = val; + emit dataModified(); + } + return true; +} - -Qt::ItemFlags AuthenticationCodeModel::flags(const QModelIndex &index) const +Qt::ItemFlags AuthenticationCodeModel::flags(const QModelIndex& index) const { - Qt::ItemFlags flags = QAbstractTableModel::flags(index); + Qt::ItemFlags flags = QAbstractTableModel::flags(index); - if ((index.row() <= rowCount()-1) && (index.column() <= columnCount() - 1)) - { - if (isEditMode()) - flags |= Qt::ItemIsEditable; - else - flags &= ~Qt::ItemIsEditable; - } - return flags; -} + if ((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) + { + if (isEditMode()) + flags |= Qt::ItemIsEditable; + else + flags &= ~Qt::ItemIsEditable; + } + return flags; +} - -void AuthenticationCodeModel::onCodificationDataChanged(const CodificationManagement::CodificationData &data, +void AuthenticationCodeModel::onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType) { - const int id = data.id(); + const int id = data.id(); - DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id - << " - AuthenticationCodeMatrix data: " << data.authenticationTableMatirx().c_str() - << " - modType: " << (int)modType; + DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id + << " - AuthenticationCodeMatrix data: " << data.authenticationTableMatirx().c_str() + << " - modType: " << (int)modType; - if (m_codificationDataId != data.id()) - return; + if (m_codificationDataId != data.id()) + return; - if (modType == DataModification::eRemoved) - { - WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - - resetMatrix(); - return; - } + if (modType == DataModification::eRemoved) + { + WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id + << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - if (modType == DataModification::eModified) - { - DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); + resetMatrix(); + return; + } - QString qs = QString::fromStdString(data.authenticationTableMatirx()); - setMatrixValuesCSV(qs); - } -} + if (modType == DataModification::eModified) + { + DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); + QString qs = QString::fromStdString(data.authenticationTableMatirx()); + setMatrixValuesCSV(qs); + } +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.h old mode 100755 new mode 100644 index 607bc8e96..7ab9da217 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_authentication_code_model.h @@ -1,99 +1,64 @@ - #pragma once -#include -#include #include - +#include +#include namespace CodificationManagement { class AuthenticationCodeModel final : public QAbstractTableModel { - Q_OBJECT -public: - explicit AuthenticationCodeModel(QObject *parent); + Q_OBJECT + public: + explicit AuthenticationCodeModel(QObject* parent); - + bool init(const std::shared_ptr& dtc, int codificationDataId, + bool isEditMode = false); - bool init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode = false); + void resetMatrix(); - + bool setMatrixValuesCSV(const QString& csvData); - void resetMatrix(); + QString getMatrixDataCSVString() const; - + void setEditMode(bool isEditMode); + bool isEditMode() const; - bool setMatrixValuesCSV(const QString &csvData); + int rowCount(const QModelIndex& parent = QModelIndex()) const override; - + int columnCount(const QModelIndex& parent = QModelIndex()) const override; - QString getMatrixDataCSVString() const; + QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - + QVariant data(const QModelIndex& index, int role) const override; - void setEditMode(bool isEditMode); - bool isEditMode() const; + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - + Qt::ItemFlags flags(const QModelIndex& index) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; + Q_SIGNALS: - + void dataModified(); - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + private Q_SLOTS: + void onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType); - + private: + NGL::INGLLogger& m_logger; + void setMatrix(const QVector& data); - QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + int m_matrix[13][5]; - + QVector m_RowSelectionValues; + QVector m_ColumnSelectionValues; - QVariant data(const QModelIndex &index, int role) const override; + std::shared_ptr m_dtc; - - - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - - - Qt::ItemFlags flags(const QModelIndex &index) const override; - -Q_SIGNALS: - - - - void dataModified(); - - -private Q_SLOTS: - void onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType); - -private: - - - - - - -NGL::INGLLogger &m_logger; - void setMatrix(const QVector &data); - - int m_matrix[13][5]; - - QVector m_RowSelectionValues; - QVector m_ColumnSelectionValues; - - std::shared_ptr m_dtc; - - int m_codificationDataId; - bool m_isEditMode; + int m_codificationDataId; + bool m_isEditMode; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.cpp old mode 100755 new mode 100644 index b84aef337..36d0ea3da --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.cpp @@ -1,133 +1,115 @@ - #include "cod_code_table_edit_delegate.h" + #include using namespace CodificationManagement; -CodeTableEditDelegate::CodeTableEditDelegate(QWidget *parent, TableType tableType) : QItemDelegate(parent) - , m_tableType(tableType), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - DEBUG_LOG(m_logger) << "CodeTableEditDelegate::ctor()"; -} - - -QWidget *CodeTableEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const +CodeTableEditDelegate::CodeTableEditDelegate(QWidget* parent, TableType tableType) + : QItemDelegate(parent), m_tableType(tableType), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - DEBUG_LOG(m_logger) << "CodeTableEditDelegate::createEditor() TableType: " << m_tableType - << " rox/column: " << index.row() << "/" << index.column() ; + DEBUG_LOG(m_logger) << "CodeTableEditDelegate::ctor()"; +} - Q_UNUSED(option) - Q_UNUSED(index) - QLineEdit *le = new QLineEdit(parent); - - switch (m_tableType) - { - case NumeralCode: - { - le->setMaxLength(1); - break; - } - case AuthenticationCode: - { - QValidator *v = new QIntValidator(0, 99, le); - le->setValidator(v); - le->setMaxLength(2); - break; - } - case LogisticalTerms: - - if ((index.row() == 0) || - ((index.column() == 0) && (index.row() > 0))) - { - le->setMaxLength(1); - break; - } - - - if ((index.column() > 0) && (index.row() > 0)) - { - - le->setMaxLength(20); - break; - } - le->setMaxLength(15); - break; - case PhraseTable: - le->setMaxLength(15); - break; - default: - break; - } - - return le; -} - - -void CodeTableEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +QWidget* CodeTableEditDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, + const QModelIndex& index) const { - QLineEdit *le = qobject_cast(editor); - if (!le) - return; + DEBUG_LOG(m_logger) << "CodeTableEditDelegate::createEditor() TableType: " << m_tableType + << " rox/column: " << index.row() << "/" << index.column(); - QVariant v = index.data(Qt::EditRole); - le->setText(v.toString()); + Q_UNUSED(option) + Q_UNUSED(index) + QLineEdit* le = new QLineEdit(parent); - DEBUG_LOG(m_logger) << "CodeTableEditDelegate::setEditorData() TableType: " << m_tableType - << " rox/column: " << index.row() << "/" << index.column() - << " Input: " << v.toString(); + switch (m_tableType) + { + case NumeralCode: { + le->setMaxLength(1); + break; + } + case AuthenticationCode: { + QValidator* v = new QIntValidator(0, 99, le); + le->setValidator(v); + le->setMaxLength(2); + break; + } + case LogisticalTerms: -} + if ((index.row() == 0) || ((index.column() == 0) && (index.row() > 0))) + { + le->setMaxLength(1); + break; + } + if ((index.column() > 0) && (index.row() > 0)) + { -void CodeTableEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const + le->setMaxLength(20); + break; + } + le->setMaxLength(15); + break; + case PhraseTable: + le->setMaxLength(15); + break; + default: + break; + } + + return le; +} + +void CodeTableEditDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { - QLineEdit *le = qobject_cast(editor); - if (!le) - return; + QLineEdit* le = qobject_cast(editor); + if (!le) + return; - DEBUG_LOG(m_logger) << "CodeTableEditDelegate::setModelData() TableType: " << m_tableType - << " rox/column: " << index.row() << "/" << index.column() - << " Input: " << le->text(); + QVariant v = index.data(Qt::EditRole); + le->setText(v.toString()); - switch (m_tableType) - { - case NumeralCode: - case AuthenticationCode: - case PhraseTable: - { - model->setData(index, le->text(), Qt::EditRole); - break; - } - case LogisticalTerms: - { - - if ((index.row() == 0) || - ((index.column() == 0) && (index.row() > 0))) + DEBUG_LOG(m_logger) << "CodeTableEditDelegate::setEditorData() TableType: " << m_tableType + << " rox/column: " << index.row() << "/" << index.column() << " Input: " << v.toString(); +} + +void CodeTableEditDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const +{ + QLineEdit* le = qobject_cast(editor); + if (!le) + return; + + DEBUG_LOG(m_logger) << "CodeTableEditDelegate::setModelData() TableType: " << m_tableType + << " rox/column: " << index.row() << "/" << index.column() << " Input: " << le->text(); + + switch (m_tableType) { - model->setData(index, le->text(), Qt::EditRole); - break; + case NumeralCode: + case AuthenticationCode: + case PhraseTable: { + model->setData(index, le->text(), Qt::EditRole); + break; + } + case LogisticalTerms: { + + if ((index.row() == 0) || ((index.column() == 0) && (index.row() > 0))) + { + model->setData(index, le->text(), Qt::EditRole); + break; + } + + if ((index.column() > 0) && (index.row() > 0)) + { + QString qs = le->text(); + if (qs.size() > 10) + { + qs.insert(10, QLatin1String("\n")); + } + model->setData(index, qs, Qt::EditRole); + } + break; + } + default: + break; } - - - if ((index.column() > 0) && (index.row() > 0)) - { - QString qs = le->text(); - if (qs.size() > 10) - { - qs.insert(10, QLatin1String("\n")); - } - model->setData(index, qs, Qt::EditRole); - } - break; - } - default: - break; - } - -} - - +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.h old mode 100755 new mode 100644 index 6d7b2a407..cce3e9e29 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_code_table_edit_delegate.h @@ -1,51 +1,32 @@ - #pragma once -#include -#include #include - +#include +#include namespace CodificationManagement { class CodeTableEditDelegate : public QItemDelegate { - Q_OBJECT + Q_OBJECT -public: + public: + enum TableType { Undefined, NumeralCode, AuthenticationCode, LogisticalTerms, PhraseTable }; - enum TableType - { - Undefined, - NumeralCode, - AuthenticationCode, - LogisticalTerms, - PhraseTable - }; + explicit CodeTableEditDelegate(QWidget* parent = nullptr, TableType tableType = Undefined); - explicit CodeTableEditDelegate(QWidget *parent = nullptr, TableType tableType = Undefined); + QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - + void setEditorData(QWidget* editor, const QModelIndex& index) const override; - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override ; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; - - - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - - - - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - -private: - -NGL::INGLLogger &m_logger; - TableType m_tableType; + private: + NGL::INGLLogger& m_logger; + TableType m_tableType; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.cpp old mode 100755 new mode 100644 index 1e1456eca..7871b403f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.cpp @@ -1,179 +1,159 @@ - #include "cod_codification_data_overview_model.h" -#include + #include #include +#include namespace CodificationManagement { - - -CodificationDataOverviewModel::CodificationDataOverviewModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Identifier"), - tr("Validity Time"), - tr("Party"), - QStringLiteral("PartyIdHiddenColumn"), - QStringLiteral("NumCodeTableColIndex"), - QStringLiteral("NumCodeTableRowIndex"), - QStringLiteral("AuthentTableColIndex"), - QStringLiteral("AuthentTableColIndex"), - QStringLiteral("AuthenTableMatrix"), - QStringLiteral("LogTermTableColIndex"), - QStringLiteral("LogTermTableRowIndex"), - QStringLiteral("LogTermTableMatrix"), - QStringLiteral("PhraseTable"), - tr("Note")}, - parent) - , m_codDtc(nullptr) +CodificationDataOverviewModel::CodificationDataOverviewModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Identifier"), tr("Validity Time"), tr("Party"), QStringLiteral("PartyIdHiddenColumn"), + QStringLiteral("NumCodeTableColIndex"), QStringLiteral("NumCodeTableRowIndex"), + QStringLiteral("AuthentTableColIndex"), QStringLiteral("AuthentTableColIndex"), + QStringLiteral("AuthenTableMatrix"), QStringLiteral("LogTermTableColIndex"), + QStringLiteral("LogTermTableRowIndex"), QStringLiteral("LogTermTableMatrix"), QStringLiteral("PhraseTable"), + tr("Note")}, + parent), + m_codDtc(nullptr) { -} +} - - -bool CodificationDataOverviewModel::initModel(const std::shared_ptr &codDtc, - const std::shared_ptr &ppmDtc) +bool CodificationDataOverviewModel::initModel(const std::shared_ptr& codDtc, + const std::shared_ptr& ppmDtc) { - DEBUG_LOG(m_logger) << "CodificationDataModel::initModel()"; + DEBUG_LOG(m_logger) << "CodificationDataModel::initModel()"; - if (!codDtc || !ppmDtc) - return false; + if (!codDtc || !ppmDtc) + return false; - m_codDtc = codDtc; - m_ppmDtc = ppmDtc; - connect(m_codDtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &CodificationDataOverviewModel::onDataChanged); - m_codDtc->codificationDatas([this](const CodificationData &item) { insertRow(item); }); - return true; -} + m_codDtc = codDtc; + m_ppmDtc = ppmDtc; + connect(m_codDtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &CodificationDataOverviewModel::onDataChanged); + m_codDtc->codificationDatas([this](const CodificationData& item) { insertRow(item); }); + return true; +} - -QVariant CodificationDataOverviewModel::data(const QModelIndex &index, int role) const +QVariant CodificationDataOverviewModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole && - role != Qt::BackgroundRole ) - return QVariant(); + if (role != Qt::DisplayRole && role != Qt::BackgroundRole) + return QVariant(); - if (!indexIsValid(index)) - return QVariant(); + if (!indexIsValid(index)) + return QVariant(); - const CodificationManagement::CodificationData &codificationData = m_vecData.at(index.row()); + const CodificationManagement::CodificationData& codificationData = m_vecData.at(index.row()); - if (role == Qt::DisplayRole) - { - switch (index.column()) + if (role == Qt::DisplayRole) { - case Id: - return codificationData.id(); - case Identifier: - return QString::fromUtf8(codificationData.identifier().c_str()); - case ValidityTime: - return QDateTime::fromMSecsSinceEpoch(codificationData.validityTime()); - case PartyId: - if (codificationData.partyId() < 0) - return QStringLiteral("---"); - - if (codificationData.partyId() == 2) - return tr("OPFOR"); - else if (codificationData.partyId() == 3) - return tr("BLUFOR"); - return ParticipantManagement::trPartyName(m_ppmDtc->party(codificationData.partyId()).name()); - case PartyIdHiddenColumn: - - return codificationData.partyId(); - case NumeralCodeTableColumnIndex: - return QString::fromUtf8(codificationData.numeralCodeTableColumnIndex().c_str()); - case NumeralCodeTableRowIndex: - return QString::fromUtf8(codificationData.numeralCodeTableRowIndex().c_str()); - case AuthenticationTableColumnIndex: - return QString::fromUtf8(codificationData.authenticationTableColumnIndex().c_str()); - case AuthenticationTableRowIndex: - return QString::fromUtf8(codificationData.authenticationTableRowIndex().c_str()); - case AuthenticationTableMatrix: - return QString::fromUtf8(codificationData.authenticationTableMatirx().c_str()); - case LogisticalTermTableColumnIndex: - return QString::fromUtf8(codificationData.logisticalTermTableColumnIndex().c_str()); - case LogisticalTermTableRowIndex: - return QString::fromUtf8(codificationData.logisticalTermTableRowIndex().c_str()); - case LogisticalTermTableMatrix: - return QString::fromUtf8(codificationData.logisticalTermTableMatrix().c_str()); - case PhraseTable: - return QString::fromUtf8(codificationData.phraseTable().c_str()); - case Note: - return QString::fromUtf8(codificationData.note().c_str()); - } - } + switch (index.column()) + { + case Id: + return codificationData.id(); + case Identifier: + return QString::fromUtf8(codificationData.identifier().c_str()); + case ValidityTime: + return QDateTime::fromMSecsSinceEpoch(codificationData.validityTime()); + case PartyId: + if (codificationData.partyId() < 0) + return QStringLiteral("---"); - if (role == Qt::BackgroundRole) - { - switch (index.column()) + if (codificationData.partyId() == 2) + return tr("OPFOR"); + else if (codificationData.partyId() == 3) + return tr("BLUFOR"); + return ParticipantManagement::trPartyName(m_ppmDtc->party(codificationData.partyId()).name()); + case PartyIdHiddenColumn: + + return codificationData.partyId(); + case NumeralCodeTableColumnIndex: + return QString::fromUtf8(codificationData.numeralCodeTableColumnIndex().c_str()); + case NumeralCodeTableRowIndex: + return QString::fromUtf8(codificationData.numeralCodeTableRowIndex().c_str()); + case AuthenticationTableColumnIndex: + return QString::fromUtf8(codificationData.authenticationTableColumnIndex().c_str()); + case AuthenticationTableRowIndex: + return QString::fromUtf8(codificationData.authenticationTableRowIndex().c_str()); + case AuthenticationTableMatrix: + return QString::fromUtf8(codificationData.authenticationTableMatirx().c_str()); + case LogisticalTermTableColumnIndex: + return QString::fromUtf8(codificationData.logisticalTermTableColumnIndex().c_str()); + case LogisticalTermTableRowIndex: + return QString::fromUtf8(codificationData.logisticalTermTableRowIndex().c_str()); + case LogisticalTermTableMatrix: + return QString::fromUtf8(codificationData.logisticalTermTableMatrix().c_str()); + case PhraseTable: + return QString::fromUtf8(codificationData.phraseTable().c_str()); + case Note: + return QString::fromUtf8(codificationData.note().c_str()); + } + } + + if (role == Qt::BackgroundRole) { - case PartyId: - if (codificationData.partyId() >= 0) - return QColor::fromRgb(QRgb(m_ppmDtc->party(codificationData.partyId()).color())); - break; - default: - break; + switch (index.column()) + { + case PartyId: + if (codificationData.partyId() >= 0) + return QColor::fromRgb(QRgb(m_ppmDtc->party(codificationData.partyId()).color())); + break; + default: + break; + } } - } - return QVariant(); -} - + return QVariant(); +} int CodificationDataOverviewModel::getCodTableId(int partyId) const { - for (const CodificationManagement::CodificationData &codificationData : m_vecData) - { - if (codificationData.partyId() == partyId) - return codificationData.id(); - } - return -1; -} - - -void CodificationDataOverviewProxyModel::setSourceModel(QAbstractItemModel *sourceModel) -{ - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + for (const CodificationManagement::CodificationData& codificationData : m_vecData) + { + if (codificationData.partyId() == partyId) + return codificationData.id(); + } + return -1; } -bool CodificationDataOverviewProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +void CodificationDataOverviewProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); +} + +bool CodificationDataOverviewProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const +{ + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case CodificationDataOverviewModel::ValidityTime: + return dataLeft.validityTime() < dataRight.validityTime(); + + case CodificationDataOverviewModel::Id: + case CodificationDataOverviewModel::Identifier: + + case CodificationDataOverviewModel::PartyId: + case CodificationDataOverviewModel::PartyIdHiddenColumn: + case CodificationDataOverviewModel::NumeralCodeTableColumnIndex: + case CodificationDataOverviewModel::NumeralCodeTableRowIndex: + case CodificationDataOverviewModel::AuthenticationTableColumnIndex: + case CodificationDataOverviewModel::AuthenticationTableRowIndex: + case CodificationDataOverviewModel::AuthenticationTableMatrix: + case CodificationDataOverviewModel::LogisticalTermTableColumnIndex: + case CodificationDataOverviewModel::LogisticalTermTableRowIndex: + case CodificationDataOverviewModel::LogisticalTermTableMatrix: + case CodificationDataOverviewModel::PhraseTable: + case CodificationDataOverviewModel::Note: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case CodificationDataOverviewModel::ValidityTime: - return dataLeft.validityTime() < dataRight.validityTime(); - - case CodificationDataOverviewModel::Id: - case CodificationDataOverviewModel::Identifier: - - case CodificationDataOverviewModel::PartyId: - case CodificationDataOverviewModel::PartyIdHiddenColumn: - case CodificationDataOverviewModel::NumeralCodeTableColumnIndex: - case CodificationDataOverviewModel::NumeralCodeTableRowIndex: - case CodificationDataOverviewModel::AuthenticationTableColumnIndex: - case CodificationDataOverviewModel::AuthenticationTableRowIndex: - case CodificationDataOverviewModel::AuthenticationTableMatrix: - case CodificationDataOverviewModel::LogisticalTermTableColumnIndex: - case CodificationDataOverviewModel::LogisticalTermTableRowIndex: - case CodificationDataOverviewModel::LogisticalTermTableMatrix: - case CodificationDataOverviewModel::PhraseTable: - case CodificationDataOverviewModel::Note: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } - - -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.h old mode 100755 new mode 100644 index 3bcf414b6..aa0b76ea3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_model.h @@ -1,72 +1,67 @@ - #pragma once -#include -#include -#include - #include #include +#include +#include +#include namespace CodificationManagement { - - class CodificationDataOverviewModel : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Id, - Identifier, - ValidityTime, - PartyId, - PartyIdHiddenColumn, - NumeralCodeTableColumnIndex, - NumeralCodeTableRowIndex, - AuthenticationTableColumnIndex, - AuthenticationTableRowIndex, - AuthenticationTableMatrix, - LogisticalTermTableColumnIndex, - LogisticalTermTableRowIndex, - LogisticalTermTableMatrix, - PhraseTable, - Note - }; + Q_OBJECT + public: + enum Columns { + Id, + Identifier, + ValidityTime, + PartyId, + PartyIdHiddenColumn, + NumeralCodeTableColumnIndex, + NumeralCodeTableRowIndex, + AuthenticationTableColumnIndex, + AuthenticationTableRowIndex, + AuthenticationTableMatrix, + LogisticalTermTableColumnIndex, + LogisticalTermTableRowIndex, + LogisticalTermTableMatrix, + PhraseTable, + Note + }; + explicit CodificationDataOverviewModel(QObject* parent = nullptr); - explicit CodificationDataOverviewModel(QObject *parent = nullptr); + bool initModel(const std::shared_ptr& codDtc, + const std::shared_ptr& ppmDtc); - bool initModel(const std::shared_ptr &codDtc, - const std::shared_ptr &ppmDtc); + int getCodTableId(int partyId) const; - int getCodTableId(int partyId) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; + friend class CodificationDataOverviewProxyModel; - friend class CodificationDataOverviewProxyModel; - -private: - -NGL::INGLLogger &m_logger; - std::shared_ptr m_codDtc; - std::shared_ptr m_ppmDtc; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_codDtc; + std::shared_ptr m_ppmDtc; }; class CodificationDataOverviewProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - CodificationDataOverviewModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + CodificationDataOverviewModel* m_sourceModel = nullptr; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.cpp old mode 100755 new mode 100644 index 6898628c4..493446899 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.cpp @@ -1,203 +1,178 @@ - #include "cod_codification_data_overview_view.h" -#include "ui_cod_codification_data_overview_view.h" -#include "cod_codification_data_table_view.h" #include "cod_codification_data_table_edit_view.h" +#include "cod_codification_data_table_view.h" +#include "ui_cod_codification_data_overview_view.h" #include #include using namespace CodificationManagement; - -CodificationDataOverviewView::CodificationDataOverviewView(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_menuGroup(menuGroup) - , m_session(session) - , m_model(nullptr) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::CodificationDataOverviewView) +CodificationDataOverviewView::CodificationDataOverviewView(const QString& menuGroup, LtsSession::LtsSession* session, + QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_menuGroup(menuGroup), + m_session(session), m_model(nullptr), m_dtc(nullptr), m_ftc(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::CodificationDataOverviewView) { - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &CodificationDataOverviewView::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &CodificationDataOverviewView::onSelectionChanged); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &CodificationDataOverviewView::onEditCodificationData); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &CodificationDataOverviewView::onEditCodificationData); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, &CodificationDataOverviewView::onShowCodificationData); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Show, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, + &CodificationDataOverviewView::onShowCodificationData); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Show, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &CodificationDataOverviewView::onAddCodificationData); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, + &CodificationDataOverviewView::onAddCodificationData); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &CodificationDataOverviewView::onEditCodificationData); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, + &CodificationDataOverviewView::onEditCodificationData); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &CodificationDataOverviewView::onRemoveCodificationData); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataOverviewView::onPrint); - -} + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, + &CodificationDataOverviewView::onRemoveCodificationData); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataOverviewView::onPrint); +} CodificationDataOverviewView::~CodificationDataOverviewView() { - delete m_ui; -} - + delete m_ui; +} void CodificationDataOverviewView::retranslate() { - translate(m_ui, tr("Codification Data")); + translate(m_ui, tr("Codification Data")); - setOnlineHelpFilename(QStringLiteral("Situation-Codification_Data")); -} + setOnlineHelpFilename(QStringLiteral("Situation-Codification_Data")); +} - -bool CodificationDataOverviewView::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc) +bool CodificationDataOverviewView::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc) { - if (!dtc || !ftc || !ppmDtc) - return false; + if (!dtc || !ftc || !ppmDtc) + return false; - m_dtc = dtc; - m_ftc = ftc; - m_ppmDtc = ppmDtc; + m_dtc = dtc; + m_ftc = ftc; + m_ppmDtc = ppmDtc; - m_model = new CodificationDataOverviewModel(this); - m_model->initModel(m_dtc, m_ppmDtc); - m_proxyModel = new CodificationDataOverviewProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->widget->setModel(m_proxyModel); + m_model = new CodificationDataOverviewModel(this); + m_model->initModel(m_dtc, m_ppmDtc); + m_proxyModel = new CodificationDataOverviewProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(CodificationDataOverviewModel::Id); + m_ui->widget->hideColumn(CodificationDataOverviewModel::Id); #endif + m_ui->widget->hideColumn(CodificationDataOverviewModel::PartyIdHiddenColumn); + m_ui->widget->hideColumn(CodificationDataOverviewModel::NumeralCodeTableColumnIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::NumeralCodeTableRowIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableColumnIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableRowIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableMatrix); + m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableColumnIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableRowIndex); + m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableMatrix); + m_ui->widget->hideColumn(CodificationDataOverviewModel::PhraseTable); - m_ui->widget->hideColumn(CodificationDataOverviewModel::PartyIdHiddenColumn); - m_ui->widget->hideColumn(CodificationDataOverviewModel::NumeralCodeTableColumnIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::NumeralCodeTableRowIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableColumnIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableRowIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::AuthenticationTableMatrix); - m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableColumnIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableRowIndex); - m_ui->widget->hideColumn(CodificationDataOverviewModel::LogisticalTermTableMatrix); - m_ui->widget->hideColumn(CodificationDataOverviewModel::PhraseTable); - - - - m_ui->widget->setSortIndicator(CodificationDataOverviewModel::Note, Qt::AscendingOrder); - - return true; -} + m_ui->widget->setSortIndicator(CodificationDataOverviewModel::Note, Qt::AscendingOrder); + return true; +} void CodificationDataOverviewView::onSelectionChanged() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, true); - - - -} + int row = idx.row(); + if (row < 0) + return; + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, true); +} void CodificationDataOverviewView::onShowCodificationData() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - CodificationManagement::CodificationData codificationData = m_model->getRowData(row); + CodificationManagement::CodificationData codificationData = m_model->getRowData(row); - DEBUG_LOG(m_logger) << "--- onShowCodificationData() " - << " id: " << codificationData.id(); + DEBUG_LOG(m_logger) << "--- onShowCodificationData() " + << " id: " << codificationData.id(); - CodificationDataTableView *dialog = new CodificationDataTableView; - dialog->init(m_dtc, m_ftc, m_session, codificationData.partyId(), codificationData.id()); - dialog->setUnchangeable(true); - - addDialog(dialog, m_menuGroup, QLatin1String("codShowCodificationData"), LtsWidgets::LayoutArea::eDialogTab); - -} + CodificationDataTableView* dialog = new CodificationDataTableView; + dialog->init(m_dtc, m_ftc, m_session, codificationData.partyId(), codificationData.id()); + dialog->setUnchangeable(true); + addDialog(dialog, m_menuGroup, QLatin1String("codShowCodificationData"), LtsWidgets::LayoutArea::eDialogTab); +} void CodificationDataOverviewView::onAddCodificationData() { - DEBUG_LOG(m_logger) << "--- onAddCodificationData() "; + DEBUG_LOG(m_logger) << "--- onAddCodificationData() "; - CodificationDataTableEditView *dialog = new CodificationDataTableEditView(this); - dialog->init(m_dtc, m_ftc, m_session, 0); - - addDialog(dialog, m_menuGroup, QLatin1String("codSetCodificationData"), LtsWidgets::LayoutArea::eDialogTab); - -} + CodificationDataTableEditView* dialog = new CodificationDataTableEditView(this); + dialog->init(m_dtc, m_ftc, m_session, 0); + addDialog(dialog, m_menuGroup, QLatin1String("codSetCodificationData"), LtsWidgets::LayoutArea::eDialogTab); +} void CodificationDataOverviewView::onEditCodificationData() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - CodificationManagement::CodificationData codificationData = m_model->getRowData(row); + CodificationManagement::CodificationData codificationData = m_model->getRowData(row); - DEBUG_LOG(m_logger) << "--- onEditCodificationData() " - << " id: " << codificationData.id(); + DEBUG_LOG(m_logger) << "--- onEditCodificationData() " + << " id: " << codificationData.id(); - CodificationDataTableEditView *dialog = new CodificationDataTableEditView(this); - dialog->init(m_dtc, m_ftc, m_session, codificationData.id()); - - addDialog(dialog, m_menuGroup, QLatin1String("codSetCodificationData"), LtsWidgets::LayoutArea::eDialogTab); - -} + CodificationDataTableEditView* dialog = new CodificationDataTableEditView(this); + dialog->init(m_dtc, m_ftc, m_session, codificationData.id()); + addDialog(dialog, m_menuGroup, QLatin1String("codSetCodificationData"), LtsWidgets::LayoutArea::eDialogTab); +} void CodificationDataOverviewView::onRemoveCodificationData() { - const QModelIndex idx = m_ui->widget->currentIndex(); - CodificationManagement::CodificationData codificationData = m_model->getRowData(idx.row()); - Core::RemoveElementRequest request(codificationData.id()); - - m_requestHelper->startSingleRequest([request, this]() - { - return m_ftc->codificationDataRemoveRequest(request, this); - }); -} + const QModelIndex idx = m_ui->widget->currentIndex(); + CodificationManagement::CodificationData codificationData = m_model->getRowData(idx.row()); + Core::RemoveElementRequest request(codificationData.id()); + m_requestHelper->startSingleRequest( + [request, this]() { return m_ftc->codificationDataRemoveRequest(request, this); }); +} void CodificationDataOverviewView::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView() ); -} + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); +} void CodificationDataOverviewView::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.h old mode 100755 new mode 100644 index 72d7cf413..190fbb5f8 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_overview_view.h @@ -1,17 +1,15 @@ - #pragma once #include "cod_codification_data_overview_model.h" -#include -#include -#include -#include #include #include - +#include +#include +#include +#include namespace Ui { @@ -21,49 +19,49 @@ class CodificationDataOverviewView; namespace CodificationManagement { - -class CodificationDataOverviewView : public LtsWidgets::LtsDialog, - protected CodificationManagement::Interface::Ftc::CodificationDataRemoveReplyHandler +class CodificationDataOverviewView + : public LtsWidgets::LtsDialog, + protected CodificationManagement::Interface::Ftc::CodificationDataRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit CodificationDataOverviewView(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~CodificationDataOverviewView(); + public: + explicit CodificationDataOverviewView(const QString& menuGroup, LtsSession::LtsSession* session, + QWidget* parent = nullptr); + ~CodificationDataOverviewView(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &ppmDtc); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& ppmDtc); - - void onCodificationDataRemoveReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onCodificationDataRemoveReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onShowCodificationData(); + void onAddCodificationData(); + void onEditCodificationData(); + void onRemoveCodificationData(); + void onPrint(); + void tableColumnOrganiserSetting() override; -private: + private: + QString m_menuGroup; + LtsSession::LtsSession* m_session; + CodificationDataOverviewModel* m_model; + CodificationDataOverviewProxyModel* m_proxyModel; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_ppmDtc; + LtsUtils::RequestHelper* m_requestHelper; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onShowCodificationData(); - void onAddCodificationData(); - void onEditCodificationData(); - void onRemoveCodificationData(); - void onPrint(); - void tableColumnOrganiserSetting() override; - -private: - QString m_menuGroup; - LtsSession::LtsSession *m_session; - CodificationDataOverviewModel *m_model; - CodificationDataOverviewProxyModel *m_proxyModel; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_ppmDtc; - - LtsUtils::RequestHelper *m_requestHelper; - - Ui::CodificationDataOverviewView *m_ui; + Ui::CodificationDataOverviewView* m_ui; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.cpp old mode 100755 new mode 100644 index 7ad1df115..258fa3700 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.cpp @@ -1,497 +1,463 @@ - #include "cod_codification_data_table_edit_view.h" -#include "cod_codification_data_report.h" -#include "ui_cod_codification_data_table_view.h" -#include -#include "cod_numeral_code_model.h" + #include "cod_authentication_code_model.h" -#include "cod_logistical_terms_model.h" -#include "cod_phrase_table_model.h" #include "cod_code_table_edit_delegate.h" +#include "cod_codification_data_report.h" #include "cod_csv_export.h" #include "cod_csv_import.h" +#include "cod_logistical_terms_model.h" +#include "cod_numeral_code_model.h" +#include "cod_phrase_table_model.h" +#include "ui_cod_codification_data_table_view.h" #include +#include #include namespace CodificationManagement { -CodificationDataTableEditView::CodificationDataTableEditView(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::CodificationDataTableView) - , m_numCodeModel(new NumeralCodeModel(this)) - , m_authenticationCodeModel(new AuthenticationCodeModel(this)) - , m_logisticalTermsModel(new LogisticalTermsModel(this)) - , m_phraseTableModel(new PhraseTableModel(this)) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +CodificationDataTableEditView::CodificationDataTableEditView(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::CodificationDataTableView), m_numCodeModel(new NumeralCodeModel(this)), + m_authenticationCodeModel(new AuthenticationCodeModel(this)), + m_logisticalTermsModel(new LogisticalTermsModel(this)), m_phraseTableModel(new PhraseTableModel(this)), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataTableEditView::onPrint); - - setOnlineHelpFilename(QStringLiteral("Situation-Add_Codification_Data")); - -} + m_ui->setupUi(this); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataTableEditView::onPrint); + setOnlineHelpFilename(QStringLiteral("Situation-Add_Codification_Data")); +} CodificationDataTableEditView::~CodificationDataTableEditView() { - delete m_ui; -} - + delete m_ui; +} void CodificationDataTableEditView::retranslate() { - translate(m_ui, m_dtc->codificationData(m_codificationDataId), tr("Codification Data")); -} + translate(m_ui, m_dtc->codificationData(m_codificationDataId), tr("Codification Data")); +} - -bool CodificationDataTableEditView::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - int codificationDataId) +bool CodificationDataTableEditView::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + LtsSession::LtsSession* session, int codificationDataId) { - DEBUG_LOG(m_logger) << "CodificationDataTableEditView::init() codificationDataId: " << codificationDataId; + DEBUG_LOG(m_logger) << "CodificationDataTableEditView::init() codificationDataId: " << codificationDataId; - if (!dtc || !ftc || !session) - { - ERROR_LOG(m_logger) << "CodificationDataTableEditView::init() Invalid shared_ptr!"; - return false; - } + if (!dtc || !ftc || !session) + { + ERROR_LOG(m_logger) << "CodificationDataTableEditView::init() Invalid shared_ptr!"; + return false; + } - m_dtc = dtc; - m_ftc = ftc; - m_session = session; - m_codificationDataId = codificationDataId; + m_dtc = dtc; + m_ftc = ftc; + m_session = session; + m_codificationDataId = codificationDataId; - m_uiRequirements->addRequirement({ m_ui->lbIdentifier, [this]() { return (!m_ui->leIdentifier->text().isEmpty()); } }); - std::function cbIsTimeValid = [this]()-> bool - { - if (m_ui->dteValidityTime->isEmpty()) - return true; - return m_ui->dteValidityTime->msecsSinceEpoch() >= m_session->partitionTime(); - }; - m_uiRequirements->addRequirement({ m_ui->lbDteValidityTime, cbIsTimeValid }); + m_uiRequirements->addRequirement( + {m_ui->lbIdentifier, [this]() { return (!m_ui->leIdentifier->text().isEmpty()); }}); + std::function cbIsTimeValid = [this]() -> bool { + if (m_ui->dteValidityTime->isEmpty()) + return true; + return m_ui->dteValidityTime->msecsSinceEpoch() >= m_session->partitionTime(); + }; + m_uiRequirements->addRequirement({m_ui->lbDteValidityTime, cbIsTimeValid}); - loadCodificationDataFromDatabase(); + loadCodificationDataFromDatabase(); - initNumeralModel(); - initAuthenticationModel(); - initLogisticalTermsModel(); - initPhraseTableModel(); + initNumeralModel(); + initAuthenticationModel(); + initLogisticalTermsModel(); + initPhraseTableModel(); - - m_ui->pteNote->setPlainText(QString::fromStdString(m_lastDdsCodificationData.note())); + m_ui->pteNote->setPlainText(QString::fromStdString(m_lastDdsCodificationData.note())); - - m_ui->leIdentifier->setText(QString::fromStdString(m_lastDdsCodificationData.identifier())); - m_ui->dteValidityTime->setMsecsSinceEpoch(m_lastDdsCodificationData.validityTime()); - m_ui->dteValidityTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + m_ui->leIdentifier->setText(QString::fromStdString(m_lastDdsCodificationData.identifier())); + m_ui->dteValidityTime->setMsecsSinceEpoch(m_lastDdsCodificationData.validityTime()); + m_ui->dteValidityTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &CodificationDataTableEditView::onLoadCodificationData); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("CSV Import")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, + &CodificationDataTableEditView::onLoadCodificationData); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("CSV Import")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, &CodificationDataTableEditView::onSaveCodificationData); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, true); - m_buttonBox->setText(LtsWidgets::DialogButton::Save, tr("CSV Export")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Save, this, + &CodificationDataTableEditView::onSaveCodificationData); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Save, true); + m_buttonBox->setText(LtsWidgets::DialogButton::Save, tr("CSV Export")); - if (m_codificationDataId < 1) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Ok, tr("Add")); - m_ui->dteValidityTime->setMinimumTimeMSec(m_session->partitionTime()); - } + if (m_codificationDataId < 1) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Ok, tr("Add")); + m_ui->dteValidityTime->setMinimumTimeMSec(m_session->partitionTime()); + } - - connect(m_numCodeModel, &NumeralCodeModel::dataModified, this, &CodificationDataTableEditView::onDataModified); - connect(m_authenticationCodeModel, &AuthenticationCodeModel::dataModified, this, &CodificationDataTableEditView::onDataModified); - connect(m_logisticalTermsModel, &LogisticalTermsModel::dataModified, this, &CodificationDataTableEditView::onDataModified); - connect(m_phraseTableModel, &PhraseTableModel::dataModified, this, &CodificationDataTableEditView::onDataModified); - connect(m_ui->pteNote, &QPlainTextEdit::textChanged, this, &CodificationDataTableEditView::onDataModified); + connect(m_numCodeModel, &NumeralCodeModel::dataModified, this, &CodificationDataTableEditView::onDataModified); + connect(m_authenticationCodeModel, &AuthenticationCodeModel::dataModified, this, + &CodificationDataTableEditView::onDataModified); + connect(m_logisticalTermsModel, &LogisticalTermsModel::dataModified, this, + &CodificationDataTableEditView::onDataModified); + connect(m_phraseTableModel, &PhraseTableModel::dataModified, this, &CodificationDataTableEditView::onDataModified); + connect(m_ui->pteNote, &QPlainTextEdit::textChanged, this, &CodificationDataTableEditView::onDataModified); - - m_buttonBox->connectLibraryButton(this, - &CodificationDataTableEditView::onImportButtonClicked, - &CodificationDataTableEditView::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &CodificationDataTableEditView::onImportButtonClicked, + &CodificationDataTableEditView::onExportButtonClicked); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - - return true; -} + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + return true; +} void CodificationDataTableEditView::onLoadCodificationData() { - DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onLoadCodificationData()"; + DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onLoadCodificationData()"; - QString note; - CSVImport csvImport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, - m_phraseTableModel, ¬e, this); + QString note; + CSVImport csvImport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel, ¬e, + this); - CSVImport::CSVImportResult result = csvImport.loadCSVData(); + CSVImport::CSVImportResult result = csvImport.loadCSVData(); - if (result == CSVImport::LoadOk) - { - DEBUG_LOG(m_logger) << "Load CSV data ok!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load CSV data ok. The loaded data must be taken over with the 'Apply' or 'Add' button."), tr("CSV Import Info")); - m_ui->pteNote->setPlainText(note); + if (result == CSVImport::LoadOk) + { + DEBUG_LOG(m_logger) << "Load CSV data ok!"; + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Load CSV data ok. The loaded data must be taken over with the 'Apply' or 'Add' button."), + tr("CSV Import Info")); + m_ui->pteNote->setPlainText(note); - - onDataModified(); - return; - } + onDataModified(); + return; + } - if (result == CSVImport::LoadFailed) - { - m_numCodeModel->resetHeader(); - m_authenticationCodeModel->resetMatrix(); - m_logisticalTermsModel->resetHeader(); - m_logisticalTermsModel->resetMatrix(); - m_phraseTableModel->resetMatrix(); - m_ui->pteNote->clear(); + if (result == CSVImport::LoadFailed) + { + m_numCodeModel->resetHeader(); + m_authenticationCodeModel->resetMatrix(); + m_logisticalTermsModel->resetHeader(); + m_logisticalTermsModel->resetMatrix(); + m_phraseTableModel->resetMatrix(); + m_ui->pteNote->clear(); - ERROR_LOG(m_logger) << "Load CSV data failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load CSV data failed!"), tr("CSV Import Info")); - return; - } - - if (result == CSVImport::UserAbort) - { - DEBUG_LOG(m_logger) << "Load CSV data abort by user"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load CSV data abort by user"), tr("CSV Import Info")); - } -} + ERROR_LOG(m_logger) << "Load CSV data failed!"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load CSV data failed!"), tr("CSV Import Info")); + return; + } + if (result == CSVImport::UserAbort) + { + DEBUG_LOG(m_logger) << "Load CSV data abort by user"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load CSV data abort by user"), tr("CSV Import Info")); + } +} void CodificationDataTableEditView::onSaveCodificationData() { - DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onSaveCodificationData()"; + DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onSaveCodificationData()"; - CSVExport csvExport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, - m_phraseTableModel, m_ui->pteNote->toPlainText(), this); - - if (!csvExport.writeCSVData()) - ERROR_LOG(m_logger) << "Write CSV data to file failed! id:" << m_codificationDataId; - else - DEBUG_LOG(m_logger) << "Write CSV data to file ok! id:" << m_codificationDataId; -} + CSVExport csvExport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel, + m_ui->pteNote->toPlainText(), this); + if (!csvExport.writeCSVData()) + ERROR_LOG(m_logger) << "Write CSV data to file failed! id:" << m_codificationDataId; + else + DEBUG_LOG(m_logger) << "Write CSV data to file ok! id:" << m_codificationDataId; +} void CodificationDataTableEditView::loadCodificationDataFromDatabase() { - m_lastDdsCodificationData = m_dtc->codificationData(m_codificationDataId); - DEBUG_LOG(m_logger) << "Load from database: ---"; - DEBUG_LOG(m_logger) << "NumCodeHorizontalHeader: " << m_lastDdsCodificationData.numeralCodeTableColumnIndex(); - DEBUG_LOG(m_logger) << "NumCodeVerticalHeader: " << m_lastDdsCodificationData.numeralCodeTableRowIndex(); + m_lastDdsCodificationData = m_dtc->codificationData(m_codificationDataId); + DEBUG_LOG(m_logger) << "Load from database: ---"; + DEBUG_LOG(m_logger) << "NumCodeHorizontalHeader: " << m_lastDdsCodificationData.numeralCodeTableColumnIndex(); + DEBUG_LOG(m_logger) << "NumCodeVerticalHeader: " << m_lastDdsCodificationData.numeralCodeTableRowIndex(); - DEBUG_LOG(m_logger) << "AuthenticationMatrix: " << m_lastDdsCodificationData.authenticationTableMatirx(); + DEBUG_LOG(m_logger) << "AuthenticationMatrix: " << m_lastDdsCodificationData.authenticationTableMatirx(); - DEBUG_LOG(m_logger) << "LogisticalTermsHorizontalHeader: " << m_lastDdsCodificationData.logisticalTermTableColumnIndex(); - DEBUG_LOG(m_logger) << "LogisticalTermsVerticalHeader: " << m_lastDdsCodificationData.logisticalTermTableRowIndex(); - DEBUG_LOG(m_logger) << "LogisticalTermsMatrix :" << m_lastDdsCodificationData.logisticalTermTableMatrix(); + DEBUG_LOG(m_logger) << "LogisticalTermsHorizontalHeader: " + << m_lastDdsCodificationData.logisticalTermTableColumnIndex(); + DEBUG_LOG(m_logger) << "LogisticalTermsVerticalHeader: " << m_lastDdsCodificationData.logisticalTermTableRowIndex(); + DEBUG_LOG(m_logger) << "LogisticalTermsMatrix :" << m_lastDdsCodificationData.logisticalTermTableMatrix(); - DEBUG_LOG(m_logger) << "PhraseTable :" << m_lastDdsCodificationData.phraseTable(); + DEBUG_LOG(m_logger) << "PhraseTable :" << m_lastDdsCodificationData.phraseTable(); - DEBUG_LOG(m_logger) << "Note: " << m_lastDdsCodificationData.note(); - - return; -} + DEBUG_LOG(m_logger) << "Note: " << m_lastDdsCodificationData.note(); + return; +} bool CodificationDataTableEditView::initNumeralModel() { - if (!m_numCodeModel->init(m_dtc, m_codificationDataId, true)) - return false; + if (!m_numCodeModel->init(m_dtc, m_codificationDataId, true)) + return false; - m_ui->tvNumeralCode->setModel(m_numCodeModel); - m_ui->tvNumeralCode->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::NumeralCode)); + m_ui->tvNumeralCode->setModel(m_numCodeModel); + m_ui->tvNumeralCode->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::NumeralCode)); - QFontMetricsF fm(font()); - const QRectF rect = fm.boundingRect(QLatin1String("W")); + QFontMetricsF fm(font()); + const QRectF rect = fm.boundingRect(QLatin1String("W")); - QHeaderView *header = m_ui->tvNumeralCode->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->resizeSection(0, rect.width() * 1.3); - - for (int i = 1; i <= 13; ++i) - header->resizeSection(i, rect.width() * 1.5); + QHeaderView* header = m_ui->tvNumeralCode->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); - QHeaderView *vheader = m_ui->tvNumeralCode->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); + header->resizeSection(0, rect.width() * 1.3); - vheader->resizeSection(0, rect.height() * 1.3); - for (int i = 1; i <= 13; ++i) - vheader->resizeSection(i, rect.height() * 1.5); + for (int i = 1; i <= 13; ++i) + header->resizeSection(i, rect.width() * 1.5); - m_ui->tvNumeralCode->setShowGrid(true); - m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); + QHeaderView* vheader = m_ui->tvNumeralCode->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); - - header->setVisible(false); - vheader->setVisible(false); - m_ui->tvNumeralCode->setColumnHidden(0, false); - m_ui->tvNumeralCode->setRowHidden(0, false); + vheader->resizeSection(0, rect.height() * 1.3); + for (int i = 1; i <= 13; ++i) + vheader->resizeSection(i, rect.height() * 1.5); - m_ui->tvNumeralCode->setMinimumWidth((rect.width() * 1.5 * 13) + rect.width() * 1.3 + 10); - m_ui->tvNumeralCode->setMinimumHeight((rect.height() * 1.5 * 13) + rect.height() * 1.3 + 10); + m_ui->tvNumeralCode->setShowGrid(true); + m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); - - if (m_codificationDataId > 0) - { - QString qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableColumnIndex()); - m_numCodeModel->setColumnSelectionValuesCSV(qs); + header->setVisible(false); + vheader->setVisible(false); + m_ui->tvNumeralCode->setColumnHidden(0, false); + m_ui->tvNumeralCode->setRowHidden(0, false); - qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableRowIndex()); - m_numCodeModel->setRowSelectionValuesCSV(qs); - } - return true; -} + m_ui->tvNumeralCode->setMinimumWidth((rect.width() * 1.5 * 13) + rect.width() * 1.3 + 10); + m_ui->tvNumeralCode->setMinimumHeight((rect.height() * 1.5 * 13) + rect.height() * 1.3 + 10); + if (m_codificationDataId > 0) + { + QString qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableColumnIndex()); + m_numCodeModel->setColumnSelectionValuesCSV(qs); + + qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableRowIndex()); + m_numCodeModel->setRowSelectionValuesCSV(qs); + } + return true; +} bool CodificationDataTableEditView::initAuthenticationModel() { - if (!m_authenticationCodeModel->init(m_dtc, m_codificationDataId, true)) - return false; + if (!m_authenticationCodeModel->init(m_dtc, m_codificationDataId, true)) + return false; - m_ui->tvAuthenticationTable->setModel(m_authenticationCodeModel); - m_ui->tvAuthenticationTable->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::AuthenticationCode)); + m_ui->tvAuthenticationTable->setModel(m_authenticationCodeModel); + m_ui->tvAuthenticationTable->setItemDelegate( + new CodeTableEditDelegate(this, CodeTableEditDelegate::AuthenticationCode)); - QFontMetricsF fm(font()); - const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WW")); + QFontMetricsF fm(font()); + const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WW")); - QHeaderView *header = m_ui->tvAuthenticationTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->setDefaultSectionSize(rectMatrix.width() * 2.1); + QHeaderView* header = m_ui->tvAuthenticationTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); - QHeaderView *vheader = m_ui->tvAuthenticationTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - - vheader->setMinimumWidth(rectHeader.width() * 1.3); - - vheader->setDefaultSectionSize(rectMatrix.height() * 1.5); + header->setDefaultSectionSize(rectMatrix.width() * 2.1); - m_ui->tvAuthenticationTable->setShowGrid(true); - m_ui->tvAuthenticationTable->setSelectionMode(QAbstractItemView::SingleSelection); + QHeaderView* vheader = m_ui->tvAuthenticationTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); - header->setVisible(true); - vheader->setVisible(true); + vheader->setMinimumWidth(rectHeader.width() * 1.3); - m_ui->tvAuthenticationTable->setMinimumWidth((rectMatrix.width() * 2.1 * 5) + rectHeader.width() * 1.3 + 5); - m_ui->tvAuthenticationTable->setMinimumHeight((rectMatrix.height() * 1.5 * 13) + rectHeader.height() * 1.3); + vheader->setDefaultSectionSize(rectMatrix.height() * 1.5); - - if (m_codificationDataId > 0) - m_authenticationCodeModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.authenticationTableMatirx())); - return true; -} + m_ui->tvAuthenticationTable->setShowGrid(true); + m_ui->tvAuthenticationTable->setSelectionMode(QAbstractItemView::SingleSelection); + header->setVisible(true); + vheader->setVisible(true); + + m_ui->tvAuthenticationTable->setMinimumWidth((rectMatrix.width() * 2.1 * 5) + rectHeader.width() * 1.3 + 5); + m_ui->tvAuthenticationTable->setMinimumHeight((rectMatrix.height() * 1.5 * 13) + rectHeader.height() * 1.3); + + if (m_codificationDataId > 0) + m_authenticationCodeModel->setMatrixValuesCSV( + QString::fromStdString(m_lastDdsCodificationData.authenticationTableMatirx())); + return true; +} bool CodificationDataTableEditView::initLogisticalTermsModel() { - if (!m_logisticalTermsModel->init(m_dtc, m_codificationDataId, true)) - return false; + if (!m_logisticalTermsModel->init(m_dtc, m_codificationDataId, true)) + return false; - m_ui->tvLogisticalTermsTable->setModel(m_logisticalTermsModel); - m_ui->tvLogisticalTermsTable->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::LogisticalTerms)); + m_ui->tvLogisticalTermsTable->setModel(m_logisticalTermsModel); + m_ui->tvLogisticalTermsTable->setItemDelegate( + new CodeTableEditDelegate(this, CodeTableEditDelegate::LogisticalTerms)); - QFontMetricsF fm(font()); - const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWW")); + QFontMetricsF fm(font()); + const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWW")); - QHeaderView *header = m_ui->tvLogisticalTermsTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->resizeSection(0, rectHeader.width() * 1.3); - - for (int i = 1; i <= 5; ++i) - header->resizeSection(i, rectMatrix.width() * 1.08); + QHeaderView* header = m_ui->tvLogisticalTermsTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); - QHeaderView *vheader = m_ui->tvLogisticalTermsTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); + header->resizeSection(0, rectHeader.width() * 1.3); - - vheader->resizeSection(0, rectHeader.height() * 1.3); - for (int i = 1; i <= 5; ++i) - vheader->resizeSection(i, rectMatrix.height() * 2.3); + for (int i = 1; i <= 5; ++i) + header->resizeSection(i, rectMatrix.width() * 1.08); - m_ui->tvLogisticalTermsTable->setShowGrid(true); - m_ui->tvLogisticalTermsTable->setSelectionMode(QAbstractItemView::SingleSelection); + QHeaderView* vheader = m_ui->tvLogisticalTermsTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); - - header->setVisible(false); - vheader->setVisible(false); - m_ui->tvLogisticalTermsTable->setColumnHidden(0, false); - m_ui->tvLogisticalTermsTable->setRowHidden(0, false); + vheader->resizeSection(0, rectHeader.height() * 1.3); + for (int i = 1; i <= 5; ++i) + vheader->resizeSection(i, rectMatrix.height() * 2.3); - m_ui->tvLogisticalTermsTable->setMinimumWidth((rectMatrix.width() * 1.08 * 5) + rectHeader.width() * 1.3 + 5); - m_ui->tvLogisticalTermsTable->setMinimumHeight((rectMatrix.height() * 2.3 * 5) + rectHeader.height() * 1.3); + m_ui->tvLogisticalTermsTable->setShowGrid(true); + m_ui->tvLogisticalTermsTable->setSelectionMode(QAbstractItemView::SingleSelection); - - - if (m_codificationDataId > 0) - { - QString qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableColumnIndex()); - m_logisticalTermsModel->setColumnSelectionValuesCSV(qs); + header->setVisible(false); + vheader->setVisible(false); + m_ui->tvLogisticalTermsTable->setColumnHidden(0, false); + m_ui->tvLogisticalTermsTable->setRowHidden(0, false); - qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableRowIndex()); - m_logisticalTermsModel->setRowSelectionValuesCSV(qs); + m_ui->tvLogisticalTermsTable->setMinimumWidth((rectMatrix.width() * 1.08 * 5) + rectHeader.width() * 1.3 + 5); + m_ui->tvLogisticalTermsTable->setMinimumHeight((rectMatrix.height() * 2.3 * 5) + rectHeader.height() * 1.3); - - m_logisticalTermsModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableMatrix())); - } - return true; -} + if (m_codificationDataId > 0) + { + QString qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableColumnIndex()); + m_logisticalTermsModel->setColumnSelectionValuesCSV(qs); + qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableRowIndex()); + m_logisticalTermsModel->setRowSelectionValuesCSV(qs); + + m_logisticalTermsModel->setMatrixValuesCSV( + QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableMatrix())); + } + return true; +} bool CodificationDataTableEditView::initPhraseTableModel() { - if (!m_phraseTableModel->init(m_dtc, m_codificationDataId, true)) - return false; + if (!m_phraseTableModel->init(m_dtc, m_codificationDataId, true)) + return false; - m_ui->tvPhraseTable->setModel(m_phraseTableModel); - m_ui->tvPhraseTable->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::PhraseTable)); + m_ui->tvPhraseTable->setModel(m_phraseTableModel); + m_ui->tvPhraseTable->setItemDelegate(new CodeTableEditDelegate(this, CodeTableEditDelegate::PhraseTable)); - QFontMetricsF fm(font()); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWWWWWWW")); + QFontMetricsF fm(font()); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWWWWWWW")); - QHeaderView *header = m_ui->tvPhraseTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - header->setDefaultSectionSize(rectMatrix.width() * 1.08); + QHeaderView* header = m_ui->tvPhraseTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); + header->setDefaultSectionSize(rectMatrix.width() * 1.08); - QHeaderView *vheader = m_ui->tvPhraseTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - vheader->setDefaultSectionSize(rectMatrix.height() * 1.3); + QHeaderView* vheader = m_ui->tvPhraseTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); + vheader->setDefaultSectionSize(rectMatrix.height() * 1.3); - m_ui->tvPhraseTable->setShowGrid(true); - m_ui->tvPhraseTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->tvPhraseTable->setShowGrid(true); + m_ui->tvPhraseTable->setSelectionMode(QAbstractItemView::SingleSelection); - - header->setVisible(false); - vheader->setVisible(false); + header->setVisible(false); + vheader->setVisible(false); - m_ui->tvPhraseTable->setMinimumWidth((rectMatrix.width() * 1.08 * 2) + 5); - m_ui->tvPhraseTable->setMinimumHeight((rectMatrix.height() * 1.3 * 13)); - - - if (m_codificationDataId > 0) - m_phraseTableModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.phraseTable())); - return true; -} + m_ui->tvPhraseTable->setMinimumWidth((rectMatrix.width() * 1.08 * 2) + 5); + m_ui->tvPhraseTable->setMinimumHeight((rectMatrix.height() * 1.3 * 13)); + if (m_codificationDataId > 0) + m_phraseTableModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.phraseTable())); + return true; +} void CodificationDataTableEditView::onDataModified() { - slotChangesMade(); -} - + slotChangesMade(); +} void CodificationDataTableEditView::onPrint() { - CodificationDataReport report(this, m_session, m_ui, m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel); - report.print(false); -} - + CodificationDataReport report(this, m_session, m_ui, m_numCodeModel, m_authenticationCodeModel, + m_logisticalTermsModel, m_phraseTableModel); + report.print(false); +} bool CodificationDataTableEditView::apply() { - DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onOkayCodificationData()"; + DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onOkayCodificationData()"; - - - - + CodificationManagement::CodificationData modifiedCodificationData(m_lastDdsCodificationData); - CodificationManagement::CodificationData modifiedCodificationData(m_lastDdsCodificationData); + modifiedCodificationData.name(m_ui->leIdentifier->text().toStdString()); - - modifiedCodificationData.name(m_ui->leIdentifier->text().toStdString()); + modifiedCodificationData.numeralCodeTableColumnIndex(m_numCodeModel->getHorizontalHeaderCSVString().toStdString()); + modifiedCodificationData.numeralCodeTableRowIndex(m_numCodeModel->getVerticalHeaderCSVString().toStdString()); - - modifiedCodificationData.numeralCodeTableColumnIndex(m_numCodeModel->getHorizontalHeaderCSVString().toStdString()); - modifiedCodificationData.numeralCodeTableRowIndex(m_numCodeModel->getVerticalHeaderCSVString().toStdString()) ; + DEBUG_LOG(m_logger) << "onOkayCodificationData() HH: " << m_numCodeModel->getHorizontalHeaderCSVString(); + DEBUG_LOG(m_logger) << "onOkayCodificationData() VH: " << m_numCodeModel->getVerticalHeaderCSVString(); - DEBUG_LOG(m_logger) << "onOkayCodificationData() HH: " << m_numCodeModel->getHorizontalHeaderCSVString(); - DEBUG_LOG(m_logger) << "onOkayCodificationData() VH: " << m_numCodeModel->getVerticalHeaderCSVString(); + modifiedCodificationData.authenticationTableMatirx( + m_authenticationCodeModel->getMatrixDataCSVString().toStdString()); + DEBUG_LOG(m_logger) << "onOkayCodificationData() authMatrix: " + << m_authenticationCodeModel->getMatrixDataCSVString(); - - modifiedCodificationData.authenticationTableMatirx(m_authenticationCodeModel->getMatrixDataCSVString().toStdString()); - DEBUG_LOG(m_logger) << "onOkayCodificationData() authMatrix: " << m_authenticationCodeModel->getMatrixDataCSVString(); + modifiedCodificationData.logisticalTermTableColumnIndex( + m_logisticalTermsModel->getHorizontalHeaderCSVString().toStdString()); + modifiedCodificationData.logisticalTermTableRowIndex( + m_logisticalTermsModel->getVerticalHeaderCSVString().toStdString()); + modifiedCodificationData.logisticalTermTableMatrix(m_logisticalTermsModel->getMatrixDataCSVString().toStdString()); + DEBUG_LOG(m_logger) << "onOkayCodificationData() HH: " << m_logisticalTermsModel->getHorizontalHeaderCSVString(); + DEBUG_LOG(m_logger) << "onOkayCodificationData() VH: " << m_logisticalTermsModel->getVerticalHeaderCSVString(); + DEBUG_LOG(m_logger) << "onOkayCodificationData() logTermsMatrix: " + << m_logisticalTermsModel->getMatrixDataCSVString(); - - modifiedCodificationData.logisticalTermTableColumnIndex(m_logisticalTermsModel->getHorizontalHeaderCSVString().toStdString()); - modifiedCodificationData.logisticalTermTableRowIndex(m_logisticalTermsModel->getVerticalHeaderCSVString().toStdString()); - modifiedCodificationData.logisticalTermTableMatrix(m_logisticalTermsModel->getMatrixDataCSVString().toStdString()); - DEBUG_LOG(m_logger) << "onOkayCodificationData() HH: " << m_logisticalTermsModel->getHorizontalHeaderCSVString(); - DEBUG_LOG(m_logger) << "onOkayCodificationData() VH: " << m_logisticalTermsModel->getVerticalHeaderCSVString(); - DEBUG_LOG(m_logger) << "onOkayCodificationData() logTermsMatrix: " << m_logisticalTermsModel->getMatrixDataCSVString(); + modifiedCodificationData.phraseTable(m_phraseTableModel->getMatrixDataCSVString().toStdString()); + DEBUG_LOG(m_logger) << "onOkayCodificationData() phraseTable: " << m_phraseTableModel->getMatrixDataCSVString(); - - modifiedCodificationData.phraseTable(m_phraseTableModel->getMatrixDataCSVString().toStdString()); - DEBUG_LOG(m_logger) << "onOkayCodificationData() phraseTable: " << m_phraseTableModel->getMatrixDataCSVString(); + modifiedCodificationData.note(m_ui->pteNote->toPlainText().toStdString()); + DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onOkayCodificationData()"; - - modifiedCodificationData.note(m_ui->pteNote->toPlainText().toStdString()); - DEBUG_LOG(m_logger) << "CodificationDataTableEditView::onOkayCodificationData()"; + modifiedCodificationData.identifier(m_ui->leIdentifier->text().toStdString()); + modifiedCodificationData.validityTime(m_ui->dteValidityTime->msecsSinceEpoch()); - modifiedCodificationData.identifier(m_ui->leIdentifier->text().toStdString()); - modifiedCodificationData.validityTime(m_ui->dteValidityTime->msecsSinceEpoch()); + if (m_codificationDataId < 1) + modifiedCodificationData.partyId(-1); - if (m_codificationDataId < 1) - modifiedCodificationData.partyId(-1); - - m_requestHelper->addRequest([this, modifiedCodificationData]() - { - return m_ftc->codificationDataModifyRequest(modifiedCodificationData, this); - }); - - return m_requestHelper->startRequests(); -} + m_requestHelper->addRequest([this, modifiedCodificationData]() { + return m_ftc->codificationDataModifyRequest(modifiedCodificationData, this); + }); + return m_requestHelper->startRequests(); +} void CodificationDataTableEditView::onExportButtonClicked() { - CSVExport csvExport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, - m_phraseTableModel, m_ui->pteNote->toPlainText(), this); + CSVExport csvExport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel, + m_ui->pteNote->toPlainText(), this); - const QByteArray byteArray = csvExport.exportToByteArray(); - - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Text, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + const QByteArray byteArray = csvExport.exportToByteArray(); + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Text, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } - void CodificationDataTableEditView::onImportButtonClicked() { - DEBUG_LOG(m_logger) << " onImportButtonClicked() "; - QString note; - CSVImport csvImport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, - m_phraseTableModel, ¬e, this); + DEBUG_LOG(m_logger) << " onImportButtonClicked() "; + QString note; + CSVImport csvImport(m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel, ¬e, + this); - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Text}, m_session->exerciseId()); - if (fileId > 0) - { - if (!content.isEmpty()) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Text}, m_session->exerciseId()); + if (fileId > 0) { - + if (!content.isEmpty()) + { - INFO_LOG(m_logger) << "--- onImportButtonClicked() "; - csvImport.loadCSVDataByteArray(content); - m_ui->pteNote->setPlainText(note); + INFO_LOG(m_logger) << "--- onImportButtonClicked() "; + csvImport.loadCSVDataByteArray(content); + m_ui->pteNote->setPlainText(note); + } } - } } - - -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.h old mode 100755 new mode 100644 index c5ab0eae5..648d99600 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_edit_view.h @@ -1,16 +1,14 @@ - #pragma once -#include +#include #include - +#include +#include +#include #include #include -#include -#include -#include namespace Ui { @@ -26,82 +24,67 @@ class LogisticalTermsModel; class PhraseTableModel; class CSVExport; -class CodificationDataTableEditView : public LtsWidgets::LtsDialog, - protected CodificationManagement::Interface::Ftc::CodificationDataModifyReplyHandler +class CodificationDataTableEditView + : public LtsWidgets::LtsDialog, + protected CodificationManagement::Interface::Ftc::CodificationDataModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit CodificationDataTableEditView(QWidget *parent = nullptr); + public: + explicit CodificationDataTableEditView(QWidget* parent = nullptr); - ~CodificationDataTableEditView(); + ~CodificationDataTableEditView(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - int codificationDataId); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, LtsSession::LtsSession* session, + int codificationDataId); + void onCodificationDataModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } - - void onCodificationDataModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - QByteArray exportToByteArray(); + QByteArray exportToByteArray(); -private slots: - + private slots: - void onDataModified(); - void onPrint(); - void onExportButtonClicked(); - void onImportButtonClicked(); + void onDataModified(); + void onPrint(); + void onExportButtonClicked(); + void onImportButtonClicked(); - - + bool apply() override; - bool apply() override; + void onLoadCodificationData(); + void onSaveCodificationData(); - void onLoadCodificationData(); - void onSaveCodificationData(); + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void loadCodificationDataFromDatabase(); + bool initNumeralModel(); -private: + bool initAuthenticationModel(); + bool initLogisticalTermsModel(); -NGL::INGLLogger &m_logger; - void retranslate() override; - void loadCodificationDataFromDatabase(); + bool initPhraseTableModel(); - + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_flmGui; + LtsSession::LtsSession* m_session{nullptr}; + int m_codificationDataId{0}; - bool initNumeralModel(); - - - - bool initAuthenticationModel(); - - - - bool initLogisticalTermsModel(); - - - - bool initPhraseTableModel(); - -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_flmGui; - LtsSession::LtsSession *m_session{nullptr}; - int m_codificationDataId{0}; - - Ui::CodificationDataTableView *m_ui{nullptr}; - NumeralCodeModel *m_numCodeModel{nullptr}; - AuthenticationCodeModel *m_authenticationCodeModel{nullptr}; - LogisticalTermsModel *m_logisticalTermsModel{nullptr}; - PhraseTableModel *m_phraseTableModel{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - CodificationManagement::CodificationData m_lastDdsCodificationData; + Ui::CodificationDataTableView* m_ui{nullptr}; + NumeralCodeModel* m_numCodeModel{nullptr}; + AuthenticationCodeModel* m_authenticationCodeModel{nullptr}; + LogisticalTermsModel* m_logisticalTermsModel{nullptr}; + PhraseTableModel* m_phraseTableModel{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + CodificationManagement::CodificationData m_lastDdsCodificationData; }; -} - - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.cpp old mode 100755 new mode 100644 index db2805f3b..91e5fbb78 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.cpp @@ -1,339 +1,307 @@ - #include "cod_codification_data_table_view.h" -#include "ui_cod_codification_data_table_view.h" -#include "cod_numeral_code_model.h" + #include "cod_authentication_code_model.h" -#include "cod_logistical_terms_model.h" -#include "cod_phrase_table_model.h" #include "cod_codification_data_report.h" +#include "cod_logistical_terms_model.h" +#include "cod_numeral_code_model.h" +#include "cod_phrase_table_model.h" +#include "ui_cod_codification_data_table_view.h" #include - using namespace CodificationManagement; -CodificationDataTableView::CodificationDataTableView(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::CodificationDataTableView) - , m_numCodeModel(new NumeralCodeModel(this)) - , m_authenticationCodeModel(new AuthenticationCodeModel(this)) - , m_logisticalTermsModel(new LogisticalTermsModel(this)) - , m_phraseTableModel(new PhraseTableModel(this)) +CodificationDataTableView::CodificationDataTableView(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ui(new Ui::CodificationDataTableView), + m_numCodeModel(new NumeralCodeModel(this)), m_authenticationCodeModel(new AuthenticationCodeModel(this)), + m_logisticalTermsModel(new LogisticalTermsModel(this)), m_phraseTableModel(new PhraseTableModel(this)) { - m_ui->setupUi(this); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataTableView::onPrint); - -} - + m_ui->setupUi(this); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CodificationDataTableView::onPrint); +} CodificationDataTableView::~CodificationDataTableView() { - delete m_ui; - delete m_numCodeModel; - delete m_authenticationCodeModel; - delete m_logisticalTermsModel; - delete m_phraseTableModel; -} - + delete m_ui; + delete m_numCodeModel; + delete m_authenticationCodeModel; + delete m_logisticalTermsModel; + delete m_phraseTableModel; +} void CodificationDataTableView::retranslate() { + if (m_partyId == 2) + translate(m_ui, tr("Codification Data Table OPFOR")); - if (m_partyId == 2) - translate(m_ui, tr("Codification Data Table OPFOR")); + if (m_partyId == 3) + translate(m_ui, tr("Codification Data Table BLUFOR")); +} - if (m_partyId == 3) - translate(m_ui, tr("Codification Data Table BLUFOR")); -} - - -bool CodificationDataTableView::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - int partyId, - int codificationDataId) +bool CodificationDataTableView::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + LtsSession::LtsSession* session, int partyId, int codificationDataId) { - DEBUG_LOG(m_logger) << "CodificationDataTableView::init()"; + DEBUG_LOG(m_logger) << "CodificationDataTableView::init()"; - m_dtc = dtc; - m_ftc = ftc; - m_session = session; - m_partyId = partyId; - m_codificationDataId = codificationDataId; + m_dtc = dtc; + m_ftc = ftc; + m_session = session; + m_partyId = partyId; + m_codificationDataId = codificationDataId; - if (!m_dtc || !m_ftc || !m_session) - { - ERROR_LOG(m_logger) << "CodificationDataTableView::init() Invalid shared_ptr!"; - return false; - } + if (!m_dtc || !m_ftc || !m_session) + { + ERROR_LOG(m_logger) << "CodificationDataTableView::init() Invalid shared_ptr!"; + return false; + } - if (codificationDataId < 0) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid codification Data Id. Probably the table is not assigned to any party.")); - ERROR_LOG(m_logger) << "CodificationDataTableView::init() Invalid codificationDataId: " << codificationDataId; - return false; - } + if (codificationDataId < 0) + { + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Invalid codification Data Id. Probably the table is not assigned to any party.")); + ERROR_LOG(m_logger) << "CodificationDataTableView::init() Invalid codificationDataId: " << codificationDataId; + return false; + } - loadCodificationDataFromDatabase(); + loadCodificationDataFromDatabase(); - initNumeralModel(); - initAuthenticationModel(); - initLogicalTermsModel(); - initPhraseTableModel(); + initNumeralModel(); + initAuthenticationModel(); + initLogicalTermsModel(); + initPhraseTableModel(); + m_ui->lbIdentifier->hide(); + m_ui->leIdentifier->hide(); + m_ui->lbDteValidityTime->hide(); + m_ui->dteValidityTime->hide(); + m_ui->pteNote->setPlainText(QString::fromStdString(m_lastDdsCodificationData.note())); + m_ui->pteNote->setReadOnly(true); + connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &CodificationDataTableView::onCodificationDataChanged); - - m_ui->lbIdentifier->hide(); - m_ui->leIdentifier->hide(); - m_ui->lbDteValidityTime->hide(); - m_ui->dteValidityTime->hide(); + if (m_partyId == 2) + setOnlineHelpFilename(QStringLiteral("Situation-Show_OPFOR_Codification_Data")); - - m_ui->pteNote->setPlainText(QString::fromStdString(m_lastDdsCodificationData.note())); - m_ui->pteNote->setReadOnly(true); - - connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &CodificationDataTableView::onCodificationDataChanged); - - if (m_partyId == 2) - setOnlineHelpFilename(QStringLiteral("Situation-Show_OPFOR_Codification_Data")); - - if (m_partyId == 3) - setOnlineHelpFilename(QStringLiteral("Situation-Show_BLUFOR_Codification_Data")); - - return true; -} + if (m_partyId == 3) + setOnlineHelpFilename(QStringLiteral("Situation-Show_BLUFOR_Codification_Data")); + return true; +} void CodificationDataTableView::loadCodificationDataFromDatabase() { - DEBUG_LOG(m_logger) << "CodificationDataTableView::loadCodificationDataFromDatabase()"; + DEBUG_LOG(m_logger) << "CodificationDataTableView::loadCodificationDataFromDatabase()"; - m_lastDdsCodificationData = m_dtc->codificationData(m_codificationDataId); - DEBUG_LOG(m_logger) << "Load from database: "; - DEBUG_LOG(m_logger) << "NumCodeHorizontalHeader: " << m_lastDdsCodificationData.numeralCodeTableColumnIndex(); - DEBUG_LOG(m_logger) << "NumCodeVerticalHeader: " << m_lastDdsCodificationData.numeralCodeTableRowIndex(); + m_lastDdsCodificationData = m_dtc->codificationData(m_codificationDataId); + DEBUG_LOG(m_logger) << "Load from database: "; + DEBUG_LOG(m_logger) << "NumCodeHorizontalHeader: " << m_lastDdsCodificationData.numeralCodeTableColumnIndex(); + DEBUG_LOG(m_logger) << "NumCodeVerticalHeader: " << m_lastDdsCodificationData.numeralCodeTableRowIndex(); - DEBUG_LOG(m_logger) << "LogisticalTermsHorizontalHeader: " << m_lastDdsCodificationData.logisticalTermTableColumnIndex(); - DEBUG_LOG(m_logger) << "LogisticalTermsVerticalHeader: " << m_lastDdsCodificationData.logisticalTermTableRowIndex(); - DEBUG_LOG(m_logger) << "LogisticalTermsMatrix: " << m_lastDdsCodificationData.logisticalTermTableMatrix(); + DEBUG_LOG(m_logger) << "LogisticalTermsHorizontalHeader: " + << m_lastDdsCodificationData.logisticalTermTableColumnIndex(); + DEBUG_LOG(m_logger) << "LogisticalTermsVerticalHeader: " << m_lastDdsCodificationData.logisticalTermTableRowIndex(); + DEBUG_LOG(m_logger) << "LogisticalTermsMatrix: " << m_lastDdsCodificationData.logisticalTermTableMatrix(); - DEBUG_LOG(m_logger) << "AuthenticationMatrix: " << m_lastDdsCodificationData.authenticationTableMatirx(); + DEBUG_LOG(m_logger) << "AuthenticationMatrix: " << m_lastDdsCodificationData.authenticationTableMatirx(); - DEBUG_LOG(m_logger) << "PhraseTable: " << m_lastDdsCodificationData.phraseTable(); + DEBUG_LOG(m_logger) << "PhraseTable: " << m_lastDdsCodificationData.phraseTable(); - DEBUG_LOG(m_logger) << "Note: " << m_lastDdsCodificationData.note(); - - return; -} + DEBUG_LOG(m_logger) << "Note: " << m_lastDdsCodificationData.note(); + return; +} void CodificationDataTableView::onPrint() { - CodificationDataReport report( this, m_session, m_ui, m_numCodeModel, m_authenticationCodeModel, m_logisticalTermsModel, m_phraseTableModel ); - report.print(true); - -} - - + CodificationDataReport report(this, m_session, m_ui, m_numCodeModel, m_authenticationCodeModel, + m_logisticalTermsModel, m_phraseTableModel); + report.print(true); +} bool CodificationDataTableView::initNumeralModel() { - bool bOk = false; + bool bOk = false; - if (!m_numCodeModel->init(m_dtc, m_codificationDataId, false)) + if (!m_numCodeModel->init(m_dtc, m_codificationDataId, false)) + return bOk; + + m_ui->tvNumeralCode->setModel(m_numCodeModel); + + QFontMetricsF fm(font()); + const QRectF rect = fm.boundingRect(QLatin1String("W")); + + QHeaderView* header = m_ui->tvNumeralCode->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); + + header->setDefaultSectionSize(rect.width() * 1.5); + + QHeaderView* vheader = m_ui->tvNumeralCode->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); + + vheader->setMinimumWidth(rect.width() * 1.3); + + vheader->setDefaultSectionSize(rect.height() * 1.5); + + m_ui->tvNumeralCode->setShowGrid(true); + m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); + + header->setVisible(true); + vheader->setVisible(true); + m_ui->tvNumeralCode->setColumnHidden(0, true); + m_ui->tvNumeralCode->setRowHidden(0, true); + + m_ui->tvNumeralCode->setMinimumWidth((rect.width() * 1.5 * 13) + rect.width() * 1.3 + 10); + m_ui->tvNumeralCode->setMinimumHeight((rect.height() * 1.5 * 13) + rect.height() * 1.5 + 10); + + if (m_codificationDataId > 0) + { + QString qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableColumnIndex()); + m_numCodeModel->setColumnSelectionValuesCSV(qs); + + qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableRowIndex()); + m_numCodeModel->setRowSelectionValuesCSV(qs); + } return bOk; - - m_ui->tvNumeralCode->setModel(m_numCodeModel); - - QFontMetricsF fm(font()); - const QRectF rect = fm.boundingRect(QLatin1String("W")); - - QHeaderView *header = m_ui->tvNumeralCode->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->setDefaultSectionSize(rect.width() * 1.5); - - QHeaderView *vheader = m_ui->tvNumeralCode->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - - vheader->setMinimumWidth(rect.width() * 1.3); - - vheader->setDefaultSectionSize(rect.height() * 1.5); - - m_ui->tvNumeralCode->setShowGrid(true); - m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); - - - header->setVisible(true); - vheader->setVisible(true); - m_ui->tvNumeralCode->setColumnHidden(0, true); - m_ui->tvNumeralCode->setRowHidden(0, true); - - m_ui->tvNumeralCode->setMinimumWidth((rect.width() * 1.5 * 13) + rect.width() * 1.3 + 10); - m_ui->tvNumeralCode->setMinimumHeight((rect.height() * 1.5 * 13) + rect.height() * 1.5 + 10); - - - if (m_codificationDataId > 0) - { - QString qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableColumnIndex()); - m_numCodeModel->setColumnSelectionValuesCSV(qs); - - qs = QString::fromStdString(m_lastDdsCodificationData.numeralCodeTableRowIndex()); - m_numCodeModel->setRowSelectionValuesCSV(qs); - } - return bOk; -} - +} bool CodificationDataTableView::initAuthenticationModel() { - bool bOk = false; + bool bOk = false; - if (!m_authenticationCodeModel->init(m_dtc, m_codificationDataId, false)) + if (!m_authenticationCodeModel->init(m_dtc, m_codificationDataId, false)) + return bOk; + + m_ui->tvAuthenticationTable->setModel(m_authenticationCodeModel); + + QFontMetricsF fm(font()); + const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WW")); + + QHeaderView* header = m_ui->tvAuthenticationTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); + + header->setDefaultSectionSize(rectMatrix.width() * 2.1); + + QHeaderView* vheader = m_ui->tvAuthenticationTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); + + vheader->setMinimumWidth(rectHeader.width() * 1.3); + + vheader->setDefaultSectionSize(rectMatrix.height() * 1.5); + + m_ui->tvAuthenticationTable->setShowGrid(true); + m_ui->tvAuthenticationTable->setSelectionMode(QAbstractItemView::SingleSelection); + + header->setVisible(true); + vheader->setVisible(true); + + m_ui->tvAuthenticationTable->setMinimumWidth((rectMatrix.width() * 2.1 * 5) + rectHeader.width() * 1.3 + 5); + m_ui->tvAuthenticationTable->setMinimumHeight((rectMatrix.height() * 1.5 * 13) + rectHeader.height() * 1.3); + + if (m_codificationDataId > 0) + { + m_authenticationCodeModel->setMatrixValuesCSV( + QString::fromStdString(m_lastDdsCodificationData.authenticationTableMatirx())); + } return bOk; - - m_ui->tvAuthenticationTable->setModel(m_authenticationCodeModel); - - QFontMetricsF fm(font()); - const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WW")); - - QHeaderView *header = m_ui->tvAuthenticationTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->setDefaultSectionSize(rectMatrix.width() * 2.1); - - QHeaderView *vheader = m_ui->tvAuthenticationTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - - vheader->setMinimumWidth(rectHeader.width() * 1.3); - - vheader->setDefaultSectionSize(rectMatrix.height() * 1.5); - - m_ui->tvAuthenticationTable->setShowGrid(true); - m_ui->tvAuthenticationTable->setSelectionMode(QAbstractItemView::SingleSelection); - - header->setVisible(true); - vheader->setVisible(true); - - m_ui->tvAuthenticationTable->setMinimumWidth((rectMatrix.width() * 2.1 * 5) + rectHeader.width() * 1.3 + 5); - m_ui->tvAuthenticationTable->setMinimumHeight((rectMatrix.height() * 1.5 * 13) + rectHeader.height() * 1.3); - - - if (m_codificationDataId > 0) - { - m_authenticationCodeModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.authenticationTableMatirx())); - } - return bOk; -} - +} bool CodificationDataTableView::initLogicalTermsModel() { - bool bOk = false; + bool bOk = false; - if (!m_logisticalTermsModel->init(m_dtc, m_codificationDataId, false)) + if (!m_logisticalTermsModel->init(m_dtc, m_codificationDataId, false)) + return bOk; + + m_ui->tvLogisticalTermsTable->setModel(m_logisticalTermsModel); + + QFontMetricsF fm(font()); + const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWW")); + + QHeaderView* header = m_ui->tvLogisticalTermsTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); + + header->setDefaultSectionSize(rectMatrix.width() * 1.08); + + QHeaderView* vheader = m_ui->tvLogisticalTermsTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); + + vheader->setMinimumWidth(rectHeader.width() * 1.08); + + vheader->setDefaultSectionSize(rectMatrix.height() * 2.3); + + m_ui->tvLogisticalTermsTable->setShowGrid(true); + m_ui->tvLogisticalTermsTable->setSelectionMode(QAbstractItemView::SingleSelection); + + header->setVisible(true); + vheader->setVisible(true); + + m_ui->tvLogisticalTermsTable->setMinimumWidth((rectMatrix.width() * 1.08 * 5) + rectHeader.width() * 1.08 + 5); + m_ui->tvLogisticalTermsTable->setMinimumHeight((rectMatrix.height() * 2.3 * 5) + rectHeader.height() * 1.3); + + if (m_codificationDataId > 0) + { + QString qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableColumnIndex()); + m_logisticalTermsModel->setColumnSelectionValuesCSV(qs); + + qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableRowIndex()); + m_logisticalTermsModel->setRowSelectionValuesCSV(qs); + + m_logisticalTermsModel->setMatrixValuesCSV( + QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableMatrix())); + } return bOk; - - m_ui->tvLogisticalTermsTable->setModel(m_logisticalTermsModel); - - QFontMetricsF fm(font()); - const QRectF rectHeader = fm.boundingRect(QLatin1String("W")); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWW")); - - QHeaderView *header = m_ui->tvLogisticalTermsTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - - header->setDefaultSectionSize(rectMatrix.width() * 1.08); - - QHeaderView *vheader = m_ui->tvLogisticalTermsTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - - vheader->setMinimumWidth(rectHeader.width() * 1.08); - - vheader->setDefaultSectionSize(rectMatrix.height() * 2.3); - - m_ui->tvLogisticalTermsTable->setShowGrid(true); - m_ui->tvLogisticalTermsTable->setSelectionMode(QAbstractItemView::SingleSelection); - - - header->setVisible(true); - vheader->setVisible(true); - - m_ui->tvLogisticalTermsTable->setMinimumWidth((rectMatrix.width() * 1.08 * 5) + rectHeader.width() * 1.08 + 5); - m_ui->tvLogisticalTermsTable->setMinimumHeight((rectMatrix.height() * 2.3 * 5) + rectHeader.height() * 1.3); - - - - if (m_codificationDataId > 0) - { - QString qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableColumnIndex()); - m_logisticalTermsModel->setColumnSelectionValuesCSV(qs); - - qs = QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableRowIndex()); - m_logisticalTermsModel->setRowSelectionValuesCSV(qs); - - - m_logisticalTermsModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.logisticalTermTableMatrix())); - } - return bOk; -} - +} bool CodificationDataTableView::initPhraseTableModel() { - bool bOk = false; + bool bOk = false; - if (!m_phraseTableModel->init(m_dtc, m_codificationDataId, false)) + if (!m_phraseTableModel->init(m_dtc, m_codificationDataId, false)) + return bOk; + + m_ui->tvPhraseTable->setModel(m_phraseTableModel); + + QFontMetricsF fm(font()); + const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWWWWWWW")); + + QHeaderView* header = m_ui->tvPhraseTable->horizontalHeader(); + header->setSectionResizeMode(QHeaderView::Fixed); + header->setDefaultSectionSize(rectMatrix.width() * 1.08); + + QHeaderView* vheader = m_ui->tvPhraseTable->verticalHeader(); + vheader->setSectionResizeMode(QHeaderView::Fixed); + vheader->setDefaultSectionSize(rectMatrix.height() * 1.3); + + m_ui->tvPhraseTable->setShowGrid(true); + m_ui->tvPhraseTable->setSelectionMode(QAbstractItemView::SingleSelection); + + header->setVisible(false); + vheader->setVisible(false); + + m_ui->tvPhraseTable->setMinimumWidth((rectMatrix.width() * 1.08 * 2) + 5); + m_ui->tvPhraseTable->setMinimumHeight(rectMatrix.height() * 1.3 * 13); + + if (m_codificationDataId > 0) + { + + m_phraseTableModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.phraseTable())); + } return bOk; +} - m_ui->tvPhraseTable->setModel(m_phraseTableModel); - - QFontMetricsF fm(font()); - const QRectF rectMatrix = fm.boundingRect(QLatin1String("WWWWWWWWWWWWWWW")); - - QHeaderView *header = m_ui->tvPhraseTable->horizontalHeader(); - header->setSectionResizeMode(QHeaderView::Fixed); - header->setDefaultSectionSize(rectMatrix.width() * 1.08); - - QHeaderView *vheader = m_ui->tvPhraseTable->verticalHeader(); - vheader->setSectionResizeMode(QHeaderView::Fixed); - vheader->setDefaultSectionSize(rectMatrix.height() * 1.3); - - m_ui->tvPhraseTable->setShowGrid(true); - m_ui->tvPhraseTable->setSelectionMode(QAbstractItemView::SingleSelection); - - - header->setVisible(false); - vheader->setVisible(false); - - m_ui->tvPhraseTable->setMinimumWidth((rectMatrix.width() * 1.08 * 2) + 5); - m_ui->tvPhraseTable->setMinimumHeight(rectMatrix.height() * 1.3 * 13); - - - if (m_codificationDataId > 0) - { - - m_phraseTableModel->setMatrixValuesCSV(QString::fromStdString(m_lastDdsCodificationData.phraseTable())); - } - return bOk; -} - - -void CodificationDataTableView::onCodificationDataChanged(const CodificationManagement::CodificationData &data, +void CodificationDataTableView::onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType) { - if (m_codificationDataId != data.id() || modType == DataModification::eRemoved) - return; - - m_ui->pteNote->setPlainText(QString::fromStdString(data.note())); - -} - + if (m_codificationDataId != data.id() || modType == DataModification::eRemoved) + return; + m_ui->pteNote->setPlainText(QString::fromStdString(data.note())); +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.h old mode 100755 new mode 100644 index c994dd012..9412cdc57 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_codification_data_table_view.h @@ -1,22 +1,18 @@ - #pragma once -#include +#include #include - +#include #include #include -#include - namespace Ui { class CodificationDataTableView; } - namespace CodificationManagement { @@ -27,61 +23,47 @@ class PhraseTableModel; class CodificationDataTableView : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit CodificationDataTableView(QWidget *parent = nullptr); + public: + explicit CodificationDataTableView(QWidget* parent = nullptr); - ~CodificationDataTableView(); + ~CodificationDataTableView(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - int partyId, - int codificationDataId); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, LtsSession::LtsSession* session, + int partyId, int codificationDataId); -private Q_SLOTS: - + private Q_SLOTS: - void onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType); + void onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void loadCodificationDataFromDatabase(); + void onPrint(); -NGL::INGLLogger &m_logger; - void retranslate() override; - void loadCodificationDataFromDatabase(); - void onPrint(); + bool initNumeralModel(); - + bool initAuthenticationModel(); - bool initNumeralModel(); + bool initLogicalTermsModel(); - + bool initPhraseTableModel(); - bool initAuthenticationModel(); - - - - bool initLogicalTermsModel(); - - - - bool initPhraseTableModel(); - -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - LtsSession::LtsSession *m_session{nullptr}; - int m_partyId{-1}; - int m_codificationDataId{0}; - Ui::CodificationDataTableView *m_ui{nullptr}; - NumeralCodeModel *m_numCodeModel{nullptr}; - AuthenticationCodeModel *m_authenticationCodeModel{nullptr}; - LogisticalTermsModel *m_logisticalTermsModel{nullptr}; - PhraseTableModel *m_phraseTableModel{nullptr}; - CodificationManagement::CodificationData m_lastDdsCodificationData; + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + LtsSession::LtsSession* m_session{nullptr}; + int m_partyId{-1}; + int m_codificationDataId{0}; + Ui::CodificationDataTableView* m_ui{nullptr}; + NumeralCodeModel* m_numCodeModel{nullptr}; + AuthenticationCodeModel* m_authenticationCodeModel{nullptr}; + LogisticalTermsModel* m_logisticalTermsModel{nullptr}; + PhraseTableModel* m_phraseTableModel{nullptr}; + CodificationManagement::CodificationData m_lastDdsCodificationData; }; -} - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.cpp old mode 100755 new mode 100644 index 9292f563d..14cffa56c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.cpp @@ -1,107 +1,91 @@ - #include "cod_csv_export.h" -#include "cod_numeral_code_model.h" + #include "cod_authentication_code_model.h" #include "cod_logistical_terms_model.h" +#include "cod_numeral_code_model.h" #include "cod_phrase_table_model.h" #include - #include #include - using namespace CodificationManagement; -CSVExport::CSVExport(const NumeralCodeModel *numCodeModel, - const AuthenticationCodeModel *authenticationCodeModel, - const LogisticalTermsModel *logisticalTermsModel, - const PhraseTableModel *phraseTableModel, - const QString ¬e, - QWidget *parent) : QWidget(parent) - , m_numCodeModel(numCodeModel) - , m_authenticationCodeModel(authenticationCodeModel) - , m_logisticalTermsModel(logisticalTermsModel) - , m_phraseTableModel(phraseTableModel) - , m_note(note), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} - +CSVExport::CSVExport(const NumeralCodeModel* numCodeModel, const AuthenticationCodeModel* authenticationCodeModel, + const LogisticalTermsModel* logisticalTermsModel, const PhraseTableModel* phraseTableModel, + const QString& note, QWidget* parent) + : QWidget(parent), m_numCodeModel(numCodeModel), m_authenticationCodeModel(authenticationCodeModel), + m_logisticalTermsModel(logisticalTermsModel), m_phraseTableModel(phraseTableModel), m_note(note), + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} QByteArray CSVExport::exportToByteArray() const { - QByteArray byteArray; + QByteArray byteArray; - - byteArray.append("\n"); - byteArray.append(m_numCodeModel->getHorizontalHeaderCSVString().toUtf8()); - byteArray.append("\n"); - byteArray.append("\n"); - byteArray.append(m_numCodeModel->getVerticalHeaderCSVString().toUtf8()); - byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_numCodeModel->getHorizontalHeaderCSVString().toUtf8()); + byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_numCodeModel->getVerticalHeaderCSVString().toUtf8()); + byteArray.append("\n"); - - byteArray.append("\n"); - byteArray.append(m_authenticationCodeModel->getMatrixDataCSVString().toUtf8()); - byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_authenticationCodeModel->getMatrixDataCSVString().toUtf8()); + byteArray.append("\n"); - - byteArray.append("\n"); - byteArray.append(m_logisticalTermsModel->getHorizontalHeaderCSVString().toUtf8()); - byteArray.append("\n"); - byteArray.append("\n"); - byteArray.append(m_logisticalTermsModel->getVerticalHeaderCSVString().toUtf8()); - byteArray.append("\n"); - byteArray.append("\n"); - byteArray.append(m_logisticalTermsModel->getMatrixDataCSVString().toUtf8()); - byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_logisticalTermsModel->getHorizontalHeaderCSVString().toUtf8()); + byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_logisticalTermsModel->getVerticalHeaderCSVString().toUtf8()); + byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_logisticalTermsModel->getMatrixDataCSVString().toUtf8()); + byteArray.append("\n"); - - byteArray.append("\n"); - byteArray.append(m_phraseTableModel->getMatrixDataCSVString().toUtf8()); - byteArray.append("\n"); + byteArray.append("\n"); + byteArray.append(m_phraseTableModel->getMatrixDataCSVString().toUtf8()); + byteArray.append("\n"); - - byteArray.append("\n"); - byteArray.append(m_note.toLocal8Bit()); - - return byteArray; + byteArray.append("\n"); + byteArray.append(m_note.toLocal8Bit()); + return byteArray; } bool CSVExport::writeCSVData() { - DEBUG_LOG(m_logger) << "writeCSVData()"; + DEBUG_LOG(m_logger) << "writeCSVData()"; - QFileDialog dialog; - dialog.setNameFilter(tr("CSV File (*.csv)")); - dialog.setAcceptMode(QFileDialog::AcceptSave); - dialog.setDirectory(QLatin1String("../TMP")); - dialog.setDefaultSuffix(QLatin1String("csv")); + QFileDialog dialog; + dialog.setNameFilter(tr("CSV File (*.csv)")); + dialog.setAcceptMode(QFileDialog::AcceptSave); + dialog.setDirectory(QLatin1String("../TMP")); + dialog.setDefaultSuffix(QLatin1String("csv")); - if (!dialog.exec()) - return false; - const QStringList fileNames = dialog.selectedFiles(); - if (fileNames.isEmpty()) - return false; + if (!dialog.exec()) + return false; + const QStringList fileNames = dialog.selectedFiles(); + if (fileNames.isEmpty()) + return false; - QFile file; - file.setFileName(fileNames.first()); + QFile file; + file.setFileName(fileNames.first()); - if (!file.open(QFile::ReadWrite)) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("File is not accessible!"), tr("CSV Export Error")); - return false; - } + if (!file.open(QFile::ReadWrite)) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("File is not accessible!"), tr("CSV Export Error")); + return false; + } - QByteArray byteArray = exportToByteArray(); + QByteArray byteArray = exportToByteArray(); - file.write(byteArray); - - file.close(); - return true; - -} + file.write(byteArray); + file.close(); + return true; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.h old mode 100755 new mode 100644 index b50493660..a2309de28 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_export.h @@ -1,12 +1,9 @@ - #pragma once -#include - #include - +#include namespace CodificationManagement { @@ -18,32 +15,25 @@ class PhraseTableModel; class CSVExport : public QWidget { - Q_OBJECT + Q_OBJECT -public: - explicit CSVExport(const NumeralCodeModel *numCodeModel, - const AuthenticationCodeModel *authenticationCodeModel, - const LogisticalTermsModel *logisticalTermsModel, - const PhraseTableModel *phraseTableModel, - const QString ¬e, - QWidget *parent = nullptr); + public: + explicit CSVExport(const NumeralCodeModel* numCodeModel, const AuthenticationCodeModel* authenticationCodeModel, + const LogisticalTermsModel* logisticalTermsModel, const PhraseTableModel* phraseTableModel, + const QString& note, QWidget* parent = nullptr); - bool writeCSVData(); - QByteArray exportToByteArray() const; + bool writeCSVData(); + QByteArray exportToByteArray() const; -private Q_SLOTS: + private Q_SLOTS: - -private: - - -NGL::INGLLogger &m_logger; - const NumeralCodeModel *m_numCodeModel; - const AuthenticationCodeModel *m_authenticationCodeModel; - const LogisticalTermsModel *m_logisticalTermsModel; - const PhraseTableModel *m_phraseTableModel; - QString m_note; + private: + NGL::INGLLogger& m_logger; + const NumeralCodeModel* m_numCodeModel; + const AuthenticationCodeModel* m_authenticationCodeModel; + const LogisticalTermsModel* m_logisticalTermsModel; + const PhraseTableModel* m_phraseTableModel; + QString m_note; }; -} - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.cpp old mode 100755 new mode 100644 index 38e79ba51..bd1d0b28b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.cpp @@ -1,573 +1,544 @@ - #include "cod_csv_import.h" -#include -#include "cod_numeral_code_model.h" + #include "cod_authentication_code_model.h" #include "cod_logistical_terms_model.h" +#include "cod_numeral_code_model.h" #include "cod_phrase_table_model.h" #include - +#include #include #include -#include +#include using namespace CodificationManagement; - -CSVImport::CSVImport(NumeralCodeModel *numCodeModel, - AuthenticationCodeModel *authenticationCodeModel, - LogisticalTermsModel *logisticalTermsModel, - PhraseTableModel *phraseTableModel, - QString *note, - QWidget *parent) : QWidget(parent) - , m_numCodeModel(numCodeModel) - , m_authenticationCodeModel(authenticationCodeModel) - , m_logisticalTermsModel(logisticalTermsModel) - , m_phraseTableModel(phraseTableModel) - , m_note(note), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} - - +CSVImport::CSVImport(NumeralCodeModel* numCodeModel, AuthenticationCodeModel* authenticationCodeModel, + LogisticalTermsModel* logisticalTermsModel, PhraseTableModel* phraseTableModel, QString* note, + QWidget* parent) + : QWidget(parent), m_numCodeModel(numCodeModel), m_authenticationCodeModel(authenticationCodeModel), + m_logisticalTermsModel(logisticalTermsModel), m_phraseTableModel(phraseTableModel), m_note(note), + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ +} CSVImport::CSVImportResult CSVImport::loadCSVDataByteArray(QByteArray content) { - QBuffer buffer; - buffer.setBuffer(&content); - buffer.open(QIODevice::ReadOnly); + QBuffer buffer; + buffer.setBuffer(&content); + buffer.open(QIODevice::ReadOnly); - QByteArray qbaNumCodeHorizontalHeader; - QByteArray qbaNumCodeVerticalHeader; - QByteArray qbaAuthenticationCodeMatrix; - QByteArray qbaLogTermsTableHorizontalHeader; - QByteArray qbaLogTermsTableVerticalHeader; - QByteArray qbaLogTermsTableMatrix; - QByteArray qbaPhraseTableMatrix; - QByteArray qbaNote; - QByteArray *qba; + QByteArray qbaNumCodeHorizontalHeader; + QByteArray qbaNumCodeVerticalHeader; + QByteArray qbaAuthenticationCodeMatrix; + QByteArray qbaLogTermsTableHorizontalHeader; + QByteArray qbaLogTermsTableVerticalHeader; + QByteArray qbaLogTermsTableMatrix; + QByteArray qbaPhraseTableMatrix; + QByteArray qbaNote; + QByteArray* qba; - qba = nullptr; + qba = nullptr; - int desiredCvsSeperatorsPerLine = 0; - int csvKeywordCount = 0; + int desiredCvsSeperatorsPerLine = 0; + int csvKeywordCount = 0; - QByteArray qbaMergeQuotedEntriesPerLine; + QByteArray qbaMergeQuotedEntriesPerLine; - bool isMergedLine = false; + bool isMergedLine = false; - while (!buffer.atEnd()) - { - QByteArray qbaLine = buffer.readLine(); - - - - - if (qbaLine.endsWith("\r\n")) - qbaLine.remove(qbaLine.lastIndexOf('\r'), 1); - - if (qbaLine.startsWith("<")) + while (!buffer.atEnd()) { - - int index = qbaLine.indexOf('>'); - qbaLine.truncate(index + 1); - qbaLine.append('\n'); + QByteArray qbaLine = buffer.readLine(); - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaNumCodeHorizontalHeader; - desiredCvsSeperatorsPerLine = 12; - ++csvKeywordCount; - continue; - } + if (qbaLine.endsWith("\r\n")) + qbaLine.remove(qbaLine.lastIndexOf('\r'), 1); - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaNumCodeVerticalHeader; - desiredCvsSeperatorsPerLine = 0; - ++csvKeywordCount; - continue; - } + if (qbaLine.startsWith("<")) + { - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaAuthenticationCodeMatrix; - desiredCvsSeperatorsPerLine = 4; - ++csvKeywordCount; - continue; - } + int index = qbaLine.indexOf('>'); + qbaLine.truncate(index + 1); + qbaLine.append('\n'); - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaLogTermsTableHorizontalHeader; - desiredCvsSeperatorsPerLine = 4; - ++csvKeywordCount; - continue; - } + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaNumCodeHorizontalHeader; + desiredCvsSeperatorsPerLine = 12; + ++csvKeywordCount; + continue; + } - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaLogTermsTableVerticalHeader; - desiredCvsSeperatorsPerLine = 0; - ++csvKeywordCount; - continue; - } + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaNumCodeVerticalHeader; + desiredCvsSeperatorsPerLine = 0; + ++csvKeywordCount; + continue; + } - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaLogTermsTableMatrix; - desiredCvsSeperatorsPerLine = 4; - ++csvKeywordCount; - continue; - } + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaAuthenticationCodeMatrix; + desiredCvsSeperatorsPerLine = 4; + ++csvKeywordCount; + continue; + } - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaPhraseTableMatrix; - desiredCvsSeperatorsPerLine = 1; - ++csvKeywordCount; - continue; - } + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaLogTermsTableHorizontalHeader; + desiredCvsSeperatorsPerLine = 4; + ++csvKeywordCount; + continue; + } - if (qbaLine == "\n") - { - DEBUG_LOG(m_logger) << "found " << qbaLine; - qba = &qbaNote; - desiredCvsSeperatorsPerLine = 0; - ++csvKeywordCount; - continue; - } + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaLogTermsTableVerticalHeader; + desiredCvsSeperatorsPerLine = 0; + ++csvKeywordCount; + continue; + } + + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaLogTermsTableMatrix; + desiredCvsSeperatorsPerLine = 4; + ++csvKeywordCount; + continue; + } + + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaPhraseTableMatrix; + desiredCvsSeperatorsPerLine = 1; + ++csvKeywordCount; + continue; + } + + if (qbaLine == "\n") + { + DEBUG_LOG(m_logger) << "found " << qbaLine; + qba = &qbaNote; + desiredCvsSeperatorsPerLine = 0; + ++csvKeywordCount; + continue; + } + } + + if (qba) + { + if (!qbaLine.contains('"') && !isMergedLine) + { + + removeRedundantCvsSeperators(qbaLine, desiredCvsSeperatorsPerLine); + qba->append(qbaLine); + continue; + } + + if (qbaLine.contains('"') && !isMergedLine) + { + isMergedLine = true; + qbaMergeQuotedEntriesPerLine.append(qbaLine); + continue; + } + + if (!qbaLine.contains('"') && isMergedLine) + { + qbaMergeQuotedEntriesPerLine.append(qbaLine); + continue; + } + + if (qbaLine.contains('"') && isMergedLine) + { + + int idx = qbaLine.indexOf('\"'); + QByteArray qbaQuotedPart = qbaLine.left(idx + 1); + qbaMergeQuotedEntriesPerLine.append(qbaQuotedPart); + + QByteArray qbaRestLine = qbaLine.mid(idx + 1); + + if (!qbaRestLine.contains('"')) + { + + qbaMergeQuotedEntriesPerLine.append(qbaRestLine); + + qbaLine = qbaMergeQuotedEntriesPerLine; + + qbaMergeQuotedEntriesPerLine.clear(); + isMergedLine = false; + + removeRedundantCvsSeperators(qbaLine, desiredCvsSeperatorsPerLine); + qba->append(qbaLine); + continue; + } + else + { + + qbaMergeQuotedEntriesPerLine.append(qbaRestLine); + continue; + } + } + } } - if (qba) + if (csvKeywordCount != 8) { - if (! qbaLine.contains('"') && ! isMergedLine) - { - - removeRedundantCvsSeperators(qbaLine, desiredCvsSeperatorsPerLine); - qba->append(qbaLine); - continue; - } + ERROR_LOG(m_logger) << "Load csv data failed! Invalid csvKeywordCount. Soll/Ist: 8/" << csvKeywordCount; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data failed! Invalid number of cvs keywords."), + tr("CSV Load Error")); + return CSVImportResult::LoadFailed; + } - - - - - - - - - - - - - - + DEBUG_LOG(m_logger) << "Load csv ready... "; + DEBUG_LOG(m_logger) << "\n-----------start show load csv data blocks -------------------------\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaNumCodeHorizontalHeader << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaNumCodeVerticalHeader << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaAuthenticationCodeMatrix << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" + << qbaLogTermsTableHorizontalHeader << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaLogTermsTableVerticalHeader + << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaLogTermsTableMatrix << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaPhraseTableMatrix << "\"\n"; + DEBUG_LOG(m_logger) << "\n: \"" << qbaNote << "\"\n"; + DEBUG_LOG(m_logger) << "\n-----------end of show load csv data blocks -------------------------\n"; - - if (qbaLine.contains('"') && ! isMergedLine) - { - isMergedLine = true; - qbaMergeQuotedEntriesPerLine.append(qbaLine); - continue; - } + qbaNumCodeHorizontalHeader = qbaNumCodeHorizontalHeader.trimmed(); + if (checkNumCodeHorizontalHeader(qbaNumCodeHorizontalHeader)) + m_numCodeModel->setColumnSelectionValuesCSV(QString::fromUtf8(qbaNumCodeHorizontalHeader)); + else + return CSVImportResult::LoadFailed; - - if (! qbaLine.contains('"') && isMergedLine) - { - qbaMergeQuotedEntriesPerLine.append(qbaLine); - continue; - } + qbaNumCodeVerticalHeader = qbaNumCodeVerticalHeader.trimmed(); + if (checkNumCodeVerticalHeader(qbaNumCodeVerticalHeader)) + m_numCodeModel->setRowSelectionValuesCSV(QString::fromUtf8(qbaNumCodeVerticalHeader)); + else + return CSVImportResult::LoadFailed; - - if (qbaLine.contains('"') && isMergedLine) - { - - int idx = qbaLine.indexOf('\"'); - QByteArray qbaQuotedPart = qbaLine.left(idx + 1); - qbaMergeQuotedEntriesPerLine.append(qbaQuotedPart); + qbaAuthenticationCodeMatrix = qbaAuthenticationCodeMatrix.trimmed(); + if (checkAuthenticationCodeMatrix(qbaAuthenticationCodeMatrix)) + m_authenticationCodeModel->setMatrixValuesCSV(QString::fromUtf8(qbaAuthenticationCodeMatrix)); + else + return CSVImportResult::LoadFailed; - - QByteArray qbaRestLine = qbaLine.mid(idx + 1); + qbaLogTermsTableHorizontalHeader = qbaLogTermsTableHorizontalHeader.trimmed(); + if (checkLogTermsTableHorizontalHeader(qbaLogTermsTableHorizontalHeader)) + m_logisticalTermsModel->setColumnSelectionValuesCSV(QString::fromUtf8(qbaLogTermsTableHorizontalHeader)); + else + return CSVImportResult::LoadFailed; - - if (! qbaRestLine.contains('"')) - { - - qbaMergeQuotedEntriesPerLine.append(qbaRestLine); - - qbaLine = qbaMergeQuotedEntriesPerLine; + qbaLogTermsTableVerticalHeader = qbaLogTermsTableVerticalHeader.trimmed(); + if (checkLogTermsTableVerticalHeader(qbaLogTermsTableVerticalHeader)) + m_logisticalTermsModel->setRowSelectionValuesCSV(QString::fromUtf8(qbaLogTermsTableVerticalHeader)); + else + return CSVImportResult::LoadFailed; - - qbaMergeQuotedEntriesPerLine.clear(); - isMergedLine = false; + qbaLogTermsTableMatrix = qbaLogTermsTableMatrix.trimmed(); + if (checkLogTermsTableMatrix(qbaLogTermsTableMatrix)) + m_logisticalTermsModel->setMatrixValuesCSV(QString::fromUtf8(qbaLogTermsTableMatrix)); + else + return CSVImportResult::LoadFailed; - - removeRedundantCvsSeperators(qbaLine, desiredCvsSeperatorsPerLine); - qba->append(qbaLine); - continue; - } - else - { - - qbaMergeQuotedEntriesPerLine.append(qbaRestLine); - continue; - } - } - } - } + qbaPhraseTableMatrix = qbaPhraseTableMatrix.trimmed(); + if (checkPhraseTableMatrix(qbaPhraseTableMatrix)) + m_phraseTableModel->setMatrixValuesCSV(QString::fromUtf8(qbaPhraseTableMatrix)); + else + return CSVImportResult::LoadFailed; - - if (csvKeywordCount != 8) - { - ERROR_LOG(m_logger) << "Load csv data failed! Invalid csvKeywordCount. Soll/Ist: 8/" << csvKeywordCount; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data failed! Invalid number of cvs keywords."), tr("CSV Load Error")); - return CSVImportResult::LoadFailed; - } - - - DEBUG_LOG(m_logger) << "Load csv ready... "; - DEBUG_LOG(m_logger) << "\n-----------start show load csv data blocks -------------------------\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaNumCodeHorizontalHeader << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaNumCodeVerticalHeader << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaAuthenticationCodeMatrix << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaLogTermsTableHorizontalHeader << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaLogTermsTableVerticalHeader << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaLogTermsTableMatrix << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaPhraseTableMatrix << "\"\n"; - DEBUG_LOG(m_logger) << "\n: \"" << qbaNote << "\"\n"; - DEBUG_LOG(m_logger) << "\n-----------end of show load csv data blocks -------------------------\n"; - - - qbaNumCodeHorizontalHeader = qbaNumCodeHorizontalHeader.trimmed(); - if (checkNumCodeHorizontalHeader(qbaNumCodeHorizontalHeader)) - m_numCodeModel->setColumnSelectionValuesCSV(QString::fromUtf8(qbaNumCodeHorizontalHeader)); - else - return CSVImportResult::LoadFailed; - - qbaNumCodeVerticalHeader = qbaNumCodeVerticalHeader.trimmed(); - if (checkNumCodeVerticalHeader(qbaNumCodeVerticalHeader)) - m_numCodeModel->setRowSelectionValuesCSV(QString::fromUtf8(qbaNumCodeVerticalHeader)); - else - return CSVImportResult::LoadFailed; - - - qbaAuthenticationCodeMatrix = qbaAuthenticationCodeMatrix.trimmed(); - if (checkAuthenticationCodeMatrix(qbaAuthenticationCodeMatrix)) - m_authenticationCodeModel->setMatrixValuesCSV(QString::fromUtf8(qbaAuthenticationCodeMatrix)); - else - return CSVImportResult::LoadFailed; - - - qbaLogTermsTableHorizontalHeader = qbaLogTermsTableHorizontalHeader.trimmed(); - if (checkLogTermsTableHorizontalHeader(qbaLogTermsTableHorizontalHeader)) - m_logisticalTermsModel->setColumnSelectionValuesCSV(QString::fromUtf8(qbaLogTermsTableHorizontalHeader)); - else - return CSVImportResult::LoadFailed; - - qbaLogTermsTableVerticalHeader = qbaLogTermsTableVerticalHeader.trimmed(); - if (checkLogTermsTableVerticalHeader(qbaLogTermsTableVerticalHeader)) - m_logisticalTermsModel->setRowSelectionValuesCSV(QString::fromUtf8(qbaLogTermsTableVerticalHeader)); - else - return CSVImportResult::LoadFailed; - - qbaLogTermsTableMatrix = qbaLogTermsTableMatrix.trimmed(); - if (checkLogTermsTableMatrix(qbaLogTermsTableMatrix)) - m_logisticalTermsModel->setMatrixValuesCSV(QString::fromUtf8(qbaLogTermsTableMatrix)); - else - return CSVImportResult::LoadFailed; - - - qbaPhraseTableMatrix = qbaPhraseTableMatrix.trimmed(); - if (checkPhraseTableMatrix(qbaPhraseTableMatrix)) - m_phraseTableModel->setMatrixValuesCSV(QString::fromUtf8(qbaPhraseTableMatrix)); - else - return CSVImportResult::LoadFailed; - - - qbaNote = qbaNote.trimmed(); - removeQuotedCharInNote(qbaNote); - m_note->clear(); - m_note->append(QString::fromUtf8(qbaNote)); - return CSVImportResult::LoadOk; + qbaNote = qbaNote.trimmed(); + removeQuotedCharInNote(qbaNote); + m_note->clear(); + m_note->append(QString::fromUtf8(qbaNote)); + return CSVImportResult::LoadOk; } - CSVImport::CSVImportResult CSVImport::loadCSVData() { - DEBUG_LOG(m_logger) << "loadCSVData()"; + DEBUG_LOG(m_logger) << "loadCSVData()"; - QFileDialog dialog; - dialog.setNameFilter(tr("CSV File (*.csv)")); - dialog.setAcceptMode(QFileDialog::AcceptOpen); - dialog.setDirectory(QLatin1String("../TMP")); + QFileDialog dialog; + dialog.setNameFilter(tr("CSV File (*.csv)")); + dialog.setAcceptMode(QFileDialog::AcceptOpen); + dialog.setDirectory(QLatin1String("../TMP")); - if (dialog.exec() == QDialog::Rejected) - return CSVImportResult::UserAbort; + if (dialog.exec() == QDialog::Rejected) + return CSVImportResult::UserAbort; - const QStringList fileNames = dialog.selectedFiles(); - if (fileNames.isEmpty()) - return CSVImportResult::LoadFailed; + const QStringList fileNames = dialog.selectedFiles(); + if (fileNames.isEmpty()) + return CSVImportResult::LoadFailed; - QFile file; - file.setFileName(fileNames.first()); + QFile file; + file.setFileName(fileNames.first()); - if (!file.open(QFile::ReadOnly)) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("File is not accessible!"), tr("CSV Import Error")); - return CSVImportResult::LoadFailed; - } - QByteArray byteArray = file.readAll(); - file.close(); - - loadCSVDataByteArray(byteArray); - - return CSVImportResult::LoadOk; - -} - - -bool CSVImport::checkNumCodeHorizontalHeader(const QByteArray &qbaNumCodeHorizontalHeader) -{ - - DEBUG_LOG(m_logger) << "Data: \"" << qbaNumCodeHorizontalHeader << "\""; - DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 + 12 = 25/" << qbaNumCodeHorizontalHeader.size(); - - if (qbaNumCodeHorizontalHeader.size() == 25) - return true; - ERROR_LOG(m_logger) << "Load csv data 'Numeral Code Horizontal Header' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Numeral Code Horizontal Header' failed!"), tr("CSV Load Error")); - return false; -} - - -bool CSVImport::checkNumCodeVerticalHeader(const QByteArray &qbaNumCodeVerticalHeader) -{ - - DEBUG_LOG(m_logger) << "Data: \"" << qbaNumCodeVerticalHeader << "\""; - DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 + 12 = 25/" << qbaNumCodeVerticalHeader.size(); - - if (qbaNumCodeVerticalHeader.size() == 25) - return true; - ERROR_LOG(m_logger) << "Load csv data 'Numeral Code Vertical Header' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Numeral Code Vertical Header' failed!"), tr("CSV Load Error")); - return false; -} - - -bool CSVImport::checkAuthenticationCodeMatrix(QByteArray &qbaAuthenticationCodeMatrix) -{ - - DEBUG_LOG(m_logger) << "Data: \"" << qbaAuthenticationCodeMatrix << "\""; - - QByteArray qbaOutMatrix; - - QList qbaLinesList = qbaAuthenticationCodeMatrix.split('\n'); - - for (QByteArray &line : qbaLinesList) - { - QList qbaLineList = line.split(';'); - - for (QByteArray &segment : qbaLineList) + if (!file.open(QFile::ReadOnly)) { - if (segment.size() == 1) - segment = segment.rightJustified(2, '0'); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("File is not accessible!"), tr("CSV Import Error")); + return CSVImportResult::LoadFailed; } - line = qbaLineList.join(';'); - } - qbaOutMatrix = qbaLinesList.join('\n'); + QByteArray byteArray = file.readAll(); + file.close(); - qbaAuthenticationCodeMatrix = qbaOutMatrix; + loadCSVDataByteArray(byteArray); - DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 * (5*2 + 4 + 1) -1 = 194 /" << qbaAuthenticationCodeMatrix.size(); + return CSVImportResult::LoadOk; +} - if (qbaAuthenticationCodeMatrix.size() == 194) - return true; - else - { - ERROR_LOG(m_logger) << "Load csv data 'Authentication Code Matrix' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Authentication Code Matrix' failed!"), tr("CSV Load Error")); - return false; - } -} - - -bool CSVImport::checkLogTermsTableHorizontalHeader(const QByteArray &qbaLogTermsTableHorizontalHeader) +bool CSVImport::checkNumCodeHorizontalHeader(const QByteArray& qbaNumCodeHorizontalHeader) { - - DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableHorizontalHeader << "\""; - DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 5 + 4 = 9/" << qbaLogTermsTableHorizontalHeader.size(); - if (qbaLogTermsTableHorizontalHeader.size() == 9) - return true; - else - { - ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Horizontal Header' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Horizontal Header' failed!"), tr("CSV Load Error")); + DEBUG_LOG(m_logger) << "Data: \"" << qbaNumCodeHorizontalHeader << "\""; + DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 + 12 = 25/" << qbaNumCodeHorizontalHeader.size(); + + if (qbaNumCodeHorizontalHeader.size() == 25) + return true; + ERROR_LOG(m_logger) << "Load csv data 'Numeral Code Horizontal Header' failed!"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Numeral Code Horizontal Header' failed!"), + tr("CSV Load Error")); return false; - } -} +} - -bool CSVImport::checkLogTermsTableVerticalHeader(const QByteArray &qbaLogTermsTableVerticalHeader) +bool CSVImport::checkNumCodeVerticalHeader(const QByteArray& qbaNumCodeVerticalHeader) { - - DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableVerticalHeader << "\""; - DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 5 + 4 = 9/" << qbaLogTermsTableVerticalHeader.size(); - if (qbaLogTermsTableVerticalHeader.size() == 9) - return true; - else - { - ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Vertical Header' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Vertical Header' failed!"), tr("CSV Load Error")); + DEBUG_LOG(m_logger) << "Data: \"" << qbaNumCodeVerticalHeader << "\""; + DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 + 12 = 25/" << qbaNumCodeVerticalHeader.size(); + + if (qbaNumCodeVerticalHeader.size() == 25) + return true; + ERROR_LOG(m_logger) << "Load csv data 'Numeral Code Vertical Header' failed!"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Numeral Code Vertical Header' failed!"), + tr("CSV Load Error")); return false; - } -} +} - -bool CSVImport::checkLogTermsTableMatrix(const QByteArray &qbaLogTermsTableMatrix) +bool CSVImport::checkAuthenticationCodeMatrix(QByteArray& qbaAuthenticationCodeMatrix) { - - DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableMatrix << "\""; - - QStringList qsl = m_logisticalTermsModel->splitQuotedStringToRows(QString::fromLatin1(qbaLogTermsTableMatrix)); + DEBUG_LOG(m_logger) << "Data: \"" << qbaAuthenticationCodeMatrix << "\""; - DEBUG_LOG(m_logger) << "Line entry size: Soll/Ist: 5/" << qsl.size(); + QByteArray qbaOutMatrix; - - if (qsl.size() == 5) - { - + QList qbaLinesList = qbaAuthenticationCodeMatrix.split('\n'); - - QString qsMatrix = qsl.join(QLatin1Char(';')); - QStringList qsl2 = qsMatrix.split(QLatin1Char(';')); - - for (int i = 0; i < qsl2.size(); ++i) + for (QByteArray& line : qbaLinesList) { - const QString &qsEntry = qsl2.at(i); + QList qbaLineList = line.split(';'); - if (! qsEntry.contains(QLatin1Char('\n'))) - { - - if (qsEntry.size() > 10) + for (QByteArray& segment : qbaLineList) { - ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per entry line exceeded in cell " << i + 1; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per entry line exceeded."), tr("CSV Load Error")); - return false; + if (segment.size() == 1) + segment = segment.rightJustified(2, '0'); } - else - continue; - } - else - { - - if ((qsEntry.size() > 21) || (qsEntry.indexOf(QLatin1Char('\n')) > 10)) - { - ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per entry line exceeded in cell " << i + 1; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per entry line exceeded."), tr("CSV Load Error")); - return false; - } - } + line = qbaLineList.join(';'); } - return true; - } - else - { - ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed!"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Matrix' failed!"), tr("CSV Load Error")); - return false; - } -} + qbaOutMatrix = qbaLinesList.join('\n'); + qbaAuthenticationCodeMatrix = qbaOutMatrix; -bool CSVImport::checkPhraseTableMatrix(const QByteArray &qbaPhraseTableMatrix) -{ - - DEBUG_LOG(m_logger) << "Data: \"" << qbaPhraseTableMatrix << "\""; + DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 13 * (5*2 + 4 + 1) -1 = 194 /" << qbaAuthenticationCodeMatrix.size(); - const QList qbaLinesList = qbaPhraseTableMatrix.split('\n'); - - - if (qbaLinesList.size() != 13) - { - ERROR_LOG(m_logger) << "Load csv data 'Phrase Table Matrix' failed! Invalid Line entry size: Soll/Ist: 13/" << qbaLinesList.size(); - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Phrase Table Matrix' failed! Invalid Line entry size."), tr("CSV Load Error")); - return false; - } - - - for (const QByteArray &line : qbaLinesList) - { - const QList qbaLine = line.split(';'); - if (qbaLine.size() == 2) + if (qbaAuthenticationCodeMatrix.size() == 194) + return true; + else { - if (qbaLine.at(0).isEmpty() || qbaLine.at(1).isEmpty() || qbaLine.at(0).size() > 15 || qbaLine.at(1).size() > 15) - { - ERROR_LOG(m_logger) << "Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or entry size is < 1 or >> 15. "; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or entry size is less than 1 or greater 15."), tr("CSV Load Error")); + ERROR_LOG(m_logger) << "Load csv data 'Authentication Code Matrix' failed!"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Authentication Code Matrix' failed!"), + tr("CSV Load Error")); return false; - } - else - continue; + } +} + +bool CSVImport::checkLogTermsTableHorizontalHeader(const QByteArray& qbaLogTermsTableHorizontalHeader) +{ + + DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableHorizontalHeader << "\""; + DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 5 + 4 = 9/" << qbaLogTermsTableHorizontalHeader.size(); + + if (qbaLogTermsTableHorizontalHeader.size() == 9) + return true; + else + { + ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Horizontal Header' failed!"; + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Load csv data 'Logistical Terms Table Horizontal Header' failed!"), tr("CSV Load Error")); + return false; + } +} + +bool CSVImport::checkLogTermsTableVerticalHeader(const QByteArray& qbaLogTermsTableVerticalHeader) +{ + + DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableVerticalHeader << "\""; + DEBUG_LOG(m_logger) << "Data.size: Soll/Ist: 5 + 4 = 9/" << qbaLogTermsTableVerticalHeader.size(); + + if (qbaLogTermsTableVerticalHeader.size() == 9) + return true; + else + { + ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Vertical Header' failed!"; + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Load csv data 'Logistical Terms Table Vertical Header' failed!"), tr("CSV Load Error")); + return false; + } +} + +bool CSVImport::checkLogTermsTableMatrix(const QByteArray& qbaLogTermsTableMatrix) +{ + + DEBUG_LOG(m_logger) << "Data: \"" << qbaLogTermsTableMatrix << "\""; + + QStringList qsl = m_logisticalTermsModel->splitQuotedStringToRows(QString::fromLatin1(qbaLogTermsTableMatrix)); + + DEBUG_LOG(m_logger) << "Line entry size: Soll/Ist: 5/" << qsl.size(); + + if (qsl.size() == 5) + { + + QString qsMatrix = qsl.join(QLatin1Char(';')); + QStringList qsl2 = qsMatrix.split(QLatin1Char(';')); + + for (int i = 0; i < qsl2.size(); ++i) + { + const QString& qsEntry = qsl2.at(i); + + if (!qsEntry.contains(QLatin1Char('\n'))) + { + + if (qsEntry.size() > 10) + { + ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 " + "characters per entry line exceeded in cell " + << i + 1; + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per " + "entry line exceeded."), + tr("CSV Load Error")); + return false; + } + else + continue; + } + else + { + + if ((qsEntry.size() > 21) || (qsEntry.indexOf(QLatin1Char('\n')) > 10)) + { + ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 " + "characters per entry line exceeded in cell " + << i + 1; + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Load csv data 'Logistical Terms Table Matrix' failed! Maximum number of 10 characters per " + "entry line exceeded."), + tr("CSV Load Error")); + return false; + } + } + } + return true; } else { - ERROR_LOG(m_logger) << "Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or empty entry per line. "; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or empty entry per line."), tr("CSV Load Error")); - return false; + ERROR_LOG(m_logger) << "Load csv data 'Logistical Terms Table Matrix' failed!"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Load csv data 'Logistical Terms Table Matrix' failed!"), + tr("CSV Load Error")); + return false; } - } - return true; -} +} - -void CSVImport::removeQuotedCharInNote(QByteArray &qbaNote) +bool CSVImport::checkPhraseTableMatrix(const QByteArray& qbaPhraseTableMatrix) { - if (qbaNote.startsWith('"')) - qbaNote.remove(0, 1); - if (qbaNote.endsWith('"')) - qbaNote.remove(qbaNote.lastIndexOf('"'), 1); + DEBUG_LOG(m_logger) << "Data: \"" << qbaPhraseTableMatrix << "\""; -} + const QList qbaLinesList = qbaPhraseTableMatrix.split('\n'); + if (qbaLinesList.size() != 13) + { + ERROR_LOG(m_logger) << "Load csv data 'Phrase Table Matrix' failed! Invalid Line entry size: Soll/Ist: 13/" + << qbaLinesList.size(); + LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Load csv data 'Phrase Table Matrix' failed! Invalid Line entry size."), tr("CSV Load Error")); + return false; + } -bool CSVImport::removeRedundantCvsSeperators(QByteArray &qbaLine, int desiredValue) const + for (const QByteArray& line : qbaLinesList) + { + const QList qbaLine = line.split(';'); + if (qbaLine.size() == 2) + { + if (qbaLine.at(0).isEmpty() || qbaLine.at(1).isEmpty() || qbaLine.at(0).size() > 15 || + qbaLine.at(1).size() > 15) + { + ERROR_LOG(m_logger) << "Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or entry " + "size is < 1 or >> 15. "; + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or entry size is less " + "than 1 or greater 15."), + tr("CSV Load Error")); + return false; + } + else + continue; + } + else + { + ERROR_LOG(m_logger) + << "Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or empty entry per line. "; + LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Load csv data 'Phrase Table Matrix' failed! Invalid number of entrys or empty entry per line."), + tr("CSV Load Error")); + return false; + } + } + return true; +} + +void CSVImport::removeQuotedCharInNote(QByteArray& qbaNote) { - int seperatorCnt = 0; + if (qbaNote.startsWith('"')) + qbaNote.remove(0, 1); - - for (const char c : std::as_const(qbaLine)) - { - if (c == ';') - ++seperatorCnt; - } + if (qbaNote.endsWith('"')) + qbaNote.remove(qbaNote.lastIndexOf('"'), 1); +} - if (seperatorCnt < desiredValue) - { - ERROR_LOG(m_logger) << "Seperator values less than desired values."; - return false; - } +bool CSVImport::removeRedundantCvsSeperators(QByteArray& qbaLine, int desiredValue) const +{ + int seperatorCnt = 0; - while (seperatorCnt > desiredValue) - { - qbaLine.remove(qbaLine.lastIndexOf(';'), 1); - --seperatorCnt; - } - DEBUG_LOG(m_logger) << "+++Data: \"" << qbaLine << "\"" << " Soll/Ist:: " << desiredValue << "/" << seperatorCnt; - return true; -} + for (const char c : std::as_const(qbaLine)) + { + if (c == ';') + ++seperatorCnt; + } + if (seperatorCnt < desiredValue) + { + ERROR_LOG(m_logger) << "Seperator values less than desired values."; + return false; + } + while (seperatorCnt > desiredValue) + { + qbaLine.remove(qbaLine.lastIndexOf(';'), 1); + --seperatorCnt; + } + DEBUG_LOG(m_logger) << "+++Data: \"" << qbaLine << "\"" << " Soll/Ist:: " << desiredValue << "/" << seperatorCnt; + return true; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.h old mode 100755 new mode 100644 index 918dfccc7..17d708562 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_csv_import.h @@ -1,12 +1,9 @@ - #pragma once -#include - #include - +#include namespace CodificationManagement { @@ -16,51 +13,40 @@ class AuthenticationCodeModel; class LogisticalTermsModel; class PhraseTableModel; - - class CSVImport : public QWidget { -public: - enum CSVImportResult - { - UserAbort, - LoadOk, - LoadFailed - }; + public: + enum CSVImportResult { UserAbort, LoadOk, LoadFailed }; - Q_OBJECT + Q_OBJECT -public: - explicit CSVImport(NumeralCodeModel *numCodeModel, - AuthenticationCodeModel *authenticationCodeModel, - LogisticalTermsModel *logisticalTermsModel, - PhraseTableModel *phraseTableModel, - QString *note, - QWidget *parent = nullptr); + public: + explicit CSVImport(NumeralCodeModel* numCodeModel, AuthenticationCodeModel* authenticationCodeModel, + LogisticalTermsModel* logisticalTermsModel, PhraseTableModel* phraseTableModel, QString* note, + QWidget* parent = nullptr); - CSVImportResult loadCSVData(); - CSVImportResult loadCSVDataByteArray(QByteArray content); + CSVImportResult loadCSVData(); + CSVImportResult loadCSVDataByteArray(QByteArray content); -private: + private: + NGL::INGLLogger& m_logger; + bool checkNumCodeHorizontalHeader(const QByteArray& qbaNumCodeHorizontalHeader); + bool checkNumCodeVerticalHeader(const QByteArray& qbaNumCodeVerticalHeader); + bool checkAuthenticationCodeMatrix(QByteArray& qbaAuthenticationCodeMatrix); + bool checkLogTermsTableHorizontalHeader(const QByteArray& qbaLogTermsTableHorizontalHeader); + bool checkLogTermsTableVerticalHeader(const QByteArray& qbaLogTermsTableVerticalHeader); + bool checkLogTermsTableMatrix(const QByteArray& qbaLogTermsTableMatrix); + bool checkPhraseTableMatrix(const QByteArray& qbaPhraseTableMatrix); -NGL::INGLLogger &m_logger; - bool checkNumCodeHorizontalHeader(const QByteArray &qbaNumCodeHorizontalHeader); - bool checkNumCodeVerticalHeader(const QByteArray &qbaNumCodeVerticalHeader); - bool checkAuthenticationCodeMatrix(QByteArray &qbaAuthenticationCodeMatrix); - bool checkLogTermsTableHorizontalHeader(const QByteArray &qbaLogTermsTableHorizontalHeader); - bool checkLogTermsTableVerticalHeader(const QByteArray &qbaLogTermsTableVerticalHeader); - bool checkLogTermsTableMatrix(const QByteArray &qbaLogTermsTableMatrix); - bool checkPhraseTableMatrix(const QByteArray &qbaPhraseTableMatrix); + static void removeQuotedCharInNote(QByteArray& qbaNote); + bool removeRedundantCvsSeperators(QByteArray& qbaLine, int desiredValue) const; - static void removeQuotedCharInNote(QByteArray &qbaNote); - bool removeRedundantCvsSeperators(QByteArray &qbaLine, int desiredValue) const; - -private: - NumeralCodeModel *m_numCodeModel; - AuthenticationCodeModel *m_authenticationCodeModel; - LogisticalTermsModel *m_logisticalTermsModel; - PhraseTableModel *m_phraseTableModel; - QString *m_note; + private: + NumeralCodeModel* m_numCodeModel; + AuthenticationCodeModel* m_authenticationCodeModel; + LogisticalTermsModel* m_logisticalTermsModel; + PhraseTableModel* m_phraseTableModel; + QString* m_note; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.cpp old mode 100755 new mode 100644 index c35ab0e5e..a1028bd8f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.cpp @@ -1,469 +1,429 @@ - - #include "cod_logistical_terms_model.h" + #include #include #include - using namespace CodificationManagement; static const int s_matrixCount = 5; -LogisticalTermsModel::LogisticalTermsModel(QWidget *parent) - : QAbstractTableModel(parent) - , m_dtc(nullptr) - , m_codificationDataId(0) - , m_isEditMode(false) +LogisticalTermsModel::LogisticalTermsModel(QWidget* parent) + : QAbstractTableModel(parent), m_dtc(nullptr), m_codificationDataId(0), m_isEditMode(false) { - DEBUG_LOG(m_logger) << "ctor LogisticalTermsModel"; - m_matrix.resize(s_matrixCount); - for (int i = 0; i < s_matrixCount; ++i) - m_matrix[i].resize(s_matrixCount); + DEBUG_LOG(m_logger) << "ctor LogisticalTermsModel"; + m_matrix.resize(s_matrixCount); + for (int i = 0; i < s_matrixCount; ++i) + m_matrix[i].resize(s_matrixCount); +} -} - - -bool LogisticalTermsModel::init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode) +bool LogisticalTermsModel::init(const std::shared_ptr& dtc, + int codificationDataId, bool isEditMode) { - DEBUG_LOG(m_logger) << "LogisticalTerms::init()"; - if (!dtc) - return false; + DEBUG_LOG(m_logger) << "LogisticalTerms::init()"; + if (!dtc) + return false; - DEBUG_LOG(m_logger) << "LogisticalTermsModel::init()..."; + DEBUG_LOG(m_logger) << "LogisticalTermsModel::init()..."; - m_dtc = dtc; - m_codificationDataId = codificationDataId; - m_isEditMode = isEditMode; + m_dtc = dtc; + m_codificationDataId = codificationDataId; + m_isEditMode = isEditMode; - resetHeader(); - resetMatrix(); - - if (!isEditMode) - { - connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &LogisticalTermsModel::onCodificationDataChanged); - } - return true; -} + resetHeader(); + resetMatrix(); + if (!isEditMode) + { + connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &LogisticalTermsModel::onCodificationDataChanged); + } + return true; +} void LogisticalTermsModel::resetHeader() { - - m_ColumnSelectionValues = QVector(s_matrixCount, QLatin1Char('?')); - m_RowSelectionValues = QVector(s_matrixCount, QLatin1Char('?')); -} + m_ColumnSelectionValues = QVector(s_matrixCount, QLatin1Char('?')); + m_RowSelectionValues = QVector(s_matrixCount, QLatin1Char('?')); +} void LogisticalTermsModel::resetMatrix() { - beginResetModel(); - for (auto &colData : m_matrix) - { - for (auto &cell : colData) - cell = QLatin1String("---"); - } - endResetModel(); + beginResetModel(); + for (auto& colData : m_matrix) + { + for (auto& cell : colData) + cell = QLatin1String("---"); + } + endResetModel(); } - - -bool LogisticalTermsModel::setColumnSelectionValuesCSV(const QString &csvData) +bool LogisticalTermsModel::setColumnSelectionValuesCSV(const QString& csvData) { - m_ColumnSelectionValues.clear(); - m_ColumnSelectionValues.resize(s_matrixCount); + m_ColumnSelectionValues.clear(); + m_ColumnSelectionValues.resize(s_matrixCount); - const QVector slColumns = csvData.splitRef(QLatin1Char(';')); + const QVector slColumns = csvData.splitRef(QLatin1Char(';')); - if (slColumns.size() != m_ColumnSelectionValues.size()) - { - ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << m_ColumnSelectionValues.size() << "/" << slColumns.size(); - m_ColumnSelectionValues.fill(QLatin1Char(' ')); - return false; - } - - for (int i = 0; i < m_ColumnSelectionValues.size(); ++i) - { - const QStringRef &qs = slColumns.at(i); - if (qs.size() != 1) + if (slColumns.size() != m_ColumnSelectionValues.size()) { - ERROR_LOG(m_logger) << "Invalid column data value at id: " << i - << " codificationDataId: " << m_codificationDataId; - return false; - } - m_ColumnSelectionValues[i] = qs.at(0); - } - emit dataChanged(index(0, 0), index(0, m_ColumnSelectionValues.size() - 1)); - return true; -} - - -bool LogisticalTermsModel::setRowSelectionValuesCSV(const QString &csvData) -{ - m_RowSelectionValues.clear(); - m_RowSelectionValues.resize(s_matrixCount); - - const QVector slRows = csvData.splitRef(QStringLiteral("\n")); - - if (slRows.size() != m_RowSelectionValues.size()) - { - ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << m_RowSelectionValues.size() << "/" << slRows.size() - << " Default values will be used. "; - m_RowSelectionValues.fill(QLatin1Char(' ')); - return false; - } - - for (int i = 0; i < m_RowSelectionValues.size(); ++i) - { - const QStringRef &qs = slRows.at(i); - if (qs.size() != 1) - { - ERROR_LOG(m_logger) << "Invalid row data value at id: " << i - << " codificationDataId: " << m_codificationDataId; - return false; - } - m_RowSelectionValues[i] = qs.at(0); - } - emit dataChanged(index(0, 0), index(0, m_RowSelectionValues.size() - 1)); - return true; -} - - -bool LogisticalTermsModel::setMatrixValuesCSV(const QString &csvData) -{ - DEBUG_LOG(m_logger) << "setMatrixValuesCSV: " << csvData; - - const QStringList slRows = splitQuotedStringToRows(csvData); - - if (slRows.isEmpty()) - { - ERROR_LOG(m_logger) << "split quoted csv data failed! " << " codificationDataId: " << m_codificationDataId - << " csvData: " << csvData; - return false; - } - - if (slRows.size() != m_matrix.size()) - { - ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << m_matrix.size() << "/" << slRows.size(); - return false; - } - - for (int row = 0; row < slRows.size(); ++row) - { - const QVector slColumns = slRows[row].splitRef(QLatin1Char(';')); - if (slColumns.size() != m_matrix.size()) - { - ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << m_matrix.size() << "/" << slColumns.size(); - return false; + ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << m_ColumnSelectionValues.size() << "/" << slColumns.size(); + m_ColumnSelectionValues.fill(QLatin1Char(' ')); + return false; } - for (int column = 0; column < m_matrix.size(); ++column) - m_matrix[row][column] = slColumns.at(column).toString(); + for (int i = 0; i < m_ColumnSelectionValues.size(); ++i) + { + const QStringRef& qs = slColumns.at(i); + if (qs.size() != 1) + { + ERROR_LOG(m_logger) << "Invalid column data value at id: " << i + << " codificationDataId: " << m_codificationDataId; + return false; + } + m_ColumnSelectionValues[i] = qs.at(0); + } + emit dataChanged(index(0, 0), index(0, m_ColumnSelectionValues.size() - 1)); + return true; +} - } - return true; -} +bool LogisticalTermsModel::setRowSelectionValuesCSV(const QString& csvData) +{ + m_RowSelectionValues.clear(); + m_RowSelectionValues.resize(s_matrixCount); + const QVector slRows = csvData.splitRef(QStringLiteral("\n")); + + if (slRows.size() != m_RowSelectionValues.size()) + { + ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << m_RowSelectionValues.size() << "/" << slRows.size() + << " Default values will be used. "; + m_RowSelectionValues.fill(QLatin1Char(' ')); + return false; + } + + for (int i = 0; i < m_RowSelectionValues.size(); ++i) + { + const QStringRef& qs = slRows.at(i); + if (qs.size() != 1) + { + ERROR_LOG(m_logger) << "Invalid row data value at id: " << i + << " codificationDataId: " << m_codificationDataId; + return false; + } + m_RowSelectionValues[i] = qs.at(0); + } + emit dataChanged(index(0, 0), index(0, m_RowSelectionValues.size() - 1)); + return true; +} + +bool LogisticalTermsModel::setMatrixValuesCSV(const QString& csvData) +{ + DEBUG_LOG(m_logger) << "setMatrixValuesCSV: " << csvData; + + const QStringList slRows = splitQuotedStringToRows(csvData); + + if (slRows.isEmpty()) + { + ERROR_LOG(m_logger) << "split quoted csv data failed! " << " codificationDataId: " << m_codificationDataId + << " csvData: " << csvData; + return false; + } + + if (slRows.size() != m_matrix.size()) + { + ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << m_matrix.size() << "/" << slRows.size(); + return false; + } + + for (int row = 0; row < slRows.size(); ++row) + { + const QVector slColumns = slRows[row].splitRef(QLatin1Char(';')); + if (slColumns.size() != m_matrix.size()) + { + ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << m_matrix.size() << "/" << slColumns.size(); + return false; + } + + for (int column = 0; column < m_matrix.size(); ++column) + m_matrix[row][column] = slColumns.at(column).toString(); + } + return true; +} QString LogisticalTermsModel::getHorizontalHeaderCSVString() const { - QStringList slColumns; - slColumns.reserve(m_ColumnSelectionValues.size()); - for (const QChar &c : m_ColumnSelectionValues) - slColumns += QString(c); - - return slColumns.join(QLatin1Char(';')); -} + QStringList slColumns; + slColumns.reserve(m_ColumnSelectionValues.size()); + for (const QChar& c : m_ColumnSelectionValues) + slColumns += QString(c); + return slColumns.join(QLatin1Char(';')); +} QString LogisticalTermsModel::getVerticalHeaderCSVString() const { - QStringList slRows; - slRows.reserve(m_RowSelectionValues.size()); - for (const QChar &c : m_RowSelectionValues) - slRows += QString(c); - - return slRows.join(QLatin1Char('\n')); -} + QStringList slRows; + slRows.reserve(m_RowSelectionValues.size()); + for (const QChar& c : m_RowSelectionValues) + slRows += QString(c); + return slRows.join(QLatin1Char('\n')); +} QString LogisticalTermsModel::getMatrixDataCSVString() const { - QStringList slColumns; - slColumns.reserve(m_matrix.size()); - QStringList slRows; - slRows.reserve(m_matrix.size()); + QStringList slColumns; + slColumns.reserve(m_matrix.size()); + QStringList slRows; + slRows.reserve(m_matrix.size()); - for (const auto &colData : m_matrix) - { - slColumns.clear(); - for (const auto &cell : colData) + for (const auto& colData : m_matrix) { - if (cell.contains(QLatin1Char('\n'))) - slColumns += QLatin1Char('\"') + cell + QLatin1Char('\"'); - else - slColumns += cell; + slColumns.clear(); + for (const auto& cell : colData) + { + if (cell.contains(QLatin1Char('\n'))) + slColumns += QLatin1Char('\"') + cell + QLatin1Char('\"'); + else + slColumns += cell; + } + slRows += slColumns.join(QLatin1Char(';')); } - slRows += slColumns.join(QLatin1Char(';')); - } - - const QString qs(slRows.join(QLatin1Char('\n'))); - DEBUG_LOG(m_logger) << "getMatrixDataCSVString() : " << qs; - return qs; -} + const QString qs(slRows.join(QLatin1Char('\n'))); + DEBUG_LOG(m_logger) << "getMatrixDataCSVString() : " << qs; + return qs; +} void LogisticalTermsModel::setEditMode(bool isEditMode) { - m_isEditMode = isEditMode; - - emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); -} + m_isEditMode = isEditMode; + emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); +} bool LogisticalTermsModel::isEditMode() const { - return m_isEditMode; -} + return m_isEditMode; +} - -int LogisticalTermsModel::rowCount(const QModelIndex &parent) const +int LogisticalTermsModel::rowCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return s_matrixCount + (m_isEditMode ? 1 : 0); -} + Q_UNUSED(parent) + return s_matrixCount + (m_isEditMode ? 1 : 0); +} - -int LogisticalTermsModel::columnCount(const QModelIndex &parent) const +int LogisticalTermsModel::columnCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return s_matrixCount + (m_isEditMode ? 1 : 0); -} - + Q_UNUSED(parent) + return s_matrixCount + (m_isEditMode ? 1 : 0); +} QVariant LogisticalTermsModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) - return QAbstractTableModel::headerData(section, orientation, role); + if (role != Qt::DisplayRole) + return QAbstractTableModel::headerData(section, orientation, role); - - if (isEditMode()) - return QVariant(); - - if (orientation == Qt::Horizontal) - { - if (section < m_ColumnSelectionValues.size()) - return m_ColumnSelectionValues.at(section); - return QChar::fromLatin1('?'); - } - - if (orientation == Qt::Vertical) - { - if (section < m_RowSelectionValues.size()) - return m_RowSelectionValues.at(section); - return QChar::fromLatin1('?'); - } - - return QAbstractTableModel::headerData(section, orientation, role); -} - - -QVariant LogisticalTermsModel::data(const QModelIndex &index, int role) const -{ - if (role == Qt::DisplayRole || role == Qt::EditRole) - { - if (!m_isEditMode) - { - - - return m_matrix[index.row()][index.column()]; - } - - if (index.column() == 0 && index.row() == 0) - return QVariant(); - - - if (index.row() == 0 && index.column() <= m_ColumnSelectionValues.size()) - { - - - return m_ColumnSelectionValues.at(index.column() - 1); - } - - - if (index.column() == 0 && index.row() <= m_RowSelectionValues.size()) - { - - - return m_RowSelectionValues.at(index.row() - 1); - } - - - if (index.column() > 0 && index.row() > 0) - { - - - return m_matrix[index.row() - 1][index.column() - 1]; - } - } - - if (role == Qt::TextAlignmentRole) - return Qt::AlignCenter; - - if (role == Qt::BackgroundRole) - { - if (m_isEditMode) - { - if ((index.row() == 0) || (index.column() == 0)) - return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); - return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); - } - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); - - } - return QVariant(); -} - - -bool LogisticalTermsModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " value:" << value.toString(); - - const QString qs = value.toString(); - if (qs.isEmpty()) - return false; - - if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Inputs with the characters ; \" are not possible."), tr("Input Error")); - return false; - } - - if (role == Qt::EditRole) - { - - if (index.row() == 0) - { - m_ColumnSelectionValues[index.column() - 1] = qs.at(0); - - - } - - - else if (index.column() == 0 && (index.row() > 0)) - m_RowSelectionValues[index.row() - 1] = qs.at(0); - - - else if ((index.column() > 0) && (index.row() > 0)) - m_matrix[index.row() - 1][index.column() - 1] = qs; - emit dataModified(); - } - return true; -} - - -Qt::ItemFlags LogisticalTermsModel::flags(const QModelIndex &index) const -{ - Qt::ItemFlags flags = QAbstractTableModel::flags(index); - - if (((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) && - !((index.row() == 0) && (index.column() == 0))) - { if (isEditMode()) - flags |= Qt::ItemIsEditable; - else - flags &= ~Qt::ItemIsEditable; - } - return flags; -} + return QVariant(); + if (orientation == Qt::Horizontal) + { + if (section < m_ColumnSelectionValues.size()) + return m_ColumnSelectionValues.at(section); + return QChar::fromLatin1('?'); + } -void LogisticalTermsModel::onCodificationDataChanged(const CodificationManagement::CodificationData &data, + if (orientation == Qt::Vertical) + { + if (section < m_RowSelectionValues.size()) + return m_RowSelectionValues.at(section); + return QChar::fromLatin1('?'); + } + + return QAbstractTableModel::headerData(section, orientation, role); +} + +QVariant LogisticalTermsModel::data(const QModelIndex& index, int role) const +{ + if (role == Qt::DisplayRole || role == Qt::EditRole) + { + if (!m_isEditMode) + { + + return m_matrix[index.row()][index.column()]; + } + + if (index.column() == 0 && index.row() == 0) + return QVariant(); + + if (index.row() == 0 && index.column() <= m_ColumnSelectionValues.size()) + { + + return m_ColumnSelectionValues.at(index.column() - 1); + } + + if (index.column() == 0 && index.row() <= m_RowSelectionValues.size()) + { + + return m_RowSelectionValues.at(index.row() - 1); + } + + if (index.column() > 0 && index.row() > 0) + { + + return m_matrix[index.row() - 1][index.column() - 1]; + } + } + + if (role == Qt::TextAlignmentRole) + return Qt::AlignCenter; + + if (role == Qt::BackgroundRole) + { + if (m_isEditMode) + { + if ((index.row() == 0) || (index.column() == 0)) + return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); + return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); + } + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + } + return QVariant(); +} + +bool LogisticalTermsModel::setData(const QModelIndex& index, const QVariant& value, int role) +{ + DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() + << " value:" << value.toString(); + + const QString qs = value.toString(); + if (qs.isEmpty()) + return false; + + if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) + { + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), + tr("Inputs with the characters ; \" are not possible."), + tr("Input Error")); + return false; + } + + if (role == Qt::EditRole) + { + + if (index.row() == 0) + { + m_ColumnSelectionValues[index.column() - 1] = qs.at(0); + } + + else if (index.column() == 0 && (index.row() > 0)) + m_RowSelectionValues[index.row() - 1] = qs.at(0); + + else if ((index.column() > 0) && (index.row() > 0)) + m_matrix[index.row() - 1][index.column() - 1] = qs; + emit dataModified(); + } + return true; +} + +Qt::ItemFlags LogisticalTermsModel::flags(const QModelIndex& index) const +{ + Qt::ItemFlags flags = QAbstractTableModel::flags(index); + + if (((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) && + !((index.row() == 0) && (index.column() == 0))) + { + if (isEditMode()) + flags |= Qt::ItemIsEditable; + else + flags &= ~Qt::ItemIsEditable; + } + return flags; +} + +void LogisticalTermsModel::onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType) { - const int id = data.id(); + const int id = data.id(); - DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id - << " - NumCodeColumnIdx data: " << data.numeralCodeTableColumnIndex().c_str() - << " - NumCodeRowIdx data: " << data.numeralCodeTableRowIndex().c_str() - << " - modType: " << modType; + DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id + << " - NumCodeColumnIdx data: " << data.numeralCodeTableColumnIndex().c_str() + << " - NumCodeRowIdx data: " << data.numeralCodeTableRowIndex().c_str() + << " - modType: " << modType; - if (m_codificationDataId != data.id()) - return; + if (m_codificationDataId != data.id()) + return; - if (modType == DataModification::eRemoved) - { - WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - - resetMatrix(); - setColumnSelectionValuesCSV(QString()); - setRowSelectionValuesCSV(QString()); - return; - } + if (modType == DataModification::eRemoved) + { + WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id + << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - if (modType == DataModification::eModified) - { - DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); + resetMatrix(); + setColumnSelectionValuesCSV(QString()); + setRowSelectionValuesCSV(QString()); + return; + } - QString qs = QString::fromStdString(data.logisticalTermTableColumnIndex()); - setColumnSelectionValuesCSV(qs); + if (modType == DataModification::eModified) + { + DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); - qs = QString::fromStdString(data.logisticalTermTableRowIndex()); - setRowSelectionValuesCSV(qs); + QString qs = QString::fromStdString(data.logisticalTermTableColumnIndex()); + setColumnSelectionValuesCSV(qs); - qs = QString::fromStdString(data.logisticalTermTableMatrix()); - setMatrixValuesCSV(qs); - } -} + qs = QString::fromStdString(data.logisticalTermTableRowIndex()); + setRowSelectionValuesCSV(qs); + qs = QString::fromStdString(data.logisticalTermTableMatrix()); + setMatrixValuesCSV(qs); + } +} -QStringList LogisticalTermsModel::splitQuotedStringToRows(const QString &str) +QStringList LogisticalTermsModel::splitQuotedStringToRows(const QString& str) { - QStringList slRows; - QString row; - row.reserve(str.size()); + QStringList slRows; + QString row; + row.reserve(str.size()); - for (int i = 0; i < str.size(); ++i) - { - if (str.at(i) != QLatin1Char('\"') && str.at(i) != QLatin1Char('\n')) + for (int i = 0; i < str.size(); ++i) { - row.append(str.at(i)); - continue; + if (str.at(i) != QLatin1Char('\"') && str.at(i) != QLatin1Char('\n')) + { + row.append(str.at(i)); + continue; + } + + if (str.at(i) == QLatin1Char('\"')) + { + ++i; + while (str.at(i) != QLatin1Char('\"')) + { + row.append(str.at(i)); + ++i; + if (i > str.size()) + return QStringList(); + } + continue; + } + + if (str.at(i) == QLatin1Char('\n')) + { + slRows += row; + row.clear(); + } } - if (str.at(i) == QLatin1Char('\"')) - { - ++i; - while (str.at(i) != QLatin1Char('\"')) - { - row.append(str.at(i)); - ++i; - if (i > str.size()) - return QStringList(); - } - continue; - } - - if (str.at(i) == QLatin1Char('\n')) - { - slRows += row; - row.clear(); - } - } - - if (!row.isEmpty()) - slRows += row; - return slRows; - -} - + if (!row.isEmpty()) + slRows += row; + return slRows; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.h old mode 100755 new mode 100644 index 605e2ea39..f54954519 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_logistical_terms_model.h @@ -1,136 +1,74 @@ - #pragma once -#include -#include #include - +#include +#include namespace CodificationManagement { class LogisticalTermsModel final : public QAbstractTableModel { - Q_OBJECT -public: - explicit LogisticalTermsModel(QWidget *parent); + Q_OBJECT + public: + explicit LogisticalTermsModel(QWidget* parent); - + bool init(const std::shared_ptr& dtc, int codificationDataId, + bool isEditMode = false); - bool init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode = false); + void resetHeader(); - + void resetMatrix(); - void resetHeader(); + bool setColumnSelectionValuesCSV(const QString& csvData); - + bool setRowSelectionValuesCSV(const QString& csvData); - void resetMatrix(); + bool setMatrixValuesCSV(const QString& csvData); - + QString getHorizontalHeaderCSVString() const; - bool setColumnSelectionValuesCSV(const QString &csvData); + QString getVerticalHeaderCSVString() const; - + QString getMatrixDataCSVString() const; - bool setRowSelectionValuesCSV(const QString &csvData); + void setEditMode(bool isEditMode); + bool isEditMode() const; - + int rowCount(const QModelIndex& parent = QModelIndex()) const override; - bool setMatrixValuesCSV(const QString &csvData); + int columnCount(const QModelIndex& parent = QModelIndex()) const override; - + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - QString getHorizontalHeaderCSVString() const; + QVariant data(const QModelIndex& index, int role) const override; - + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - QString getVerticalHeaderCSVString() const; + Qt::ItemFlags flags(const QModelIndex& index) const override; - + QStringList splitQuotedStringToRows(const QString& str); - QString getMatrixDataCSVString() const; + Q_SIGNALS: - + void dataModified(); - void setEditMode(bool isEditMode); - bool isEditMode() const; + private Q_SLOTS: + void onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType); - + private: + NGL::INGLLogger& m_logger; + QVector> m_matrix; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVector m_RowSelectionValues; + QVector m_ColumnSelectionValues; - + std::shared_ptr m_dtc; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - - - - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - - - - QVariant data(const QModelIndex &index, int role) const override; - - - - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - - - Qt::ItemFlags flags(const QModelIndex &index) const override; - - - - QStringList splitQuotedStringToRows(const QString &str); - -Q_SIGNALS: - - - - void dataModified(); - - -private Q_SLOTS: - void onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType); - - - - - - - - - - -private: - - - - - - - - - - - -NGL::INGLLogger &m_logger; - QVector> m_matrix; - - QVector m_RowSelectionValues; - QVector m_ColumnSelectionValues; - - std::shared_ptr m_dtc; - - int m_codificationDataId; - bool m_isEditMode; + int m_codificationDataId; + bool m_isEditMode; }; -} - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.cpp old mode 100755 new mode 100644 index 3e52d267f..cc37f3459 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.cpp @@ -1,430 +1,383 @@ - - #include "cod_numeral_code_model.h" + #include #include #include using namespace CodificationManagement; -NumeralCodeModel::NumeralCodeModel(QWidget *parent) - : QAbstractTableModel(parent) - , m_dtc(nullptr) - , m_codificationDataId(0) - , m_isEditMode(false) +NumeralCodeModel::NumeralCodeModel(QWidget* parent) + : QAbstractTableModel(parent), m_dtc(nullptr), m_codificationDataId(0), m_isEditMode(false) { -} +} - -bool NumeralCodeModel::init(const std::shared_ptr &dtc, - int codificationDataId, +bool NumeralCodeModel::init(const std::shared_ptr& dtc, int codificationDataId, bool isEditMode) { - if (!dtc) - return false; + if (!dtc) + return false; - m_dtc = dtc; - m_codificationDataId = codificationDataId; - m_isEditMode = isEditMode; + m_dtc = dtc; + m_codificationDataId = codificationDataId; + m_isEditMode = isEditMode; + m_MatrixNumeralSet.resize(10); + for (int i = 0; i < 10; ++i) + m_MatrixNumeralSet[i] = QLatin1Char('0' + i); - m_MatrixNumeralSet.resize(10); - for (int i = 0; i < 10; ++i) - m_MatrixNumeralSet[i] = QLatin1Char('0' + i); + m_MatrixCharacterSet1.resize(26); + for (int i = 0; i < 26; ++i) + m_MatrixCharacterSet1[i] = QLatin1Char('A' + i); - m_MatrixCharacterSet1.resize(26); - for (int i = 0; i < 26; ++i) - m_MatrixCharacterSet1[i] = QLatin1Char('A' + i); + m_MatrixCharacterSet2 << QLatin1Char('D') << QLatin1Char('E') << QLatin1Char('G') << QLatin1Char('H') + << QLatin1Char('I') << QLatin1Char('L') << QLatin1Char('N') << QLatin1Char('O') + << QLatin1Char('R') << QLatin1Char('S') << QLatin1Char('T') << QLatin1Char('U'); - m_MatrixCharacterSet2 << QLatin1Char('D') << QLatin1Char('E') << QLatin1Char('G') << QLatin1Char('H') << QLatin1Char('I') << QLatin1Char('L') - << QLatin1Char('N') << QLatin1Char('O') << QLatin1Char('R') << QLatin1Char('S') << QLatin1Char('T') << QLatin1Char('U'); - - resetHeader(); - initMatrix(); - - if (!isEditMode) - { - connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &NumeralCodeModel::onCodificationDataChanged); - } - return true; -} + resetHeader(); + initMatrix(); + if (!isEditMode) + { + connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &NumeralCodeModel::onCodificationDataChanged); + } + return true; +} void NumeralCodeModel::resetHeader() { - - m_ColumnSelectionValues = QVector(columnCount() - 1, QLatin1Char('?')); - m_RowSelectionValues = QVector(rowCount() - 1, QLatin1Char('?')); -} + m_ColumnSelectionValues = QVector(columnCount() - 1, QLatin1Char('?')); + m_RowSelectionValues = QVector(rowCount() - 1, QLatin1Char('?')); +} -bool NumeralCodeModel::setColumnSelectionValuesCSV(const QString &csvData) +bool NumeralCodeModel::setColumnSelectionValuesCSV(const QString& csvData) { - m_ColumnSelectionValues = QVector(columnCount() - 1, QLatin1Char(' ')); + m_ColumnSelectionValues = QVector(columnCount() - 1, QLatin1Char(' ')); - const QVector slColumns = csvData.splitRef(QLatin1Char(';')); + const QVector slColumns = csvData.splitRef(QLatin1Char(';')); - if (slColumns.size() != columnCount() - 1) - { - ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << columnCount() - 1 << "/" << slColumns.size(); - return false; - } - - for (int i = 0; i < columnCount() - 1; ++i) - { - const QStringRef &qs = slColumns.at(i); - if (qs.size() != 1) + if (slColumns.size() != columnCount() - 1) { - ERROR_LOG(m_logger) << "Invalid column data value at id: " << i - << " codificationDataId: " << m_codificationDataId; - return false; + ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << columnCount() - 1 << "/" << slColumns.size(); + return false; } - m_ColumnSelectionValues[i] = qs.at(0); - } - emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); - return true; -} + for (int i = 0; i < columnCount() - 1; ++i) + { + const QStringRef& qs = slColumns.at(i); + if (qs.size() != 1) + { + ERROR_LOG(m_logger) << "Invalid column data value at id: " << i + << " codificationDataId: " << m_codificationDataId; + return false; + } + m_ColumnSelectionValues[i] = qs.at(0); + } + emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); + return true; +} -bool NumeralCodeModel::setRowSelectionValuesCSV(const QString &csvData) +bool NumeralCodeModel::setRowSelectionValuesCSV(const QString& csvData) { - m_RowSelectionValues = QVector(rowCount() - 1, QLatin1Char(' ')); - const QVector slRows = csvData.splitRef(QStringLiteral("\n")); + m_RowSelectionValues = QVector(rowCount() - 1, QLatin1Char(' ')); + const QVector slRows = csvData.splitRef(QStringLiteral("\n")); - if (slRows.size() != rowCount() - 1) - { - ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << rowCount() - 1 << "/" << slRows.size() - << " Default values will be used. "; - return false; - } - - for (int i = 0; i < rowCount() - 1; ++i) - { - const QStringRef &qs = slRows.at(i); - if (qs.size() != 1) + if (slRows.size() != rowCount() - 1) { - ERROR_LOG(m_logger) << "Invalid row data value at id: " << i - << " codificationDataId: " << m_codificationDataId; - return false; + ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << rowCount() - 1 << "/" << slRows.size() + << " Default values will be used. "; + return false; } - m_RowSelectionValues[i] = qs.at(0); - } - emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); - return true; -} + for (int i = 0; i < rowCount() - 1; ++i) + { + const QStringRef& qs = slRows.at(i); + if (qs.size() != 1) + { + ERROR_LOG(m_logger) << "Invalid row data value at id: " << i + << " codificationDataId: " << m_codificationDataId; + return false; + } + m_RowSelectionValues[i] = qs.at(0); + } + emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); + return true; +} QString NumeralCodeModel::getHorizontalHeaderCSVString() const { - QStringList slColumns; - slColumns.reserve(columnCount() - 1); - for (int i = 0; i < columnCount() -1; ++i) - { - slColumns << QStringLiteral("%1").arg(m_ColumnSelectionValues.at(i)); - } - return slColumns.join(QLatin1Char(';')); -} - + QStringList slColumns; + slColumns.reserve(columnCount() - 1); + for (int i = 0; i < columnCount() - 1; ++i) + { + slColumns << QStringLiteral("%1").arg(m_ColumnSelectionValues.at(i)); + } + return slColumns.join(QLatin1Char(';')); +} QString NumeralCodeModel::getVerticalHeaderCSVString() const { - QStringList slRows; - slRows.reserve(rowCount() - 1); - for (int i = 0; i < rowCount() - 1; ++i) - { - slRows << QStringLiteral("%1").arg(m_RowSelectionValues.at(i)); - } - return slRows.join(QStringLiteral("\n")); -} - + QStringList slRows; + slRows.reserve(rowCount() - 1); + for (int i = 0; i < rowCount() - 1; ++i) + { + slRows << QStringLiteral("%1").arg(m_RowSelectionValues.at(i)); + } + return slRows.join(QStringLiteral("\n")); +} void NumeralCodeModel::setEditMode(bool isEditMode) { - m_isEditMode = isEditMode; - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); -} - + m_isEditMode = isEditMode; + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); +} bool NumeralCodeModel::isEditMode() const { - return m_isEditMode; -} + return m_isEditMode; +} - -int NumeralCodeModel::rowCount(const QModelIndex &parent) const +int NumeralCodeModel::rowCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 14; -} + Q_UNUSED(parent) + return 14; +} - -int NumeralCodeModel::columnCount(const QModelIndex &parent) const +int NumeralCodeModel::columnCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 14; -} - + Q_UNUSED(parent) + return 14; +} QVariant NumeralCodeModel::headerData(int column, Qt::Orientation orientation, int role) const { - if (role == Qt::DisplayRole ) - { - if (isEditMode()) + if (role == Qt::DisplayRole) { - - return QVariant(); + if (isEditMode()) + { + + return QVariant(); + } + else + { + if (column == 0) + return QVariant(); + if (orientation == Qt::Horizontal) + { + if (!m_ColumnSelectionValues.isEmpty()) + return m_ColumnSelectionValues.at(column - 1); + return QChar::fromLatin1('?'); + } + if (orientation == Qt::Vertical) + { + if (!m_RowSelectionValues.isEmpty()) + return m_RowSelectionValues.at(column - 1); + return QChar::fromLatin1('?'); + } + } } - else + + if (role == Qt::BackgroundRole) { - if (column == 0) - return QVariant(); - if (orientation == Qt::Horizontal) - { - if (!m_ColumnSelectionValues.isEmpty()) - return m_ColumnSelectionValues.at(column - 1); - return QChar::fromLatin1('?'); - } - if (orientation == Qt::Vertical) - { - if (!m_RowSelectionValues.isEmpty()) - return m_RowSelectionValues.at(column - 1); - return QChar::fromLatin1('?'); - } + if (isEditMode()) + + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); + else + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); } - } - if (role == Qt::BackgroundRole) - { - if (isEditMode()) - - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); - else - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); - } + return QAbstractTableModel::headerData(column, orientation, role); +} - return QAbstractTableModel::headerData(column, orientation, role); -} - - -QVariant NumeralCodeModel::data(const QModelIndex &index, int role) const +QVariant NumeralCodeModel::data(const QModelIndex& index, int role) const { - if ((role == Qt::DisplayRole || role == Qt::EditRole)) - { - - if ((index.column() == 0) && (index.row() == 0)) - return QVariant(); - - - if (index.row() == 0) + if ((role == Qt::DisplayRole || role == Qt::EditRole)) { - if (!m_ColumnSelectionValues.isEmpty()) - return m_ColumnSelectionValues[index.column() - 1]; - return QChar::fromLatin1('?'); + + if ((index.column() == 0) && (index.row() == 0)) + return QVariant(); + + if (index.row() == 0) + { + if (!m_ColumnSelectionValues.isEmpty()) + return m_ColumnSelectionValues[index.column() - 1]; + return QChar::fromLatin1('?'); + } + + if ((index.column() == 0)) + { + if (!m_RowSelectionValues.isEmpty()) + return m_RowSelectionValues[index.row() - 1]; + return QChar::fromLatin1('?'); + } + + if ((index.column() > 0) && (index.row() > 0)) + { + return m_matrix[index.row() - 1][index.column() - 1]; + } } - - if ((index.column() == 0)) + if (role == Qt::TextAlignmentRole) + return Qt::AlignCenter; + + if (role == Qt::BackgroundRole) { - if (!m_RowSelectionValues.isEmpty()) - return m_RowSelectionValues[index.row() - 1]; - return QChar::fromLatin1('?'); + if ((index.row() > 0) && (index.column() > 0)) + + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + else + { + if (isEditMode()) + + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); + else + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + } } - - if ((index.column() > 0) && (index.row() > 0)) + if (role == Qt::ForegroundRole) { - return m_matrix[index.row() - 1][index.column() - 1]; + if ((index.row() == 0) && (index.column() == 0)) + return QColor(Qt::red); } + return QVariant(); +} - - - - } - - if (role == Qt::TextAlignmentRole) - return Qt::AlignCenter; - - if (role == Qt::BackgroundRole) - { - if ((index.row() > 0) && (index.column() > 0)) - - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); - else - { - if (isEditMode()) - - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); - else - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); - } - } - - if (role == Qt::ForegroundRole) - { - if ((index.row() == 0) && (index.column() == 0)) - return QColor(Qt::red); - } - - return QVariant(); - -} - - -bool NumeralCodeModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool NumeralCodeModel::setData(const QModelIndex& index, const QVariant& value, int role) { - DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " char:" << value.toString(); + DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() + << " char:" << value.toString(); - if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Inputs with the characters ; \" are not possible."), tr("Input Error")); - return false; - } + if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) + { + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), + tr("Inputs with the characters ; \" are not possible."), + tr("Input Error")); + return false; + } - QString tmp = value.toString(); - if (tmp.isEmpty()) - return false; + QString tmp = value.toString(); + if (tmp.isEmpty()) + return false; - const QChar c = tmp.at(0); + const QChar c = tmp.at(0); - if (role == Qt::EditRole) - { - - if (index.row() == 0) - m_ColumnSelectionValues[index.column() - 1] = c; - - if (index.column() == 0 && (index.row() > 0)) - m_RowSelectionValues[index.row() - 1] = c; - emit dataModified(); - } + if (role == Qt::EditRole) + { - return true; -} + if (index.row() == 0) + m_ColumnSelectionValues[index.column() - 1] = c; + if (index.column() == 0 && (index.row() > 0)) + m_RowSelectionValues[index.row() - 1] = c; + emit dataModified(); + } -Qt::ItemFlags NumeralCodeModel::flags(const QModelIndex &index) const + return true; +} + +Qt::ItemFlags NumeralCodeModel::flags(const QModelIndex& index) const { - Qt::ItemFlags flags = QAbstractTableModel::flags(index); - if (((index.row() == 0) && (index.column() > 0)) || - ((index.row() > 0) && (index.column() == 0))) - { - if (isEditMode()) - flags |= Qt::ItemIsEditable; - else - flags &= ~Qt::ItemIsEditable; - } - return flags; -} - + Qt::ItemFlags flags = QAbstractTableModel::flags(index); + if (((index.row() == 0) && (index.column() > 0)) || ((index.row() > 0) && (index.column() == 0))) + { + if (isEditMode()) + flags |= Qt::ItemIsEditable; + else + flags &= ~Qt::ItemIsEditable; + } + return flags; +} void NumeralCodeModel::initMatrix() { - int lastMatrixValueCnt = 0; - int lastMatrixCharacterCnt = 0; - int lastMatrixCharacterIndex = 0; - int numOfCharacter = 4; + int lastMatrixValueCnt = 0; + int lastMatrixCharacterCnt = 0; + int lastMatrixCharacterIndex = 0; + int numOfCharacter = 4; - for (int row = 0; row < 13; ++row) - { - - if (row > 3) + for (int row = 0; row < 13; ++row) { - numOfCharacter = 3; - lastMatrixValueCnt -= 1; + + if (row > 3) + { + numOfCharacter = 3; + lastMatrixValueCnt -= 1; + } + + if (row == 9) + lastMatrixCharacterIndex = 0; + + for (int col = 0; col < 13; ++col) + { + if (lastMatrixValueCnt < 10) + { + m_matrix[row][col] = m_MatrixNumeralSet.at(lastMatrixValueCnt); + lastMatrixValueCnt += 1; + + if (lastMatrixValueCnt == 10) + lastMatrixCharacterCnt = 0; + } + else + { + if (row < 9) + m_matrix[row][col] = m_MatrixCharacterSet1.at(lastMatrixCharacterIndex); + else + m_matrix[row][col] = m_MatrixCharacterSet2.at(lastMatrixCharacterIndex); + lastMatrixCharacterCnt += 1; + lastMatrixCharacterIndex += 1; + + if (lastMatrixCharacterCnt == numOfCharacter) + lastMatrixValueCnt = 0; + } + + if ((row < 9) && (lastMatrixCharacterIndex == 26)) + lastMatrixCharacterIndex = 0; + + if ((row >= 9) && (lastMatrixCharacterIndex == 12)) + lastMatrixCharacterIndex = 0; + } } - - if (row == 9) - lastMatrixCharacterIndex = 0; + return; +} - for (int col = 0; col < 13; ++col) - { - if (lastMatrixValueCnt < 10) - { - m_matrix[row][col] = m_MatrixNumeralSet.at(lastMatrixValueCnt); - lastMatrixValueCnt += 1; - - if (lastMatrixValueCnt == 10) - lastMatrixCharacterCnt = 0; - } - else - { - if (row < 9) - m_matrix[row][col] = m_MatrixCharacterSet1.at(lastMatrixCharacterIndex); - else - m_matrix[row][col] = m_MatrixCharacterSet2.at(lastMatrixCharacterIndex); - lastMatrixCharacterCnt += 1; - lastMatrixCharacterIndex += 1; - - if (lastMatrixCharacterCnt == numOfCharacter) - lastMatrixValueCnt = 0; - } - - - if ((row < 9) && (lastMatrixCharacterIndex == 26)) - lastMatrixCharacterIndex = 0; - - - if ((row >= 9) && (lastMatrixCharacterIndex == 12)) - lastMatrixCharacterIndex = 0; - } - } - - - - - - - - - - - - - - - - - return; -} - - -void NumeralCodeModel::onCodificationDataChanged(const CodificationManagement::CodificationData &data, +void NumeralCodeModel::onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType) { - const int id = data.id(); + const int id = data.id(); - DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id - << " - NumCodeColumnIdx data: " << data.numeralCodeTableColumnIndex().c_str() - << " - NumCodeRowIdx data: " << data.numeralCodeTableRowIndex().c_str() - << " - modType: " << (int)modType; + DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id + << " - NumCodeColumnIdx data: " << data.numeralCodeTableColumnIndex().c_str() + << " - NumCodeRowIdx data: " << data.numeralCodeTableRowIndex().c_str() + << " - modType: " << (int)modType; - if (m_codificationDataId != data.id()) - return; + if (m_codificationDataId != data.id()) + return; - if (modType == DataModification::eRemoved) - { - WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - setColumnSelectionValuesCSV(QString()); - setRowSelectionValuesCSV(QString()); - return; - } + if (modType == DataModification::eRemoved) + { + WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id + << " ToDo: 'ShowCodificationData' Tab loeschen !?"; + setColumnSelectionValuesCSV(QString()); + setRowSelectionValuesCSV(QString()); + return; + } - if (modType == DataModification::eModified) - { - DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); + if (modType == DataModification::eModified) + { + DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); - QString qs = QString::fromStdString(data.numeralCodeTableColumnIndex()); - setColumnSelectionValuesCSV(qs); - - qs = QString::fromStdString(data.numeralCodeTableRowIndex()); - setRowSelectionValuesCSV(qs); - } -} + QString qs = QString::fromStdString(data.numeralCodeTableColumnIndex()); + setColumnSelectionValuesCSV(qs); + qs = QString::fromStdString(data.numeralCodeTableRowIndex()); + setRowSelectionValuesCSV(qs); + } +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.h old mode 100755 new mode 100644 index 07f349685..9f80c2e28 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_numeral_code_model.h @@ -1,111 +1,74 @@ - #pragma once -#include -#include #include - +#include +#include namespace CodificationManagement { class NumeralCodeModel final : public QAbstractTableModel { - Q_OBJECT -public: - explicit NumeralCodeModel(QWidget *parent); + Q_OBJECT + public: + explicit NumeralCodeModel(QWidget* parent); - ~NumeralCodeModel() = default; + ~NumeralCodeModel() = default; - + bool init(const std::shared_ptr& dtc, int codificationDataId, + bool isEditMode = false); - bool init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode = false); + void resetHeader(); - + bool setColumnSelectionValuesCSV(const QString& csvData); - void resetHeader(); + bool setRowSelectionValuesCSV(const QString& csvData); - + QString getHorizontalHeaderCSVString() const; - bool setColumnSelectionValuesCSV(const QString &csvData); + QString getVerticalHeaderCSVString() const; - + void setEditMode(bool isEditMode); + bool isEditMode() const; - bool setRowSelectionValuesCSV(const QString &csvData); + int rowCount(const QModelIndex& parent = QModelIndex()) const override; - + int columnCount(const QModelIndex& parent = QModelIndex()) const override; - QString getHorizontalHeaderCSVString() const; + QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - + QVariant data(const QModelIndex& index, int role) const override; - QString getVerticalHeaderCSVString() const; + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - + Qt::ItemFlags flags(const QModelIndex& index) const override; - void setEditMode(bool isEditMode); - bool isEditMode() const; + Q_SIGNALS: - + void dataModified(); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; + private Q_SLOTS: + void onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType); - + private: + NGL::INGLLogger& m_logger; + void initMatrix(); - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QVector m_MatrixNumeralSet; + QVector m_MatrixCharacterSet1; + QVector m_MatrixCharacterSet2; - + QChar m_matrix[13][13]; - QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVector m_RowSelectionValues; + QVector m_ColumnSelectionValues; - + std::shared_ptr m_dtc; - QVariant data(const QModelIndex &index, int role) const override; - - - - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - - - Qt::ItemFlags flags(const QModelIndex &index) const override; - -Q_SIGNALS: - - - - void dataModified(); - - -private Q_SLOTS: - void onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType); - -private: - - - - -NGL::INGLLogger &m_logger; - void initMatrix(); - - QVector m_MatrixNumeralSet; - QVector m_MatrixCharacterSet1; - QVector m_MatrixCharacterSet2; - - QChar m_matrix[13][13]; - - QVector m_RowSelectionValues; - QVector m_ColumnSelectionValues; - - std::shared_ptr m_dtc; - - int m_codificationDataId; - bool m_isEditMode; + int m_codificationDataId; + bool m_isEditMode; }; -} +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.cpp old mode 100755 new mode 100644 index 5096b262f..21fa4272a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.cpp @@ -1,301 +1,276 @@ - - #include "cod_phrase_table_model.h" + #include #include #include using namespace CodificationManagement; -PhraseTableModel::PhraseTableModel(QWidget *parent) - : QAbstractTableModel(parent) - , m_dtc(nullptr) - , m_codificationDataId(0) - , m_isEditMode(false) +PhraseTableModel::PhraseTableModel(QWidget* parent) + : QAbstractTableModel(parent), m_dtc(nullptr), m_codificationDataId(0), m_isEditMode(false) { - DEBUG_LOG(m_logger) << "ctor PhraseTableModel"; + DEBUG_LOG(m_logger) << "ctor PhraseTableModel"; +} -} - - -bool PhraseTableModel::init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode) +bool PhraseTableModel::init(const std::shared_ptr& dtc, int codificationDataId, + bool isEditMode) { - DEBUG_LOG(m_logger) << "PhraseTableModel::init()"; - if (!dtc) - return false; + DEBUG_LOG(m_logger) << "PhraseTableModel::init()"; + if (!dtc) + return false; - m_dtc = dtc; - m_codificationDataId = codificationDataId; - m_isEditMode = isEditMode; + m_dtc = dtc; + m_codificationDataId = codificationDataId; + m_isEditMode = isEditMode; - - resetMatrix(); - - if (!isEditMode) - { - connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, - this, &PhraseTableModel::onCodificationDataChanged); - } - return true; -} + resetMatrix(); + if (!isEditMode) + { + connect(m_dtc.get(), &CodificationManagement::Interface::Dtc::codificationDataChanged, this, + &PhraseTableModel::onCodificationDataChanged); + } + return true; +} void PhraseTableModel::resetMatrix() { - for (int row = 0; row < rowCount(); ++row) - { - for (int column = 0; column < columnCount(); ++column) + for (int row = 0; row < rowCount(); ++row) { - if ((row == 0) && (column == 0)) - { - m_matrix[row][column] = QLatin1String("A-Warnung "); - } - if ((row == 1) && (column == 0)) - { - m_matrix[row][column] = QLatin1String("B-Warnung "); - } - if ((row == 2) && (column == 0)) - { - m_matrix[row][column] = QLatin1String("C-Warnung "); - } + for (int column = 0; column < columnCount(); ++column) + { + if ((row == 0) && (column == 0)) + { + m_matrix[row][column] = QLatin1String("A-Warnung "); + } + if ((row == 1) && (column == 0)) + { + m_matrix[row][column] = QLatin1String("B-Warnung "); + } + if ((row == 2) && (column == 0)) + { + m_matrix[row][column] = QLatin1String("C-Warnung "); + } - if ((row <= 2 && column > 0) || (row > 2)) - m_matrix[row][column] = QLatin1String("--- "); + if ((row <= 2 && column > 0) || (row > 2)) + m_matrix[row][column] = QLatin1String("--- "); + } } - } - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); - return ; -} + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); + return; +} - -bool PhraseTableModel::setMatrixValuesCSV(const QString &csvData) +bool PhraseTableModel::setMatrixValuesCSV(const QString& csvData) { - DEBUG_LOG(m_logger) << "setMatrixValuesCSV() data: " << csvData; + DEBUG_LOG(m_logger) << "setMatrixValuesCSV() data: " << csvData; - const QVector slRows = csvData.splitRef(QLatin1Char('\n')); - if (slRows.count() != rowCount()) - { - ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << rowCount() << "/" << slRows.size(); - return false; - } - - for (int row = 0; row < rowCount(); ++row) - { - const QStringList slColumns = splitQuotedString(QLatin1Char(';'), slRows[row].toString()); - if (slColumns.count() != columnCount()) + const QVector slRows = csvData.splitRef(QLatin1Char('\n')); + if (slRows.count() != rowCount()) { - ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId - << " Soll/Ist: " << columnCount() << "/" << slColumns.size(); - return false; + ERROR_LOG(m_logger) << "Invalid row data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << rowCount() << "/" << slRows.size(); + return false; } - for (int column = 0; column < columnCount(); ++column) + for (int row = 0; row < rowCount(); ++row) { - m_matrix[row][column] = slColumns[column]; - } - } - return true; -} + const QStringList slColumns = splitQuotedString(QLatin1Char(';'), slRows[row].toString()); + if (slColumns.count() != columnCount()) + { + ERROR_LOG(m_logger) << "Invalid column data count." << " codificationDataId: " << m_codificationDataId + << " Soll/Ist: " << columnCount() << "/" << slColumns.size(); + return false; + } + for (int column = 0; column < columnCount(); ++column) + { + m_matrix[row][column] = slColumns[column]; + } + } + return true; +} QString PhraseTableModel::getMatrixDataCSVString() const { - QStringList slColumns; - slColumns.reserve(columnCount()); - QStringList slRows; - slRows.reserve(rowCount() * columnCount()); - for (int row = 0; row < rowCount(); ++row) - { - slColumns.clear(); - for (int column = 0; column < columnCount(); ++column) + QStringList slColumns; + slColumns.reserve(columnCount()); + QStringList slRows; + slRows.reserve(rowCount() * columnCount()); + for (int row = 0; row < rowCount(); ++row) { - const QString &cell = m_matrix[row][column]; - if (cell.contains(QLatin1Char(';'))) - slColumns += QLatin1Char('\"') + cell + QLatin1Char('\"'); - else - slColumns += cell; + slColumns.clear(); + for (int column = 0; column < columnCount(); ++column) + { + const QString& cell = m_matrix[row][column]; + if (cell.contains(QLatin1Char(';'))) + slColumns += QLatin1Char('\"') + cell + QLatin1Char('\"'); + else + slColumns += cell; + } + slRows << slColumns.join(QLatin1Char(';')); } - slRows << slColumns.join(QLatin1Char(';')); - } - return slRows.join(QLatin1Char('\n')); -} - + return slRows.join(QLatin1Char('\n')); +} void PhraseTableModel::setEditMode(bool isEditMode) { - m_isEditMode = isEditMode; - - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); -} + m_isEditMode = isEditMode; + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); +} bool PhraseTableModel::isEditMode() const { - return m_isEditMode; -} + return m_isEditMode; +} - -int PhraseTableModel::rowCount(const QModelIndex &parent) const +int PhraseTableModel::rowCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 13; -} + Q_UNUSED(parent) + return 13; +} - -int PhraseTableModel::columnCount(const QModelIndex &parent) const +int PhraseTableModel::columnCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 2; -} - + Q_UNUSED(parent) + return 2; +} QVariant PhraseTableModel::headerData(int column, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) - return QAbstractTableModel::headerData(column, orientation, role); + if (role != Qt::DisplayRole) + return QAbstractTableModel::headerData(column, orientation, role); - - return QVariant(); -} + return QVariant(); +} - -QVariant PhraseTableModel::data(const QModelIndex &index, int role) const +QVariant PhraseTableModel::data(const QModelIndex& index, int role) const { - if ((role == Qt::DisplayRole || role == Qt::EditRole)) - { - - - return m_matrix[index.row()][index.column()]; - } - - if (role == Qt::TextAlignmentRole) - return Qt::AlignCenter; - - if (role == Qt::BackgroundRole) - { - if ((index.row() <= rowCount()-1) && (index.column() <= columnCount() - 1)) + if ((role == Qt::DisplayRole || role == Qt::EditRole)) { - if (m_isEditMode) - { - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); - } - else - - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + return m_matrix[index.row()][index.column()]; } - } - return QVariant(); -} + if (role == Qt::TextAlignmentRole) + return Qt::AlignCenter; -bool PhraseTableModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " value:" << value.toString(); - - - if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) - { - LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), tr("Inputs with the characters ; \" are not possible."), tr("Input Error")); - return false; - } - - QString qs = value.toString(); - if (qs.isEmpty()) - return false; - - if (role == Qt::EditRole) - { - if ((index.row() <= rowCount()-1) && (index.column() <= columnCount() - 1)) + if (role == Qt::BackgroundRole) { - m_matrix[index.row()][index.column()] = qs; - emit dataModified(); + if ((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) + { + if (m_isEditMode) + { + + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); + } + else + + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::Base); + } } - } - return true; -} + return QVariant(); +} - -Qt::ItemFlags PhraseTableModel::flags(const QModelIndex &index) const +bool PhraseTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { - Qt::ItemFlags flags = QAbstractTableModel::flags(index); + DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() + << " value:" << value.toString(); - if (isEditMode()) - { - if ((index.row() <= rowCount()-1) && (index.column() <= columnCount() - 1)) - flags |= Qt::ItemIsEditable; + if (value.toString().contains(QLatin1Char('\"')) || value.toString().contains(QLatin1Char(';'))) + { + LtsWidgets::LtsMessageDialog::showMessage(qobject_cast(parent()), + tr("Inputs with the characters ; \" are not possible."), + tr("Input Error")); + return false; + } - - if ((index.column() == 0) && (index.row() <= 2)) - flags &= ~Qt::ItemIsEditable; - } - else - { - if ((index.row() <= rowCount()-1) && (index.column() <= columnCount() - 1)) - flags &= ~Qt::ItemIsEditable; - } - return flags; -} + QString qs = value.toString(); + if (qs.isEmpty()) + return false; + if (role == Qt::EditRole) + { + if ((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) + { + m_matrix[index.row()][index.column()] = qs; + emit dataModified(); + } + } + return true; +} -void PhraseTableModel::onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType) +Qt::ItemFlags PhraseTableModel::flags(const QModelIndex& index) const { - const int id = data.id(); + Qt::ItemFlags flags = QAbstractTableModel::flags(index); - DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id - << " - PhraseTableModel data: " << data.phraseTable().c_str() - << " - modType: " << (int)modType; + if (isEditMode()) + { + if ((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) + flags |= Qt::ItemIsEditable; - if (m_codificationDataId != data.id()) - return; + if ((index.column() == 0) && (index.row() <= 2)) + flags &= ~Qt::ItemIsEditable; + } + else + { + if ((index.row() <= rowCount() - 1) && (index.column() <= columnCount() - 1)) + flags &= ~Qt::ItemIsEditable; + } + return flags; +} - if (modType == DataModification::eRemoved) - { - WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - - resetMatrix(); - return; - } - - if (modType == DataModification::eModified) - { - DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); - - QString qs = QString::fromStdString(data.phraseTable()); - setMatrixValuesCSV(qs); - } -} - - -QStringList PhraseTableModel::splitQuotedString(const QChar &sep, const QString &inString) +void PhraseTableModel::onCodificationDataChanged(const CodificationManagement::CodificationData& data, + DataModification modType) { - QString str = inString; - QStringList result; + const int id = data.id(); - while (str.contains(QLatin1Char('\"'))) - { - int i = str.indexOf(QLatin1Char('\"')); - QString part = str.left(i); + DEBUG_LOG(m_logger) << "onCodificationDataChanged for CodificationData id: " << id + << " - PhraseTableModel data: " << data.phraseTable().c_str() << " - modType: " << (int)modType; - result += part.split(sep, QString::SkipEmptyParts); + if (m_codificationDataId != data.id()) + return; - str.remove(0, i + 1); + if (modType == DataModification::eRemoved) + { + WARNING_LOG(m_logger) << "CodificationData was removed. id: " << id + << " ToDo: 'ShowCodificationData' Tab loeschen !?"; - i = str.indexOf(QLatin1Char('\"')); + resetMatrix(); + return; + } - result += str.left(i); - str.remove(0,i + 1); - } - result += str.split(sep, QString::SkipEmptyParts); + if (modType == DataModification::eModified) + { + DEBUG_LOG(m_logger) << "CodificationData was modifed. id: " << id << " - " << data.note(); - return result; -} + QString qs = QString::fromStdString(data.phraseTable()); + setMatrixValuesCSV(qs); + } +} +QStringList PhraseTableModel::splitQuotedString(const QChar& sep, const QString& inString) +{ + QString str = inString; + QStringList result; + while (str.contains(QLatin1Char('\"'))) + { + int i = str.indexOf(QLatin1Char('\"')); + QString part = str.left(i); + + result += part.split(sep, QString::SkipEmptyParts); + + str.remove(0, i + 1); + + i = str.indexOf(QLatin1Char('\"')); + + result += str.left(i); + str.remove(0, i + 1); + } + result += str.split(sep, QString::SkipEmptyParts); + + return result; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.h old mode 100755 new mode 100644 index 0ef6069f2..bc9c8c976 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Gui/CodificationData/cod_phrase_table_model.h @@ -1,104 +1,64 @@ - #pragma once -#include -#include #include - +#include +#include namespace CodificationManagement { class PhraseTableModel final : public QAbstractTableModel { - Q_OBJECT -public: - explicit PhraseTableModel(QWidget *parent); + Q_OBJECT + public: + explicit PhraseTableModel(QWidget* parent); - ~PhraseTableModel() = default; + ~PhraseTableModel() = default; - + bool init(const std::shared_ptr& dtc, int codificationDataId, + bool isEditMode = false); - bool init(const std::shared_ptr &dtc, - int codificationDataId, - bool isEditMode = false); + void resetMatrix(); - + bool setMatrixValuesCSV(const QString& csvData); - void resetMatrix(); + QString getMatrixDataCSVString() const; - + void setEditMode(bool isEditMode); + bool isEditMode() const; - bool setMatrixValuesCSV(const QString &csvData); + int rowCount(const QModelIndex& parent = QModelIndex()) const override; - + int columnCount(const QModelIndex& parent = QModelIndex()) const override; - QString getMatrixDataCSVString() const; + QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - + QVariant data(const QModelIndex& index, int role) const override; - void setEditMode(bool isEditMode); - bool isEditMode() const; + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - + Qt::ItemFlags flags(const QModelIndex& index) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; + Q_SIGNALS: - + void dataModified(); - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + private Q_SLOTS: + void onCodificationDataChanged(const CodificationManagement::CodificationData& data, DataModification modType); - + private: + NGL::INGLLogger& m_logger; + QStringList splitQuotedString(const QChar& sep, const QString& inString); - QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + private: + QString m_matrix[13][2]; - + std::shared_ptr m_dtc; - QVariant data(const QModelIndex &index, int role) const override; - - - - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - - - Qt::ItemFlags flags(const QModelIndex &index) const override; - -Q_SIGNALS: - - - - void dataModified(); - - -private Q_SLOTS: - void onCodificationDataChanged(const CodificationManagement::CodificationData &data, - DataModification modType); - -private: - - - -NGL::INGLLogger &m_logger; - QStringList splitQuotedString(const QChar &sep, const QString &inString); - -private: - - - - - - - QString m_matrix[13][2]; - - std::shared_ptr m_dtc; - - int m_codificationDataId; - bool m_isEditMode; + int m_codificationDataId; + bool m_isEditMode; }; -} - - +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.cpp old mode 100755 new mode 100644 index 977e6f3c8..1129728d1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.cpp @@ -1,378 +1,314 @@ - - #include "cod_numeral_code_model.h" -#include -#include -#include +#include +#include #include +#include NumeralCodeModel::NumeralCodeModel(QWidget *parent) : QAbstractTableModel(parent) , m_isEditMode(false) .getNGLLogger("COD_Test_NumeralCodeTableModel")) { - init(); - -} - - -NumeralCodeModel::~NumeralCodeModel() -{ - -} + init(); +} +NumeralCodeModel::~NumeralCodeModel() {} bool NumeralCodeModel::init() { - m_MatrixNumeralSet << '0' << '1' << '2' << '3' << '4' - << '5' << '6' << '7' << '8' << '9'; + m_MatrixNumeralSet << '0' << '1' << '2' << '3' << '4' << '5' << '6' << '7' << '8' << '9'; + m_MatrixCharacterSet1 << 'A' << 'B' << 'C' << 'D' << 'E' << 'F' << 'G' << 'H' << 'I' << 'J' << 'K' << 'L' << 'M' + << 'N' << 'O' << 'P' << 'Q' << 'R' << 'S' << 'T' << 'U' << 'V' << 'W' << 'X' << 'Y' << 'Z'; - m_MatrixCharacterSet1 << 'A' << 'B' << 'C' << 'D' << 'E' << 'F' - << 'G' << 'H' << 'I' << 'J' << 'K' << 'L' - << 'M' << 'N' << 'O' << 'P' << 'Q' << 'R' - << 'S' << 'T' << 'U' << 'V' << 'W' << 'X' - << 'Y' << 'Z'; + m_MatrixCharacterSet2 << 'D' << 'E' << 'G' << 'H' << 'I' << 'L' << 'N' << 'O' << 'R' << 'S' << 'T' << 'U'; - m_MatrixCharacterSet2 << 'D' << 'E' << 'G' << 'H' << 'I' << 'L' - << 'N' << 'O' << 'R' << 'S' << 'T' << 'U'; + m_ColumnSelectionValues << 'A' << 'B' << 'C' << 'D' << 'E' << 'F' << 'G' << 'H' << 'I' << 'J' << 'K' << 'L' << 'M'; + m_RowSelectionValues << 'a' << 'b' << 'c' << 'd' << 'e' << 'f' << 'g' << 'h' << 'i' << 'j' << 'k' << 'l' << 'm'; + return initMatrix(); +} - - m_ColumnSelectionValues << 'A' << 'B' << 'C' - << 'D' << 'E' << 'F' - << 'G' << 'H' << 'I' - << 'J' << 'K' << 'L' - << 'M' ; - - - m_RowSelectionValues << 'a' << 'b' << 'c' - << 'd' << 'e' << 'f' - << 'g' << 'h' << 'i' - << 'j' << 'k' << 'l' - << 'm' ; - - - return initMatrix(); -} - - -bool NumeralCodeModel::setColumnSelectionValues(const QVector &data) +bool NumeralCodeModel::setColumnSelectionValues(const QVector& data) { - m_ColumnSelectionValues = data; - emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); - return true; -} + m_ColumnSelectionValues = data; + emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); + return true; +} - -bool NumeralCodeModel::setColumnSelectionValuesCSV(const QVector &csvData) +bool NumeralCodeModel::setColumnSelectionValuesCSV(const QVector& csvData) { - QStringList qsList; - for (int i = 0; i < csvData.size(); ++i) - { - if (QLatin1Char(csvData.at(i)) != QLatin1Char(';')) - qsList.append(QString(QLatin1Char(csvData.at(i)))); - } + QStringList qsList; + for (int i = 0; i < csvData.size(); ++i) + { + if (QLatin1Char(csvData.at(i)) != QLatin1Char(';')) + qsList.append(QString(QLatin1Char(csvData.at(i)))); + } + QVector data; + for (int i = 0; i < qsList.size(); ++i) + { + const QString& qs = qsList.at(i); + if (qs.isEmpty()) + continue; + char c = qs.at(0).toLatin1(); + data.append(c); + } + return setColumnSelectionValues(data); + ; +} - - - - QVector data; - for (int i = 0; i < qsList.size(); ++i) - { - const QString &qs = qsList.at(i); - if (qs.isEmpty()) - continue; - - char c = qs.at(0).toLatin1(); - data.append(c); - } - return setColumnSelectionValues(data);; -} - - -bool NumeralCodeModel::setRowSelectionValues(const QVector &data) +bool NumeralCodeModel::setRowSelectionValues(const QVector& data) { - m_RowSelectionValues = data; - emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); - return true; -} + m_RowSelectionValues = data; + emit dataChanged(createIndex(0, 0), createIndex(0, columnCount() - 1)); + return true; +} - -bool NumeralCodeModel::setRowSelectionValuesCSV(const QVector &csvData) +bool NumeralCodeModel::setRowSelectionValuesCSV(const QVector& csvData) { - QStringList qsList; - for (int i = 0; i < csvData.size(); ++i) - { - if (QLatin1Char(csvData.at(i)) != QLatin1Char(';')) - qsList.append(QString(QLatin1Char(csvData.at(i)))); - } + QStringList qsList; + for (int i = 0; i < csvData.size(); ++i) + { + if (QLatin1Char(csvData.at(i)) != QLatin1Char(';')) + qsList.append(QString(QLatin1Char(csvData.at(i)))); + } - QVector data; - for (int i = 0; i < qsList.size(); ++i) - { - const QString &qs = qsList.at(i); - if (qs.isEmpty()) - continue; - - char c = qs.at(0).toLatin1(); - data.append(c); - } - return setRowSelectionValues(data); -} + QVector data; + for (int i = 0; i < qsList.size(); ++i) + { + const QString& qs = qsList.at(i); + if (qs.isEmpty()) + continue; + char c = qs.at(0).toLatin1(); + data.append(c); + } + return setRowSelectionValues(data); +} QVector NumeralCodeModel::getHorizontalHeaderCSV() const { - QVector qVec; - qVec.reserve(m_ColumnSelectionValues.size() * 2); - for (int i = 0; i < m_ColumnSelectionValues.size(); ++i) - { - qVec.append(m_ColumnSelectionValues.at(i)); - qVec.append(';'); - } - - qVec.remove(m_ColumnSelectionValues.size() * 2 - 1); + QVector qVec; + qVec.reserve(m_ColumnSelectionValues.size() * 2); + for (int i = 0; i < m_ColumnSelectionValues.size(); ++i) + { + qVec.append(m_ColumnSelectionValues.at(i)); + qVec.append(';'); + } - return qVec; -} + qVec.remove(m_ColumnSelectionValues.size() * 2 - 1); + return qVec; +} -QVector NumeralCodeModel::getVerticalHeaderCSV() const +QVector NumeralCodeModel::getVerticalHeaderCSV() const { - QVector qVec; - qVec.reserve(m_RowSelectionValues.size() * 2); - for (int i = 0; i < m_RowSelectionValues.size(); ++i) - { - qVec.append(m_RowSelectionValues.at(i)); - qVec.append(';'); - } - - qVec.remove(m_RowSelectionValues.size() * 2 - 1); + QVector qVec; + qVec.reserve(m_RowSelectionValues.size() * 2); + for (int i = 0; i < m_RowSelectionValues.size(); ++i) + { + qVec.append(m_RowSelectionValues.at(i)); + qVec.append(';'); + } - return qVec; -} + qVec.remove(m_RowSelectionValues.size() * 2 - 1); + return qVec; +} void NumeralCodeModel::setEditMode(bool isEditMode) { - m_isEditMode = isEditMode; - - emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); - -} + m_isEditMode = isEditMode; + emit dataChanged(createIndex(0, 0), createIndex(rowCount() - 1, columnCount() - 1)); +} bool NumeralCodeModel::isEditMode() const { - return m_isEditMode; -} + return m_isEditMode; +} - -int NumeralCodeModel::rowCount(const QModelIndex &parent) const +int NumeralCodeModel::rowCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 14; -} + Q_UNUSED(parent) + return 14; +} - -int NumeralCodeModel::columnCount(const QModelIndex &parent) const +int NumeralCodeModel::columnCount(const QModelIndex& parent) const { - Q_UNUSED(parent) - return 14; -} - + Q_UNUSED(parent) + return 14; +} QVariant NumeralCodeModel::headerData(int column, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole) - return QAbstractTableModel::headerData(column, orientation, role); + if (role != Qt::DisplayRole) + return QAbstractTableModel::headerData(column, orientation, role); - if (isEditMode()) - { - - return QVariant(); - } - else - { - if (column == 0) - return QVariant(); - if (orientation == Qt::Horizontal) - return QChar::fromLatin1(m_ColumnSelectionValues.at(column - 1)); - if (orientation == Qt::Vertical) - return QChar::fromLatin1(m_RowSelectionValues.at(column - 1)); - } - - return QAbstractTableModel::headerData(column, orientation, role); -} - - -QVariant NumeralCodeModel::data(const QModelIndex &index, int role) const -{ - if ((role == Qt::DisplayRole || role == Qt::EditRole)) - { - - if ((index.column() == 0) && (index.row() == 0)) - return QVariant(); - - - if (index.row() == 0) - return QChar::fromLatin1(m_ColumnSelectionValues[index.column() - 1]); - - - if ((index.column() == 0)) - return QChar::fromLatin1(m_RowSelectionValues[index.row() - 1]); - - - if ((index.column() > 0) && (index.row() > 0)) + if (isEditMode()) { - return QChar::fromLatin1(m_matrix[index.row() - 1][index.column() - 1]); - } - - - - - } - - if (role == Qt::TextAlignmentRole) - return Qt::AlignCenter; - - if (role == Qt::BackgroundRole) - { - if ((index.row() > 0) && (index.column() > 0)) - { - if (m_isEditMode) - return QColor(Qt::darkRed); - else - return QColor(Qt::darkGray); + return QVariant(); } else - return QColor(Qt::darkYellow); - } + { + if (column == 0) + return QVariant(); + if (orientation == Qt::Horizontal) + return QChar::fromLatin1(m_ColumnSelectionValues.at(column - 1)); + if (orientation == Qt::Vertical) + return QChar::fromLatin1(m_RowSelectionValues.at(column - 1)); + } - if (role == Qt::ForegroundRole) - { - if ((index.row() == 0) && (index.column() == 0)) - return QColor(Qt::red); - } + return QAbstractTableModel::headerData(column, orientation, role); +} - return QVariant(); - -} - - -bool NumeralCodeModel::setData(const QModelIndex &index, const QVariant &value, int role) +QVariant NumeralCodeModel::data(const QModelIndex& index, int role) const { - DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() - << " char:" << value.toString(); + if ((role == Qt::DisplayRole || role == Qt::EditRole)) + { - QString tmp = value.toString(); - if (tmp.isEmpty()) - return false; + if ((index.column() == 0) && (index.row() == 0)) + return QVariant(); - const char c = tmp.at(0).toLatin1(); + if (index.row() == 0) + return QChar::fromLatin1(m_ColumnSelectionValues[index.column() - 1]); - if (role == Qt::EditRole) - { - - if (index.row() == 0) - m_ColumnSelectionValues[index.column() - 1] = c; - - if (index.column() == 0 && (index.row() > 0)) - m_RowSelectionValues[index.row() - 1] = c; - } + if ((index.column() == 0)) + return QChar::fromLatin1(m_RowSelectionValues[index.row() - 1]); - return true; -} + if ((index.column() > 0) && (index.row() > 0)) + { + return QChar::fromLatin1(m_matrix[index.row() - 1][index.column() - 1]); + } + } + if (role == Qt::TextAlignmentRole) + return Qt::AlignCenter; -Qt::ItemFlags NumeralCodeModel::flags(const QModelIndex &index) const + if (role == Qt::BackgroundRole) + { + if ((index.row() > 0) && (index.column() > 0)) + { + if (m_isEditMode) + return QColor(Qt::darkRed); + else + return QColor(Qt::darkGray); + } + else + return QColor(Qt::darkYellow); + } + + if (role == Qt::ForegroundRole) + { + if ((index.row() == 0) && (index.column() == 0)) + return QColor(Qt::red); + } + + return QVariant(); +} + +bool NumeralCodeModel::setData(const QModelIndex& index, const QVariant& value, int role) { - Qt::ItemFlags flags = QAbstractTableModel::flags(index); - if (((index.row() == 0) && (index.column() > 0)) || - ((index.row() > 0) && (index.column() == 0))) - flags |= Qt::ItemIsEditable; + DEBUG_LOG(m_logger) << "setData() row/col: " << index.row() << "/" << index.column() + << " char:" << value.toString(); - return flags; -} + QString tmp = value.toString(); + if (tmp.isEmpty()) + return false; + const char c = tmp.at(0).toLatin1(); + + if (role == Qt::EditRole) + { + + if (index.row() == 0) + m_ColumnSelectionValues[index.column() - 1] = c; + + if (index.column() == 0 && (index.row() > 0)) + m_RowSelectionValues[index.row() - 1] = c; + } + + return true; +} + +Qt::ItemFlags NumeralCodeModel::flags(const QModelIndex& index) const +{ + Qt::ItemFlags flags = QAbstractTableModel::flags(index); + if (((index.row() == 0) && (index.column() > 0)) || ((index.row() > 0) && (index.column() == 0))) + flags |= Qt::ItemIsEditable; + + return flags; +} bool NumeralCodeModel::initMatrix() { - int lastMatrixValueCnt = 0; - int lastMatrixCharacterCnt = 0; - int lastMatrixCharacterIndex = 0; - int numOfCharacter = 4; + int lastMatrixValueCnt = 0; + int lastMatrixCharacterCnt = 0; + int lastMatrixCharacterIndex = 0; + int numOfCharacter = 4; - for (int row = 0; row < 13; ++row) - { - - if (row > 3) + for (int row = 0; row < 13; ++row) { - numOfCharacter = 3; - lastMatrixValueCnt -= 1; + + if (row > 3) + { + numOfCharacter = 3; + lastMatrixValueCnt -= 1; + } + + if (row == 9) + lastMatrixCharacterIndex = 0; + + for (int col = 0; col < 13; ++col) + { + if (lastMatrixValueCnt < 10) + { + m_matrix[row][col] = m_MatrixNumeralSet.at(lastMatrixValueCnt); + lastMatrixValueCnt += 1; + + if (lastMatrixValueCnt == 10) + lastMatrixCharacterCnt = 0; + } + else + { + if (row < 9) + m_matrix[row][col] = m_MatrixCharacterSet1.at(lastMatrixCharacterIndex); + else + m_matrix[row][col] = m_MatrixCharacterSet2.at(lastMatrixCharacterIndex); + lastMatrixCharacterCnt += 1; + lastMatrixCharacterIndex += 1; + + if (lastMatrixCharacterCnt == numOfCharacter) + lastMatrixValueCnt = 0; + } + + if ((row < 9) && (lastMatrixCharacterIndex == 26)) + lastMatrixCharacterIndex = 0; + + if ((row >= 9) && (lastMatrixCharacterIndex == 12)) + lastMatrixCharacterIndex = 0; + } } - - if (row == 9) - lastMatrixCharacterIndex = 0; - - for (int col = 0; col < 13; ++col) + QString qs; + for (int row = 0; row < 13; ++row) { - if (lastMatrixValueCnt < 10) - { - m_matrix[row][col] = m_MatrixNumeralSet.at(lastMatrixValueCnt); - lastMatrixValueCnt += 1; - - if (lastMatrixValueCnt == 10) - lastMatrixCharacterCnt = 0; - } - else - { - if (row < 9) - m_matrix[row][col] = m_MatrixCharacterSet1.at(lastMatrixCharacterIndex); - else - m_matrix[row][col] = m_MatrixCharacterSet2.at(lastMatrixCharacterIndex); - lastMatrixCharacterCnt += 1; - lastMatrixCharacterIndex += 1; - - if (lastMatrixCharacterCnt == numOfCharacter) - lastMatrixValueCnt = 0; - } - - - if ((row < 9) && (lastMatrixCharacterIndex == 26)) - lastMatrixCharacterIndex = 0; - - - if ((row >= 9) && (lastMatrixCharacterIndex == 12)) - lastMatrixCharacterIndex = 0; + for (int col = 0; col < 13; ++col) + { + qs.append(QLatin1Char(m_matrix[row][col])); + qs.append(QLatin1String("; ")); + } + qs.append(QLatin1String("\n")); } - } - - - QString qs; - for (int row = 0; row < 13; ++row) - { - for (int col = 0; col < 13; ++col) - { - qs.append(QLatin1Char(m_matrix[row][col])); - qs.append(QLatin1String("; ")); - } - qs.append(QLatin1String("\n")); - } - QString qs1(QLatin1String("\n")); - qs1.append(qs); - - - return true; -} - + QString qs1(QLatin1String("\n")); + qs1.append(qs); + return true; +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.h old mode 100755 new mode 100644 index 9e178443e..f64cd45e5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/cod_numeral_code_model.h @@ -1,7 +1,5 @@ - - #pragma once #include @@ -13,79 +11,51 @@ class INGLLogger; class NumeralCodeModel final : public QAbstractTableModel { - Q_OBJECT -public: - explicit NumeralCodeModel(QWidget *parent); + Q_OBJECT + public: + explicit NumeralCodeModel(QWidget* parent); - ~NumeralCodeModel(); + ~NumeralCodeModel(); - + bool init(); - bool init(); + bool setColumnSelectionValues(const QVector& data); + bool setColumnSelectionValuesCSV(const QVector& csvData); - + bool setRowSelectionValues(const QVector& data); + bool setRowSelectionValuesCSV(const QVector& csvData); - bool setColumnSelectionValues(const QVector &data); - bool setColumnSelectionValuesCSV(const QVector &csvData); + QVector getHorizontalHeaderCSV() const; - + QVector getVerticalHeaderCSV() const; - bool setRowSelectionValues(const QVector &data); - bool setRowSelectionValuesCSV(const QVector &csvData); + void setEditMode(bool isEditMode); + bool isEditMode() const; - + int rowCount(const QModelIndex& parent = QModelIndex()) const override; - QVector getHorizontalHeaderCSV() const; - + int columnCount(const QModelIndex& parent = QModelIndex()) const override; - QVector getVerticalHeaderCSV() const; + QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role) const override; - + bool setData(const QModelIndex& index, const QVariant& value, int role) override; - void setEditMode(bool isEditMode); - bool isEditMode() const; + Qt::ItemFlags flags(const QModelIndex& index) const override; - + private: + NGL::INGLLogger& m_logger; + bool initMatrix(); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVector m_MatrixNumeralSet; + QVector m_MatrixCharacterSet1; + QVector m_MatrixCharacterSet2; - + char m_matrix[13][13]; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QVector m_RowSelectionValues; + QVector m_ColumnSelectionValues; - - - QVariant headerData(int column, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - - - - QVariant data(const QModelIndex &index, int role) const override; - - - - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - - - Qt::ItemFlags flags(const QModelIndex &index) const override; - -private: - - - - -NGL::INGLLogger &m_logger; - bool initMatrix(); - - QVector m_MatrixNumeralSet; - QVector m_MatrixCharacterSet1; - QVector m_MatrixCharacterSet2; - - char m_matrix[13][13]; - - QVector m_RowSelectionValues; - QVector m_ColumnSelectionValues; - - bool m_isEditMode; + bool m_isEditMode; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.cpp old mode 100755 new mode 100644 index 018711807..d1553beb1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.cpp @@ -1,210 +1,167 @@ - #include "maindialog.h" -#include "ui_maindialog.h" #include "cod_numeral_code_model.h" +#include "ui_maindialog.h" -#include #include - +#include MainDialog::MainDialog(QWidget *parent) : QDialog(parent) , m_ui(new Ui::MainDialog) , m_numCodeModel(new NumeralCodeModel(parent)) .getNGLLogger("COD_Test_NumeralCodeTableMainDialog")), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_ui->setupUi(this); -} - + m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + m_ui->setupUi(this); +} MainDialog::~MainDialog() { - delete m_ui; -} - + delete m_ui; +} bool MainDialog::init() { - bool bOk = initNumeralModel(); + bool bOk = initNumeralModel(); - connect(m_ui->cbEditMode, &QCheckBox::toggled, - this, &MainDialog::onCbEditModeToggled); + connect(m_ui->cbEditMode, &QCheckBox::toggled, this, &MainDialog::onCbEditModeToggled); + connect(m_ui->pbSetHorizontalHeader, &QPushButton::clicked, this, &MainDialog::onPbSetHorizontalHeaderCSV); + connect(m_ui->pbSetVerticalHeader, &QPushButton::clicked, this, &MainDialog::onPbSetVerticalHeaderCSV); - - - connect(m_ui->pbSetHorizontalHeader, &QPushButton::clicked, - this, &MainDialog::onPbSetHorizontalHeaderCSV); - - - - - connect(m_ui->pbSetVerticalHeader, &QPushButton::clicked, - this, &MainDialog::onPbSetVerticalHeaderCSV); - - - m_ui->cbEditMode->setChecked(false); - onCbEditModeToggled(false); - m_ui->pbSetHorizontalHeader->setEnabled(false); - m_ui->pbSetVerticalHeader->setEnabled(false); - - return bOk; -} - - -bool MainDialog::initNumeralModel() -{ - m_ui->tvNumeralCode->setModel(m_numCodeModel); - - QHeaderView *header = m_ui->tvNumeralCode->horizontalHeader(); - - header->setVisible(true); - - QHeaderView *vheader = m_ui->tvNumeralCode->verticalHeader(); - vheader->setVisible(true); - - m_ui->tvNumeralCode->setShowGrid(true); - - m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); - - return true; -} - - -void MainDialog::onCbEditModeToggled(bool isChecked) -{ - m_numCodeModel->setEditMode(isChecked); - - QHeaderView *header = m_ui->tvNumeralCode->horizontalHeader(); - QHeaderView *vheader = m_ui->tvNumeralCode->verticalHeader(); - - if (isChecked) - { - header->setVisible(false); - vheader->setVisible(false); - m_ui->tvNumeralCode->setColumnHidden(0, false); - m_ui->tvNumeralCode->setRowHidden(0, false); - - m_ui->pbSetHorizontalHeader->setEnabled(true); - m_ui->pbSetVerticalHeader->setEnabled(true); - } - else - { - header->setVisible(true); - vheader->setVisible(true); - m_ui->tvNumeralCode->setColumnHidden(0, true); - m_ui->tvNumeralCode->setRowHidden(0, true); - + m_ui->cbEditMode->setChecked(false); + onCbEditModeToggled(false); m_ui->pbSetHorizontalHeader->setEnabled(false); m_ui->pbSetVerticalHeader->setEnabled(false); - getNumeralCodeHeader(); - } -} + return bOk; +} +bool MainDialog::initNumeralModel() +{ + m_ui->tvNumeralCode->setModel(m_numCodeModel); + + QHeaderView* header = m_ui->tvNumeralCode->horizontalHeader(); + + header->setVisible(true); + + QHeaderView* vheader = m_ui->tvNumeralCode->verticalHeader(); + vheader->setVisible(true); + + m_ui->tvNumeralCode->setShowGrid(true); + + m_ui->tvNumeralCode->setSelectionMode(QAbstractItemView::SingleSelection); + + return true; +} + +void MainDialog::onCbEditModeToggled(bool isChecked) +{ + m_numCodeModel->setEditMode(isChecked); + + QHeaderView* header = m_ui->tvNumeralCode->horizontalHeader(); + QHeaderView* vheader = m_ui->tvNumeralCode->verticalHeader(); + + if (isChecked) + { + header->setVisible(false); + vheader->setVisible(false); + m_ui->tvNumeralCode->setColumnHidden(0, false); + m_ui->tvNumeralCode->setRowHidden(0, false); + + m_ui->pbSetHorizontalHeader->setEnabled(true); + m_ui->pbSetVerticalHeader->setEnabled(true); + } + else + { + header->setVisible(true); + vheader->setVisible(true); + m_ui->tvNumeralCode->setColumnHidden(0, true); + m_ui->tvNumeralCode->setRowHidden(0, true); + + m_ui->pbSetHorizontalHeader->setEnabled(false); + m_ui->pbSetVerticalHeader->setEnabled(false); + + getNumeralCodeHeader(); + } +} void MainDialog::onPbSetHorizontalHeader() { - QVector columnSelectionValues; - columnSelectionValues << 'h' << 'o' << 'r' - << 'i' << 'z' << 'o' - << 'n' << 't' << 'a' - << 'l' << 'i' << 'd' - << 'x'; - - m_numCodeModel->setColumnSelectionValues(columnSelectionValues); -} + QVector columnSelectionValues; + columnSelectionValues << 'h' << 'o' << 'r' << 'i' << 'z' << 'o' << 'n' << 't' << 'a' << 'l' << 'i' << 'd' << 'x'; + m_numCodeModel->setColumnSelectionValues(columnSelectionValues); +} void MainDialog::onPbSetHorizontalHeaderCSV() { - QVector columnSelectionValues; - columnSelectionValues << 'h' << 'o' << 'r' - << 'i' << 'z' << 'o' - << 'n' << 't' << 'a' - << 'l' << 'c' << 's' - << 'v'; + QVector columnSelectionValues; + columnSelectionValues << 'h' << 'o' << 'r' << 'i' << 'z' << 'o' << 'n' << 't' << 'a' << 'l' << 'c' << 's' << 'v'; - QVector csvVec; - csvVec.reserve(columnSelectionValues.size() * 2); - for (int i = 0; i < columnSelectionValues.size(); ++i) - { - csvVec.append(columnSelectionValues.at(i)); - csvVec.append(';'); - } - - csvVec.remove(columnSelectionValues.size() * 2 - 1); + QVector csvVec; + csvVec.reserve(columnSelectionValues.size() * 2); + for (int i = 0; i < columnSelectionValues.size(); ++i) + { + csvVec.append(columnSelectionValues.at(i)); + csvVec.append(';'); + } - DEBUG_LOG(m_logger) << "onPbSetHorizontalHeaderCSV() " - << " csvVec.size(): " << csvVec.size(); + csvVec.remove(columnSelectionValues.size() * 2 - 1); - m_numCodeModel->setColumnSelectionValuesCSV(csvVec); -} + DEBUG_LOG(m_logger) << "onPbSetHorizontalHeaderCSV() " + << " csvVec.size(): " << csvVec.size(); + m_numCodeModel->setColumnSelectionValuesCSV(csvVec); +} void MainDialog::onPbSetVerticalHeader() { - QVector rowSelectionValues; - rowSelectionValues << 'v' << 'e' << 'r' - << 't' << 'i' << 'c' - << 'a' << 'l' << 'i' - << 'n' << 'd' << 'e' - << 'x' ; - - m_numCodeModel->setRowSelectionValues(rowSelectionValues); -} + QVector rowSelectionValues; + rowSelectionValues << 'v' << 'e' << 'r' << 't' << 'i' << 'c' << 'a' << 'l' << 'i' << 'n' << 'd' << 'e' << 'x'; + m_numCodeModel->setRowSelectionValues(rowSelectionValues); +} void MainDialog::onPbSetVerticalHeaderCSV() { - QVector rowSelectionValues; - rowSelectionValues << 'v' << 'e' << 'r' - << 't' << 'i' << 'c' - << 'a' << 'l' << 'i' - << 'n' << 'c' << 's' - << 'v'; + QVector rowSelectionValues; + rowSelectionValues << 'v' << 'e' << 'r' << 't' << 'i' << 'c' << 'a' << 'l' << 'i' << 'n' << 'c' << 's' << 'v'; - QVector csvVec; - csvVec.reserve(rowSelectionValues.size() * 2); - for (int i = 0; i < rowSelectionValues.size(); ++i) - { - csvVec.append(rowSelectionValues.at(i)); - csvVec.append(';'); - } - - csvVec.remove(rowSelectionValues.size() * 2 - 1); + QVector csvVec; + csvVec.reserve(rowSelectionValues.size() * 2); + for (int i = 0; i < rowSelectionValues.size(); ++i) + { + csvVec.append(rowSelectionValues.at(i)); + csvVec.append(';'); + } - DEBUG_LOG(m_logger) << "onPbSetVerticalHeaderCSV() " - << " csvVec.size(): " << csvVec.size(); + csvVec.remove(rowSelectionValues.size() * 2 - 1); - m_numCodeModel->setRowSelectionValuesCSV(csvVec); -} + DEBUG_LOG(m_logger) << "onPbSetVerticalHeaderCSV() " + << " csvVec.size(): " << csvVec.size(); + m_numCodeModel->setRowSelectionValuesCSV(csvVec); +} void MainDialog::getNumeralCodeHeader() { - QVector qVecHH = m_numCodeModel->getHorizontalHeaderCSV(); - QByteArray qbaHH; + QVector qVecHH = m_numCodeModel->getHorizontalHeaderCSV(); + QByteArray qbaHH; - for (int i = 0; i < qVecHH.size(); ++i) - qbaHH.append(qVecHH.at(i)); + for (int i = 0; i < qVecHH.size(); ++i) + qbaHH.append(qVecHH.at(i)); - QVector qVecVH = m_numCodeModel->getVerticalHeaderCSV(); - QByteArray qbaVH; - - for (int i = 0; i < qVecVH.size(); ++i) - qbaVH.append(qVecVH.at(i)); - - DEBUG_LOG(m_logger) << "getNumeralCodeHeader()" - << " HH: " << qbaHH << " size: " << qbaHH.size() - << " VH: " << qbaVH << " size: " << qbaVH.size(); - - - - -} + QVector qVecVH = m_numCodeModel->getVerticalHeaderCSV(); + QByteArray qbaVH; + for (int i = 0; i < qVecVH.size(); ++i) + qbaVH.append(qVecVH.at(i)); + DEBUG_LOG(m_logger) << "getNumeralCodeHeader()" + << " HH: " << qbaHH << " size: " << qbaHH.size() << " VH: " << qbaVH + << " size: " << qbaVH.size(); +} diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.h old mode 100755 new mode 100644 index 374b2703b..dd65a2fbd --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/CodificationManagement/Test/maindialog.h @@ -1,12 +1,9 @@ - - #pragma once #include - namespace Ui { class MainDialog; @@ -21,27 +18,27 @@ class NumeralCodeModel; class MainDialog : public QDialog { - Q_OBJECT + Q_OBJECT -public: - explicit MainDialog(QWidget *parent = nullptr); - ~MainDialog(); + public: + explicit MainDialog(QWidget* parent = nullptr); + ~MainDialog(); - bool init(); - bool initNumeralModel(); + bool init(); + bool initNumeralModel(); -private Q_SLOTS: - void onCbEditModeToggled(bool isChecked); + private Q_SLOTS: + void onCbEditModeToggled(bool isChecked); - void onPbSetHorizontalHeader(); - void onPbSetHorizontalHeaderCSV(); - void onPbSetVerticalHeader(); - void onPbSetVerticalHeaderCSV(); + void onPbSetHorizontalHeader(); + void onPbSetHorizontalHeaderCSV(); + void onPbSetVerticalHeader(); + void onPbSetVerticalHeaderCSV(); - void getNumeralCodeHeader(); + void getNumeralCodeHeader(); -private: - NGL::INGLLogger &m_logger; - Ui::MainDialog *m_ui; - NumeralCodeModel *m_numCodeModel; + private: + NGL::INGLLogger& m_logger; + Ui::MainDialog* m_ui; + NumeralCodeModel* m_numCodeModel; }; diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.cpp old mode 100755 new mode 100644 index f8f00accc..39ab52171 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.cpp @@ -1,250 +1,202 @@ - #include "efm_sound_area_edit_dialog.h" -#include -#include "ui_efm_sound_area_edit_dialog.h" + +#include "../logger.h" #include "efm_sound_area.h" -#include "efm_sound_area_helper.h" #include "efm_sound_area_edit_model_playlist.h" #include "efm_sound_area_edit_model_tree.h" +#include "efm_sound_area_helper.h" #include "efm_switch_item_delegate.h" -#include "../logger.h" +#include "ui_efm_sound_area_edit_dialog.h" #include +#include #include #include -#include -#include #include - -#include +#include #include - +#include +#include using namespace SoundManagement; namespace EffectManagement { - - - - -SoundAreaEditDialog::SoundAreaEditDialog(const SoundArea &soundArea, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_soundArea(new SoundArea(soundArea)) - , m_ui(new Ui::SoundAreaEditDialog) +SoundAreaEditDialog::SoundAreaEditDialog(const SoundArea& soundArea, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_soundArea(new SoundArea(soundArea)), + m_ui(new Ui::SoundAreaEditDialog) { - m_ui->setupUi(this); - m_buttonBox->getButton(LtsWidgets::DialogButton::Hide)->setIcon(QIcon(QStringLiteral("icon:avm_stop.svg"))); - setOnlineHelpFilename(QStringLiteral("Sound-Area_Edit_Dialog")); + m_ui->setupUi(this); + m_buttonBox->getButton(LtsWidgets::DialogButton::Hide)->setIcon(QIcon(QStringLiteral("icon:avm_stop.svg"))); + setOnlineHelpFilename(QStringLiteral("Sound-Area_Edit_Dialog")); } SoundAreaEditDialog::~SoundAreaEditDialog() { - delete m_ui; + delete m_ui; } void SoundAreaEditDialog::retranslate() { - translate(m_ui, tr("Manage Sound Area #%1").arg(m_soundArea->id)); - m_buttonBox->getButton(LtsWidgets::DialogButton::Hide)->setText(tr("Stop All Sounds")); + translate(m_ui, tr("Manage Sound Area #%1").arg(m_soundArea->id)); + m_buttonBox->getButton(LtsWidgets::DialogButton::Hide)->setText(tr("Stop All Sounds")); } - - - - void SoundAreaEditDialog::onPlaySound(SoundManagement::SoundCategory category, int soundId, bool inLoop, int volume) { - qWarning() << "onPlaySound" << volume; + qWarning() << "onPlaySound" << volume; - SoundManagement::PlayControl control = inLoop ? SoundManagement::PlayControl_def::PlayLoop : SoundManagement::PlayControl_def::PlaySingle; + SoundManagement::PlayControl control = + inLoop ? SoundManagement::PlayControl_def::PlayLoop : SoundManagement::PlayControl_def::PlaySingle; - for (const auto &egcuId : std::as_const(m_soundArea->egcuIds)) - { - if (!m_egcuCheckBoxes.value(egcuId)->isChecked()) - continue; - - SoundManagement::ControlSoundRequest req( - egcuId, - soundId, - category, - volume, - control - ); - - auto *reqHandler = new ControlSoundRequester; - - if (!m_somFtc->controlSoundRequest(req, reqHandler)) - return; - - connect(reqHandler, &ControlSoundRequester::finished, - this, [this, reqHandler](const QString &msg) + for (const auto& egcuId : std::as_const(m_soundArea->egcuIds)) { - if (!msg.isEmpty()) - { - LtsWidgets::LtsMessageDialogNew(this, msg); - return; - } + if (!m_egcuCheckBoxes.value(egcuId)->isChecked()) + continue; - reqHandler->deleteLater(); - }); - } + SoundManagement::ControlSoundRequest req(egcuId, soundId, category, volume, control); + + auto* reqHandler = new ControlSoundRequester; + + if (!m_somFtc->controlSoundRequest(req, reqHandler)) + return; + + connect(reqHandler, &ControlSoundRequester::finished, this, [this, reqHandler](const QString& msg) { + if (!msg.isEmpty()) + { + LtsWidgets::LtsMessageDialogNew(this, msg); + return; + } + + reqHandler->deleteLater(); + }); + } } void SoundAreaEditDialog::onStopAllSounds() { - DEBUG_LOG(m_logger) << "onStopAllSounds"; + DEBUG_LOG(m_logger) << "onStopAllSounds"; - QList egcuIds; + QList egcuIds; - - for (const auto &egcu : std::as_const(m_soundArea->egcuIds)) - { - if (!m_egcuCheckBoxes.value(egcu)->isChecked()) - continue; - DEBUG_LOG(m_logger) << "onStopAllSounds add egcu=" << egcu; - egcuIds.append(egcu); - } - - for (const auto &egcu : std::as_const(egcuIds)) - { - DEBUG_LOG(m_logger) << "onStopAllSounds egcu=" << egcu; - SoundManagement::StopAllSoundsRequest req(egcu); - -m_somFtc->stopAllSoundsRequest(req, nullptr); - - } -} - - - - - -bool SoundAreaEditDialog::init(LtsSession::LtsSessionDataDds *session) -{ - DEBUG_LOG(m_logger) << "init"; - - m_session = session; - - - std::shared_ptr ismDtc; - if (!m_session->getDtc(ismDtc)) - { - ERROR_LOG(m_logger) << "connection to ISM-DTC failed"; - return false; - } - - if (!m_session->getDtc(m_somDtc)) - { - ERROR_LOG(m_logger) << "connection to SOM-DTC failed"; - return false; - } - - if (!m_session->getFtc(m_somFtc)) - { - ERROR_LOG(m_logger) << "connection to SOM-FTC failed"; - return false; - } - - m_helper = std::make_shared(new SoundAreaHelper(ismDtc, m_somDtc)); - - - QGridLayout *layout = new QGridLayout(); - int i = 0; - for (const auto &egcu : std::as_const(m_soundArea->egcuIds)) - { - QCheckBox *chBox = new QCheckBox(m_helper->egcuName(egcu)); - chBox->setChecked(true); - m_egcuCheckBoxes.insert(egcu, chBox); - layout->addWidget(m_egcuCheckBoxes.value(egcu), int(i / 2), i % 2); - ++i; - } - m_ui->wEgcu->setLayout(layout); - - - delete m_treeModel; - m_treeModel = new SoundAreaTreeModel(m_soundArea->egcuIds, m_helper, this); - m_treeModel->init(m_somDtc); - m_ui->tvSounds->setModel(m_treeModel); - m_ui->tvSounds->expandAll(); - m_ui->tvSounds->header()->resizeSection(SoundAreaTreeModel::Column::Loop, 50); - m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Category, QHeaderView::Interactive); - m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Sound, QHeaderView::Stretch); - m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Loop, QHeaderView::Fixed); - - delete m_playlistModel; - m_playlistModel = new SoundAreaPlaylistModel(m_soundArea->egcuIds, m_helper, this); - m_playlistModel->init(m_somDtc); - m_ui->tvPlaylist->setModel(m_playlistModel); - m_ui->tvPlaylist->horizontalHeader()->resizeSection(SoundAreaPlaylistModel::Column::Duration, 100); - m_ui->tvPlaylist->horizontalHeader()->resizeSection(SoundAreaPlaylistModel::Column::Option, 50); - - m_ui->tvPlaylist->horizontalHeader()->setSectionResizeMode(SoundAreaPlaylistModel::Column::Sound, QHeaderView::Stretch); - - - m_ui->tvPlaylist->horizontalHeader()->setSectionResizeMode(SoundAreaPlaylistModel::Column::Option, QHeaderView::Fixed); - - m_ui->tvSounds->setItemDelegateForColumn(SoundAreaTreeModel::Column::Loop, new SwitchItemDelegate(m_treeModel)); - m_ui->tvSounds->setItemDelegateForColumn(SoundAreaTreeModel::Column::Volume, new SpinBoxDelegate(m_treeModel)); - - m_ui->tvPlaylist->setItemDelegate(new SoundAreaEditPlaylistDelegate(m_playlistModel)); - - - connect(m_treeModel, &SoundAreaTreeModel::playSound, this, &SoundAreaEditDialog::onPlaySound); - connect(m_ui->tvSounds, &QTreeView::clicked, m_treeModel, &SoundAreaTreeModel::onSoundTreeItemActivated); - connect(m_ui->tvPlaylist, &QTableView::clicked, this, [this](const QModelIndex &index) - { - if (index.column() != SoundAreaPlaylistModel::Column::Option) - return; - - - const SoundState ss(m_playlistModel->getRowData(index.row())); - - - - - - - - - - - - - - - auto *reqHandler = new ControlSoundRequester; - - if (!m_somFtc->controlSoundRequest(ControlSoundRequest(ss.egcuId(), ss.soundId(), ss.category(), 0, PlayControl::StopSound), reqHandler)) + for (const auto& egcu : std::as_const(m_soundArea->egcuIds)) { - new LtsWidgets::LtsMessageDialogNew(this, tr("Stopping sound failed with unknown error")); - return; + if (!m_egcuCheckBoxes.value(egcu)->isChecked()) + continue; + DEBUG_LOG(m_logger) << "onStopAllSounds add egcu=" << egcu; + egcuIds.append(egcu); } - connect(reqHandler, &ControlSoundRequester::finished, - this, [this, reqHandler](const QString &msg) + for (const auto& egcu : std::as_const(egcuIds)) { - if (!msg.isEmpty()) - { - new LtsWidgets::LtsMessageDialogNew(this, msg); - return; - } + DEBUG_LOG(m_logger) << "onStopAllSounds egcu=" << egcu; + SoundManagement::StopAllSoundsRequest req(egcu); - reqHandler->deleteLater(); + m_somFtc->stopAllSoundsRequest(req, nullptr); + } +} + +bool SoundAreaEditDialog::init(LtsSession::LtsSessionDataDds* session) +{ + DEBUG_LOG(m_logger) << "init"; + + m_session = session; + + std::shared_ptr ismDtc; + if (!m_session->getDtc(ismDtc)) + { + ERROR_LOG(m_logger) << "connection to ISM-DTC failed"; + return false; + } + + if (!m_session->getDtc(m_somDtc)) + { + ERROR_LOG(m_logger) << "connection to SOM-DTC failed"; + return false; + } + + if (!m_session->getFtc(m_somFtc)) + { + ERROR_LOG(m_logger) << "connection to SOM-FTC failed"; + return false; + } + + m_helper = std::make_shared(new SoundAreaHelper(ismDtc, m_somDtc)); + + QGridLayout* layout = new QGridLayout(); + int i = 0; + for (const auto& egcu : std::as_const(m_soundArea->egcuIds)) + { + QCheckBox* chBox = new QCheckBox(m_helper->egcuName(egcu)); + chBox->setChecked(true); + m_egcuCheckBoxes.insert(egcu, chBox); + layout->addWidget(m_egcuCheckBoxes.value(egcu), int(i / 2), i % 2); + ++i; + } + m_ui->wEgcu->setLayout(layout); + + delete m_treeModel; + m_treeModel = new SoundAreaTreeModel(m_soundArea->egcuIds, m_helper, this); + m_treeModel->init(m_somDtc); + m_ui->tvSounds->setModel(m_treeModel); + m_ui->tvSounds->expandAll(); + m_ui->tvSounds->header()->resizeSection(SoundAreaTreeModel::Column::Loop, 50); + m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Category, QHeaderView::Interactive); + m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Sound, QHeaderView::Stretch); + m_ui->tvSounds->header()->setSectionResizeMode(SoundAreaTreeModel::Column::Loop, QHeaderView::Fixed); + + delete m_playlistModel; + m_playlistModel = new SoundAreaPlaylistModel(m_soundArea->egcuIds, m_helper, this); + m_playlistModel->init(m_somDtc); + m_ui->tvPlaylist->setModel(m_playlistModel); + m_ui->tvPlaylist->horizontalHeader()->resizeSection(SoundAreaPlaylistModel::Column::Duration, 100); + m_ui->tvPlaylist->horizontalHeader()->resizeSection(SoundAreaPlaylistModel::Column::Option, 50); + + m_ui->tvPlaylist->horizontalHeader()->setSectionResizeMode(SoundAreaPlaylistModel::Column::Sound, + QHeaderView::Stretch); + + m_ui->tvPlaylist->horizontalHeader()->setSectionResizeMode(SoundAreaPlaylistModel::Column::Option, + QHeaderView::Fixed); + + m_ui->tvSounds->setItemDelegateForColumn(SoundAreaTreeModel::Column::Loop, new SwitchItemDelegate(m_treeModel)); + m_ui->tvSounds->setItemDelegateForColumn(SoundAreaTreeModel::Column::Volume, new SpinBoxDelegate(m_treeModel)); + + m_ui->tvPlaylist->setItemDelegate(new SoundAreaEditPlaylistDelegate(m_playlistModel)); + + connect(m_treeModel, &SoundAreaTreeModel::playSound, this, &SoundAreaEditDialog::onPlaySound); + connect(m_ui->tvSounds, &QTreeView::clicked, m_treeModel, &SoundAreaTreeModel::onSoundTreeItemActivated); + connect(m_ui->tvPlaylist, &QTableView::clicked, this, [this](const QModelIndex& index) { + if (index.column() != SoundAreaPlaylistModel::Column::Option) + return; + + const SoundState ss(m_playlistModel->getRowData(index.row())); + + auto* reqHandler = new ControlSoundRequester; + + if (!m_somFtc->controlSoundRequest( + ControlSoundRequest(ss.egcuId(), ss.soundId(), ss.category(), 0, PlayControl::StopSound), reqHandler)) + { + new LtsWidgets::LtsMessageDialogNew(this, tr("Stopping sound failed with unknown error")); + return; + } + + connect(reqHandler, &ControlSoundRequester::finished, this, [this, reqHandler](const QString& msg) { + if (!msg.isEmpty()) + { + new LtsWidgets::LtsMessageDialogNew(this, msg); + return; + } + + reqHandler->deleteLater(); + }); }); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Hide, this, &SoundAreaEditDialog::onStopAllSounds); - - - - }); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Hide, this, &SoundAreaEditDialog::onStopAllSounds); - - DEBUG_LOG(m_logger) << "init successful"; - return true; + DEBUG_LOG(m_logger) << "init successful"; + return true; } -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.h old mode 100755 new mode 100644 index 56c0c0b39..150ee194c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_dialog.h @@ -1,14 +1,12 @@ - #pragma once -#include #include +#include #include #include - namespace NGL { class INGLLogger; @@ -28,8 +26,7 @@ namespace Ui { class SoundAreaEditDialog; class AddSoundProcessDialog; -} - +} // namespace Ui namespace EffectManagement { @@ -40,113 +37,60 @@ class SoundAreaTreeModel; class SoundAreaPlaylistModel; class SoundAreaEditDialog; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -class ControlSoundRequester - : public QObject - , public SoundManagement::Interface::Ftc::ControlSoundReplyHandler +class ControlSoundRequester : public QObject, public SoundManagement::Interface::Ftc::ControlSoundReplyHandler { - Q_OBJECT -public: - void onControlSoundReply(const Core::FunctionReplyObject &reply) override final - { - m_reply = reply; - emit finished(m_reply.translated()); - deleteLater(); - } + Q_OBJECT + public: + void onControlSoundReply(const Core::FunctionReplyObject& reply) override final + { + m_reply = reply; + emit finished(m_reply.translated()); + deleteLater(); + } -signals: - void finished(const QString &msg); + signals: + void finished(const QString& msg); -private: - -NGL::INGLLogger &m_logger; - Core::FunctionReplyObject m_reply; + private: + NGL::INGLLogger& m_logger; + Core::FunctionReplyObject m_reply; }; - - - - -class SoundAreaEditDialog - : public LtsWidgets::LtsDialog +class SoundAreaEditDialog : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit SoundAreaEditDialog(const SoundArea &soundArea, QWidget *parent = nullptr); - ~SoundAreaEditDialog(); + public: + explicit SoundAreaEditDialog(const SoundArea& soundArea, QWidget* parent = nullptr); + ~SoundAreaEditDialog(); + private slots: -private slots: - + void onPlaySound(SoundManagement::SoundCategory category, int soundId, bool inLoop, int volume); - void onPlaySound(SoundManagement::SoundCategory category, int soundId, bool inLoop, int volume); + void onStopAllSounds(); - + public: + bool init(LtsSession::LtsSessionDataDds* session); - void onStopAllSounds(); + private: + void retranslate() override; + std::shared_ptr m_somDtc{nullptr}; + std::shared_ptr m_somFtc{nullptr}; -public: - bool init(LtsSession::LtsSessionDataDds *session); + std::shared_ptr m_helper{nullptr}; -private: - void retranslate() override; + QString m_menuGroup; + SoundArea* m_soundArea; + SoundAreaTreeModel* m_treeModel{nullptr}; + SoundAreaPlaylistModel* m_playlistModel{nullptr}; - std::shared_ptr m_somDtc{nullptr}; - std::shared_ptr m_somFtc{nullptr}; + QHash m_egcuCheckBoxes; - std::shared_ptr m_helper{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + Ui::SoundAreaEditDialog* m_ui{nullptr}; +}; - QString m_menuGroup; - SoundArea *m_soundArea; - - SoundAreaTreeModel *m_treeModel{nullptr}; - SoundAreaPlaylistModel *m_playlistModel{nullptr}; - - QHash m_egcuCheckBoxes; - - LtsSession::LtsSessionDataDds *m_session{nullptr}; - Ui::SoundAreaEditDialog *m_ui{nullptr}; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.cpp old mode 100755 new mode 100644 index e02a6aab9..7e9137ab2 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.cpp @@ -1,268 +1,232 @@ - #include "efm_sound_area_edit_model_playlist.h" -#include -#include "efm_sound_area_helper.h" + #include "../logger.h" +#include "efm_sound_area_helper.h" -#include #include -#include -#include -#include #include - +#include +#include +#include +#include +#include namespace EffectManagement { - - - - QIcon SoundAreaEditPlaylistDelegate::s_iconInf = QIcon(QStringLiteral("icon:infinity.svg")); - -SoundAreaEditPlaylistDelegate::SoundAreaEditPlaylistDelegate(QObject *parent) : QStyledItemDelegate(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} - - - - - -void SoundAreaEditPlaylistDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ - const QVariant data(index.data(Qt::DisplayRole)); - - if ((index.column() == SoundAreaPlaylistModel::Column::Duration) && (data.toString().isEmpty())) - { - s_iconInf.paint(painter, option.rect, Qt::AlignCenter); - return; - } - - if (index.column() != SoundAreaPlaylistModel::Column::Option) - { - QStyledItemDelegate::paint(painter, option, index); - return; - } - - QStyleOptionButton button; - button.rect = option.rect; - button.state = QStyle::State_Enabled; - button.iconSize = QSize(25, 25); - button.icon = QIcon(QStringLiteral("icon:delete.svg")); - - QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); -} - - - - - - - -SoundAreaPlaylistModel::SoundAreaPlaylistModel(const QVector &egcuIds, std::shared_ptr &helper, QWidget *parent) - : LtsAbstractTableModel({tr("Category"), - tr("Sound"), - tr("EGCU"), - tr("Duration"), - tr("Option")}, - parent) - , m_helper(helper) - , m_egcuIds(egcuIds) +SoundAreaEditPlaylistDelegate::SoundAreaEditPlaylistDelegate(QObject* parent) + : QStyledItemDelegate(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { } +void SoundAreaEditPlaylistDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + const QVariant data(index.data(Qt::DisplayRole)); + if ((index.column() == SoundAreaPlaylistModel::Column::Duration) && (data.toString().isEmpty())) + { + s_iconInf.paint(painter, option.rect, Qt::AlignCenter); + return; + } + if (index.column() != SoundAreaPlaylistModel::Column::Option) + { + QStyledItemDelegate::paint(painter, option, index); + return; + } + QStyleOptionButton button; + button.rect = option.rect; + button.state = QStyle::State_Enabled; + button.iconSize = QSize(25, 25); + button.icon = QIcon(QStringLiteral("icon:delete.svg")); + QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); +} - - +SoundAreaPlaylistModel::SoundAreaPlaylistModel(const QVector& egcuIds, + std::shared_ptr& helper, QWidget* parent) + : LtsAbstractTableModel({tr("Category"), tr("Sound"), tr("EGCU"), tr("Duration"), tr("Option")}, + parent), + m_helper(helper), m_egcuIds(egcuIds) +{ +} void SoundAreaPlaylistModel::onTimeout() { - for (int i = 0; i < m_vecData.count(); ++i) - m_vecData[i].duration(std::max(0, m_vecData[i].duration() - 1000)); - emit dataChanged({}, {}); + for (int i = 0; i < m_vecData.count(); ++i) + m_vecData[i].duration(std::max(0, m_vecData[i].duration() - 1000)); + emit dataChanged({}, {}); } - - - - -bool SoundAreaPlaylistModel::init(std::shared_ptr &somDtc) +bool SoundAreaPlaylistModel::init(std::shared_ptr& somDtc) { - DEBUG_LOG(m_logger) << "init"; + DEBUG_LOG(m_logger) << "init"; - const QMap soundStates = somDtc->soundStates(); - for (const auto &data : std::as_const(soundStates)) - { - if (!m_egcuIds.contains(data.egcuId())) - continue; + const QMap soundStates = somDtc->soundStates(); + for (const auto& data : std::as_const(soundStates)) + { + if (!m_egcuIds.contains(data.egcuId())) + continue; - addActiveSound(SoundState(data)); - } + addActiveSound(SoundState(data)); + } - somDtc->enableSoundState(true); + somDtc->enableSoundState(true); - connect(somDtc.get(), &SoundManagement::Interface::Dtc::soundStateChanged, this, - [this](const SoundManagement::SoundState &data, DataModification modType) - { - onDataChanged(SoundState(data), modType); - }); + connect(somDtc.get(), &SoundManagement::Interface::Dtc::soundStateChanged, this, + [this](const SoundManagement::SoundState& data, DataModification modType) { + onDataChanged(SoundState(data), modType); + }); - m_timer = new QTimer(this); - connect(m_timer, &QTimer::timeout, this, &SoundAreaPlaylistModel::onTimeout); - m_timer->start(1000); + m_timer = new QTimer(this); + connect(m_timer, &QTimer::timeout, this, &SoundAreaPlaylistModel::onTimeout); + m_timer->start(1000); - DEBUG_LOG(m_logger) << "init successful"; - return true; + DEBUG_LOG(m_logger) << "init successful"; + return true; } -int SoundAreaPlaylistModel::indexOf(const SoundState &data) const +int SoundAreaPlaylistModel::indexOf(const SoundState& data) const { - int idx = 0; - for (const auto &item : std::as_const(m_vecData)) - { - if ( (item.category() == data.category()) && - (item.soundId() == data.soundId()) && - (item.egcuId() == data.egcuId()) ) - return idx; - ++idx; - } - return -1; + int idx = 0; + for (const auto& item : std::as_const(m_vecData)) + { + if ((item.category() == data.category()) && (item.soundId() == data.soundId()) && + (item.egcuId() == data.egcuId())) + return idx; + ++idx; + } + return -1; } - bool SoundAreaPlaylistModel::addActiveSound(SoundState data) { - data.duration(m_helper->soundDuration(data.category(), data.soundId())); - const int row = indexOf(data); - const QString name(m_helper->soundName(data.category(), data.soundId())); + data.duration(m_helper->soundDuration(data.category(), data.soundId())); + const int row = indexOf(data); + const QString name(m_helper->soundName(data.category(), data.soundId())); - if (row != -1) - { - ERROR_LOG(m_logger) << "'" << name << "' is already active"; - return false; - } - - data.status(SoundState::Status::Active); - insertRow(data); - - DEBUG_LOG(m_logger) << "adding '" << name << "' to active Sounds"; - return true; -} - - -bool SoundAreaPlaylistModel::removeActiveSound(const QModelIndex &index) -{ - if (!index.isValid()) - return false; - - return removeRow(index.row()); -} - - -QVariant SoundAreaPlaylistModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); - - const SoundState &soundState = m_vecData.at(index.row()); - - switch (role) - { - case Qt::DisplayRole: - case Qt::EditRole: - switch (index.column()) + if (row != -1) { - case Column::Category: - return m_helper->categoryName(soundState.category()); + ERROR_LOG(m_logger) << "'" << name << "' is already active"; + return false; + } - case Column::Sound: - return m_helper->soundName(soundState.category(), soundState.soundId()); + data.status(SoundState::Status::Active); + insertRow(data); - case Column::Egcu: - return m_helper->egcuName(soundState.egcuId()); - - case Column::Duration: - return soundState.inLoop() ? QString() : QTime(0, 0).addMSecs(soundState.duration()).toString(QStringLiteral("hh:mm:ss.zzz")); - - case Column::Option: - default: - return soundState.status(); - } - - case Qt::BackgroundColorRole: - if ( (index.column() != Column::Category) && (index.column() != Column::Sound)) - return QVariant(); - return m_helper->soundCategoryBackgroundColor(static_cast(soundState.category().underlying())); - - case Qt::TextColorRole: - if ( (index.column() != Column::Category) && (index.column() != Column::Sound)) - return QVariant(); - return m_helper->soundCategoryTextColor(static_cast(soundState.category().underlying())); - - case Qt::TextAlignmentRole: - return index.column() == Column::Duration ? Qt::AlignCenter : Qt::AlignVCenter; - - default: - return QVariant(); - } + DEBUG_LOG(m_logger) << "adding '" << name << "' to active Sounds"; + return true; } -bool SoundAreaPlaylistModel::onDataChanged(const SoundState &data, DataModification modType) +bool SoundAreaPlaylistModel::removeActiveSound(const QModelIndex& index) { - if (!m_egcuIds.contains(data.egcuId())) - return false; + if (!index.isValid()) + return false; - int row; - QModelIndex idx; + return removeRow(index.row()); +} - switch (modType) - { - case DataModification::eAdded: - return addActiveSound(data); +QVariant SoundAreaPlaylistModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid()) + return QVariant(); - case DataModification::eModified: - WARNING_LOG(m_logger) << "handling eModified for sound states not implemented yet"; - return false; + const SoundState& soundState = m_vecData.at(index.row()); - case DataModification::eRemoved: - row = indexOf(data); - idx = SoundAreaPlaylistModel::index(m_vecData.indexOf(data), 0); - if (row == -1) + switch (role) { - ERROR_LOG(m_logger) << "'" << m_helper->soundName(data.category(), data.soundId()) << "' is neither scheduled nor active"; - return false; - } - return removeActiveSound(idx); + case Qt::DisplayRole: + case Qt::EditRole: + switch (index.column()) + { + case Column::Category: + return m_helper->categoryName(soundState.category()); - default: - Q_UNREACHABLE(); - return false; - } + case Column::Sound: + return m_helper->soundName(soundState.category(), soundState.soundId()); + + case Column::Egcu: + return m_helper->egcuName(soundState.egcuId()); + + case Column::Duration: + return soundState.inLoop() + ? QString() + : QTime(0, 0).addMSecs(soundState.duration()).toString(QStringLiteral("hh:mm:ss.zzz")); + + case Column::Option: + default: + return soundState.status(); + } + + case Qt::BackgroundColorRole: + if ((index.column() != Column::Category) && (index.column() != Column::Sound)) + return QVariant(); + return m_helper->soundCategoryBackgroundColor(static_cast(soundState.category().underlying())); + + case Qt::TextColorRole: + if ((index.column() != Column::Category) && (index.column() != Column::Sound)) + return QVariant(); + return m_helper->soundCategoryTextColor(static_cast(soundState.category().underlying())); + + case Qt::TextAlignmentRole: + return index.column() == Column::Duration ? Qt::AlignCenter : Qt::AlignVCenter; + + default: + return QVariant(); + } } -bool SoundAreaPlaylistModel::insertRow(const SoundState &item) +bool SoundAreaPlaylistModel::onDataChanged(const SoundState& data, DataModification modType) { - beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); - m_vecData.push_back(item); - endInsertRows(); - return true; + if (!m_egcuIds.contains(data.egcuId())) + return false; + + int row; + QModelIndex idx; + + switch (modType) + { + case DataModification::eAdded: + return addActiveSound(data); + + case DataModification::eModified: + WARNING_LOG(m_logger) << "handling eModified for sound states not implemented yet"; + return false; + + case DataModification::eRemoved: + row = indexOf(data); + idx = SoundAreaPlaylistModel::index(m_vecData.indexOf(data), 0); + if (row == -1) + { + ERROR_LOG(m_logger) << "'" << m_helper->soundName(data.category(), data.soundId()) + << "' is neither scheduled nor active"; + return false; + } + return removeActiveSound(idx); + + default: + Q_UNREACHABLE(); + return false; + } +} + +bool SoundAreaPlaylistModel::insertRow(const SoundState& item) +{ + beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); + m_vecData.push_back(item); + endInsertRows(); + return true; } bool SoundAreaPlaylistModel::removeRow(int row) { - return removeRows(row, 1); + return removeRows(row, 1); } - - - - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.h old mode 100755 new mode 100644 index 0843b8bb3..ca073038a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_playlist.h @@ -1,15 +1,12 @@ - #pragma once #include "efm_sound_state.h" #include -#include - #include - +#include class QTimer; @@ -18,7 +15,6 @@ namespace NGL class INGLLogger; } - namespace EffectManagement { @@ -26,70 +22,52 @@ using SoundKey = QPair; class SoundAreaHelper; - - - - -class SoundAreaEditPlaylistDelegate - : public QStyledItemDelegate +class SoundAreaEditPlaylistDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT -public: - SoundAreaEditPlaylistDelegate(QObject *parent = nullptr); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + public: + SoundAreaEditPlaylistDelegate(QObject* parent = nullptr); + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; -private: + private: + NGL::INGLLogger& m_logger; + static QIcon s_iconInf; +}; -NGL::INGLLogger &m_logger; - static QIcon s_iconInf; - -}; - - - - - -class SoundAreaPlaylistModel - : public LtsWidgets::LtsAbstractTableModel +class SoundAreaPlaylistModel : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Column { Category, Sound, Egcu, Duration, Option }; + public: + enum Column { Category, Sound, Egcu, Duration, Option }; - explicit SoundAreaPlaylistModel(const QVector &egcuIds, std::shared_ptr &helper, QWidget *parent = nullptr); + explicit SoundAreaPlaylistModel(const QVector& egcuIds, std::shared_ptr& helper, + QWidget* parent = nullptr); -private slots: - + private slots: - void onTimeout(); + void onTimeout(); -public: - bool init(std::shared_ptr &somDtc); + public: + bool init(std::shared_ptr& somDtc); - + int indexOf(const SoundState& data) const; - int indexOf(const SoundState &data) const; + bool addActiveSound(SoundState data); - + bool removeActiveSound(const QModelIndex& index); - bool addActiveSound(SoundState data); + protected: + QVariant data(const QModelIndex& index, int role) const override; + bool onDataChanged(const SoundState& data, DataModification modType) override; + bool insertRow(const SoundState& item) override; + bool removeRow(int row) override; - + private: + std::shared_ptr m_helper{nullptr}; + QVector m_egcuIds; + QTimer* m_timer{nullptr}; +}; - bool removeActiveSound(const QModelIndex &index); - -protected: - QVariant data(const QModelIndex &index, int role) const override; - bool onDataChanged(const SoundState &data, DataModification modType) override; - bool insertRow(const SoundState &item) override; - bool removeRow(int row) override; - -private: - std::shared_ptr m_helper{nullptr}; - QVector m_egcuIds; - QTimer *m_timer{nullptr}; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.cpp old mode 100755 new mode 100644 index 9a9ec17df..5ed32e5a9 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.cpp @@ -1,401 +1,356 @@ - #include "efm_sound_area_edit_model_tree.h" -#include + +#include "../logger.h" #include "efm_sound_area.h" #include "efm_sound_area_helper.h" -#include "../logger.h" -#include #include - -#include - - - - - - - - - - - #include - - - - - - - +#include +#include +#include namespace EffectManagement { +SpinBoxDelegate::SpinBoxDelegate(QObject* parent) : QStyledItemDelegate(parent) {} - - -SpinBoxDelegate::SpinBoxDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{} - -QWidget *SpinBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const +QWidget* SpinBoxDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, + const QModelIndex& index) const { - if (index.column() != SoundAreaTreeModel::Column::Volume) - return QStyledItemDelegate::createEditor(parent, option, index); - auto *sb = new QSpinBox(parent); - sb->setFrame(false); - sb->setSuffix(QStringLiteral(" %")); - sb->setRange(0, 100); - return sb; + if (index.column() != SoundAreaTreeModel::Column::Volume) + return QStyledItemDelegate::createEditor(parent, option, index); + auto* sb = new QSpinBox(parent); + sb->setFrame(false); + sb->setSuffix(QStringLiteral(" %")); + sb->setRange(0, 100); + return sb; } -void SpinBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +void SpinBoxDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { - if (index.column() != SoundAreaTreeModel::Column::Volume) - { - QStyledItemDelegate::setEditorData(editor, index); + if (index.column() != SoundAreaTreeModel::Column::Volume) + { + QStyledItemDelegate::setEditorData(editor, index); + return; + } + + qWarning() << index << index.data(); + const int val = index.data(Qt::EditRole).toInt(); + + auto* sb = qobject_cast(editor); + sb->setValue(val); return; - } - - qWarning() << index << index.data(); - const int val = index.data(Qt::EditRole).toInt(); - - auto *sb = qobject_cast(editor); - sb->setValue(val); - return; } -void SpinBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const +void SpinBoxDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { - if (index.column() != SoundAreaTreeModel::Column::Volume) - { - QStyledItemDelegate::setModelData(editor, model, index); - return; - } + if (index.column() != SoundAreaTreeModel::Column::Volume) + { + QStyledItemDelegate::setModelData(editor, model, index); + return; + } - auto *sb = qobject_cast(editor); - const int val = sb->value(); - model->setData(index, val, Qt::EditRole); + auto* sb = qobject_cast(editor); + const int val = sb->value(); + model->setData(index, val, Qt::EditRole); } -void SpinBoxDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const +void SpinBoxDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, + const QModelIndex&) const { - editor->setGeometry(option.rect); + editor->setGeometry(option.rect); } - - - - - - -SoundTreeItem::SoundTreeItem(const QVector &data, const SoundKey &key, SoundTreeItem *parent) : m_parent(parent) - , m_data(data) - , m_soundKey(key), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { +SoundTreeItem::SoundTreeItem(const QVector& data, const SoundKey& key, SoundTreeItem* parent) + : m_parent(parent), m_data(data), m_soundKey(key), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ } SoundTreeItem::~SoundTreeItem() { - qDeleteAll(m_children); + qDeleteAll(m_children); } - - - - -void SoundTreeItem::appendChild(SoundTreeItem *item) +void SoundTreeItem::appendChild(SoundTreeItem* item) { - m_children.append(item); + m_children.append(item); } void SoundTreeItem::toogleLoop() { - if (isRepeatable()) - m_data[SoundAreaTreeModel::Column::Loop] = -1 * m_data[SoundAreaTreeModel::Column::Loop].toInt(); + if (isRepeatable()) + m_data[SoundAreaTreeModel::Column::Loop] = -1 * m_data[SoundAreaTreeModel::Column::Loop].toInt(); } void SoundTreeItem::toggleLoop(int inLoop) { - if (isRepeatable()) - { - if ( (inLoop != -1) && (inLoop != 1) ) - return; - m_data[SoundAreaTreeModel::Column::Loop] = inLoop; - } + if (isRepeatable()) + { + if ((inLoop != -1) && (inLoop != 1)) + return; + m_data[SoundAreaTreeModel::Column::Loop] = inLoop; + } } - QString SoundTreeItem::toString() const { - return QStringLiteral("SoundTreeItem( category : ") + QString::number(m_soundKey.first) + QStringLiteral(" | id : ") + - QString::number(m_soundKey.second) + QStringLiteral(" )"); + return QStringLiteral("SoundTreeItem( category : ") + QString::number(m_soundKey.first) + + QStringLiteral(" | id : ") + QString::number(m_soundKey.second) + QStringLiteral(" )"); } - - - - -SoundAreaTreeModel::SoundAreaTreeModel(const QVector &egcuIds, std::shared_ptr &helper, QWidget *parent) - : QAbstractItemModel(parent) - , m_helper(helper) - , m_root(new SoundTreeItem({tr("Category"), tr("Sound"), tr("Loop"), tr("Volume")}, SoundKey(0, 0))) - , m_egcuIds(egcuIds) +SoundAreaTreeModel::SoundAreaTreeModel(const QVector& egcuIds, std::shared_ptr& helper, + QWidget* parent) + : QAbstractItemModel(parent), m_helper(helper), + m_root(new SoundTreeItem({tr("Category"), tr("Sound"), tr("Loop"), tr("Volume")}, SoundKey(0, 0))), + m_egcuIds(egcuIds) { } SoundAreaTreeModel::~SoundAreaTreeModel() { - delete m_root; + delete m_root; } - - - - - -void SoundAreaTreeModel::onSoundTreeItemActivated(const QModelIndex &index) +void SoundAreaTreeModel::onSoundTreeItemActivated(const QModelIndex& index) { - if (!index.isValid()) - return; + if (!index.isValid()) + return; - switch (index.column()) - { - case Column::Loop: - { - onToggleLoop(index); - break; - } - - case Column::Volume: - break; - - default: - { - onPlaySound(index); - break; - } - } -} - - - - - -bool SoundAreaTreeModel::onPlaySound(const QModelIndex &index) -{ - SoundTreeItem *item = static_cast(index.internalPointer()); - emit playSound(m_helper->soundCategory(item->soundKey().first), item->soundKey().second, item->inLoop(), item->volume()); - - return true; -} - -bool SoundAreaTreeModel::onToggleLoop(const QModelIndex &index) -{ - SoundTreeItem *item = static_cast(index.internalPointer()); - item->toogleLoop(); - emit dataChanged(index, index); - return true; -} - - - - - -bool SoundAreaTreeModel::init(const std::shared_ptr &somDtc) -{ - DEBUG_LOG(m_logger) << "init"; - - - SoundKey key; - QVector categories = m_helper->soundCategories(); - for (const auto &category : std::as_const(categories)) - { - QString name{m_helper->categoryName(category)}; - QVector data{QVector{name, QVariant(), 0, 100}}; - key.first = static_cast(category.underlying()); - key.second = 0; - m_root->appendChild(new SoundTreeItem(data, key, m_root)); - } - - - SoundManagement::Sounds sounds = somDtc->sounds(); - for (const auto &sound : std::as_const(sounds.sounds())) - { - for (auto &category : m_root->children()) - { - if (category->soundKey().first == static_cast(sound.category().underlying())) - { - QString displayName = m_helper->soundName(sound.category(), sound.soundId()); - QVector data{QVector{category->data(0).toString(), displayName, sound.isRepeatable() ? 1 : 0, 100}}; - key.first = static_cast(sound.category().underlying()); - key.second = sound.soundId(); - category->appendChild(new SoundTreeItem(data, key, category)); - break; - } - } - } - - return true; -} - -bool SoundAreaTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) -{ - if (index.column() != SoundAreaTreeModel::Column::Volume - || role != Qt::EditRole) - return QAbstractItemModel::setData(index, value, role); - - bool k; - int val = value.toInt(&k); - if (!k) - return false; - - static_cast(index.internalPointer())->setVolume(val); - emit dataChanged(index, index); - return true; -} - -SoundTreeItem * SoundAreaTreeModel::find(const SoundKey &key) -{ - QVector categories = m_root->children(); - for (auto category : std::as_const(categories)) - { - if (category->soundKey() == key) - return category; - - QVector sounds = category->children(); - for (auto sound : std::as_const(sounds)) - if (sound->soundKey() == key) - return sound; - } - - return nullptr; -} - -Qt::ItemFlags SoundAreaTreeModel::flags(const QModelIndex &index) const -{ - if (!index.isValid()) - return Qt::NoItemFlags; - - if (index.column() != SoundAreaTreeModel::Column::Volume) - return QAbstractItemModel::flags(index); - return QAbstractItemModel::flags(index).setFlag(Qt::ItemFlag::ItemIsEditable); -} - -QVariant SoundAreaTreeModel::data(const QModelIndex &index, int role) const -{ - if (!index.isValid()) - return QVariant(); - - if ( (role != Qt::DisplayRole) && (role != Qt::ToolTipRole) && - (role != Qt::BackgroundColorRole) && (role != Qt::TextColorRole) && - (role != Qt::EditRole)) - return QVariant(); - - SoundTreeItem *item = static_cast(index.internalPointer()); - - switch (role) - { - case Qt::EditRole: switch (index.column()) { - case Column::Volume: return item->volume(); - default: - Q_UNREACHABLE(); - return QVariant(); + case Column::Loop: { + onToggleLoop(index); + break; + } + + case Column::Volume: + break; + + default: { + onPlaySound(index); + break; + } } - case Qt::DisplayRole: - if (item->soundKey().second == 0) - return index.column() == Column::Category ? item->data(index.column()) : QVariant(); - switch (index.column()) +} + +bool SoundAreaTreeModel::onPlaySound(const QModelIndex& index) +{ + SoundTreeItem* item = static_cast(index.internalPointer()); + emit playSound(m_helper->soundCategory(item->soundKey().first), item->soundKey().second, item->inLoop(), + item->volume()); + + return true; +} + +bool SoundAreaTreeModel::onToggleLoop(const QModelIndex& index) +{ + SoundTreeItem* item = static_cast(index.internalPointer()); + item->toogleLoop(); + emit dataChanged(index, index); + return true; +} + +bool SoundAreaTreeModel::init(const std::shared_ptr& somDtc) +{ + DEBUG_LOG(m_logger) << "init"; + + SoundKey key; + QVector categories = m_helper->soundCategories(); + for (const auto& category : std::as_const(categories)) { - case Column::Category: return QVariant(); - case Column::Sound: return item->data(index.column()); - case Column::Loop: return item->isRepeatable() ? item->data(index.column()) : QVariant(); - case Column::Volume: return QStringLiteral("%1 %").arg(item->volume()); - default: - Q_UNREACHABLE(); - return QVariant(); - } + QString name{m_helper->categoryName(category)}; + QVector data{QVector{name, QVariant(), 0, 100}}; + key.first = static_cast(category.underlying()); + key.second = 0; + m_root->appendChild(new SoundTreeItem(data, key, m_root)); + } - case Qt::ToolTipRole: - if ( (item->soundKey().second == 0) && (index.column() != Column::Category) ) - return QVariant(); - switch (index.column()) + SoundManagement::Sounds sounds = somDtc->sounds(); + for (const auto& sound : std::as_const(sounds.sounds())) { - case Column::Category: return item->data(Column::Category).toString(); - case Column::Sound: return item->data(Column::Sound).toString(); - case Column::Loop: return item->inLoop() ? tr("play in loop") : tr("play once"); - case Column::Volume: return tr("Volume: %1 %").arg(item->volume()); - default: - Q_UNREACHABLE(); - return QVariant(); - } + for (auto& category : m_root->children()) + { + if (category->soundKey().first == static_cast(sound.category().underlying())) + { + QString displayName = m_helper->soundName(sound.category(), sound.soundId()); + QVector data{ + QVector{category->data(0).toString(), displayName, sound.isRepeatable() ? 1 : 0, 100}}; + key.first = static_cast(sound.category().underlying()); + key.second = sound.soundId(); + category->appendChild(new SoundTreeItem(data, key, category)); + break; + } + } + } - case Qt::BackgroundRole: - if ( (index.column() == Column::Category) || - ( (index.column() == Column::Sound) && (item->soundKey().second != 0) ) ) - return m_helper->soundCategoryBackgroundColor(item->soundKey().first); - return QVariant(); + return true; +} - case Qt::TextColorRole: - if ((index.column() == Column::Category) || (index.column() == Column::Sound)) - return m_helper->soundCategoryTextColor(item->soundKey().first); - return QVariant(); +bool SoundAreaTreeModel::setData(const QModelIndex& index, const QVariant& value, int role) +{ + if (index.column() != SoundAreaTreeModel::Column::Volume || role != Qt::EditRole) + return QAbstractItemModel::setData(index, value, role); - default: - Q_UNREACHABLE(); - return QVariant(); - } + bool k; + int val = value.toInt(&k); + if (!k) + return false; + + static_cast(index.internalPointer())->setVolume(val); + emit dataChanged(index, index); + return true; +} + +SoundTreeItem* SoundAreaTreeModel::find(const SoundKey& key) +{ + QVector categories = m_root->children(); + for (auto category : std::as_const(categories)) + { + if (category->soundKey() == key) + return category; + + QVector sounds = category->children(); + for (auto sound : std::as_const(sounds)) + if (sound->soundKey() == key) + return sound; + } + + return nullptr; +} + +Qt::ItemFlags SoundAreaTreeModel::flags(const QModelIndex& index) const +{ + if (!index.isValid()) + return Qt::NoItemFlags; + + if (index.column() != SoundAreaTreeModel::Column::Volume) + return QAbstractItemModel::flags(index); + return QAbstractItemModel::flags(index).setFlag(Qt::ItemFlag::ItemIsEditable); +} + +QVariant SoundAreaTreeModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid()) + return QVariant(); + + if ((role != Qt::DisplayRole) && (role != Qt::ToolTipRole) && (role != Qt::BackgroundColorRole) && + (role != Qt::TextColorRole) && (role != Qt::EditRole)) + return QVariant(); + + SoundTreeItem* item = static_cast(index.internalPointer()); + + switch (role) + { + case Qt::EditRole: + switch (index.column()) + { + case Column::Volume: + return item->volume(); + default: + Q_UNREACHABLE(); + return QVariant(); + } + case Qt::DisplayRole: + if (item->soundKey().second == 0) + return index.column() == Column::Category ? item->data(index.column()) : QVariant(); + switch (index.column()) + { + case Column::Category: + return QVariant(); + case Column::Sound: + return item->data(index.column()); + case Column::Loop: + return item->isRepeatable() ? item->data(index.column()) : QVariant(); + case Column::Volume: + return QStringLiteral("%1 %").arg(item->volume()); + default: + Q_UNREACHABLE(); + return QVariant(); + } + + case Qt::ToolTipRole: + if ((item->soundKey().second == 0) && (index.column() != Column::Category)) + return QVariant(); + switch (index.column()) + { + case Column::Category: + return item->data(Column::Category).toString(); + case Column::Sound: + return item->data(Column::Sound).toString(); + case Column::Loop: + return item->inLoop() ? tr("play in loop") : tr("play once"); + case Column::Volume: + return tr("Volume: %1 %").arg(item->volume()); + default: + Q_UNREACHABLE(); + return QVariant(); + } + + case Qt::BackgroundRole: + if ((index.column() == Column::Category) || + ((index.column() == Column::Sound) && (item->soundKey().second != 0))) + return m_helper->soundCategoryBackgroundColor(item->soundKey().first); + return QVariant(); + + case Qt::TextColorRole: + if ((index.column() == Column::Category) || (index.column() == Column::Sound)) + return m_helper->soundCategoryTextColor(item->soundKey().first); + return QVariant(); + + default: + Q_UNREACHABLE(); + return QVariant(); + } } QVariant SoundAreaTreeModel::headerData(int section, Qt::Orientation orientation, int role) const { - return ( (orientation == Qt::Horizontal) && (role == Qt::DisplayRole) ) ? m_root->data(section) : QVariant(); + return ((orientation == Qt::Horizontal) && (role == Qt::DisplayRole)) ? m_root->data(section) : QVariant(); } -QModelIndex SoundAreaTreeModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex SoundAreaTreeModel::index(int row, int column, const QModelIndex& parent) const { - if (!hasIndex(row, column, parent)) - return {}; + if (!hasIndex(row, column, parent)) + return {}; - SoundTreeItem *item; - if(!parent.isValid()) - item = m_root; - else - item = static_cast(parent.internalPointer()); - SoundTreeItem *child = item->child(row); - return child ? createIndex(row, column, child) : QModelIndex(); + SoundTreeItem* item; + if (!parent.isValid()) + item = m_root; + else + item = static_cast(parent.internalPointer()); + SoundTreeItem* child = item->child(row); + return child ? createIndex(row, column, child) : QModelIndex(); } -QModelIndex SoundAreaTreeModel::parent(const QModelIndex &index) const +QModelIndex SoundAreaTreeModel::parent(const QModelIndex& index) const { - if (!index.isValid()) - return {}; + if (!index.isValid()) + return {}; - SoundTreeItem *parent = static_cast(index.internalPointer())->parent(); - return parent == m_root ? QModelIndex() : createIndex(parent->row(), 0, parent); + SoundTreeItem* parent = static_cast(index.internalPointer())->parent(); + return parent == m_root ? QModelIndex() : createIndex(parent->row(), 0, parent); } -int SoundAreaTreeModel::rowCount(const QModelIndex &index) const +int SoundAreaTreeModel::rowCount(const QModelIndex& index) const { - if (index.column() > 0) - return 0; + if (index.column() > 0) + return 0; - SoundTreeItem *parent; - if (!index.isValid()) - parent = m_root; - else - parent = static_cast(index.internalPointer()); - return parent->childCount(); + SoundTreeItem* parent; + if (!index.isValid()) + parent = m_root; + else + parent = static_cast(index.internalPointer()); + return parent->childCount(); } -int SoundAreaTreeModel::columnCount(const QModelIndex &index) const +int SoundAreaTreeModel::columnCount(const QModelIndex& index) const { - return index.isValid() ? static_cast(index.internalPointer())->columnCount() : m_root->columnCount(); + return index.isValid() ? static_cast(index.internalPointer())->columnCount() + : m_root->columnCount(); } -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.h old mode 100755 new mode 100644 index 5d5c40e91..ff4128d11 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_edit_model_tree.h @@ -1,21 +1,17 @@ - #pragma once #include -#include - #include #include - +#include namespace NGL { class INGLLogger; } - namespace EffectManagement { @@ -24,130 +20,151 @@ using SoundKey = QPair; struct SoundArea; class SoundAreaHelper; - - - - class SoundTreeItem { -public: - enum Column { Category, Sound, Loop, Volume }; + public: + enum Column { Category, Sound, Loop, Volume }; - explicit SoundTreeItem(const QVector &data, const SoundKey &key, SoundTreeItem *parent = nullptr); - ~SoundTreeItem(); + explicit SoundTreeItem(const QVector& data, const SoundKey& key, SoundTreeItem* parent = nullptr); + ~SoundTreeItem(); - + void appendChild(SoundTreeItem* item); - void appendChild(SoundTreeItem *item); - + void toogleLoop(); - void toogleLoop(); - + void toggleLoop(int inLoop); - void toggleLoop(int inLoop); + QVariant data(const int& column) const + { + return (column < 0 || column >= m_data.size()) ? QVariant() : m_data.at(column); + } - QVariant data(const int &column) const { return (column < 0 || column >= m_data.size()) ? QVariant() : m_data.at(column); } - SoundKey soundKey() const { return m_soundKey; } + SoundKey soundKey() const + { + return m_soundKey; + } - bool isRepeatable() const { return m_data[Column::Loop] != 0; } - bool inLoop() const { return m_data[Column::Loop] == 1; } - int volume() const { return m_data[Column::Volume].toInt(); } - void setVolume(int volume) { m_data[Column::Volume] = volume; } + bool isRepeatable() const + { + return m_data[Column::Loop] != 0; + } - SoundTreeItem *parent() { return m_parent; } - SoundTreeItem *child(int row) { return (row < 0 || row >= m_children.size()) ? nullptr : m_children.at(row); } - QVector children() const { return m_children; } + bool inLoop() const + { + return m_data[Column::Loop] == 1; + } - int row() const { return m_parent ? m_parent->m_children.indexOf(const_cast(this)) : 0; } - int columnCount() const { return m_data.count(); } - int childCount() const { return m_children.count(); } + int volume() const + { + return m_data[Column::Volume].toInt(); + } - QString toString() const; + void setVolume(int volume) + { + m_data[Column::Volume] = volume; + } -private: + SoundTreeItem* parent() + { + return m_parent; + } -NGL::INGLLogger &m_logger; - QVector m_children; - SoundTreeItem *m_parent{nullptr}; - QVector m_data; - SoundKey m_soundKey; + SoundTreeItem* child(int row) + { + return (row < 0 || row >= m_children.size()) ? nullptr : m_children.at(row); + } -}; + QVector children() const + { + return m_children; + } + int row() const + { + return m_parent ? m_parent->m_children.indexOf(const_cast(this)) : 0; + } + int columnCount() const + { + return m_data.count(); + } + int childCount() const + { + return m_children.count(); + } + + QString toString() const; + + private: + NGL::INGLLogger& m_logger; + QVector m_children; + SoundTreeItem* m_parent{nullptr}; + QVector m_data; + SoundKey m_soundKey; +}; class SpinBoxDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT -public: - SpinBoxDelegate(QObject *parent = nullptr); + public: + SpinBoxDelegate(QObject* parent = nullptr); -protected: - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; - void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + protected: + QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override; + void setEditorData(QWidget* editor, const QModelIndex& index) const override; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; + void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, + const QModelIndex& index) const override; }; - - - - -class SoundAreaTreeModel - : public QAbstractItemModel +class SoundAreaTreeModel : public QAbstractItemModel { - Q_OBJECT + Q_OBJECT -public: - enum Column { Category, Sound, Loop, Volume }; + public: + enum Column { Category, Sound, Loop, Volume }; - explicit SoundAreaTreeModel(const QVector &egcuIds, std::shared_ptr &helper, QWidget *parent = nullptr); - ~SoundAreaTreeModel(); + explicit SoundAreaTreeModel(const QVector& egcuIds, std::shared_ptr& helper, + QWidget* parent = nullptr); + ~SoundAreaTreeModel(); -signals: - + signals: - void playSound(const SoundManagement::SoundCategory, const int, const bool, const int); + void playSound(const SoundManagement::SoundCategory, const int, const bool, const int); -public slots: - + public slots: - void onSoundTreeItemActivated(const QModelIndex &index); + void onSoundTreeItemActivated(const QModelIndex& index); -private slots: - + private slots: - bool onPlaySound(const QModelIndex &index); - + bool onPlaySound(const QModelIndex& index); - bool onToggleLoop(const QModelIndex &index); + bool onToggleLoop(const QModelIndex& index); + public: + bool init(const std::shared_ptr& somDtc); -public: - bool init(const std::shared_ptr &somDtc); + SoundTreeItem* find(const SoundKey& key); - + protected: + bool setData(const QModelIndex& index, const QVariant& value, int role) override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QVariant data(const QModelIndex& index, int role) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + QModelIndex index(int row, int column, const QModelIndex& parent) const override; + QModelIndex parent(const QModelIndex& index) const override; + int rowCount(const QModelIndex& index) const override; + int columnCount(const QModelIndex& index) const override; - SoundTreeItem * find(const SoundKey &key); + private: + std::shared_ptr m_helper{nullptr}; -protected: - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - QModelIndex index(int row, int column, const QModelIndex &parent) const override; - QModelIndex parent(const QModelIndex &index) const override; - int rowCount(const QModelIndex &index) const override; - int columnCount(const QModelIndex &index) const override; + SoundTreeItem* m_root{nullptr}; + QVector m_egcuIds; +}; -private: - std::shared_ptr m_helper{nullptr}; - - SoundTreeItem *m_root{nullptr}; - QVector m_egcuIds; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.cpp old mode 100755 new mode 100644 index afc7bb1fb..6339e74b5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.cpp @@ -1,279 +1,328 @@  - #include "efm_sound_area_helper.h" -#include + #include "../logger.h" -#include #include - +#include +#include namespace EffectManagement { - - - - -SoundAreaHelper::SoundAreaHelper(SoundAreaHelper *helper) : m_ismDtc(helper->ismDtc()) - , m_somDtc(helper->somDtc()), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - QMap assets = m_ismDtc->instrumentationAssets(); - for (const auto &asset : std::as_const(assets)) - if (asset.mountingPointTypeId() == InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit) - m_egcuNames.insert(asset.id(), QString::fromStdString(asset.name())); - - SoundManagement::Sounds sounds = m_somDtc->sounds(); - for (const auto &sound : std::as_const(sounds.sounds())) - m_soundDuration.insert(SoundKey(sound.category().underlying(), sound.soundId()), sound.duration()); -} - -SoundAreaHelper::SoundAreaHelper(std::shared_ptr &ismDtc, - std::shared_ptr &somDtc) - : m_ismDtc(ismDtc) - , m_somDtc(somDtc) +SoundAreaHelper::SoundAreaHelper(SoundAreaHelper* helper) + : m_ismDtc(helper->ismDtc()), m_somDtc(helper->somDtc()), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - QMap assets = m_ismDtc->instrumentationAssets(); - for (const auto &asset : std::as_const(assets)) - if (asset.mountingPointTypeId() == InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit) - m_egcuNames.insert(asset.id(), QString::fromStdString(asset.name())); + QMap assets = m_ismDtc->instrumentationAssets(); + for (const auto& asset : std::as_const(assets)) + if (asset.mountingPointTypeId() == InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit) + m_egcuNames.insert(asset.id(), QString::fromStdString(asset.name())); - SoundManagement::Sounds sounds = m_somDtc->sounds(); - for (const auto &sound : std::as_const(sounds.sounds())) - m_soundDuration.insert(SoundKey(sound.category().underlying(), sound.soundId()), sound.duration()); + SoundManagement::Sounds sounds = m_somDtc->sounds(); + for (const auto& sound : std::as_const(sounds.sounds())) + m_soundDuration.insert(SoundKey(sound.category().underlying(), sound.soundId()), sound.duration()); } +SoundAreaHelper::SoundAreaHelper(std::shared_ptr& ismDtc, + std::shared_ptr& somDtc) + : m_ismDtc(ismDtc), m_somDtc(somDtc) +{ + QMap assets = m_ismDtc->instrumentationAssets(); + for (const auto& asset : std::as_const(assets)) + if (asset.mountingPointTypeId() == InfrastructureManagement::MountingPointType_def::EffectGenerationControlUnit) + m_egcuNames.insert(asset.id(), QString::fromStdString(asset.name())); - - + SoundManagement::Sounds sounds = m_somDtc->sounds(); + for (const auto& sound : std::as_const(sounds.sounds())) + m_soundDuration.insert(SoundKey(sound.category().underlying(), sound.soundId()), sound.duration()); +} QVector SoundAreaHelper::soundCategories() { - QVector categories = QVector - { - SoundManagement::SoundCategory_def::Aircraft, - SoundManagement::SoundCategory_def::Battlefield, - SoundManagement::SoundCategory_def::Boat, - SoundManagement::SoundCategory_def::Explosion, - SoundManagement::SoundCategory_def::Helicopter, - SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic, - SoundManagement::SoundCategory_def::Vehicle, - SoundManagement::SoundCategory_def::InsideBuilding - }; - return categories; + QVector categories = QVector{ + SoundManagement::SoundCategory_def::Aircraft, SoundManagement::SoundCategory_def::Battlefield, + SoundManagement::SoundCategory_def::Boat, SoundManagement::SoundCategory_def::Explosion, + SoundManagement::SoundCategory_def::Helicopter, SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic, + SoundManagement::SoundCategory_def::Vehicle, SoundManagement::SoundCategory_def::InsideBuilding}; + return categories; } - QString SoundAreaHelper::categoryName(SoundManagement::SoundCategory category) { - switch (category.underlying()) - { - case SoundManagement::SoundCategory_def::Aircraft: return QStringLiteral("Aircraft"); - case SoundManagement::SoundCategory_def::Battlefield: return QStringLiteral("Battlefield"); - case SoundManagement::SoundCategory_def::Boat: return QStringLiteral("Boat"); - case SoundManagement::SoundCategory_def::Explosion: return QStringLiteral("Explosion"); - case SoundManagement::SoundCategory_def::Helicopter: return QStringLiteral("Helicopter"); - case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: return QStringLiteral("MotorsAndUrbanTraffic"); - case SoundManagement::SoundCategory_def::Vehicle: return QStringLiteral("Vehicle"); - case SoundManagement::SoundCategory_def::InsideBuilding: return QStringLiteral("InsideBuilding"); - case SoundManagement::SoundCategory_def::Unknown: return QStringLiteral("Unknown"); - default: - return QString(); - } -} - -QString SoundAreaHelper::categoryName(const int32_t &category) -{ - return categoryName(soundCategory(category)); -} - - -QString SoundAreaHelper::soundName(SoundManagement::SoundCategory category, const int &id) -{ - switch (category.underlying()) - { - case SoundManagement::SoundCategory_def::Aircraft: - switch (id) + switch (category.underlying()) { - case 1: return QStringLiteral("Jet_Pass_by_Military"); - case 2: return QStringLiteral("Military_Aircraft_Fires"); - case 3: return QStringLiteral("Military_Aircraft_Fly_By"); - case 4: return QStringLiteral("Military_Airplane_Drops"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Battlefield: - switch (id) - { - case 1: return QStringLiteral("Battlefield_Ambience_Noise"); - case 2: return QStringLiteral("Battlefield_Ambience_Tank"); - case 3: return QStringLiteral("Battlefield_Ambience_War"); - case 4: return QStringLiteral("Explosions_Battlefield"); - case 5: return QStringLiteral("Explosions_Battlefield_1"); - case 6: return QStringLiteral("Ground_Battle_with_Machine_Guns"); - case 7: return QStringLiteral("Modern_Battlefield"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Boat: - switch (id) - { - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Explosion: - switch (id) - { - case 1: return QStringLiteral("Explosion_Building_Crash"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Helicopter: - switch (id) - { - case 1: return QStringLiteral("Helicopter_Crash"); - case 2: return QStringLiteral("Helicopter_Fly_Overhead"); - case 3: return QStringLiteral("Helicopter_Landing"); - case 4: return QStringLiteral("Helicopter_Pass_by_Military"); - case 5: return QStringLiteral("Helicopter_Take_off"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: - switch (id) - { - case 1: return QStringLiteral("Big_City_Street_Traffic"); - case 2: return QStringLiteral("City_Crossroads_Traffic"); - case 3: return QStringLiteral("City_Street_Heavy_Traffic"); - case 4: return QStringLiteral("City_Street_Noisy_Walking"); - case 5: return QStringLiteral("Construction_Building_Ambient"); - case 6: return QStringLiteral("Demonstration_and_Rioting"); - case 7: return QStringLiteral("Noisy_City_Street"); - case 8: return QStringLiteral("Stadium_Crowd_Ambient"); - case 9: return QStringLiteral("Stadium_Crowd_Applause"); - case 10: return QStringLiteral("Traffic_from_Car"); - case 11: return QStringLiteral("Muezzincalling"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Vehicle: - switch (id) - { - case 1: return QStringLiteral("Tank_Starting_and_Stopping"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::InsideBuilding: - switch (id) - { - case 1: return QStringLiteral("Fire_quietly"); - case 2: return QStringLiteral("Fire_a_little_louder"); - case 3: return QStringLiteral("Fire_louder"); - case 4: return QStringLiteral("Fire_loud"); - case 5: return QStringLiteral("Extinguishing_Noise"); - case 7: return QStringLiteral("This_Room_is_Destroyed"); - case 8: return QStringLiteral("This_Building_is_Destroyed"); - default: - return QStringLiteral("Error"); - } - - case SoundManagement::SoundCategory_def::Unknown: - switch(id) - { - default: - return QStringLiteral("Error"); - } - - default: - return QStringLiteral("Error"); - } + case SoundManagement::SoundCategory_def::Aircraft: + return QStringLiteral("Aircraft"); + case SoundManagement::SoundCategory_def::Battlefield: + return QStringLiteral("Battlefield"); + case SoundManagement::SoundCategory_def::Boat: + return QStringLiteral("Boat"); + case SoundManagement::SoundCategory_def::Explosion: + return QStringLiteral("Explosion"); + case SoundManagement::SoundCategory_def::Helicopter: + return QStringLiteral("Helicopter"); + case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: + return QStringLiteral("MotorsAndUrbanTraffic"); + case SoundManagement::SoundCategory_def::Vehicle: + return QStringLiteral("Vehicle"); + case SoundManagement::SoundCategory_def::InsideBuilding: + return QStringLiteral("InsideBuilding"); + case SoundManagement::SoundCategory_def::Unknown: + return QStringLiteral("Unknown"); + default: + return QString(); + } } -QString SoundAreaHelper::soundName(const int &category, const int &id) +QString SoundAreaHelper::categoryName(const int32_t& category) { - return soundName(soundCategory(category), id); + return categoryName(soundCategory(category)); } - -int SoundAreaHelper::soundDuration(SoundManagement::SoundCategory category, const int &id) const +QString SoundAreaHelper::soundName(SoundManagement::SoundCategory category, const int& id) { - return soundDuration(static_cast(category.underlying()), id); + switch (category.underlying()) + { + case SoundManagement::SoundCategory_def::Aircraft: + switch (id) + { + case 1: + return QStringLiteral("Jet_Pass_by_Military"); + case 2: + return QStringLiteral("Military_Aircraft_Fires"); + case 3: + return QStringLiteral("Military_Aircraft_Fly_By"); + case 4: + return QStringLiteral("Military_Airplane_Drops"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Battlefield: + switch (id) + { + case 1: + return QStringLiteral("Battlefield_Ambience_Noise"); + case 2: + return QStringLiteral("Battlefield_Ambience_Tank"); + case 3: + return QStringLiteral("Battlefield_Ambience_War"); + case 4: + return QStringLiteral("Explosions_Battlefield"); + case 5: + return QStringLiteral("Explosions_Battlefield_1"); + case 6: + return QStringLiteral("Ground_Battle_with_Machine_Guns"); + case 7: + return QStringLiteral("Modern_Battlefield"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Boat: + switch (id) + { + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Explosion: + switch (id) + { + case 1: + return QStringLiteral("Explosion_Building_Crash"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Helicopter: + switch (id) + { + case 1: + return QStringLiteral("Helicopter_Crash"); + case 2: + return QStringLiteral("Helicopter_Fly_Overhead"); + case 3: + return QStringLiteral("Helicopter_Landing"); + case 4: + return QStringLiteral("Helicopter_Pass_by_Military"); + case 5: + return QStringLiteral("Helicopter_Take_off"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: + switch (id) + { + case 1: + return QStringLiteral("Big_City_Street_Traffic"); + case 2: + return QStringLiteral("City_Crossroads_Traffic"); + case 3: + return QStringLiteral("City_Street_Heavy_Traffic"); + case 4: + return QStringLiteral("City_Street_Noisy_Walking"); + case 5: + return QStringLiteral("Construction_Building_Ambient"); + case 6: + return QStringLiteral("Demonstration_and_Rioting"); + case 7: + return QStringLiteral("Noisy_City_Street"); + case 8: + return QStringLiteral("Stadium_Crowd_Ambient"); + case 9: + return QStringLiteral("Stadium_Crowd_Applause"); + case 10: + return QStringLiteral("Traffic_from_Car"); + case 11: + return QStringLiteral("Muezzincalling"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Vehicle: + switch (id) + { + case 1: + return QStringLiteral("Tank_Starting_and_Stopping"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::InsideBuilding: + switch (id) + { + case 1: + return QStringLiteral("Fire_quietly"); + case 2: + return QStringLiteral("Fire_a_little_louder"); + case 3: + return QStringLiteral("Fire_louder"); + case 4: + return QStringLiteral("Fire_loud"); + case 5: + return QStringLiteral("Extinguishing_Noise"); + case 7: + return QStringLiteral("This_Room_is_Destroyed"); + case 8: + return QStringLiteral("This_Building_is_Destroyed"); + default: + return QStringLiteral("Error"); + } + + case SoundManagement::SoundCategory_def::Unknown: + switch (id) + { + default: + return QStringLiteral("Error"); + } + + default: + return QStringLiteral("Error"); + } } -int SoundAreaHelper::soundDuration(const int &category, const int &id) const +QString SoundAreaHelper::soundName(const int& category, const int& id) { - SoundKey key{category, id}; - return m_soundDuration.contains(key) ? m_soundDuration.value(key) : 0; + return soundName(soundCategory(category), id); } - -QString SoundAreaHelper::egcuName(const int &id) const +int SoundAreaHelper::soundDuration(SoundManagement::SoundCategory category, const int& id) const { - return m_egcuNames.contains(id) ? m_egcuNames.value(id) : QString(); + return soundDuration(static_cast(category.underlying()), id); } - -QColor SoundAreaHelper::soundCategoryTextColor(const int32_t &category) +int SoundAreaHelper::soundDuration(const int& category, const int& id) const { - switch (category) - { - case SoundManagement::SoundCategory_def::Aircraft: return {Qt::white}; - case SoundManagement::SoundCategory_def::Battlefield: return {Qt::white}; - case SoundManagement::SoundCategory_def::Boat: return {Qt::black}; - case SoundManagement::SoundCategory_def::Explosion: return {Qt::white}; - case SoundManagement::SoundCategory_def::Helicopter: return {Qt::white}; - case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: return {Qt::white}; - case SoundManagement::SoundCategory_def::Vehicle: return {Qt::black}; - case SoundManagement::SoundCategory_def::InsideBuilding: return {Qt::black}; - case SoundManagement::SoundCategory_def::Unknown: return {Qt::white}; - default: - return {Qt::black}; - } + SoundKey key{category, id}; + return m_soundDuration.contains(key) ? m_soundDuration.value(key) : 0; } -QColor SoundAreaHelper::soundCategoryBackgroundColor(const int32_t &category) +QString SoundAreaHelper::egcuName(const int& id) const { - switch (category) - { - case SoundManagement::SoundCategory_def::Aircraft: return QColor::fromRgb( 25, 25, 112); - case SoundManagement::SoundCategory_def::Battlefield: return QColor::fromRgb(160, 82, 45); - case SoundManagement::SoundCategory_def::Boat: return QColor::fromRgb(127, 255, 212); - case SoundManagement::SoundCategory_def::Explosion: return QColor::fromRgb(255, 0, 0); - case SoundManagement::SoundCategory_def::Helicopter: return QColor::fromRgb(153, 50, 204); - case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: return QColor::fromRgb( 85, 107, 47); - case SoundManagement::SoundCategory_def::Vehicle: return QColor::fromRgb(255, 255, 0); - case SoundManagement::SoundCategory_def::InsideBuilding: return QColor::fromRgb(255, 160, 122); - case SoundManagement::SoundCategory_def::Unknown: return QColor::fromRgb(119, 136, 153); - default: - return {Qt::white}; - } + return m_egcuNames.contains(id) ? m_egcuNames.value(id) : QString(); } - -SoundManagement::SoundCategory SoundAreaHelper::soundCategory(const int &i) +QColor SoundAreaHelper::soundCategoryTextColor(const int32_t& category) { - switch (i) - { - case 1: return SoundManagement::SoundCategory_def::Aircraft; - case 2: return SoundManagement::SoundCategory_def::Battlefield; - case 3: return SoundManagement::SoundCategory_def::Boat; - case 4: return SoundManagement::SoundCategory_def::Explosion; - case 5: return SoundManagement::SoundCategory_def::Helicopter; - case 6: return SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic; - case 7: return SoundManagement::SoundCategory_def::Vehicle; - case 8: return SoundManagement::SoundCategory_def::InsideBuilding; - case 9: - default: - return SoundManagement::SoundCategory_def::Unknown; - } + switch (category) + { + case SoundManagement::SoundCategory_def::Aircraft: + return {Qt::white}; + case SoundManagement::SoundCategory_def::Battlefield: + return {Qt::white}; + case SoundManagement::SoundCategory_def::Boat: + return {Qt::black}; + case SoundManagement::SoundCategory_def::Explosion: + return {Qt::white}; + case SoundManagement::SoundCategory_def::Helicopter: + return {Qt::white}; + case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: + return {Qt::white}; + case SoundManagement::SoundCategory_def::Vehicle: + return {Qt::black}; + case SoundManagement::SoundCategory_def::InsideBuilding: + return {Qt::black}; + case SoundManagement::SoundCategory_def::Unknown: + return {Qt::white}; + default: + return {Qt::black}; + } } -} +QColor SoundAreaHelper::soundCategoryBackgroundColor(const int32_t& category) +{ + switch (category) + { + case SoundManagement::SoundCategory_def::Aircraft: + return QColor::fromRgb(25, 25, 112); + case SoundManagement::SoundCategory_def::Battlefield: + return QColor::fromRgb(160, 82, 45); + case SoundManagement::SoundCategory_def::Boat: + return QColor::fromRgb(127, 255, 212); + case SoundManagement::SoundCategory_def::Explosion: + return QColor::fromRgb(255, 0, 0); + case SoundManagement::SoundCategory_def::Helicopter: + return QColor::fromRgb(153, 50, 204); + case SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic: + return QColor::fromRgb(85, 107, 47); + case SoundManagement::SoundCategory_def::Vehicle: + return QColor::fromRgb(255, 255, 0); + case SoundManagement::SoundCategory_def::InsideBuilding: + return QColor::fromRgb(255, 160, 122); + case SoundManagement::SoundCategory_def::Unknown: + return QColor::fromRgb(119, 136, 153); + default: + return {Qt::white}; + } +} + +SoundManagement::SoundCategory SoundAreaHelper::soundCategory(const int& i) +{ + switch (i) + { + case 1: + return SoundManagement::SoundCategory_def::Aircraft; + case 2: + return SoundManagement::SoundCategory_def::Battlefield; + case 3: + return SoundManagement::SoundCategory_def::Boat; + case 4: + return SoundManagement::SoundCategory_def::Explosion; + case 5: + return SoundManagement::SoundCategory_def::Helicopter; + case 6: + return SoundManagement::SoundCategory_def::MotorsAndUrbanTraffic; + case 7: + return SoundManagement::SoundCategory_def::Vehicle; + case 8: + return SoundManagement::SoundCategory_def::InsideBuilding; + case 9: + default: + return SoundManagement::SoundCategory_def::Unknown; + } +} + +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.h old mode 100755 new mode 100644 index 94d395a75..619b56fad --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_helper.h @@ -1,91 +1,68 @@ - #pragma once - -#include #include - +#include namespace NGL { class INGLLogger; } - namespace EffectManagement { using SoundKey = QPair; - - - - class SoundAreaHelper { -public: - explicit SoundAreaHelper(SoundAreaHelper *helper); - explicit SoundAreaHelper(std::shared_ptr &ismDtc, - std::shared_ptr &somDtc); + public: + explicit SoundAreaHelper(SoundAreaHelper* helper); + explicit SoundAreaHelper(std::shared_ptr& ismDtc, + std::shared_ptr& somDtc); -public: - std::shared_ptr ismDtc() const { return m_ismDtc; } - std::shared_ptr somDtc() const { return m_somDtc; } + public: + std::shared_ptr ismDtc() const + { + return m_ismDtc; + } - + std::shared_ptr somDtc() const + { + return m_somDtc; + } - static QVector soundCategories(); + static QVector soundCategories(); - + static QString categoryName(SoundManagement::SoundCategory category); - static QString categoryName(SoundManagement::SoundCategory category); - + static QString categoryName(const int32_t& category); - static QString categoryName(const int32_t &category); + static QString soundName(SoundManagement::SoundCategory category, const int& id); - + static QString soundName(const int& category, const int& id); - static QString soundName(SoundManagement::SoundCategory category, const int &id); - + int soundDuration(SoundManagement::SoundCategory category, const int& id) const; - static QString soundName(const int &category, const int &id); + int soundDuration(const int& category, const int& id) const; + QString egcuName(const int& id) const; - + static QColor soundCategoryTextColor(const int32_t& category); - int soundDuration(SoundManagement::SoundCategory category, const int &id) const; + static QColor soundCategoryBackgroundColor(const int32_t& category); - + static SoundManagement::SoundCategory soundCategory(const int& i); - int soundDuration(const int &category, const int &id) const; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_ismDtc; + std::shared_ptr m_somDtc; + QMap m_egcuNames; + QMap m_soundDuration; +}; - - - QString egcuName(const int &id) const; - - - - static QColor soundCategoryTextColor(const int32_t &category); - - - static QColor soundCategoryBackgroundColor(const int32_t &category); - - - - static SoundManagement::SoundCategory soundCategory(const int &i); - -private: - -NGL::INGLLogger &m_logger; - std::shared_ptr m_ismDtc; - std::shared_ptr m_somDtc; - - QMap m_egcuNames; - QMap m_soundDuration; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.cpp old mode 100755 new mode 100644 index cdcd1d28b..0b0b9a318 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.cpp @@ -1,167 +1,150 @@ - #include "efm_sound_area_select_dialog.h" -#include -#include "ui_efm_sound_area_select_dialog.h" -#include "efm_sound_area_select_model.h" -#include "efm_sound_area_edit_dialog.h" + #include "../logger.h" +#include "efm_sound_area_edit_dialog.h" +#include "efm_sound_area_select_model.h" +#include "ui_efm_sound_area_select_dialog.h" #include #include -#include #include - +#include +#include namespace EffectManagement { - - - - -SoundAreaSelectDialog::SoundAreaSelectDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_model(new SoundAreaSelectModel(this)) - , m_ui(new Ui::SoundAreasDialog) +SoundAreaSelectDialog::SoundAreaSelectDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_model(new SoundAreaSelectModel(this)), m_ui(new Ui::SoundAreasDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Stop All Sounds")); - m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setIcon(QIcon(QStringLiteral("icon:avm_stop.svg"))); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setText(tr("Stop All Sounds")); + m_buttonBox->getButton(LtsWidgets::DialogButton::Edit)->setIcon(QIcon(QStringLiteral("icon:avm_stop.svg"))); } SoundAreaSelectDialog::~SoundAreaSelectDialog() { - delete m_ui; + delete m_ui; } - - - - -void SoundAreaSelectDialog::onSelectSoundArea(const QModelIndex &index) +void SoundAreaSelectDialog::onSelectSoundArea(const QModelIndex& index) { - if (!index.isValid()) - return; + if (!index.isValid()) + return; - if (index.column() == SoundAreaSelectModel::Column::Stop) - { - onStopSounds(index); - return; - } - - SoundArea soundArea = m_model->getRowData(index.row()); - SoundAreaEditDialog *dialog = new SoundAreaEditDialog(soundArea); - dialog->init(m_session); - addDialog(dialog, menuGroup(), soundArea.displayName, LtsWidgets::LayoutArea::eDialogTab); -} - -void SoundAreaSelectDialog::onStopSounds(const QModelIndex &index) -{ - SoundArea soundArea = m_model->getRowData(index.row()); - - if ( soundArea.egcuIds.isEmpty()) - return; - - const QVector &egcuIds = soundArea.egcuIds; - for (const auto &egcu : std::as_const(egcuIds)) - { - SoundManagement::StopAllSoundsRequest req(egcu); - m_requestHelper->startSingleRequest([this, req]() + if (index.column() == SoundAreaSelectModel::Column::Stop) { - return m_somFtc->stopAllSoundsRequest(req, this); - }); - } + onStopSounds(index); + return; + } + + SoundArea soundArea = m_model->getRowData(index.row()); + SoundAreaEditDialog* dialog = new SoundAreaEditDialog(soundArea); + dialog->init(m_session); + addDialog(dialog, menuGroup(), soundArea.displayName, LtsWidgets::LayoutArea::eDialogTab); +} + +void SoundAreaSelectDialog::onStopSounds(const QModelIndex& index) +{ + SoundArea soundArea = m_model->getRowData(index.row()); + + if (soundArea.egcuIds.isEmpty()) + return; + + const QVector& egcuIds = soundArea.egcuIds; + for (const auto& egcu : std::as_const(egcuIds)) + { + SoundManagement::StopAllSoundsRequest req(egcu); + m_requestHelper->startSingleRequest([this, req]() { return m_somFtc->stopAllSoundsRequest(req, this); }); + } } void SoundAreaSelectDialog::onStopAllSounds() { - const QVector &soundAreas = m_model->soundAreas(); - for (const auto &soundArea : std::as_const(soundAreas)) - { - - const QVector &egcuIds = soundArea.egcuIds; - for (const auto &egcu : std::as_const(egcuIds)) + const QVector& soundAreas = m_model->soundAreas(); + for (const auto& soundArea : std::as_const(soundAreas)) { - SoundManagement::StopAllSoundsRequest req(egcu); - m_requestHelper->startSingleRequest([this, req]() { - return m_somFtc->stopAllSoundsRequest(req, this); - }); + + const QVector& egcuIds = soundArea.egcuIds; + for (const auto& egcu : std::as_const(egcuIds)) + { + SoundManagement::StopAllSoundsRequest req(egcu); + m_requestHelper->startSingleRequest([this, req]() { return m_somFtc->stopAllSoundsRequest(req, this); }); + } } - } } - - - - -bool SoundAreaSelectDialog::init(LtsSession::LtsSessionDataDds *session, const QString &menuGroup) +bool SoundAreaSelectDialog::init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup) { - DEBUG_LOG(m_logger) << "init"; + DEBUG_LOG(m_logger) << "init"; - m_session = session; - setMenuGroup(menuGroup); + m_session = session; + setMenuGroup(menuGroup); - std::shared_ptr ismDtc; - std::shared_ptr somDtc; + std::shared_ptr ismDtc; + std::shared_ptr somDtc; - if (!m_session->getDtc(ismDtc)) - { - ERROR_LOG(m_logger) << "connection to ISM-DTC failed"; - return false; - } + if (!m_session->getDtc(ismDtc)) + { + ERROR_LOG(m_logger) << "connection to ISM-DTC failed"; + return false; + } - if (!m_session->getDtc(somDtc)) - { - ERROR_LOG(m_logger) << "connection to SOM-DTC failed"; - return false; - } + if (!m_session->getDtc(somDtc)) + { + ERROR_LOG(m_logger) << "connection to SOM-DTC failed"; + return false; + } - if (!m_session->getFtc(m_somFtc)) - { - ERROR_LOG(m_logger) << "connection to SOM-FTC failed"; - return false; - } + if (!m_session->getFtc(m_somFtc)) + { + ERROR_LOG(m_logger) << "connection to SOM-FTC failed"; + return false; + } - if (!m_model->init(ismDtc, somDtc)) - { - ERROR_LOG(m_logger) << "sound area select model initialization failed"; - return false; - } + if (!m_model->init(ismDtc, somDtc)) + { + ERROR_LOG(m_logger) << "sound area select model initialization failed"; + return false; + } - m_ui->tvSoundlist->setModel(m_model); + m_ui->tvSoundlist->setModel(m_model); - SoundAreaSelectDelegate *delegate = new SoundAreaSelectDelegate(m_model); - m_ui->tvSoundlist->setItemDelegate(delegate); + SoundAreaSelectDelegate* delegate = new SoundAreaSelectDelegate(m_model); + m_ui->tvSoundlist->setItemDelegate(delegate); - m_ui->tvSoundlist->horizontalHeader()->resizeSection(SoundAreaSelectModel::Column::Id, 50); - m_ui->tvSoundlist->horizontalHeader()->resizeSection(SoundAreaSelectModel::Column::Stop, 100); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Id, QHeaderView::Fixed); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Name, QHeaderView::ResizeToContents); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::AreaEgcu, QHeaderView::ResizeToContents); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Egcus, QHeaderView::Stretch); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::ActiveSounds, QHeaderView::ResizeToContents); - m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Stop, QHeaderView::Fixed); + m_ui->tvSoundlist->horizontalHeader()->resizeSection(SoundAreaSelectModel::Column::Id, 50); + m_ui->tvSoundlist->horizontalHeader()->resizeSection(SoundAreaSelectModel::Column::Stop, 100); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Id, QHeaderView::Fixed); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Name, + QHeaderView::ResizeToContents); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::AreaEgcu, + QHeaderView::ResizeToContents); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Egcus, + QHeaderView::Stretch); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::ActiveSounds, + QHeaderView::ResizeToContents); + m_ui->tvSoundlist->horizontalHeader()->setSectionResizeMode(SoundAreaSelectModel::Column::Stop, QHeaderView::Fixed); - connect(m_ui->tvSoundlist, &QTableView::clicked, this, &SoundAreaSelectDialog::onSelectSoundArea); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SoundAreaSelectDialog::onStopAllSounds); + connect(m_ui->tvSoundlist, &QTableView::clicked, this, &SoundAreaSelectDialog::onSelectSoundArea); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SoundAreaSelectDialog::onStopAllSounds); - DEBUG_LOG(m_logger) << "init successful"; - return true; + DEBUG_LOG(m_logger) << "init successful"; + return true; } - void SoundAreaSelectDialog::retranslate() { - translate(m_ui, tr("Sound Area Select")); + translate(m_ui, tr("Sound Area Select")); } -void SoundAreaSelectDialog::onStopAllSoundsReply(const Core::FunctionReplyObject &replyObject) +void SoundAreaSelectDialog::onStopAllSoundsReply(const Core::FunctionReplyObject& replyObject) { - m_requestHelper->requestReply(replyObject); + m_requestHelper->requestReply(replyObject); } -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.h old mode 100755 new mode 100644 index b58c295de..eabf943fa --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_dialog.h @@ -1,11 +1,9 @@ - #pragma once -#include #include - +#include namespace NGL { @@ -27,54 +25,43 @@ namespace Ui class SoundAreasDialog; } - namespace EffectManagement { class SoundAreaSelectModel; - - -class SoundAreaSelectDialog - : public LtsWidgets::LtsDialog - , protected SoundManagement::Interface::Ftc::StopAllSoundsReplyHandler +class SoundAreaSelectDialog : public LtsWidgets::LtsDialog, + protected SoundManagement::Interface::Ftc::StopAllSoundsReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit SoundAreaSelectDialog(QWidget *parent = nullptr); - ~SoundAreaSelectDialog(); + public: + explicit SoundAreaSelectDialog(QWidget* parent = nullptr); + ~SoundAreaSelectDialog(); + private slots: -private slots: - + void onSelectSoundArea(const QModelIndex& index); - void onSelectSoundArea(const QModelIndex &index); - + void onStopSounds(const QModelIndex& index); - void onStopSounds(const QModelIndex &index); - + void onStopAllSounds(); - void onStopAllSounds(); + public: + bool init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup); + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onStopAllSoundsReply(const Core::FunctionReplyObject& replyObject) override final; -public: - bool init(LtsSession::LtsSessionDataDds *session, const QString &menuGroup); + std::shared_ptr m_somFtc{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; -private: + SoundAreaSelectModel* m_model{nullptr}; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onStopAllSoundsReply(const Core::FunctionReplyObject &replyObject) override final; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + Ui::SoundAreasDialog* m_ui{nullptr}; +}; - - std::shared_ptr m_somFtc{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - - SoundAreaSelectModel *m_model{nullptr}; - - LtsSession::LtsSessionDataDds *m_session{nullptr}; - Ui::SoundAreasDialog *m_ui{nullptr}; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.cpp old mode 100755 new mode 100644 index 8a2c4add9..06bcf77dd --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.cpp @@ -1,282 +1,239 @@ - #include "efm_sound_area_select_model.h" -#include "efm_sound_area_helper.h" -#include "../logger.h" -#include +#include "../logger.h" +#include "efm_sound_area_helper.h" #include #include - +#include namespace EffectManagement { - - - - -SoundAreaSelectDelegate::SoundAreaSelectDelegate(QObject *parent) : QItemDelegate(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} - - - - - -void SoundAreaSelectDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +SoundAreaSelectDelegate::SoundAreaSelectDelegate(QObject* parent) + : QItemDelegate(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - if (index.column() != SoundAreaSelectModel::Column::Stop) - { - QItemDelegate::paint(painter, option, index); - return; - } - - QStyleOptionButton button; - button.rect = option.rect; - button.state = index.data().toBool() ? QStyle::State_Enabled : QStyle::State_ReadOnly; - button.iconSize = QSize(25, 25); - button.icon = QIcon(QStringLiteral("icon:avm_stop.svg")); - - QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); } - - - - -SoundAreaSelectModel::SoundAreaSelectModel(QWidget *parent) - : LtsWidgets::LtsAbstractTableModel( +void SoundAreaSelectDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, + const QModelIndex& index) const +{ + if (index.column() != SoundAreaSelectModel::Column::Stop) { - tr("ID"), - tr("Name"), - tr("Main EGCU"), - tr("Sound Area EGCUs"), - tr("Active Sounds"), - tr("Stop") - }, parent) + QItemDelegate::paint(painter, option, index); + return; + } + + QStyleOptionButton button; + button.rect = option.rect; + button.state = index.data().toBool() ? QStyle::State_Enabled : QStyle::State_ReadOnly; + button.iconSize = QSize(25, 25); + button.icon = QIcon(QStringLiteral("icon:avm_stop.svg")); + + QApplication::style()->drawControl(QStyle::CE_PushButton, &button, painter); +} + +SoundAreaSelectModel::SoundAreaSelectModel(QWidget* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("ID"), tr("Name"), tr("Main EGCU"), tr("Sound Area EGCUs"), tr("Active Sounds"), tr("Stop")}, parent) { } - - - - -bool SoundAreaSelectModel::onSoundStateChanged(const SoundManagement::SoundState &data, DataModification modType) +bool SoundAreaSelectModel::onSoundStateChanged(const SoundManagement::SoundState& data, DataModification modType) { - for (auto &soundArea : m_vecData) - { - if (soundArea.egcuIds.contains(data.egcuId())) + for (auto& soundArea : m_vecData) { - QHash::iterator it = soundArea.activeSounds.find(data.id()); - switch (modType) - { - case DataModification::eAdded: - if (it != soundArea.activeSounds.end()) + if (soundArea.egcuIds.contains(data.egcuId())) { - DEBUG_LOG(m_logger) << "'" << m_helper->soundName(data.category(), data.soundId()) << "' is already active"; - return false; - } - else - { - soundArea.activeSounds.insert(data.id(), data); - emit dataChanged( - SoundAreaSelectModel::index(0, Column::ActiveSounds), - SoundAreaSelectModel::index(m_vecData.size(), Column::ActiveSounds) - ); - return true; - } + QHash::iterator it = soundArea.activeSounds.find(data.id()); + switch (modType) + { + case DataModification::eAdded: + if (it != soundArea.activeSounds.end()) + { + DEBUG_LOG(m_logger) + << "'" << m_helper->soundName(data.category(), data.soundId()) << "' is already active"; + return false; + } + else + { + soundArea.activeSounds.insert(data.id(), data); + emit dataChanged(SoundAreaSelectModel::index(0, Column::ActiveSounds), + SoundAreaSelectModel::index(m_vecData.size(), Column::ActiveSounds)); + return true; + } - case DataModification::eRemoved: - if (it == soundArea.activeSounds.end()) - { - DEBUG_LOG(m_logger) << "'" << m_helper->soundName(data.category(), data.soundId()) << "' is not active"; - return false; - } - else - { - soundArea.activeSounds.remove(it.key()); - emit dataChanged( - SoundAreaSelectModel::index(0, Column::ActiveSounds), - SoundAreaSelectModel::index(m_vecData.size(), Column::ActiveSounds) - ); - return true; - } + case DataModification::eRemoved: + if (it == soundArea.activeSounds.end()) + { + DEBUG_LOG(m_logger) + << "'" << m_helper->soundName(data.category(), data.soundId()) << "' is not active"; + return false; + } + else + { + soundArea.activeSounds.remove(it.key()); + emit dataChanged(SoundAreaSelectModel::index(0, Column::ActiveSounds), + SoundAreaSelectModel::index(m_vecData.size(), Column::ActiveSounds)); + return true; + } - case DataModification::eModified: - default: - return false; - } - } - } + case DataModification::eModified: + default: + return false; + } + } + } - return false; + return false; } - - - - -bool SoundAreaSelectModel::init(const std::shared_ptr &ismDtc, - const std::shared_ptr &somDtc) +bool SoundAreaSelectModel::init(const std::shared_ptr& ismDtc, + const std::shared_ptr& somDtc) { - DEBUG_LOG(m_logger) << "init"; + DEBUG_LOG(m_logger) << "init"; - m_ismDtc = ismDtc; - m_somDtc = somDtc; + m_ismDtc = ismDtc; + m_somDtc = somDtc; - m_helper = std::make_shared(new SoundAreaHelper(m_ismDtc, m_somDtc)); + m_helper = std::make_shared(new SoundAreaHelper(m_ismDtc, m_somDtc)); - - connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::effectAreaChanged, this, - [this](const InfrastructureManagement::EffectArea &data, DataModification modType) - { - return onDataChanged(SoundArea(data), modType); - }); + connect(m_ismDtc.get(), &InfrastructureManagement::Interface::Dtc::effectAreaChanged, this, + [this](const InfrastructureManagement::EffectArea& data, DataModification modType) { + return onDataChanged(SoundArea(data), modType); + }); - m_ismDtc->effectAreas([this](const InfrastructureManagement::EffectArea &effectArea) - { - insertRow(SoundArea(effectArea)); - }); + m_ismDtc->effectAreas( + [this](const InfrastructureManagement::EffectArea& effectArea) { insertRow(SoundArea(effectArea)); }); - - connect(m_somDtc.get(), &SoundManagement::Interface::Dtc::soundStateChanged, this, - [this](const SoundManagement::SoundState &data, DataModification modType) - { - return onSoundStateChanged(data, modType); - }); + connect(m_somDtc.get(), &SoundManagement::Interface::Dtc::soundStateChanged, this, + [this](const SoundManagement::SoundState& data, DataModification modType) { + return onSoundStateChanged(data, modType); + }); - m_somDtc->soundStates([this](const SoundManagement::SoundState &soundState) - { - onSoundStateChanged(soundState, DataModification::eAdded); - }); + m_somDtc->soundStates([this](const SoundManagement::SoundState& soundState) { + onSoundStateChanged(soundState, DataModification::eAdded); + }); - DEBUG_LOG(m_logger) << "init successful"; - return true; + DEBUG_LOG(m_logger) << "init successful"; + return true; } - -bool SoundAreaSelectModel::insertRow(const SoundArea &item) +bool SoundAreaSelectModel::insertRow(const SoundArea& item) { - beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); - m_vecData.push_back(item); - endInsertRows(); - return true; + beginInsertRows(QModelIndex(), m_vecData.size(), m_vecData.size()); + m_vecData.push_back(item); + endInsertRows(); + return true; } bool SoundAreaSelectModel::removeRow(int row) { - removeRows(row, 1); - return true; + removeRows(row, 1); + return true; } -QVariant SoundAreaSelectModel::data(const QModelIndex &index, int role) const +QVariant SoundAreaSelectModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) - return QVariant(); + if (!index.isValid()) + return QVariant(); - if ( (role != Qt::DisplayRole) && (role != Qt::ToolTipRole) ) - return QVariant{}; + if ((role != Qt::DisplayRole) && (role != Qt::ToolTipRole)) + return QVariant{}; - const SoundArea &soundArea = m_vecData.at(index.row()); - std::string str = ""; + const SoundArea& soundArea = m_vecData.at(index.row()); + std::string str = ""; - switch (role) - { - case Qt::DisplayRole: - switch (index.column()) + switch (role) { - case Column::Id: return soundArea.id; + case Qt::DisplayRole: + switch (index.column()) + { + case Column::Id: + return soundArea.id; - case Column::Name: return soundArea.displayName; + case Column::Name: + return soundArea.displayName; - case Column::AreaEgcu: return m_helper->egcuName(soundArea.areaEgcuId); + case Column::AreaEgcu: + return m_helper->egcuName(soundArea.areaEgcuId); - case Column::Egcus: - for (const auto &egcu : soundArea.egcuIds) - str += m_helper->egcuName(egcu).toStdString() + ", "; - if (str.size() > 1) - str = str.substr(0, str.length() - 2); - return QString::fromStdString(str); + case Column::Egcus: + for (const auto& egcu : soundArea.egcuIds) + str += m_helper->egcuName(egcu).toStdString() + ", "; + if (str.size() > 1) + str = str.substr(0, str.length() - 2); + return QString::fromStdString(str); - case Column::ActiveSounds: - if (soundArea.activeSounds.size() > 0) - { - SoundManagement::SoundState sound = soundArea.activeSounds.begin().value(); - return m_helper->soundName(sound.category(), sound.soundId()); - } - return QString(); + case Column::ActiveSounds: + if (soundArea.activeSounds.size() > 0) + { + SoundManagement::SoundState sound = soundArea.activeSounds.begin().value(); + return m_helper->soundName(sound.category(), sound.soundId()); + } + return QString(); - case Column::Stop: - return soundArea.activeSounds.size() > 0; + case Column::Stop: + return soundArea.activeSounds.size() > 0; - default: - Q_UNREACHABLE(); - return QVariant{}; - } + default: + Q_UNREACHABLE(); + return QVariant{}; + } - case Qt::ToolTipRole: - switch (index.column()) - { - case Column::Id: - case Column::Name: - case Column::AreaEgcu: - return data(index, Qt::DisplayRole); + case Qt::ToolTipRole: + switch (index.column()) + { + case Column::Id: + case Column::Name: + case Column::AreaEgcu: + return data(index, Qt::DisplayRole); - case Column::Egcus: - for (const auto &egcu : soundArea.egcuIds) - str += m_helper->egcuName(egcu).toStdString() + "\n"; - if (str.size() > 1) - str = str.substr(0, str.length() - 1); - return QString::fromStdString(str); + case Column::Egcus: + for (const auto& egcu : soundArea.egcuIds) + str += m_helper->egcuName(egcu).toStdString() + "\n"; + if (str.size() > 1) + str = str.substr(0, str.length() - 1); + return QString::fromStdString(str); - case Column::ActiveSounds: - for (const auto &sound : soundArea.activeSounds) - str += m_helper->soundName(sound.category(), sound.soundId()).toStdString() + "\n"; - if (str.size() > 1) - str = str.substr(0, str.length() - 1); - return QString::fromStdString(str); + case Column::ActiveSounds: + for (const auto& sound : soundArea.activeSounds) + str += m_helper->soundName(sound.category(), sound.soundId()).toStdString() + "\n"; + if (str.size() > 1) + str = str.substr(0, str.length() - 1); + return QString::fromStdString(str); - case Column::Stop: - return QStringLiteral("Stop all Sounds"); + case Column::Stop: + return QStringLiteral("Stop all Sounds"); - default: - Q_UNREACHABLE(); - return QVariant(); - } - - default: - Q_UNREACHABLE(); - return QVariant(); - } + default: + Q_UNREACHABLE(); + return QVariant(); + } + default: + Q_UNREACHABLE(); + return QVariant(); + } } - - - - -bool SoundAreaSelectModel::onDataChanged(const SoundArea &data, DataModification modType) +bool SoundAreaSelectModel::onDataChanged(const SoundArea& data, DataModification modType) { - if (modType == DataModification::eAdded) - return insertRow(data); + if (modType == DataModification::eAdded) + return insertRow(data); - int row = indexOf(data); - if (modType == DataModification::eRemoved) - return removeRow(row); + int row = indexOf(data); + if (modType == DataModification::eRemoved) + return removeRow(row); - return setRowData(row, data); + return setRowData(row, data); } - - - - -int SoundAreaSelectModel::indexOf(const SoundArea &data) const +int SoundAreaSelectModel::indexOf(const SoundArea& data) const { - return m_vecData.indexOf(data); + return m_vecData.indexOf(data); } -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.h old mode 100755 new mode 100644 index b1527dcc7..28ca7c763 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_sound_area_select_model.h @@ -1,25 +1,21 @@ - #pragma once #include "efm_sound_area.h" -#include -#include #include +#include +#include +#include #include #include -#include - - namespace NGL { class INGLLogger; } - namespace EffectManagement { @@ -27,65 +23,52 @@ using SoundKey = QPair; class SoundAreaHelper; - - -class SoundAreaSelectDelegate - : public QItemDelegate +class SoundAreaSelectDelegate : public QItemDelegate { - Q_OBJECT + Q_OBJECT -public: - SoundAreaSelectDelegate(QObject *parent = nullptr); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + public: + SoundAreaSelectDelegate(QObject* parent = nullptr); + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; +}; -}; - - - - - -class SoundAreaSelectModel final - : public LtsWidgets::LtsAbstractTableModel +class SoundAreaSelectModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Column { Id, Name, AreaEgcu, Egcus, ActiveSounds, Stop }; + public: + enum Column { Id, Name, AreaEgcu, Egcus, ActiveSounds, Stop }; - explicit SoundAreaSelectModel(QWidget *parent = nullptr); + explicit SoundAreaSelectModel(QWidget* parent = nullptr); + private slots: -private slots: - + bool onSoundStateChanged(const SoundManagement::SoundState& data, DataModification modType); - bool onSoundStateChanged(const SoundManagement::SoundState &data, DataModification modType); + public: + bool init(const std::shared_ptr& ismDtc, + const std::shared_ptr& somDtc); + QVector soundAreas() const + { + return m_vecData; + } -public: - bool init(const std::shared_ptr &ismDtc, - const std::shared_ptr &somDtc); + bool insertRow(const SoundArea& item) override; + bool removeRow(int row) override; + QVariant data(const QModelIndex& index, int role) const override; - QVector soundAreas() const { return m_vecData; } + protected: + NGL::INGLLogger& m_logger; + bool onDataChanged(const SoundArea& data, DataModification modType) override; - bool insertRow(const SoundArea &item) override; - bool removeRow(int row) override; - QVariant data(const QModelIndex &index, int role) const override; + private: + int indexOf(const SoundArea& data) const; -protected: + std::shared_ptr m_ismDtc{nullptr}; + std::shared_ptr m_somDtc{nullptr}; -NGL::INGLLogger &m_logger; - bool onDataChanged(const SoundArea &data, DataModification modType) override; + std::shared_ptr m_helper{nullptr}; +}; -private: - - - int indexOf(const SoundArea &data) const; - - - std::shared_ptr m_ismDtc{nullptr}; - std::shared_ptr m_somDtc{nullptr}; - - std::shared_ptr m_helper{nullptr}; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.cpp old mode 100755 new mode 100644 index 6042e8981..beab25d9e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.cpp @@ -1,29 +1,29 @@ - #include "efm_switch_item_delegate.h" -#include "../logger.h" -#include +#include "../logger.h" + +#include namespace EffectManagement { -const QIcon SwitchItemDelegate::s_iconOn = QIcon(QStringLiteral("icon:switch_on.svg")); +const QIcon SwitchItemDelegate::s_iconOn = QIcon(QStringLiteral("icon:switch_on.svg")); const QIcon SwitchItemDelegate::s_iconOff = QIcon(QStringLiteral("icon:switch_off.svg")); - -SwitchItemDelegate::SwitchItemDelegate(QObject *parent) : QStyledItemDelegate(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { -} - -void SwitchItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +SwitchItemDelegate::SwitchItemDelegate(QObject* parent) + : QStyledItemDelegate(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - if (index.data().toInt() == 1) - s_iconOn.paint(painter, option.rect, Qt::AlignCenter); - else if (index.data().toInt() == -1) - s_iconOff.paint(painter, option.rect, Qt::AlignCenter); } -} +void SwitchItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const +{ + if (index.data().toInt() == 1) + s_iconOn.paint(painter, option.rect, Qt::AlignCenter); + else if (index.data().toInt() == -1) + s_iconOff.paint(painter, option.rect, Qt::AlignCenter); +} + +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.h old mode 100755 new mode 100644 index 056a815c5..14aecd258 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/SoundArea/efm_switch_item_delegate.h @@ -1,35 +1,30 @@ - #pragma once #include - namespace NGL { class INGLLogger; } - namespace EffectManagement { -class SwitchItemDelegate - : public QStyledItemDelegate +class SwitchItemDelegate : public QStyledItemDelegate { - Q_OBJECT + Q_OBJECT -public: - SwitchItemDelegate(QObject *parent = nullptr); + public: + SwitchItemDelegate(QObject* parent = nullptr); - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; -private: + private: + NGL::INGLLogger& m_logger; + static const QIcon s_iconOn; + static const QIcon s_iconOff; +}; -NGL::INGLLogger &m_logger; - static const QIcon s_iconOn; - static const QIcon s_iconOff; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/efm_sound_management_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/efm_sound_management_dialog.h old mode 100755 new mode 100644 index a2d6d0f37..652c23ebb --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/efm_sound_management_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectManagement/Gui/efm_sound_management_dialog.h @@ -1,17 +1,15 @@ - #pragma once #include "efm_effect_area.h" #include "efm_sound_helper.h" -#include #include +#include #include #include - namespace NGL { class INGLLogger; @@ -32,54 +30,49 @@ namespace Ui class SoundManagementDialog; } - namespace EffectManagement { class SoundTreeModel; class SoundPlaylistModel; - -class SoundManagementDialog - : public LtsWidgets::LtsDialog - , protected SoundManagement::Interface::Ftc::ControlSoundReplyHandler +class SoundManagementDialog : public LtsWidgets::LtsDialog, + protected SoundManagement::Interface::Ftc::ControlSoundReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit SoundManagementDialog(const EffectAreaData &data, QWidget *parent = nullptr); - ~SoundManagementDialog(); + public: + explicit SoundManagementDialog(const EffectAreaData& data, QWidget* parent = nullptr); + ~SoundManagementDialog(); + private slots: + void onAddSoundToPlaylist(const SoundKey& key); + void onStopAllSounds(); -private slots: - void onAddSoundToPlaylist(const SoundKey &key); - void onStopAllSounds(); + public: + bool init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup); -public: - bool init(LtsSession::LtsSessionDataDds *session, const QString &menuGroup); + private: + NGL::INGLLogger& m_logger; + void onControlSoundReply(const Core::FunctionReplyObject& replyObject) override final; + void retranslate() override; + bool apply() override; -private: + std::shared_ptr m_somDtc{nullptr}; + std::shared_ptr m_somFtc{nullptr}; + std::shared_ptr m_helper{nullptr}; -NGL::INGLLogger &m_logger; - void onControlSoundReply(const Core::FunctionReplyObject &replyObject) override final; - void retranslate() override; - bool apply() override; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; - std::shared_ptr m_somDtc{nullptr}; - std::shared_ptr m_somFtc{nullptr}; - std::shared_ptr m_helper{nullptr}; + EffectAreaData* m_data{nullptr}; + SoundTreeModel* m_treeModel{nullptr}; + SoundPlaylistModel* m_playlistModel{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; + QHash m_egcuCheckBoxes; + QString m_menuGroup; - EffectAreaData *m_data{nullptr}; - SoundTreeModel *m_treeModel{nullptr}; - SoundPlaylistModel *m_playlistModel{nullptr}; + Ui::SoundManagementDialog* m_ui{nullptr}; +}; - QHash m_egcuCheckBoxes; - QString m_menuGroup; - - Ui::SoundManagementDialog *m_ui{nullptr}; -}; - -} +} // namespace EffectManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.cpp old mode 100755 new mode 100644 index 83406957f..feeeff41f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.cpp @@ -1,343 +1,336 @@ - #include "esc_firing_explosion.h" -#include "ui_esc_firing_explosion.h" -#include "esc_safety_confirmation_widget.h" + #include "esc_order_edit.h" +#include "esc_safety_confirmation_widget.h" +#include "ui_esc_firing_explosion.h" namespace EffectShowClient { -FiringExplosion::FiringExplosion(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_timer(new QTimer(this)) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_session(nullptr) - , m_safetyConfirmationWidget(nullptr) - , m_ui(new Ui::FiringExplosion) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_idOrder(0) - , m_idEffectShow(0) - , m_shotsAvail(0) - , m_isClearance(true) - , m_firingClearanceCountDown(0) - , m_endOfFiringClearanceCountDown(0) +FiringExplosion::FiringExplosion(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_timer(new QTimer(this)), + m_dtc(nullptr), m_ftc(nullptr), m_session(nullptr), m_safetyConfirmationWidget(nullptr), + m_ui(new Ui::FiringExplosion), m_requestHelper(new LtsUtils::RequestHelper(this)), m_idOrder(0), + m_idEffectShow(0), m_shotsAvail(0), m_isClearance(true), m_firingClearanceCountDown(0), + m_endOfFiringClearanceCountDown(0) { - m_ui->setupUi(this); - m_ui->pbFire->setEnabled(false); - connect(m_ui->pbApply, &QPushButton::clicked, - this, &FiringExplosion::onApply); - connect(m_ui->pbFire, &QPushButton::clicked, - this, &FiringExplosion::onFire); - connect(m_ui->pbInterrupt, &QPushButton::clicked, - this, &FiringExplosion::onInterrupt); - connect(m_timer, &QTimer::timeout, this, &FiringExplosion::onFiringClearanceCountDown); + m_ui->setupUi(this); + m_ui->pbFire->setEnabled(false); + connect(m_ui->pbApply, &QPushButton::clicked, this, &FiringExplosion::onApply); + connect(m_ui->pbFire, &QPushButton::clicked, this, &FiringExplosion::onFire); + connect(m_ui->pbInterrupt, &QPushButton::clicked, this, &FiringExplosion::onInterrupt); + connect(m_timer, &QTimer::timeout, this, &FiringExplosion::onFiringClearanceCountDown); - - QFont pbFont = m_ui->pbApply->font(); + QFont pbFont = m_ui->pbApply->font(); #ifdef TABLET_MODE - pbFont.setPointSizeF(pbFont.pointSizeF()*1.5); + pbFont.setPointSizeF(pbFont.pointSizeF() * 1.5); #endif - m_ui->pbApply->setFont(pbFont); - m_ui->pbFire->setFont(pbFont); - m_ui->pbInterrupt->setFont(pbFont); - - setOnlineHelpFilename(QLatin1String("OC-Firing_Explosive")); + m_ui->pbApply->setFont(pbFont); + m_ui->pbFire->setFont(pbFont); + m_ui->pbInterrupt->setFont(pbFont); + setOnlineHelpFilename(QLatin1String("OC-Firing_Explosive")); } FiringExplosion::~FiringExplosion() { - delete m_ui; + delete m_ui; } -bool FiringExplosion::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, bool freeForm) +bool FiringExplosion::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + LtsSession::LtsSession* session, bool freeForm) { - DEBUG_LOG(m_logger) << "FiringExplosion::init()"; + DEBUG_LOG(m_logger) << "FiringExplosion::init()"; - if (!dtc || !ftc) - { - ERROR_LOG(m_logger) << "FiringExplosion::init() Invalid shared_ptr!"; - return false; - } + if (!dtc || !ftc) + { + ERROR_LOG(m_logger) << "FiringExplosion::init() Invalid shared_ptr!"; + return false; + } - m_dtc = dtc; - m_ftc = ftc; - m_session = session; + m_dtc = dtc; + m_ftc = ftc; + m_session = session; - m_safetyConfirmationWidget = new SafetyConfirmationWidget(this); - if (!m_safetyConfirmationWidget->init(m_ftc)) - { - ERROR_LOG(m_logger) << "Can't create SafetiConfirmationWidget"; - return false; - } - m_ui->mainVertLayout->insertWidget(3, m_safetyConfirmationWidget); + m_safetyConfirmationWidget = new SafetyConfirmationWidget(this); + if (!m_safetyConfirmationWidget->init(m_ftc)) + { + ERROR_LOG(m_logger) << "Can't create SafetiConfirmationWidget"; + return false; + } + m_ui->mainVertLayout->insertWidget(3, m_safetyConfirmationWidget); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingExplosionEntityChanged, - this, &FiringExplosion::onFiringExplosionEntityChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, - this, &FiringExplosion::onOperatingConditionEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingExplosionEntityChanged, this, + &FiringExplosion::onFiringExplosionEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, this, + &FiringExplosion::onOperatingConditionEntityChanged); - - if (!freeForm) - onFiringExplosionEntityChanged(m_dtc->firingExplosionEntity(), DataModification::eAdded); + if (!freeForm) + onFiringExplosionEntityChanged(m_dtc->firingExplosionEntity(), DataModification::eAdded); - m_buttonBox->connectButton(LtsWidgets::DialogButton::No, this, &FiringExplosion::onAbort); - m_buttonBox->getButton(LtsWidgets::DialogButton::No)->setText(tr("Abort")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::No, this, &FiringExplosion::onAbort); + m_buttonBox->getButton(LtsWidgets::DialogButton::No)->setText(tr("Abort")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Yes, this, &FiringExplosion::onCarriedOut); - m_buttonBox->getButton(LtsWidgets::DialogButton::Yes)->setText(tr("Carried Out")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Yes, this, &FiringExplosion::onCarriedOut); + m_buttonBox->getButton(LtsWidgets::DialogButton::Yes)->setText(tr("Carried Out")); - m_ui->sbDuration->setMinimum(5); - return true; + m_ui->sbDuration->setMinimum(5); + return true; } void FiringExplosion::retranslate() { - translate(m_ui, tr("Firing Explosive")); + translate(m_ui, tr("Firing Explosive")); } -void FiringExplosion::onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity &data, DataModification modType) +void FiringExplosion::onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity& data, + DataModification modType) { - if (modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - m_idOrder = data.idOrder(); - m_idEffectShow = data.idEffectShow(); - - + m_idOrder = data.idOrder(); + m_idEffectShow = data.idEffectShow(); - m_ui->pbApply->setEnabled(!data.isActive()); + m_ui->pbApply->setEnabled(!data.isActive()); - OperatingConditionEntity opcon = m_dtc->operatingConditionEntity(); - bool fireUnitsActive = opcon.firingUnitReadyAftLh() || opcon.firingUnitReadyAftRh() || opcon.firingUnitReadyFwdLh() || opcon.firingUnitReadyFwdRh(); - bool pbActiv = (data.fireEnabled() && data.safetyConfirmation() != EffectShowClient::SafetyConfirmation_e::SafetyNotConfirmed); + OperatingConditionEntity opcon = m_dtc->operatingConditionEntity(); + bool fireUnitsActive = opcon.firingUnitReadyAftLh() || opcon.firingUnitReadyAftRh() || + opcon.firingUnitReadyFwdLh() || opcon.firingUnitReadyFwdRh(); + bool pbActiv = + (data.fireEnabled() && data.safetyConfirmation() != EffectShowClient::SafetyConfirmation_e::SafetyNotConfirmed); - if (!fireUnitsActive && m_safetyConfirmationWidget) - m_safetyConfirmationWidget->setMessage(tr("Waiting for ready firing unit")); - else - m_safetyConfirmationWidget->setMessage(QString()); + if (!fireUnitsActive && m_safetyConfirmationWidget) + m_safetyConfirmationWidget->setMessage(tr("Waiting for ready firing unit")); + else + m_safetyConfirmationWidget->setMessage(QString()); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Yes, data.carriedOutEnabled()); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Yes, data.carriedOutEnabled()); + if (m_oldEntity.numberOfVolley() != data.numberOfVolley()) + m_ui->sbNumberOfVolley->setValue(data.numberOfVolley()); + if (m_oldEntity.numberOfShot() != data.numberOfShot()) + m_ui->sbNumberOfShot->setValue(data.numberOfShot()); + if (m_oldEntity.duration() != data.duration()) + m_ui->sbDuration->setValue(data.duration() / 1000); - if (m_oldEntity.numberOfVolley() != data.numberOfVolley()) - m_ui->sbNumberOfVolley->setValue(data.numberOfVolley()); - if (m_oldEntity.numberOfShot() != data.numberOfShot()) - m_ui->sbNumberOfShot->setValue(data.numberOfShot()); - if (m_oldEntity.duration() != data.duration()) - m_ui->sbDuration->setValue(data.duration() / 1000); + if (m_idEffectShow > 0) + { + QString textStr = QString::fromStdString(m_dtc->order(m_idEffectShow).info()); + m_ui->leEffectShow->setText(textStr); + } + else + m_ui->leEffectShow->setText(QString()); - if (m_idEffectShow > 0) - { - QString textStr = QString::fromStdString(m_dtc->order(m_idEffectShow).info()); - m_ui->leEffectShow->setText(textStr); - } - else - m_ui->leEffectShow->setText(QString()); + m_timer->stop(); - m_timer->stop(); + m_firingClearanceCountDown = data.firingClearanceTime().is_set() + ? (1000 + data.firingClearanceTime().get() - m_session->partitionTime()) + : 0; + m_endOfFiringClearanceCountDown = data.endOfFiringClearanceTime().is_set() + ? (1000 + data.endOfFiringClearanceTime().get() - m_session->partitionTime()) + : 0; - m_firingClearanceCountDown = data.firingClearanceTime().is_set() ? (1000 + data.firingClearanceTime().get() - m_session->partitionTime()) : 0; - m_endOfFiringClearanceCountDown = data.endOfFiringClearanceTime().is_set() ? (1000 + data.endOfFiringClearanceTime().get() - m_session->partitionTime()) : 0; + onFiringClearanceCountDown(); + if (data.idOrder() == 0 || (!data.firingClearanceTime().is_set() && data.duration() == 0)) + m_isClearance = true; + else + m_isClearance = (m_firingClearanceCountDown <= 0 && m_endOfFiringClearanceCountDown > 0); - onFiringClearanceCountDown(); - if (data.idOrder() == 0 || (!data.firingClearanceTime().is_set() && data.duration() == 0)) - m_isClearance = true; - else - m_isClearance = (m_firingClearanceCountDown <= 0 && m_endOfFiringClearanceCountDown > 0); + m_ui->pbFire->setEnabled(pbActiv && fireUnitsActive && m_isClearance); - - m_ui->pbFire->setEnabled(pbActiv && fireUnitsActive && m_isClearance); - - bool isInterruptEnabled = !data.carriedOutEnabled() && !m_ui->pbFire->isEnabled() && data.isActive() && m_isClearance; - m_ui->pbInterrupt->setEnabled(isInterruptEnabled); + bool isInterruptEnabled = + !data.carriedOutEnabled() && !m_ui->pbFire->isEnabled() && data.isActive() && m_isClearance; + m_ui->pbInterrupt->setEnabled(isInterruptEnabled); - m_ui->leRemainingShots->setText(data.remainingShots() > 0 ? QString::number(data.remainingShots()) : QString::number(0)); - m_ui->leRemainingTime->setText(QString::number(data.remainingTime() / 1000)); - m_ui->leRemainingVolley->setText(data.remainingVolleys() > 0 ? QString::number(data.remainingVolleys()) : QString::number(0)); - m_safetyConfirmation = data.safetyConfirmation(); - onSafetyConfirmationDisplay(); + m_ui->leRemainingShots->setText(data.remainingShots() > 0 ? QString::number(data.remainingShots()) + : QString::number(0)); + m_ui->leRemainingTime->setText(QString::number(data.remainingTime() / 1000)); + m_ui->leRemainingVolley->setText(data.remainingVolleys() > 0 ? QString::number(data.remainingVolleys()) + : QString::number(0)); + m_safetyConfirmation = data.safetyConfirmation(); + onSafetyConfirmationDisplay(); - m_oldEntity = data; + m_oldEntity = data; } -void FiringExplosion::onOperatingConditionEntityChanged(const OperatingConditionEntity &data, DataModification modType) +void FiringExplosion::onOperatingConditionEntityChanged(const OperatingConditionEntity& data, DataModification modType) { - Q_UNUSED(modType) - if (m_safetyConfirmationWidget) - m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); - m_shotsAvail = data.ammunitionMagazine(); - m_ui->lblShotsAvail->setText(QString::number(m_shotsAvail)); + Q_UNUSED(modType) + if (m_safetyConfirmationWidget) + m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); + m_shotsAvail = data.ammunitionMagazine(); + m_ui->lblShotsAvail->setText(QString::number(m_shotsAvail)); } - void FiringExplosion::onApply() { - if (!statusChangedForManuallyEffectShow(EffectShowStatus_e::Apply)) - ERROR_LOG(m_logger) << "Apply failed"; + if (!statusChangedForManuallyEffectShow(EffectShowStatus_e::Apply)) + ERROR_LOG(m_logger) << "Apply failed"; } void FiringExplosion::onFire() { - bool rc; - if (m_idOrder > 0) - rc = statusChangedForOrderedEffectShow(EffectShowStatus_e::Fire); - else - rc = statusChangedForManuallyEffectShow(EffectShowStatus_e::Fire); + bool rc; + if (m_idOrder > 0) + rc = statusChangedForOrderedEffectShow(EffectShowStatus_e::Fire); + else + rc = statusChangedForManuallyEffectShow(EffectShowStatus_e::Fire); - if (!rc) - ERROR_LOG(m_logger) << "Firing Explosion Order Execution failed"; + if (!rc) + ERROR_LOG(m_logger) << "Firing Explosion Order Execution failed"; } + void FiringExplosion::onInterrupt() { - bool rc; - if (m_idOrder > 0) - rc = statusChangedForOrderedEffectShow(EffectShowStatus_e::Interrupt); - else - rc = statusChangedForManuallyEffectShow(EffectShowStatus_e::Interrupt); + bool rc; + if (m_idOrder > 0) + rc = statusChangedForOrderedEffectShow(EffectShowStatus_e::Interrupt); + else + rc = statusChangedForManuallyEffectShow(EffectShowStatus_e::Interrupt); - if (!rc) - ERROR_LOG(m_logger) << "Firing Explosion Order Execution failed"; + if (!rc) + ERROR_LOG(m_logger) << "Firing Explosion Order Execution failed"; } void FiringExplosion::onAbort() { - if (m_idOrder > 0) - { - OrderEdit *edit = new OrderEdit(m_dtc->order(m_idEffectShow), false, this); - edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::Abort); - addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); - - return; - } - else - statusChangedForManuallyEffectShow(EffectShowStatus_e::Abort); + if (m_idOrder > 0) + { + OrderEdit* edit = new OrderEdit(m_dtc->order(m_idEffectShow), false, this); + edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::Abort); + addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); + + return; + } + else + statusChangedForManuallyEffectShow(EffectShowStatus_e::Abort); } void FiringExplosion::onCarriedOut() { - if (m_idOrder > 0) - { - OrderEdit *edit = new OrderEdit(m_dtc->order(m_idEffectShow), false, this); - edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::OrderCarriedOut); - addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); - } - else - statusChangedForManuallyEffectShow(EffectShowStatus_e::CarriedOut); + if (m_idOrder > 0) + { + OrderEdit* edit = new OrderEdit(m_dtc->order(m_idEffectShow), false, this); + edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::OrderCarriedOut); + addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); + } + else + statusChangedForManuallyEffectShow(EffectShowStatus_e::CarriedOut); } void FiringExplosion::onSafetyConfirmationDisplay() { - if (m_safetyConfirmationWidget) - m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation); + if (m_safetyConfirmationWidget) + m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation); } void FiringExplosion::onFiringClearanceCountDown() { - if (m_timer->isActive()) - { - m_firingClearanceCountDown -= 1000; - m_endOfFiringClearanceCountDown -= 1000; - } + if (m_timer->isActive()) + { + m_firingClearanceCountDown -= 1000; + m_endOfFiringClearanceCountDown -= 1000; + } - if (m_firingClearanceCountDown > 0) - m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(m_firingClearanceCountDown / 1000)); - else - m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); + if (m_firingClearanceCountDown > 0) + m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(m_firingClearanceCountDown / 1000)); + else + m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); - if (m_endOfFiringClearanceCountDown > 0) - m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(m_endOfFiringClearanceCountDown / 1000)); - else - m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); + if (m_endOfFiringClearanceCountDown > 0) + m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(m_endOfFiringClearanceCountDown / 1000)); + else + m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); - if ((m_firingClearanceCountDown > 0) || (m_endOfFiringClearanceCountDown > 0)) - m_timer->start(1000); + if ((m_firingClearanceCountDown > 0) || (m_endOfFiringClearanceCountDown > 0)) + m_timer->start(1000); - m_isClearance = (m_firingClearanceCountDown <= 0 && m_endOfFiringClearanceCountDown > 0); + m_isClearance = (m_firingClearanceCountDown <= 0 && m_endOfFiringClearanceCountDown > 0); } bool FiringExplosion::statusChangedForManuallyEffectShow(EffectShowStatus_e status) { - m_uiRequirements->clear(); - if (status == EffectShowStatus_e::Apply) - { - m_uiRequirements->addRequirement({m_ui->lbShotsAvail, [this]() { return !(m_shotsAvail < m_ui->sbNumberOfShot->value()); }}); - m_uiRequirements->addRequirement({m_ui->lblNumberOfVolley, [this]() { return !(m_ui->sbNumberOfShot->value() < m_ui->sbNumberOfVolley->value()); }}); - m_uiRequirements->addRequirement({m_ui->lblDuration, [this]() { return !(m_ui->sbDuration->value() * 1000 < ((m_ui->sbNumberOfShot->value() * 1000) + (m_ui->sbNumberOfVolley->value() * 2000 ))); }}); - } - - if (!m_uiRequirements->checkRequirements(this)) - return false; - - return m_requestHelper->startSingleRequest([this, status]() - { - EffectShowClient::ManuallyExplosionRequest request; - if (status == EffectShowStatus_e::Interrupt) + m_uiRequirements->clear(); + if (status == EffectShowStatus_e::Apply) { - const EffectShowClient::FiringExplosionEntity manEx = m_dtc->firingExplosionEntity(); - - request.numberOfVolley(manEx.remainingVolleys()); - request.numberOfShot(manEx.remainingShots()); - request.duration(manEx.remainingTime()); + m_uiRequirements->addRequirement( + {m_ui->lbShotsAvail, [this]() { return !(m_shotsAvail < m_ui->sbNumberOfShot->value()); }}); + m_uiRequirements->addRequirement({m_ui->lblNumberOfVolley, [this]() { + return !(m_ui->sbNumberOfShot->value() < m_ui->sbNumberOfVolley->value()); + }}); + m_uiRequirements->addRequirement( + {m_ui->lblDuration, [this]() { + return !(m_ui->sbDuration->value() * 1000 < + ((m_ui->sbNumberOfShot->value() * 1000) + (m_ui->sbNumberOfVolley->value() * 2000))); + }}); } - else - { - request.numberOfVolley(m_ui->sbNumberOfVolley->value()); - request.numberOfShot(m_ui->sbNumberOfShot->value()); - request.duration(m_ui->sbDuration->value() * 1000); - } - request.pbFire(status == EffectShowStatus_e::Fire); - request.pbAbort(status == EffectShowStatus_e::Abort); - request.pbInterrupt(status == EffectShowStatus_e::Interrupt); - request.pbCarriedOut(status == EffectShowStatus_e::CarriedOut || status == EffectShowStatus_e::Abort); + if (!m_uiRequirements->checkRequirements(this)) + return false; - return m_ftc->manuallyExplosionRequest(request, this); - }); + return m_requestHelper->startSingleRequest([this, status]() { + EffectShowClient::ManuallyExplosionRequest request; + if (status == EffectShowStatus_e::Interrupt) + { + const EffectShowClient::FiringExplosionEntity manEx = m_dtc->firingExplosionEntity(); + request.numberOfVolley(manEx.remainingVolleys()); + request.numberOfShot(manEx.remainingShots()); + request.duration(manEx.remainingTime()); + } + else + { + request.numberOfVolley(m_ui->sbNumberOfVolley->value()); + request.numberOfShot(m_ui->sbNumberOfShot->value()); + request.duration(m_ui->sbDuration->value() * 1000); + } + request.pbFire(status == EffectShowStatus_e::Fire); + request.pbAbort(status == EffectShowStatus_e::Abort); + request.pbInterrupt(status == EffectShowStatus_e::Interrupt); + + request.pbCarriedOut(status == EffectShowStatus_e::CarriedOut || status == EffectShowStatus_e::Abort); + + return m_ftc->manuallyExplosionRequest(request, this); + }); } bool FiringExplosion::statusChangedForOrderedEffectShow(EffectShowStatus_e status) { - m_uiRequirements->clear(); + m_uiRequirements->clear(); - if (!m_uiRequirements->checkRequirements(this)) - return true; + if (!m_uiRequirements->checkRequirements(this)) + return true; - return m_requestHelper->startSingleRequest([this, status]() - { - OrderModifyRequest orderModifyRequest; + return m_requestHelper->startSingleRequest([this, status]() { + OrderModifyRequest orderModifyRequest; - orderModifyRequest.id(m_idEffectShow); - EffectShowManagement::OrderConfirmation_e oc; - switch (status) - { - case EffectShowStatus_e::Fire: - oc = EffectShowManagement::OrderConfirmation_e_def::Execution; - break; - case EffectShowStatus_e::CarriedOut: - oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; - break; - case EffectShowStatus_e::Interrupt: - oc = EffectShowManagement::OrderConfirmation_e_def::InterruptExecution; - break; - default: - DEBUG_LOG(m_logger) << "FiringExplosion::statusChangedForOrderedEffectShow switch is defaulting, should not happen I guess..."; - break; - } - orderModifyRequest.orderConfirmation(oc); - orderModifyRequest.answerText(QString().toStdString()); - - return m_ftc->orderModifyRequest(orderModifyRequest, this); - }); + orderModifyRequest.id(m_idEffectShow); + EffectShowManagement::OrderConfirmation_e oc; + switch (status) + { + case EffectShowStatus_e::Fire: + oc = EffectShowManagement::OrderConfirmation_e_def::Execution; + break; + case EffectShowStatus_e::CarriedOut: + oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; + break; + case EffectShowStatus_e::Interrupt: + oc = EffectShowManagement::OrderConfirmation_e_def::InterruptExecution; + break; + default: + DEBUG_LOG(m_logger) << "FiringExplosion::statusChangedForOrderedEffectShow switch is defaulting, " + "should not happen I guess..."; + break; + } + orderModifyRequest.orderConfirmation(oc); + orderModifyRequest.answerText(QString().toStdString()); + return m_ftc->orderModifyRequest(orderModifyRequest, this); + }); } - -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.h old mode 100755 new mode 100644 index e25453a50..74ff807ff --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_explosion.h @@ -1,18 +1,15 @@ - #pragma once #include "esc_order_model.h" -#include +#include #include +#include +#include +#include #include #include -#include -#include - -#include - namespace Ui { @@ -28,64 +25,69 @@ namespace EffectShowClient { class SafetyConfirmationWidget; - - -class FiringExplosion : public LtsWidgets::LtsDialog - , protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler - , protected EffectShowClient::Interface::Ftc::ManuallyExplosionReplyHandler +class FiringExplosion : public LtsWidgets::LtsDialog, + protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler, + protected EffectShowClient::Interface::Ftc::ManuallyExplosionReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit FiringExplosion(QWidget *parent = nullptr); - ~FiringExplosion(); + public: + explicit FiringExplosion(QWidget* parent = nullptr); + ~FiringExplosion(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - bool freeForm = false); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, LtsSession::LtsSession* session, + bool freeForm = false); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onOrderModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - void onManuallyExplosionReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onOrderModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private Q_SLOTS: - void onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity &data, DataModification modType); - void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity &data, DataModification modType); - void onApply(); - void onFire(); - void onAbort(); - void onInterrupt(); - void onCarriedOut(); - void onSafetyConfirmationDisplay(); - void onFiringClearanceCountDown(); + void onManuallyExplosionReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private: - enum class EffectShowStatus_e : unsigned int { Apply, Fire, Abort, Interrupt, CarriedOut }; - bool statusChangedForManuallyEffectShow(EffectShowStatus_e status); - bool statusChangedForOrderedEffectShow(EffectShowStatus_e status); + private Q_SLOTS: + void onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity& data, DataModification modType); + void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity& data, + DataModification modType); + void onApply(); + void onFire(); + void onAbort(); + void onInterrupt(); + void onCarriedOut(); + void onSafetyConfirmationDisplay(); + void onFiringClearanceCountDown(); -private: - QTimer *m_timer; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - LtsSession::LtsSession *m_session; - SafetyConfirmationWidget *m_safetyConfirmationWidget; + private: + enum class EffectShowStatus_e : unsigned int { Apply, Fire, Abort, Interrupt, CarriedOut }; + bool statusChangedForManuallyEffectShow(EffectShowStatus_e status); + bool statusChangedForOrderedEffectShow(EffectShowStatus_e status); - Ui::FiringExplosion *m_ui; - LtsUtils::RequestHelper *m_requestHelper; + private: + QTimer* m_timer; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + LtsSession::LtsSession* m_session; + SafetyConfirmationWidget* m_safetyConfirmationWidget; - EffectShowClient::FiringExplosionEntity m_oldEntity; - EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; - int m_idOrder; - int m_idEffectShow; - int m_shotsAvail; - bool m_isClearance; - qint64 m_firingClearanceCountDown; - qint64 m_endOfFiringClearanceCountDown; + Ui::FiringExplosion* m_ui; + LtsUtils::RequestHelper* m_requestHelper; + + EffectShowClient::FiringExplosionEntity m_oldEntity; + EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; + int m_idOrder; + int m_idEffectShow; + int m_shotsAvail; + bool m_isClearance; + qint64 m_firingClearanceCountDown; + qint64 m_endOfFiringClearanceCountDown; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.cpp old mode 100755 new mode 100644 index 25ea646fa..a566fdf35 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.cpp @@ -1,294 +1,284 @@ - #include "esc_firing_smoke.h" -#include "ui_esc_firing_smoke.h" -#include "esc_smoke_state.h" -#include "esc_safety_confirmation_widget.h" + #include "esc_order_edit.h" +#include "esc_safety_confirmation_widget.h" +#include "esc_smoke_state.h" +#include "ui_esc_firing_smoke.h" #include namespace EffectShowClient { -FiringSmoke::FiringSmoke(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_timer(new QTimer(this)) - , m_meteoTimer(new QTimer(this)) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_session(nullptr) - , m_smokeState(nullptr) - , m_safetyConfirmationWidget(nullptr) - , m_ui(new Ui::FiringSmoke) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_idOrder(0) - , m_firingClearanceCountDown(0) - , m_endOfFiringClearanceCountDown(0) +FiringSmoke::FiringSmoke(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_timer(new QTimer(this)), + m_meteoTimer(new QTimer(this)), m_dtc(nullptr), m_ftc(nullptr), m_session(nullptr), m_smokeState(nullptr), + m_safetyConfirmationWidget(nullptr), m_ui(new Ui::FiringSmoke), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_idOrder(0), m_firingClearanceCountDown(0), + m_endOfFiringClearanceCountDown(0) { - DEBUG_LOG(m_logger) << "FiringSmoke::FiringSmoke()"; + DEBUG_LOG(m_logger) << "FiringSmoke::FiringSmoke()"; - m_ui->setupUi(this); - m_smokeState = new SmokeState(this); - m_ui->layoutSmokeState->addWidget(m_smokeState); + m_ui->setupUi(this); + m_smokeState = new SmokeState(this); + m_ui->layoutSmokeState->addWidget(m_smokeState); - m_meteoTimer->setInterval(15 * 60 * 1000); - connect(m_timer, &QTimer::timeout, this, &FiringSmoke::onFiringClearanceCountDown); - connect(m_meteoTimer, &QTimer::timeout, this, &FiringSmoke::onMeteoTimerTimeout); + m_meteoTimer->setInterval(15 * 60 * 1000); + connect(m_timer, &QTimer::timeout, this, &FiringSmoke::onFiringClearanceCountDown); + connect(m_meteoTimer, &QTimer::timeout, this, &FiringSmoke::onMeteoTimerTimeout); - setOnlineHelpFilename(QLatin1String("OC-Smoke")); + setOnlineHelpFilename(QLatin1String("OC-Smoke")); } FiringSmoke::~FiringSmoke() { - delete m_ui; + delete m_ui; } -bool FiringSmoke::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, bool freeForm) +bool FiringSmoke::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, LtsSession::LtsSession* session, + bool freeForm) { - DEBUG_LOG(m_logger) << "FiringSmoke::init()"; + DEBUG_LOG(m_logger) << "FiringSmoke::init()"; - if (!dtc || !ftc) - { - ERROR_LOG(m_logger) << "FiringSmoke::init() Invalid shared_ptr!"; - return false; - } + if (!dtc || !ftc) + { + ERROR_LOG(m_logger) << "FiringSmoke::init() Invalid shared_ptr!"; + return false; + } - m_dtc = dtc; - m_ftc = ftc; - m_session = session; + m_dtc = dtc; + m_ftc = ftc; + m_session = session; - m_safetyConfirmationWidget = new EffectShowClient::SafetyConfirmationWidget(this); - m_safetyConfirmationWidget->init(m_ftc); - - m_ui->hz->insertWidget(0, m_safetyConfirmationWidget); + m_safetyConfirmationWidget = new EffectShowClient::SafetyConfirmationWidget(this); + m_safetyConfirmationWidget->init(m_ftc); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingSmokeEntityChanged, - this, &FiringSmoke::onFiringSmokeEntityChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, - this, &FiringSmoke::onOperatingConditionEntityChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::meteoNearVehicleChanged, - this, &FiringSmoke::onMeteoDataChanged); + m_ui->hz->insertWidget(0, m_safetyConfirmationWidget); - const EffectShowClient::MeteoNearVehicle dat = m_dtc.get()->meteoNearVehicle(); - if (dat.windDirection() > 0) - onMeteoDataChanged(dat, DataModification()); - else - onMeteoTimerTimeout(); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingSmokeEntityChanged, this, + &FiringSmoke::onFiringSmokeEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, this, + &FiringSmoke::onOperatingConditionEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::meteoNearVehicleChanged, this, + &FiringSmoke::onMeteoDataChanged); - - if (!freeForm) - onFiringSmokeEntityChanged(m_dtc->firingSmokeEntity(), DataModification::eAdded); + const EffectShowClient::MeteoNearVehicle dat = m_dtc.get()->meteoNearVehicle(); + if (dat.windDirection() > 0) + onMeteoDataChanged(dat, DataModification()); + else + onMeteoTimerTimeout(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Yes, this, &FiringSmoke::onCarriedOut); - m_buttonBox->setText(LtsWidgets::DialogButton::Yes, tr("Carried Out")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::No, this, &FiringSmoke::onAbort); - m_buttonBox->setText(LtsWidgets::DialogButton::No, tr("Abort")); + if (!freeForm) + onFiringSmokeEntityChanged(m_dtc->firingSmokeEntity(), DataModification::eAdded); - return true; + m_buttonBox->connectButton(LtsWidgets::DialogButton::Yes, this, &FiringSmoke::onCarriedOut); + m_buttonBox->setText(LtsWidgets::DialogButton::Yes, tr("Carried Out")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::No, this, &FiringSmoke::onAbort); + m_buttonBox->setText(LtsWidgets::DialogButton::No, tr("Abort")); + + return true; } void FiringSmoke::retranslate() { - translate(m_ui, tr("Firing Smoke")); + translate(m_ui, tr("Firing Smoke")); } - -void FiringSmoke::onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity &data, DataModification modType) +void FiringSmoke::onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity& data, DataModification modType) { - if (modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - m_idOrder = data.idOrder(); + m_idOrder = data.idOrder(); - if (data.idEffectShow() > 0) - { - const EffectShowClient::Order &order = m_dtc->order(data.idOrder()); - m_ui->leEffectShow->setText(QString::fromStdString(order.info())); - m_ui->lblLengthOfFogZone->setText(tr("%1m x %2m").arg(QString::number(order.areaWidth()), QString::number(order.areaDepth()))); - m_ui->lblDirectionOfFogZone->setText(QString::number(order.areaRotation())); - } - else - { - m_ui->leEffectShow->setText(QString()); - m_ui->lblLengthOfFogZone->setText(tr("0m x 0m")); - m_ui->lblDirectionOfFogZone->setText(QString::number(0)); - } + if (data.idEffectShow() > 0) + { + const EffectShowClient::Order& order = m_dtc->order(data.idOrder()); + m_ui->leEffectShow->setText(QString::fromStdString(order.info())); + m_ui->lblLengthOfFogZone->setText( + tr("%1m x %2m").arg(QString::number(order.areaWidth()), QString::number(order.areaDepth()))); + m_ui->lblDirectionOfFogZone->setText(QString::number(order.areaRotation())); + } + else + { + m_ui->leEffectShow->setText(QString()); + m_ui->lblLengthOfFogZone->setText(tr("0m x 0m")); + m_ui->lblDirectionOfFogZone->setText(QString::number(0)); + } - m_firingClearanceCountDown = data.firingClearanceTime().is_set() ? (1000 + data.firingClearanceTime().get() - m_session->partitionTime()) : 0; - m_endOfFiringClearanceCountDown = data.endOfFiringClearanceTime().is_set() ? (1000 + data.endOfFiringClearanceTime().get() - m_session->partitionTime()) : 0; - m_timer->stop(); - onFiringClearanceCountDown(); + m_firingClearanceCountDown = data.firingClearanceTime().is_set() + ? (1000 + data.firingClearanceTime().get() - m_session->partitionTime()) + : 0; + m_endOfFiringClearanceCountDown = data.endOfFiringClearanceTime().is_set() + ? (1000 + data.endOfFiringClearanceTime().get() - m_session->partitionTime()) + : 0; + m_timer->stop(); + onFiringClearanceCountDown(); - m_safetyConfirmation = data.safetyConfirmation(); - onSafetyConfirmationDisplay(); - - m_oldEntity = data; + m_safetyConfirmation = data.safetyConfirmation(); + onSafetyConfirmationDisplay(); + m_oldEntity = data; } -void FiringSmoke::onOperatingConditionEntityChanged(const OperatingConditionEntity &data, DataModification modType) +void FiringSmoke::onOperatingConditionEntityChanged(const OperatingConditionEntity& data, DataModification modType) { - Q_UNUSED(modType) + Q_UNUSED(modType) - QVector onColor = - { - data.smokeCartridge1().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge2().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge3().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge4().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge5().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0) - }; - QVector status = - { - ((data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ) - }; - - m_smokeState->setSmokeState(status, onColor); - m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); + QVector onColor = { + data.smokeCartridge1().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge2().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge3().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge4().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge5().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0)}; + QVector status = { + ((data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking))}; + m_smokeState->setSmokeState(status, onColor); + m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); } -void FiringSmoke::onMeteoDataChanged(const MeteoNearVehicle &data, DataModification modType) +void FiringSmoke::onMeteoDataChanged(const MeteoNearVehicle& data, DataModification modType) { - Q_UNUSED(modType) - m_meteoTimer->start(), - m_ui->lblWeather->setText(tr("Speed [m/s]: %1 | Direction [°]: %2").arg(data.windSpeed()).arg(data.windDirection())); - + Q_UNUSED(modType) + m_meteoTimer->start(), + m_ui->lblWeather->setText( + tr("Speed [m/s]: %1 | Direction [°]: %2").arg(data.windSpeed()).arg(data.windDirection())); } void FiringSmoke::onMeteoTimerTimeout() { - m_ui->lblWeather->setText(tr("Speed [m/s]: --- | Direction [°]: ---")); + m_ui->lblWeather->setText(tr("Speed [m/s]: --- | Direction [°]: ---")); } void FiringSmoke::onApply() { - if (!statusChangedForManuallyEffectShow(EffectShowStatus_e::Apply)) - ERROR_LOG(m_logger) << "Firing Smoke Apply failed"; + if (!statusChangedForManuallyEffectShow(EffectShowStatus_e::Apply)) + ERROR_LOG(m_logger) << "Firing Smoke Apply failed"; } - void FiringSmoke::onAbort() { - if (m_idOrder > 0) - { - OrderEdit *edit = new OrderEdit(m_dtc->order(m_idOrder), false, this); - edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::Abort); - addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); - return; - } - else - statusChangedForManuallyEffectShow(EffectShowStatus_e::Abort); - + if (m_idOrder > 0) + { + OrderEdit* edit = new OrderEdit(m_dtc->order(m_idOrder), false, this); + edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::Abort); + addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); + return; + } + else + statusChangedForManuallyEffectShow(EffectShowStatus_e::Abort); } void FiringSmoke::onCarriedOut() { - if (m_idOrder > 0) - { - OrderEdit *edit = new OrderEdit(m_dtc->order(m_idOrder), false, this); - edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::OrderCarriedOut); - addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); - return; - } - else - statusChangedForManuallyEffectShow(EffectShowStatus_e::CarriedOut); - + if (m_idOrder > 0) + { + OrderEdit* edit = new OrderEdit(m_dtc->order(m_idOrder), false, this); + edit->init(m_ftc, EffectShowManagement::OrderConfirmation_e::OrderCarriedOut); + addDialog(edit, menuGroup(), QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); + return; + } + else + statusChangedForManuallyEffectShow(EffectShowStatus_e::CarriedOut); } void FiringSmoke::onSafetyConfirmationDisplay() { - if (!m_safetyConfirmationWidget) - return; - m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation.underlying()); + if (!m_safetyConfirmationWidget) + return; + m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation.underlying()); } void FiringSmoke::onFiringClearanceCountDown() { - if (m_timer->isActive()) - { - m_firingClearanceCountDown -= 1000; - m_endOfFiringClearanceCountDown -= 1000; - } + if (m_timer->isActive()) + { + m_firingClearanceCountDown -= 1000; + m_endOfFiringClearanceCountDown -= 1000; + } - if (m_firingClearanceCountDown > 0) - m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(m_firingClearanceCountDown / 1000)); - else - m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); + if (m_firingClearanceCountDown > 0) + m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(m_firingClearanceCountDown / 1000)); + else + m_ui->leFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); - if (m_endOfFiringClearanceCountDown > 0) - m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(m_endOfFiringClearanceCountDown / 1000)); - else - m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); + if (m_endOfFiringClearanceCountDown > 0) + m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(m_endOfFiringClearanceCountDown / 1000)); + else + m_ui->leEndOfFiringClearanceIn->setText(OrderModel::timeOfDayString(0)); - if ((m_firingClearanceCountDown > 0) || (m_endOfFiringClearanceCountDown > 0)) - m_timer->start(1000); + if ((m_firingClearanceCountDown > 0) || (m_endOfFiringClearanceCountDown > 0)) + m_timer->start(1000); } bool FiringSmoke::statusChangedForManuallyEffectShow(EffectShowStatus_e status) { - m_uiRequirements->clear(); + m_uiRequirements->clear(); - return m_requestHelper->startSingleRequest([this, status]() - { - EffectShowClient::ManuallySmokeRequest request; - request.directionOfFogZone(0); - request.lengthOfFogZone(0); - request.pbAbort(status == EffectShowStatus_e::Abort); - request.pbCarriedOut(status == EffectShowStatus_e::CarriedOut); - return m_ftc->manuallySmokeRequest(request, this); - }); + return m_requestHelper->startSingleRequest([this, status]() { + EffectShowClient::ManuallySmokeRequest request; + request.directionOfFogZone(0); + request.lengthOfFogZone(0); + request.pbAbort(status == EffectShowStatus_e::Abort); + request.pbCarriedOut(status == EffectShowStatus_e::CarriedOut); + return m_ftc->manuallySmokeRequest(request, this); + }); } bool FiringSmoke::statusChangedForOrderedEffectShow(EffectShowStatus_e status) { - m_uiRequirements->clear(); + m_uiRequirements->clear(); - if (!m_uiRequirements->checkRequirements(this)) - return true; + if (!m_uiRequirements->checkRequirements(this)) + return true; - return m_requestHelper->startSingleRequest([this, status]() - { - OrderModifyRequest orderModifyRequest; + return m_requestHelper->startSingleRequest([this, status]() { + OrderModifyRequest orderModifyRequest; - orderModifyRequest.id(m_idOrder); - EffectShowManagement::OrderConfirmation_e oc; - switch (status) - { - case EffectShowStatus_e::Abort: - oc = EffectShowManagement::OrderConfirmation_e_def::Abort; - break; - case EffectShowStatus_e::CarriedOut: - oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; - break; - default: - DEBUG_LOG(m_logger) << "FiringSmoke::statusChangedForOrderedEffectShow switch is defaulting, should not happen I guess..."; - break; - } - orderModifyRequest.orderConfirmation(oc); - orderModifyRequest.answerText(QString().toStdString()); + orderModifyRequest.id(m_idOrder); + EffectShowManagement::OrderConfirmation_e oc; + switch (status) + { + case EffectShowStatus_e::Abort: + oc = EffectShowManagement::OrderConfirmation_e_def::Abort; + break; + case EffectShowStatus_e::CarriedOut: + oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; + break; + default: + DEBUG_LOG(m_logger) << "FiringSmoke::statusChangedForOrderedEffectShow switch is defaulting, should " + "not happen I guess..."; + break; + } + orderModifyRequest.orderConfirmation(oc); + orderModifyRequest.answerText(QString().toStdString()); - return m_ftc->orderModifyRequest(orderModifyRequest, this); - }); + return m_ftc->orderModifyRequest(orderModifyRequest, this); + }); } -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.h old mode 100755 new mode 100644 index adae18556..a247467af --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_firing_smoke.h @@ -1,17 +1,15 @@ - #pragma once #include "esc_order_model.h" -#include +#include #include +#include +#include +#include #include #include -#include -#include - -#include namespace Ui { @@ -28,65 +26,69 @@ namespace EffectShowClient class SmokeState; class SafetyConfirmationWidget; - - -class FiringSmoke : public LtsWidgets::LtsDialog - , protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler - , protected EffectShowClient::Interface::Ftc::ManuallySmokeReplyHandler +class FiringSmoke : public LtsWidgets::LtsDialog, + protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler, + protected EffectShowClient::Interface::Ftc::ManuallySmokeReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit FiringSmoke(QWidget *parent = nullptr); - ~FiringSmoke(); + public: + explicit FiringSmoke(QWidget* parent = nullptr); + ~FiringSmoke(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - LtsSession::LtsSession *session, - bool freeForm = false); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, LtsSession::LtsSession* session, + bool freeForm = false); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onOrderModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - void onManuallySmokeReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onOrderModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private Q_SLOTS: - void onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity &data, DataModification modType); - void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity &data, DataModification modType); - void onMeteoDataChanged(const EffectShowClient::MeteoNearVehicle &data, DataModification modType); - void onMeteoTimerTimeout(); - void onApply(); - void onAbort(); - void onCarriedOut(); - void onSafetyConfirmationDisplay(); - void onFiringClearanceCountDown(); + void onManuallySmokeReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private: - enum class EffectShowStatus_e : unsigned int { Apply, Abort, CarriedOut }; - bool statusChangedForManuallyEffectShow(EffectShowStatus_e status); - bool statusChangedForOrderedEffectShow(EffectShowStatus_e status); + private Q_SLOTS: + void onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity& data, DataModification modType); + void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity& data, + DataModification modType); + void onMeteoDataChanged(const EffectShowClient::MeteoNearVehicle& data, DataModification modType); + void onMeteoTimerTimeout(); + void onApply(); + void onAbort(); + void onCarriedOut(); + void onSafetyConfirmationDisplay(); + void onFiringClearanceCountDown(); + private: + enum class EffectShowStatus_e : unsigned int { Apply, Abort, CarriedOut }; + bool statusChangedForManuallyEffectShow(EffectShowStatus_e status); + bool statusChangedForOrderedEffectShow(EffectShowStatus_e status); -private: - QTimer *m_timer; - QTimer *m_meteoTimer; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - LtsSession::LtsSession *m_session; + private: + QTimer* m_timer; + QTimer* m_meteoTimer; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + LtsSession::LtsSession* m_session; - EffectShowClient::SmokeState *m_smokeState; - SafetyConfirmationWidget *m_safetyConfirmationWidget; + EffectShowClient::SmokeState* m_smokeState; + SafetyConfirmationWidget* m_safetyConfirmationWidget; - Ui::FiringSmoke *m_ui; - LtsUtils::RequestHelper *m_requestHelper; + Ui::FiringSmoke* m_ui; + LtsUtils::RequestHelper* m_requestHelper; - EffectShowClient::FiringSmokeEntity m_oldEntity; - EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; - int m_idOrder; - qint64 m_firingClearanceCountDown; - qint64 m_endOfFiringClearanceCountDown; + EffectShowClient::FiringSmokeEntity m_oldEntity; + EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; + int m_idOrder; + qint64 m_firingClearanceCountDown; + qint64 m_endOfFiringClearanceCountDown; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.cpp old mode 100755 new mode 100644 index bbdea16ed..fce363d1d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.cpp @@ -1,377 +1,352 @@ - #include "esc_operating_condition.h" -#include "ui_esc_operating_condition.h" -#include "esc_smoke_state.h" -#include "esc_safety_confirmation_widget.h" + #include "LtsWidgets/lts_message_dialog.h" +#include "esc_safety_confirmation_widget.h" +#include "esc_smoke_state.h" +#include "ui_esc_operating_condition.h" -#include - -#include #include - +#include +#include namespace EffectShowClient { - -OperatingCondition::OperatingCondition(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_lastState(EffectShowClient::OperatingConditionEntity()) - , m_meteoTimerTimeout(60 * 1000 * 15) - , m_meteoTimer(new QTimer(this)) - , m_smokeState(nullptr) - , m_safetyConfirmationWidget(nullptr) - , m_ui(new Ui::OperatingCondition) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +OperatingCondition::OperatingCondition(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_dtc(nullptr), m_ftc(nullptr), + m_lastState(EffectShowClient::OperatingConditionEntity()), m_meteoTimerTimeout(60 * 1000 * 15), + m_meteoTimer(new QTimer(this)), m_smokeState(nullptr), m_safetyConfirmationWidget(nullptr), + m_ui(new Ui::OperatingCondition), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - m_smokeState = new EffectShowClient::SmokeState(this); - m_ui->hz->insertWidget(1, m_smokeState); - m_smokeState->setVisible(false); - - m_ui->lblStation->hide(); - m_ui->leStation->hide(); + m_ui->setupUi(this); + m_smokeState = new EffectShowClient::SmokeState(this); + m_ui->hz->insertWidget(1, m_smokeState); + m_smokeState->setVisible(false); - m_ui->leLastUpdate->clear(); - m_ui->leLastUpdate->setEnabled(false); + m_ui->lblStation->hide(); + m_ui->leStation->hide(); - m_batteryVoltage.maximumValue = m_ui->frameGreenVoltage->width(); + m_ui->leLastUpdate->clear(); + m_ui->leLastUpdate->setEnabled(false); - connect(m_ui->pbSendAmmunition, &QPushButton::clicked, - this, &OperatingCondition::onSendAmmunition); + m_batteryVoltage.maximumValue = m_ui->frameGreenVoltage->width(); - setOnlineHelpFilename(QLatin1String("OC-Operating_Condition")); + connect(m_ui->pbSendAmmunition, &QPushButton::clicked, this, &OperatingCondition::onSendAmmunition); + + setOnlineHelpFilename(QLatin1String("OC-Operating_Condition")); } - OperatingCondition::~OperatingCondition() { - delete m_ui; + delete m_ui; } - -bool OperatingCondition::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc) +bool OperatingCondition::init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc) { - DEBUG_LOG(m_logger) << "OperatingCondition::init()"; + DEBUG_LOG(m_logger) << "OperatingCondition::init()"; - if (!dtc || !ftc) - { - ERROR_LOG(m_logger) << "OperatingCondition::init() Invalid shared_ptr!"; - return false; - } + if (!dtc || !ftc) + { + ERROR_LOG(m_logger) << "OperatingCondition::init() Invalid shared_ptr!"; + return false; + } - m_dtc = dtc; - m_ftc = ftc; + m_dtc = dtc; + m_ftc = ftc; - m_safetyConfirmationWidget = new EffectShowClient::SafetyConfirmationWidget(this); - m_safetyConfirmationWidget->init(m_ftc); - m_ui->safetyLayout->insertWidget(0, m_safetyConfirmationWidget); + m_safetyConfirmationWidget = new EffectShowClient::SafetyConfirmationWidget(this); + m_safetyConfirmationWidget->init(m_ftc); + m_ui->safetyLayout->insertWidget(0, m_safetyConfirmationWidget); - - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, - this, &OperatingCondition::onOperatingConditionEntityChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::meteoNearVehicleChanged, - this, &OperatingCondition::onMeteoNearVehicleChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::operatingConditionEntityChanged, this, + &OperatingCondition::onOperatingConditionEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::meteoNearVehicleChanged, this, + &OperatingCondition::onMeteoNearVehicleChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingExplosionEntityChanged, - this, &OperatingCondition::onFiringExplosionEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingExplosionEntityChanged, this, + &OperatingCondition::onFiringExplosionEntityChanged); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingSmokeEntityChanged, - this, &OperatingCondition::onFiringSmokeEntityChanged); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::firingSmokeEntityChanged, this, + &OperatingCondition::onFiringSmokeEntityChanged); - connect(m_meteoTimer, &QTimer::timeout, - this, &OperatingCondition::onMeteoTimeout); + connect(m_meteoTimer, &QTimer::timeout, this, &OperatingCondition::onMeteoTimeout); - m_meteoTimer->start(m_meteoTimerTimeout); - - onMeteoTimeout(); + m_meteoTimer->start(m_meteoTimerTimeout); - - setBatteryVoltageConstraints(21.0, 22.0, 36.0); + onMeteoTimeout(); - - onOperatingConditionEntityChanged(m_dtc->operatingConditionEntity(), DataModification::eAdded); + setBatteryVoltageConstraints(21.0, 22.0, 36.0); - const EffectShowClient::MeteoNearVehicle mdmv = m_dtc->meteoNearVehicle(); - if (mdmv.temperature() > 0 && mdmv.windSpeed() > 0) - onMeteoNearVehicleChanged(m_dtc->meteoNearVehicle(), DataModification::eAdded); + onOperatingConditionEntityChanged(m_dtc->operatingConditionEntity(), DataModification::eAdded); - connect(m_ui->pbConfirmReadiness, &QPushButton::clicked, this, &OperatingCondition::onSendConfirmReadiness); - connect(m_ui->pbRevokeReadiness, &QPushButton::clicked, this, &OperatingCondition::onSendRevokeReadiness); + const EffectShowClient::MeteoNearVehicle mdmv = m_dtc->meteoNearVehicle(); + if (mdmv.temperature() > 0 && mdmv.windSpeed() > 0) + onMeteoNearVehicleChanged(m_dtc->meteoNearVehicle(), DataModification::eAdded); - onSafetyConfirmationDisplay(); + connect(m_ui->pbConfirmReadiness, &QPushButton::clicked, this, &OperatingCondition::onSendConfirmReadiness); + connect(m_ui->pbRevokeReadiness, &QPushButton::clicked, this, &OperatingCondition::onSendRevokeReadiness); - return true; + onSafetyConfirmationDisplay(); + + return true; } - void OperatingCondition::retranslate() { - translate(m_ui, tr("Operating Condition")); + translate(m_ui, tr("Operating Condition")); } int OperatingCondition::getSmokeCount() { - const OperatingConditionEntity &data = m_dtc->operatingConditionEntity(); - int currentSmokeLoad = 0; - if (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) - currentSmokeLoad++; - if (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) - currentSmokeLoad++; - if (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) - currentSmokeLoad++; - if (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) - currentSmokeLoad++; - if (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) - currentSmokeLoad++; + const OperatingConditionEntity& data = m_dtc->operatingConditionEntity(); + int currentSmokeLoad = 0; + if (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) + currentSmokeLoad++; + if (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) + currentSmokeLoad++; + if (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) + currentSmokeLoad++; + if (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) + currentSmokeLoad++; + if (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) + currentSmokeLoad++; - return currentSmokeLoad; + return currentSmokeLoad; } - -void OperatingCondition::onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity &data, DataModification modType) +void OperatingCondition::onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity& data, + DataModification modType) { - if (modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - m_lastState = data; + m_lastState = data; - if (data.vehicleFeature() == EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion24)) - { - m_ui->ledAftLh->hide(); - m_ui->ledAftRh->hide(); - } - else if (data.vehicleFeature() == EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion48)) - { - m_ui->ledAftLh->show(); - m_ui->ledAftRh->show(); - } - bool isExp = data.vehicleFeature() != EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke); - m_ui->frame->setHidden(!isExp); - m_ui->lblMagazine->setHidden(!isExp); - m_ui->lblMag->setHidden(!isExp); - m_ui->sbMagazine->setHidden(!isExp); - m_smokeState->setHidden(isExp); - - - if (m_safetyConfirmationWidget) - { - bool hasNoWarnings = m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); - m_ui->pbConfirmReadiness->setEnabled(hasNoWarnings); - } - - - setBatteryVoltage(data.batteryVoltage()); - - if (data.vehicleFeature() != EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke)) - { - if (data.vehicleFeature() == EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::NotSpecified)) - return; - - int max = data.vehicleFeature() == EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion24) ? 24 : 48; - m_ui->sbMagazine->setMaximum(max); - m_ui->sbAvailable->setMaximum(255); - - m_ui->ledFwdLh->setStatus(data.firingUnitReadyFwdLh()); - m_ui->ledAftLh->setStatus(data.firingUnitReadyAftLh()); - m_ui->ledFwdRh->setStatus(data.firingUnitReadyFwdRh()); - m_ui->ledAftRh->setStatus(data.firingUnitReadyAftRh()); - } - else - { - - m_ui->sbMagazine->setMaximum(5); - m_ui->sbAvailable->setMaximum(12); - QVector onColor = + if (data.vehicleFeature() == + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion24)) { - data.smokeCartridge1().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge2().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge3().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge4().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0), - data.smokeCartridge5().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready ? QColor(0, 255, 0) : QColor(255, 255, 0) - }; - QVector status = + m_ui->ledAftLh->hide(); + m_ui->ledAftRh->hide(); + } + else if (data.vehicleFeature() == + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion48)) { - ((data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ), - ((data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || - (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking) - ) - }; + m_ui->ledAftLh->show(); + m_ui->ledAftRh->show(); + } + bool isExp = data.vehicleFeature() != + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke); + m_ui->frame->setHidden(!isExp); + m_ui->lblMagazine->setHidden(!isExp); + m_ui->lblMag->setHidden(!isExp); + m_ui->sbMagazine->setHidden(!isExp); + m_smokeState->setHidden(isExp); - m_smokeState->setSmokeState(status, onColor); + if (m_safetyConfirmationWidget) + { + bool hasNoWarnings = m_safetyConfirmationWidget->onOperatingConditionEntityChanged(data); + m_ui->pbConfirmReadiness->setEnabled(hasNoWarnings); + } - } + setBatteryVoltage(data.batteryVoltage()); - - m_ui->ltsLedWidget->setColor(data.readiness() ? QColor(0, 255, 0) : QColor(255, 0, 0)); - m_ui->ltsLedWidget->setStatus(true); - if (m_ui->lblAva->text().toInt() != data.ammunitionAvailable()) - m_ui->sbAvailable->setValue(data.ammunitionAvailable()); - m_ui->lblAva->setText(QString::number(data.ammunitionAvailable())); - m_ui->lblMag->setText(QString::number(data.ammunitionMagazine())); - - - - - - + if (data.vehicleFeature() != + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke)) + { + if (data.vehicleFeature() == + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::NotSpecified)) + return; + + int max = data.vehicleFeature() == + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Explosion24) + ? 24 + : 48; + m_ui->sbMagazine->setMaximum(max); + m_ui->sbAvailable->setMaximum(255); + + m_ui->ledFwdLh->setStatus(data.firingUnitReadyFwdLh()); + m_ui->ledAftLh->setStatus(data.firingUnitReadyAftLh()); + m_ui->ledFwdRh->setStatus(data.firingUnitReadyFwdRh()); + m_ui->ledAftRh->setStatus(data.firingUnitReadyAftRh()); + } + else + { + + m_ui->sbMagazine->setMaximum(5); + m_ui->sbAvailable->setMaximum(12); + QVector onColor = { + data.smokeCartridge1().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge2().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge3().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge4().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0), + data.smokeCartridge5().underlying() <= EffectShowClient::StatusSmokeCartridge_e_def::Ready + ? QColor(0, 255, 0) + : QColor(255, 255, 0)}; + QVector status = { + ((data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge1().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge2().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge3().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge4().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking)), + ((data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Ready) || + (data.smokeCartridge5().underlying() == EffectShowClient::StatusSmokeCartridge_e_def::Smoking))}; + + m_smokeState->setSmokeState(status, onColor); + } + + m_ui->ltsLedWidget->setColor(data.readiness() ? QColor(0, 255, 0) : QColor(255, 0, 0)); + m_ui->ltsLedWidget->setStatus(true); + if (m_ui->lblAva->text().toInt() != data.ammunitionAvailable()) + m_ui->sbAvailable->setValue(data.ammunitionAvailable()); + m_ui->lblAva->setText(QString::number(data.ammunitionAvailable())); + m_ui->lblMag->setText(QString::number(data.ammunitionMagazine())); } -void OperatingCondition::onFiringExplosionEntityChanged(const FiringExplosionEntity &data, DataModification modType) +void OperatingCondition::onFiringExplosionEntityChanged(const FiringExplosionEntity& data, DataModification modType) { - Q_UNUSED(modType) + Q_UNUSED(modType) - m_safetyConfirmation = data.safetyConfirmation(); - onSafetyConfirmationDisplay(); + m_safetyConfirmation = data.safetyConfirmation(); + onSafetyConfirmationDisplay(); } -void OperatingCondition::onFiringSmokeEntityChanged(const FiringSmokeEntity &data, DataModification modType) +void OperatingCondition::onFiringSmokeEntityChanged(const FiringSmokeEntity& data, DataModification modType) { - Q_UNUSED(modType) - m_safetyConfirmation = data.safetyConfirmation(); - onSafetyConfirmationDisplay(); + Q_UNUSED(modType) + m_safetyConfirmation = data.safetyConfirmation(); + onSafetyConfirmationDisplay(); } void OperatingCondition::onSafetyConfirmationDisplay() { - if (!m_safetyConfirmationWidget) - return; - m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation.underlying()); + if (!m_safetyConfirmationWidget) + return; + m_safetyConfirmationWidget->setNewSafetyConfirmationDisplay(m_safetyConfirmation.underlying()); } bool OperatingCondition::onSendRevokeReadiness() { - bool ret = m_requestHelper->startSingleRequest([this]() - { - EffectShowClient::SendReadinessRequest request; - request.readiness(false); - return m_ftc->sendReadinessRequest(request, this); - }); + bool ret = m_requestHelper->startSingleRequest([this]() { + EffectShowClient::SendReadinessRequest request; + request.readiness(false); + return m_ftc->sendReadinessRequest(request, this); + }); - return ret; + return ret; } bool OperatingCondition::onSendConfirmReadiness() { - bool ret = m_requestHelper->startSingleRequest([this]() - { - EffectShowClient::SendReadinessRequest request; - request.readiness(true); - return m_ftc->sendReadinessRequest(request, this); - }); + bool ret = m_requestHelper->startSingleRequest([this]() { + EffectShowClient::SendReadinessRequest request; + request.readiness(true); + return m_ftc->sendReadinessRequest(request, this); + }); - return ret; + return ret; } - -void OperatingCondition::onMeteoNearVehicleChanged(const EffectShowClient::MeteoNearVehicle &data, DataModification modType) +void OperatingCondition::onMeteoNearVehicleChanged(const EffectShowClient::MeteoNearVehicle& data, + DataModification modType) { - if (modType == DataModification::eRemoved) - return; + if (modType == DataModification::eRemoved) + return; - m_meteoTimer->start(m_meteoTimerTimeout); - m_ui->leTemperature->setText(QString::number(data.temperature(), 'f', 2)); - m_ui->leHumidity->setText(QString::number(data.humidity(), 'f', 2)); - m_ui->lePressure->setText(QString::number(data.pressure(), 'f', 2)); - m_ui->leWindSpeed->setText(QString::number(data.windSpeed(), 'f', 2)); - m_ui->leWindDirection->setText(QString::number(data.windDirection(), 'f', 2)); - m_ui->leLastUpdate->setText(DTG::toString(QDateTime::currentDateTime())); + m_meteoTimer->start(m_meteoTimerTimeout); + m_ui->leTemperature->setText(QString::number(data.temperature(), 'f', 2)); + m_ui->leHumidity->setText(QString::number(data.humidity(), 'f', 2)); + m_ui->lePressure->setText(QString::number(data.pressure(), 'f', 2)); + m_ui->leWindSpeed->setText(QString::number(data.windSpeed(), 'f', 2)); + m_ui->leWindDirection->setText(QString::number(data.windDirection(), 'f', 2)); + m_ui->leLastUpdate->setText(DTG::toString(QDateTime::currentDateTime())); } void OperatingCondition::onMeteoTimeout() { - const QLatin1String lit("---"); - m_ui->leTemperature->setText(lit); - m_ui->leHumidity->setText(lit); - m_ui->lePressure->setText(lit); - m_ui->leWindSpeed->setText(lit); - m_ui->leWindDirection->setText(lit); - m_ui->leLastUpdate->clear(); + const QLatin1String lit("---"); + m_ui->leTemperature->setText(lit); + m_ui->leHumidity->setText(lit); + m_ui->lePressure->setText(lit); + m_ui->leWindSpeed->setText(lit); + m_ui->leWindDirection->setText(lit); + m_ui->leLastUpdate->clear(); } - bool OperatingCondition::onSendAmmunition() { - if (m_ui->sbMagazine->value() > m_ui->sbAvailable->value()) - { - new LtsWidgets::LtsMessageDialogNew(this, tr("The value for Magazine must not be higher than the value for Available.")); - QPalette *palette = new QPalette(); - palette->setColor(QPalette::Background, Qt::red); - m_ui->sbMagazine->setPalette(*palette); - return false; - } + if (m_ui->sbMagazine->value() > m_ui->sbAvailable->value()) + { + new LtsWidgets::LtsMessageDialogNew( + this, tr("The value for Magazine must not be higher than the value for Available.")); + QPalette* palette = new QPalette(); + palette->setColor(QPalette::Background, Qt::red); + m_ui->sbMagazine->setPalette(*palette); + return false; + } - m_ui->sbMagazine->setPalette(QApplication::palette(m_ui->sbMagazine)); + m_ui->sbMagazine->setPalette(QApplication::palette(m_ui->sbMagazine)); - return m_requestHelper->startSingleRequest([this]() - { - EffectShowClient::SendAmmunitionRequest request; - const OperatingConditionEntity &condition = m_dtc->operatingConditionEntity(); - if (condition.vehicleFeature() == EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke)) - request.ammunitionMagazine(getSmokeCount()); - else - request.ammunitionMagazine(m_ui->sbMagazine->value()); + return m_requestHelper->startSingleRequest([this]() { + EffectShowClient::SendAmmunitionRequest request; + const OperatingConditionEntity& condition = m_dtc->operatingConditionEntity(); + if (condition.vehicleFeature() == + EffectShowManagement::Feature_e::inner_enum(EffectShowManagement::Feature_e_def::Smoke)) + request.ammunitionMagazine(getSmokeCount()); + else + request.ammunitionMagazine(m_ui->sbMagazine->value()); - request.ammunitionAvailable(m_ui->sbAvailable->value()); - - return m_ftc->sendAmmunitionRequest(request, this); - }); + request.ammunitionAvailable(m_ui->sbAvailable->value()); + return m_ftc->sendAmmunitionRequest(request, this); + }); } - void OperatingCondition::setBatteryVoltageConstraints(double redBoundary, double yellowBoundary, double greenMaximum) { - m_batteryVoltage.redBoundary = redBoundary; - m_batteryVoltage.yellowBoundary = yellowBoundary; - m_batteryVoltage.greenMaximum = greenMaximum; + m_batteryVoltage.redBoundary = redBoundary; + m_batteryVoltage.yellowBoundary = yellowBoundary; + m_batteryVoltage.greenMaximum = greenMaximum; - QRect greenRect = m_ui->frameGreenVoltage->geometry(); - double greenWidth = (double)greenRect.width(); - QRect setVal = greenRect; + QRect greenRect = m_ui->frameGreenVoltage->geometry(); + double greenWidth = (double)greenRect.width(); + QRect setVal = greenRect; - setVal.setWidth((int)(greenWidth * redBoundary / greenMaximum)); - m_ui->frameRedVoltage->setGeometry(setVal); + setVal.setWidth((int)(greenWidth * redBoundary / greenMaximum)); + m_ui->frameRedVoltage->setGeometry(setVal); - setVal.setWidth((int)(greenWidth * yellowBoundary / greenMaximum)); - m_ui->frameYellowVoltage->setGeometry(setVal); + setVal.setWidth((int)(greenWidth * yellowBoundary / greenMaximum)); + m_ui->frameYellowVoltage->setGeometry(setVal); } - void OperatingCondition::setBatteryVoltage(double batteryVoltage) { - - if (batteryVoltage < m_batteryVoltage.redBoundary) - m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(255, 0, 0)")); - else if (batteryVoltage < m_batteryVoltage.yellowBoundary) - m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(255, 255, 0)")); - else - m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(0, 255, 0)")); - - QRect barRect = m_ui->frameBarVoltage->geometry(); - barRect.setWidth((int)(m_batteryVoltage.maximumValue * batteryVoltage / m_batteryVoltage.greenMaximum)); - m_ui->frameBarVoltage->setGeometry(barRect); + if (batteryVoltage < m_batteryVoltage.redBoundary) + m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(255, 0, 0)")); + else if (batteryVoltage < m_batteryVoltage.yellowBoundary) + m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(255, 255, 0)")); + else + m_ui->leVoltage->setStyleSheet(QLatin1String("background-color: rgb(0, 255, 0)")); - - m_ui->leVoltage->setText(QString::number(batteryVoltage, 'f', 1)); + QRect barRect = m_ui->frameBarVoltage->geometry(); + barRect.setWidth((int)(m_batteryVoltage.maximumValue * batteryVoltage / m_batteryVoltage.greenMaximum)); + m_ui->frameBarVoltage->setGeometry(barRect); + + m_ui->leVoltage->setText(QString::number(batteryVoltage, 'f', 1)); } -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.h old mode 100755 new mode 100644 index c6bef8845..10bd8e1df --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_operating_condition.h @@ -1,15 +1,13 @@ - #pragma once -#include -#include -#include #include #include - +#include #include +#include +#include namespace Ui { @@ -23,75 +21,80 @@ class ForeignGuiInterface; namespace EffectShowClient { - class SmokeState; - class SafetyConfirmationWidget; - - +class SmokeState; +class SafetyConfirmationWidget; class OperatingCondition : public LtsWidgets::LtsDialog, - protected EffectShowClient::Interface::Ftc::SendAmmunitionReplyHandler, - protected EffectShowClient::Interface::Ftc::SendReadinessReplyHandler + protected EffectShowClient::Interface::Ftc::SendAmmunitionReplyHandler, + protected EffectShowClient::Interface::Ftc::SendReadinessReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit OperatingCondition(QWidget *parent = nullptr); - ~OperatingCondition(); + public: + explicit OperatingCondition(QWidget* parent = nullptr); + ~OperatingCondition(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc); -private: -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSendAmmunitionReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - void onSendReadinessReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - int getSmokeCount(); + bool init(const std::shared_ptr& dtc, + const std::shared_ptr& ftc); -private Q_SLOTS: - void onMeteoNearVehicleChanged(const EffectShowClient::MeteoNearVehicle &data, DataModification modType); - void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity &data, DataModification modType); - void onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity &data, DataModification modType); - void onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity &data, DataModification modType); - void onSafetyConfirmationDisplay(); - bool onSendRevokeReadiness(); - bool onSendConfirmReadiness(); + private: + NGL::INGLLogger& m_logger; + void retranslate() override; - bool onSendAmmunition(); + void onSendAmmunitionReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private: - + void onSendReadinessReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } - struct BatteryVoltage_t - { - double redBoundary = 5; - double yellowBoundary = 15; - double greenMaximum = 25; - double maximumValue = 100; - }; - + int getSmokeCount(); - void setBatteryVoltageConstraints(double redBoundary, double yellowBoundary, double greenMaximum); - + private Q_SLOTS: + void onMeteoNearVehicleChanged(const EffectShowClient::MeteoNearVehicle& data, DataModification modType); + void onOperatingConditionEntityChanged(const EffectShowClient::OperatingConditionEntity& data, + DataModification modType); + void onFiringExplosionEntityChanged(const EffectShowClient::FiringExplosionEntity& data, DataModification modType); + void onFiringSmokeEntityChanged(const EffectShowClient::FiringSmokeEntity& data, DataModification modType); + void onSafetyConfirmationDisplay(); + bool onSendRevokeReadiness(); + bool onSendConfirmReadiness(); - void setBatteryVoltage(double batteryVoltage); - void onMeteoTimeout(); + bool onSendAmmunition(); -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; + private: + struct BatteryVoltage_t + { + double redBoundary = 5; + double yellowBoundary = 15; + double greenMaximum = 25; + double maximumValue = 100; + }; - EffectShowClient::OperatingConditionEntity m_lastState; - EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; + void setBatteryVoltageConstraints(double redBoundary, double yellowBoundary, double greenMaximum); - int m_meteoTimerTimeout; - QTimer *m_meteoTimer; + void setBatteryVoltage(double batteryVoltage); + void onMeteoTimeout(); - SmokeState *m_smokeState; - SafetyConfirmationWidget *m_safetyConfirmationWidget; - Ui::OperatingCondition *m_ui; - LtsUtils::RequestHelper *m_requestHelper; + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; - BatteryVoltage_t m_batteryVoltage; + EffectShowClient::OperatingConditionEntity m_lastState; + EffectShowClient::SafetyConfirmation_e m_safetyConfirmation; + + int m_meteoTimerTimeout; + QTimer* m_meteoTimer; + + SmokeState* m_smokeState; + SafetyConfirmationWidget* m_safetyConfirmationWidget; + Ui::OperatingCondition* m_ui; + LtsUtils::RequestHelper* m_requestHelper; + + BatteryVoltage_t m_batteryVoltage; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.cpp old mode 100755 new mode 100644 index 1a66c9dc1..8460f6f98 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.cpp @@ -1,213 +1,209 @@ - #include "esc_order_edit.h" + #include "ui_esc_order_edit.h" #include - namespace EffectShowClient { -OrderEdit::OrderEdit(const Order &order, bool fireReadinessAvailable, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel) - , m_ftc(nullptr) - , m_ui(new Ui::OrderEdit) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_order(order) - , m_fireReadinessAvailable(fireReadinessAvailable) +OrderEdit::OrderEdit(const Order& order, bool fireReadinessAvailable, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel), m_ftc(nullptr), m_ui(new Ui::OrderEdit), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_order(order), + m_fireReadinessAvailable(fireReadinessAvailable) { - m_ui->setupUi(this); + m_ui->setupUi(this); } OrderEdit::~OrderEdit() { - delete m_ui; + delete m_ui; } -bool OrderEdit::init(const std::shared_ptr &ftc, EffectShowManagement::OrderConfirmation_e order) +bool OrderEdit::init(const std::shared_ptr& ftc, + EffectShowManagement::OrderConfirmation_e order) { - DEBUG_LOG(m_logger) << "OrderEdit::init()"; + DEBUG_LOG(m_logger) << "OrderEdit::init()"; - if (!ftc) - { - ERROR_LOG(m_logger) << "OrderEdit::init() Invalid shared_ptr!"; - return false; - } + if (!ftc) + { + ERROR_LOG(m_logger) << "OrderEdit::init() Invalid shared_ptr!"; + return false; + } - m_ftc = ftc; + m_ftc = ftc; - - QFont cbFont = m_ui->cbOrderConfirmation->font(); + QFont cbFont = m_ui->cbOrderConfirmation->font(); #ifdef TABLET_MODE - m_ui->cbxAnswer->setMinimumHeight(50); - cbFont.setPointSizeF(cbFont.pointSizeF()*1.5); + m_ui->cbxAnswer->setMinimumHeight(50); + cbFont.setPointSizeF(cbFont.pointSizeF() * 1.5); #endif - m_ui->cbOrderConfirmation->setFont(cbFont); - m_ui->cbxAnswer->setFont(cbFont); + m_ui->cbOrderConfirmation->setFont(cbFont); + m_ui->cbxAnswer->setFont(cbFont); - createOrderList(); - if (order == EffectShowManagement::OrderConfirmation_e::WaitingForAcceptance) - showOrder(); - else - { - m_ui->cbOrderConfirmation->addItem(m_orderList[order.underlying()]); - m_ui->cbOrderConfirmation->setEnabled(false); - slotChangesMade(); - setUnchangeable(true); - } + createOrderList(); + if (order == EffectShowManagement::OrderConfirmation_e::WaitingForAcceptance) + showOrder(); + else + { + m_ui->cbOrderConfirmation->addItem(m_orderList[order.underlying()]); + m_ui->cbOrderConfirmation->setEnabled(false); + slotChangesMade(); + setUnchangeable(true); + } - if (m_ui->cbxAnswer->lineEdit()) - { - m_ui->cbxAnswer->lineEdit()->setFont(cbFont); - m_ui->cbxAnswer->lineEdit()->setMaxLength(39); - } - m_ui->cbxAnswer->addItem(QString()); - m_ui->cbxAnswer->addItem(tr("Remaining time not sufficient")); - m_ui->cbxAnswer->addItem(tr("Not enough ammunition for order")); - m_ui->cbxAnswer->addItem(tr("Presentation vehicle has got stuck")); - m_ui->cbxAnswer->addItem(tr("Commanding a fixed restricted area")); - m_ui->cbxAnswer->addItem(tr("Command into a variable restricted area")); - m_ui->cbxAnswer->addItem(tr("Maximum permissible working time exceeded")); - m_ui->cbxAnswer->addItem(tr("Order executed, no confirmation")); + if (m_ui->cbxAnswer->lineEdit()) + { + m_ui->cbxAnswer->lineEdit()->setFont(cbFont); + m_ui->cbxAnswer->lineEdit()->setMaxLength(39); + } + m_ui->cbxAnswer->addItem(QString()); + m_ui->cbxAnswer->addItem(tr("Remaining time not sufficient")); + m_ui->cbxAnswer->addItem(tr("Not enough ammunition for order")); + m_ui->cbxAnswer->addItem(tr("Presentation vehicle has got stuck")); + m_ui->cbxAnswer->addItem(tr("Commanding a fixed restricted area")); + m_ui->cbxAnswer->addItem(tr("Command into a variable restricted area")); + m_ui->cbxAnswer->addItem(tr("Maximum permissible working time exceeded")); + m_ui->cbxAnswer->addItem(tr("Order executed, no confirmation")); - m_uiRequirements->addRequirement({m_ui->lblOrderConfirmation, [this]() { return (m_ui->cbOrderConfirmation->currentIndex() != -1); }}); - m_uiRequirements->addRequirement({m_ui->lblAnswer, [this]() { return checkForAnswerUiRequirement(); }}); + m_uiRequirements->addRequirement( + {m_ui->lblOrderConfirmation, [this]() { return (m_ui->cbOrderConfirmation->currentIndex() != -1); }}); + m_uiRequirements->addRequirement({m_ui->lblAnswer, [this]() { return checkForAnswerUiRequirement(); }}); - return true; + return true; } bool OrderEdit::apply() { - - return m_requestHelper->startSingleRequest([this]() - { - OrderModifyRequest orderModifyRequest; - int key = m_orderList.key(m_ui->cbOrderConfirmation->currentText()); - EffectShowManagement::OrderConfirmation_e oc = EffectShowManagement::OrderConfirmation_e::inner_enum(key); - orderModifyRequest.orderConfirmation(oc); + return m_requestHelper->startSingleRequest([this]() { + OrderModifyRequest orderModifyRequest; - orderModifyRequest.answerText(m_ui->cbxAnswer->currentText().toStdString()); + int key = m_orderList.key(m_ui->cbOrderConfirmation->currentText()); + EffectShowManagement::OrderConfirmation_e oc = EffectShowManagement::OrderConfirmation_e::inner_enum(key); + orderModifyRequest.orderConfirmation(oc); - orderModifyRequest.id(m_order.id()); + orderModifyRequest.answerText(m_ui->cbxAnswer->currentText().toStdString()); - return m_ftc->orderModifyRequest(orderModifyRequest, this); - }); + orderModifyRequest.id(m_order.id()); + + return m_ftc->orderModifyRequest(orderModifyRequest, this); + }); } void OrderEdit::retranslate() { - if (m_order.typeOfOrder() == 0) - translate(m_ui, tr("Edit relocation order")); - else - translate(m_ui, tr("Edit Effectshow Order")); + if (m_order.typeOfOrder() == 0) + translate(m_ui, tr("Edit relocation order")); + else + translate(m_ui, tr("Edit Effectshow Order")); } bool OrderEdit::checkForAnswerUiRequirement() const { - if (m_ui->cbOrderConfirmation->currentIndex() == -1) - return true; + if (m_ui->cbOrderConfirmation->currentIndex() == -1) + return true; - int key = m_orderList.key(m_ui->cbOrderConfirmation->currentText()); - return !(((key == EffectShowManagement::OrderConfirmation_e_def::Nonacceptance) || - (key == EffectShowManagement::OrderConfirmation_e_def::Abort)) && - m_ui->cbxAnswer->currentText().isEmpty()); + int key = m_orderList.key(m_ui->cbOrderConfirmation->currentText()); + return !(((key == EffectShowManagement::OrderConfirmation_e_def::Nonacceptance) || + (key == EffectShowManagement::OrderConfirmation_e_def::Abort)) && + m_ui->cbxAnswer->currentText().isEmpty()); } void OrderEdit::showOrder() { - QStringList orderList; + QStringList orderList; - switch (m_order.orderConfirmation().underlying()) - { - case EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; + switch (m_order.orderConfirmation().underlying()) + { + case EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; - if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; + if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Nonacceptance]; - break; - case EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Nonacceptance]; + break; + case EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; - if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; + if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::DriveOff: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::DriveOff: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; - if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; + if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::PositionReached: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation]; - if (m_fireReadinessAvailable) - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::FiringReadiness: - - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::Execution: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; - if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - case EffectShowManagement::OrderConfirmation_e_def::InterruptExecution: - - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut] - << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - default: - orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; - break; - } - m_ui->cbOrderConfirmation->addItems(orderList); - m_ui->cbOrderConfirmation->setCurrentIndex(-1); + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::PositionReached: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation]; + if (m_fireReadinessAvailable) + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::FiringReadiness: + + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::Execution: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::DriveOff] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::PositionReached]; + if (m_order.typeOfOrder() != 0 && m_fireReadinessAvailable) + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::FiringReadiness]; + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + case EffectShowManagement::OrderConfirmation_e_def::InterruptExecution: + + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut] + << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + default: + orderList << m_orderList[EffectShowManagement::OrderConfirmation_e_def::Abort]; + break; + } + m_ui->cbOrderConfirmation->addItems(orderList); + m_ui->cbOrderConfirmation->setCurrentIndex(-1); } void OrderEdit::createOrderList() { - EffectShowManagement::OrderConfirmation_e oc = EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::DriveOff; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::PositionReached; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::FiringReadiness; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::Execution; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::InterruptExecution; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::Abort; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::Nonacceptance; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); - oc = EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation; - m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + EffectShowManagement::OrderConfirmation_e oc = EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::OrderAcceptance; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::DriveOff; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::PositionReached; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::FiringReadiness; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::Execution; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::InterruptExecution; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::Abort; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::Nonacceptance; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); + oc = EffectShowManagement::OrderConfirmation_e_def::InterruptRelocation; + m_orderList[oc.underlying()] = EffectShowManagement::toString(oc); } -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.h old mode 100755 new mode 100644 index f77ff8ac8..5ce6b683e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_edit.h @@ -1,14 +1,12 @@ - #pragma once #include "esc_order_model.h" -#include -#include #include #include - +#include +#include namespace Ui { @@ -18,37 +16,40 @@ class OrderEdit; namespace EffectShowClient { - -class OrderEdit : public LtsWidgets::LtsDialog, - protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler +class OrderEdit : public LtsWidgets::LtsDialog, protected EffectShowClient::Interface::Ftc::OrderModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit OrderEdit(const Order &order, bool fireReadinessAvailable, QWidget *parent = nullptr); - ~OrderEdit(); + public: + explicit OrderEdit(const Order& order, bool fireReadinessAvailable, QWidget* parent = nullptr); + ~OrderEdit(); - bool init(const std::shared_ptr &ftc, EffectShowManagement::OrderConfirmation_e order = EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance); - bool apply() override; + bool init(const std::shared_ptr& ftc, + EffectShowManagement::OrderConfirmation_e order = + EffectShowManagement::OrderConfirmation_e_def::WaitingForAcceptance); + bool apply() override; -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool checkForAnswerUiRequirement() const; + void showOrder(); + void createOrderList(); -NGL::INGLLogger &m_logger; - void retranslate() override; - bool checkForAnswerUiRequirement() const; - void showOrder(); - void createOrderList(); - void onOrderModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onOrderModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private: - std::shared_ptr m_ftc; - Ui::OrderEdit *m_ui; - LtsUtils::RequestHelper *m_requestHelper; - Order m_order; - bool m_fireReadinessAvailable; - EffectShowManagement::OrderConfirmation_e_def m_forcedState; - QHash m_orderList; + private: + std::shared_ptr m_ftc; + Ui::OrderEdit* m_ui; + LtsUtils::RequestHelper* m_requestHelper; + Order m_order; + bool m_fireReadinessAvailable; + EffectShowManagement::OrderConfirmation_e_def m_forcedState; + QHash m_orderList; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.cpp old mode 100755 new mode 100644 index 59b3d7c14..c38121cd4 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.cpp @@ -1,281 +1,258 @@ - #include "esc_order_list.h" -#include "ui_esc_order_list.h" -#include "esc_order_model.h" -#include "esc_order_edit.h" + #include "esc_firing_explosion.h" #include "esc_firing_smoke.h" -#include -#include +#include "esc_order_edit.h" +#include "esc_order_model.h" +#include "ui_esc_order_list.h" #include #include +#include +#include #include namespace EffectShowClient { -OrderList::OrderList(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_menuGroup(menuGroup) - , m_model(nullptr) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_sitMapGuiIfc(nullptr) - , m_session(session) - , m_ui(new Ui::OrderList) - , m_isEffectShow(false) +OrderList::OrderList(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_menuGroup(menuGroup), m_model(nullptr), + m_dtc(nullptr), m_ftc(nullptr), m_sitMapGuiIfc(nullptr), m_session(session), m_ui(new Ui::OrderList), + m_isEffectShow(false) { - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &OrderList::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &OrderList::onSelectionChanged); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &OrderList::onEditOrder); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &OrderList::onEditOrder); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &OrderList::onEditOrder); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, &OrderList::onShowOrder); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &OrderList::onEditOrder); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &OrderList::onPrint); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Show, this, &OrderList::onShowOrder); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &OrderList::onCreateShowEscOrderPosition); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &OrderList::onPrint); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &OrderList::onRemoveEscOrderPosition); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &OrderList::onCreateShowEscOrderPosition); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &OrderList::onRemoveEscOrderPosition); - - m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Create ESC Order Pos")); - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Remove ESC Order Pos")); + m_buttonBox->setText(LtsWidgets::DialogButton::Add, tr("Create ESC Order Pos")); + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Remove ESC Order Pos")); - setOnlineHelpFilename(QLatin1String("OC-Order_List")); - -} + setOnlineHelpFilename(QLatin1String("OC-Order_List")); +} OrderList::~OrderList() { - delete m_ui; -} + delete m_ui; +} -bool OrderList::init(bool isEffectShow, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &dtcTabOC) +bool OrderList::init(bool isEffectShow, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& dtcTabOC) { - if (!dtc || !ftc) - return false; + if (!dtc || !ftc) + return false; - m_dtc = dtc; - m_ftc = ftc; - if (!m_session->getForeignGuiInterface(m_sitMapGuiIfc)) - return false; - EffectShowManagement::Feature_e feature = m_dtc->operatingConditionEntity().vehicleFeature(); - if (isEffectShow && feature == EffectShowManagement::Feature_e::NotSpecified) - return false; + m_dtc = dtc; + m_ftc = ftc; + if (!m_session->getForeignGuiInterface(m_sitMapGuiIfc)) + return false; + EffectShowManagement::Feature_e feature = m_dtc->operatingConditionEntity().vehicleFeature(); + if (isEffectShow && feature == EffectShowManagement::Feature_e::NotSpecified) + return false; - m_isEffectShow = isEffectShow; + m_isEffectShow = isEffectShow; - bool isSmoke = (feature == EffectShowManagement::Feature_e::Smoke); - - m_model = new OrderModel(this); - m_model->initModel(m_dtc, dtcTabOC, m_isEffectShow); - m_proxyModel = new OrderProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->widget->setModel(m_proxyModel); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Type); - connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::orderChanged, - this, &OrderList::onSelectionChanged); + bool isSmoke = (feature == EffectShowManagement::Feature_e::Smoke); + m_model = new OrderModel(this); + m_model->initModel(m_dtc, dtcTabOC, m_isEffectShow); + m_proxyModel = new OrderProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->widget->setModel(m_proxyModel); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Type); + connect(m_dtc.get(), &EffectShowClient::Interface::Dtc::orderChanged, this, &OrderList::onSelectionChanged); #ifndef LTS_DEBUG - + #endif - if (m_isEffectShow) - { - if (isSmoke) + if (m_isEffectShow) { - - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Volley); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::ShotsInTotal); + if (isSmoke) + { + + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Volley); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::ShotsInTotal); + } + else + { + + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Area); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Rotation); + } } else { - - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Area); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Rotation); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Duration); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Area); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Rotation); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::Volley); + m_ui->widget->hideColumn(EffectShowClient::OrderModel::ShotsInTotal); } - } - else - { - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Duration); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Area); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Rotation); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::Volley); - m_ui->widget->hideColumn(EffectShowClient::OrderModel::ShotsInTotal); - } - DEBUG_LOG(m_logger) << "esc Order is visible:" << m_sitMapGuiIfc->isEscOrderPositionVisible(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_sitMapGuiIfc->isEscOrderPositionVisible()); - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Show, m_isEffectShow); + DEBUG_LOG(m_logger) << "esc Order is visible:" << m_sitMapGuiIfc->isEscOrderPositionVisible(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, m_sitMapGuiIfc->isEscOrderPositionVisible()); + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Show, m_isEffectShow); - return true; -} + return true; +} void OrderList::retranslate() { - if (m_isEffectShow) - translate(m_ui, tr("Order List")); - else - translate(m_ui, tr("Relocation List")); - + if (m_isEffectShow) + translate(m_ui, tr("Order List")); + else + translate(m_ui, tr("Relocation List")); } void OrderList::onSelectionChanged() { - if (m_ui->widget->selectionModel()->selectedRows().size() <= 0) - { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); - return; - } + if (m_ui->widget->selectionModel()->selectedRows().size() <= 0) + { + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, false); + return; + } - const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - const EffectShowClient::Order order = m_model->getRowData(row); - bool isReady = order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::FiringReadiness - || order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::Execution; + const QModelIndex idx = m_ui->widget->currentIndex(); + int row = idx.row(); + const EffectShowClient::Order order = m_model->getRowData(row); + bool isReady = order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::FiringReadiness || + order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::Execution; - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, isReady); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); -} + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Show, isReady); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); +} void OrderList::onEditOrder() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - const EffectShowClient::Order order = m_model->getRowData(row); + const EffectShowClient::Order order = m_model->getRowData(row); - - DEBUG_LOG(m_logger) << "--- onEditOrder() "; - if (order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut) - return; - bool fireReadinessEnable = true; - const auto orders = m_dtc->orders(); - for (const auto &ord : orders) - { - if (ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::FiringReadiness || - ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::InterruptExecution || - ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::Execution) + DEBUG_LOG(m_logger) << "--- onEditOrder() "; + if (order.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut) + return; + bool fireReadinessEnable = true; + const auto orders = m_dtc->orders(); + for (const auto& ord : orders) { - - fireReadinessEnable = false; - break; + if (ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::FiringReadiness || + ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::InterruptExecution || + ord.orderConfirmation() == EffectShowManagement::OrderConfirmation_e_def::Execution) + { + + fireReadinessEnable = false; + break; + } } - } - - OrderEdit *dialog = new OrderEdit(order, fireReadinessEnable, this); - dialog->init(m_ftc); - addDialog(dialog, m_menuGroup, QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); + OrderEdit* dialog = new OrderEdit(order, fireReadinessEnable, this); + dialog->init(m_ftc); + addDialog(dialog, m_menuGroup, QLatin1String("escOrder"), LtsWidgets::LayoutArea::eDialogTab); } - void OrderList::onShowOrder() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - EffectShowManagement::Feature_e feature = m_dtc->operatingConditionEntity().vehicleFeature(); - if (feature == EffectShowManagement::Feature_e::NotSpecified) - return; + EffectShowManagement::Feature_e feature = m_dtc->operatingConditionEntity().vehicleFeature(); + if (feature == EffectShowManagement::Feature_e::NotSpecified) + return; - if (feature == EffectShowManagement::Feature_e::Smoke) - { - FiringSmoke *dialog = new FiringSmoke(this); - if (!dialog->init(m_dtc, m_ftc, m_session)) + if (feature == EffectShowManagement::Feature_e::Smoke) { - delete dialog; - return; + FiringSmoke* dialog = new FiringSmoke(this); + if (!dialog->init(m_dtc, m_ftc, m_session)) + { + delete dialog; + return; + } + addDialog(dialog, m_menuGroup, QLatin1String("escFiringSmoke")); } - addDialog(dialog, m_menuGroup, QLatin1String("escFiringSmoke")); - } - else if (feature == EffectShowManagement::Feature_e::Explosion24 || - feature == EffectShowManagement::Feature_e::Explosion48) - { - FiringExplosion *dialog = new FiringExplosion(this); - if (!dialog->init(m_dtc, m_ftc, m_session)) + else if (feature == EffectShowManagement::Feature_e::Explosion24 || + feature == EffectShowManagement::Feature_e::Explosion48) { - delete dialog; - return; + FiringExplosion* dialog = new FiringExplosion(this); + if (!dialog->init(m_dtc, m_ftc, m_session)) + { + delete dialog; + return; + } + addDialog(dialog, m_menuGroup, QLatin1String("escFiringExplosion")); } - addDialog(dialog, m_menuGroup, QLatin1String("escFiringExplosion")); - } } void OrderList::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); -} - + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); +} void OrderList::onCreateShowEscOrderPosition() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - const EffectShowClient::Order order = m_model->getRowData(row); + const EffectShowClient::Order order = m_model->getRowData(row); - bool is_smoke = m_dtc.get()->operatingConditionEntity().vehicleFeature() == EffectShowManagement::Feature_e::Smoke && m_isEffectShow; + bool is_smoke = + m_dtc.get()->operatingConditionEntity().vehicleFeature() == EffectShowManagement::Feature_e::Smoke && + m_isEffectShow; - const QPointF &pos = QPointF(order.position().lon(), order.position().lat()); - m_sitMapGuiIfc->escOrderPosition_create(pos, order.areaWidth(), order.areaDepth(), order.areaRotation(), is_smoke); - m_sitMapGuiIfc->setCenterPoint(pos); + const QPointF& pos = QPointF(order.position().lon(), order.position().lat()); + m_sitMapGuiIfc->escOrderPosition_create(pos, order.areaWidth(), order.areaDepth(), order.areaRotation(), is_smoke); + m_sitMapGuiIfc->setCenterPoint(pos); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, false); } - void OrderList::onRemoveEscOrderPosition() { - m_sitMapGuiIfc->escOrderPosition_remove(); + m_sitMapGuiIfc->escOrderPosition_remove(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - DEBUG_LOG(m_logger) << "esc Order row selected:" << m_ui->widget->selectionModel()->selectedRows().size(); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, m_ui->widget->selectionModel()->selectedRows().size() > 0); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + DEBUG_LOG(m_logger) << "esc Order row selected:" << m_ui->widget->selectionModel()->selectedRows().size(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, + m_ui->widget->selectionModel()->selectedRows().size() > 0); } void OrderList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } - -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.h old mode 100755 new mode 100644 index df316b810..2ecef7762 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_list.h @@ -1,15 +1,13 @@ - #pragma once #include #include -#include - -#include -#include #include +#include +#include +#include namespace Ui { @@ -26,44 +24,40 @@ namespace EffectShowClient class OrderModel; class OrderProxyModel; - - class OrderList : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit OrderList(const QString &menuGroup, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~OrderList(); - bool init(bool isEffectShow, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &dtcTabOC); + public: + explicit OrderList(const QString& menuGroup, LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~OrderList(); + bool init(bool isEffectShow, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& dtcTabOC); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onEditOrder(); + void onShowOrder(); + void onPrint(); + void onCreateShowEscOrderPosition(); + void onRemoveEscOrderPosition(); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onEditOrder(); - void onShowOrder(); - void onPrint(); - void onCreateShowEscOrderPosition(); - void onRemoveEscOrderPosition(); - void tableColumnOrganiserSetting() override; + private: + QString m_menuGroup; + OrderModel* m_model; + OrderProxyModel* m_proxyModel; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_sitMapGuiIfc; -private: - QString m_menuGroup; - OrderModel *m_model; - OrderProxyModel *m_proxyModel; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_sitMapGuiIfc; + LtsSession::LtsSession* m_session; + Ui::OrderList* m_ui; - LtsSession::LtsSession *m_session; - Ui::OrderList *m_ui; - - bool m_isEffectShow; + bool m_isEffectShow; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_model.h old mode 100755 new mode 100644 index 5c26731f6..4f8c6f41f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowClient/Gui/esc_order_model.h @@ -1,75 +1,68 @@ - #pragma once - #include #include -#include - #include #include +#include namespace EffectShowClient { - - class OrderModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Id, - Type, - Info, - Status, - StartTime, - Duration, - Distance, - Position, - Area, - Rotation, - Volley, - ShotsInTotal - }; - explicit OrderModel(QObject *parent = nullptr); + Q_OBJECT + public: + enum Columns { + Id, + Type, + Info, + Status, + StartTime, + Duration, + Distance, + Position, + Area, + Rotation, + Volley, + ShotsInTotal + }; - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &dtcTabOC, - bool isEffectShow); + explicit OrderModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& dtcTabOC, bool isEffectShow); - + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - static QString timeOfDayString(int seconds); -private slots: - bool onDataChanged(const EffectShowClient::Order &data, DataModification modType) override; - void onOwnPositionChanged(const TrainingAreaBaseOC::OwnPosition &data); + static QString timeOfDayString(int seconds); + private slots: + bool onDataChanged(const EffectShowClient::Order& data, DataModification modType) override; + void onOwnPositionChanged(const TrainingAreaBaseOC::OwnPosition& data); -private: - -NGL::INGLLogger &m_logger; - std::shared_ptr m_dtc; - std::shared_ptr m_dtcTabOC; - TrainingAreaBaseOC::OwnPosition m_ownPosition; - friend class OrderProxyModel; - bool m_isEffectShow = true; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_dtc; + std::shared_ptr m_dtcTabOC; + TrainingAreaBaseOC::OwnPosition m_ownPosition; + friend class OrderProxyModel; + bool m_isEffectShow = true; }; class OrderProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - OrderModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + OrderModel* m_sourceModel = nullptr; }; -} +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_list.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_list.h old mode 100755 new mode 100644 index 39c3882d6..f188c2904 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_list.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_list.h @@ -1,47 +1,43 @@ - #pragma once #include "esm_effect_show_model.h" -#include -#include - -#include #include +#include +#include +#include namespace Ui { class EffectShowActorList; } + namespace EffectShowManagement { - - class EffectShowActorList : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: - explicit EffectShowActorList(QWidget *parent = nullptr); - ~EffectShowActorList(); - bool init(LtsSession::LtsSession *session); + public: + explicit EffectShowActorList(QWidget* parent = nullptr); + ~EffectShowActorList(); + bool init(LtsSession::LtsSession* session); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onShowEffectShowActor(); + void onPrint(); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onShowEffectShowActor(); - void onPrint(); - void tableColumnOrganiserSetting() override; - -private: - EffectShowModel *m_effectShowModel; - LtsSession::LtsSession *m_session; - Ui::EffectShowActorList *m_ui; + private: + EffectShowModel* m_effectShowModel; + LtsSession::LtsSession* m_session; + Ui::EffectShowActorList* m_ui; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_model.h old mode 100755 new mode 100644 index 7236e287c..66659efeb --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_model.h @@ -1,106 +1,91 @@ - #pragma once #include "esm_effect_show_model.h" -#include #include #include - #include #include - +#include namespace EffectShowManagement { - class EffectShowActorProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT + Q_OBJECT -public: - EffectShowActorProxyModel(EffectShowActorModel *sourceModel, EffectShowModel *effectShowModel, QObject *parent); + public: + EffectShowActorProxyModel(EffectShowActorModel* sourceModel, EffectShowModel* effectShowModel, QObject* parent); -protected: + protected: + NGL::INGLLogger& m_logger; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; -NGL::INGLLogger &m_logger; - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; - - EffectShowModel *m_effectShowModel; - EffectShowActorModel *m_sourceModel; + EffectShowModel* m_effectShowModel; + EffectShowActorModel* m_sourceModel; }; - class EffectShowModel; - class EffectShowActorModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Name, - Status, - BITE, - Feature, - Position, - EffectShow, - Relocation, - RestMagazine, - RestAmmunition - }; + Q_OBJECT + public: + enum Columns { Name, Status, BITE, Feature, Position, EffectShow, Relocation, RestMagazine, RestAmmunition }; - enum eFeature - { - NotSpecified = Feature_e_def::NotSpecified, - Smoke = Feature_e_def::Smoke, - Explosion24 = Feature_e_def::Explosion24, - Explosion48 = Feature_e_def::Explosion48, - SmokeAndExplosion48 = Explosion48 + 1 - }; - static QVector s_features; + enum eFeature { + NotSpecified = Feature_e_def::NotSpecified, + Smoke = Feature_e_def::Smoke, + Explosion24 = Feature_e_def::Explosion24, + Explosion48 = Feature_e_def::Explosion48, + SmokeAndExplosion48 = Explosion48 + 1 + }; - enum eStatus - { - NotOperational = 0, - Operational = 1 - }; - static QVector s_status; + static QVector s_features; - explicit EffectShowActorModel(EffectShowModel *effectShowModel, QObject *parent); + enum eStatus { NotOperational = 0, Operational = 1 }; - bool initModel(LtsSession::LtsSession *session); + static QVector s_status; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + explicit EffectShowActorModel(EffectShowModel* effectShowModel, QObject* parent); - + bool initModel(LtsSession::LtsSession* session); - bool isFiltered(const ParticipantManagement::Participant &data, DataModification modType) const override final; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; - QVector::const_iterator getIt(int id) const; - QVector::const_iterator getItBegin() const { return m_vecData.begin(); } - QVector::const_iterator getItEnd() const { return m_vecData.end(); } - Feature_e getFeature(int rowId) const; - static QString getFeatureName(const eFeature &feature); - bool isOperational(int rowId) const; - bool isMatchedByFilter(const int &equipmentNumber, const int &featureFilter) const; + bool isFiltered(const ParticipantManagement::Participant& data, DataModification modType) const override final; -private: - void onParticipantPositionChanged(const ParticipantManagement::ParticipantPosition &data, DataModification modType); + QVector::const_iterator getIt(int id) const; - QString faultStatus(bool fault) const; + QVector::const_iterator getItBegin() const + { + return m_vecData.begin(); + } -private: - std::shared_ptr m_dtc; + QVector::const_iterator getItEnd() const + { + return m_vecData.end(); + } - QHash m_ppmPositions; + Feature_e getFeature(int rowId) const; + static QString getFeatureName(const eFeature& feature); + bool isOperational(int rowId) const; + bool isMatchedByFilter(const int& equipmentNumber, const int& featureFilter) const; - EffectShowModel *m_effectShowModel; - friend class EffectShowActorProxyModel; + private: + void onParticipantPositionChanged(const ParticipantManagement::ParticipantPosition& data, DataModification modType); + QString faultStatus(bool fault) const; + + private: + std::shared_ptr m_dtc; + + QHash m_ppmPositions; + + EffectShowModel* m_effectShowModel; + friend class EffectShowActorProxyModel; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.cpp old mode 100755 new mode 100644 index 75beda4b6..0d0435397 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.cpp @@ -1,189 +1,175 @@ - #include "esm_effect_show_actor_relocation_edit.h" -#include + #include "ParticipantManagement/ppm_data_plugin_interface.h" #include "esm_effect_show_actor_model.h" #include "esm_effect_show_actor_relocation_model.h" -#include "ui_esm_effect_show_actor_relocation_list.h" #include "ui_esm_effect_show_actor_relocation_edit.h" +#include "ui_esm_effect_show_actor_relocation_list.h" + #include +#include +#include #include #include -#include -#include - +#include namespace EffectShowManagement { -EffectShowActorRelocationEdit::EffectShowActorRelocationEdit(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_ppmDtc(nullptr) - , m_sitMapGuiIfc(nullptr) - , m_model(nullptr) - , m_session(nullptr) - , m_ui(new Ui::EffectShowActorRelocationEdit) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +EffectShowActorRelocationEdit::EffectShowActorRelocationEdit(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_dtc(nullptr), m_ftc(nullptr), + m_ppmDtc(nullptr), m_sitMapGuiIfc(nullptr), m_model(nullptr), m_session(nullptr), + m_ui(new Ui::EffectShowActorRelocationEdit), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); } - EffectShowActorRelocationEdit::~EffectShowActorRelocationEdit() { - delete m_ui; + delete m_ui; } void EffectShowActorRelocationEdit::getPosition() { - if (!m_sitMapGuiIfc) - return; + if (!m_sitMapGuiIfc) + return; - m_sitMapGuiIfc->getCoordinate(m_ui->cwCoordinate, SLOT(setCoordinate(QPointF)), nullptr); + m_sitMapGuiIfc->getCoordinate(m_ui->cwCoordinate, SLOT(setCoordinate(QPointF)), nullptr); } -void EffectShowActorRelocationEdit::onEffectShowActorFilterChanged(const int &idx) +void EffectShowActorRelocationEdit::onEffectShowActorFilterChanged(const int& idx) { - Q_UNUSED(idx); + Q_UNUSED(idx); - int selectedParticipantId = -1; - if (m_ui->cbEffectShowActor->count() > 0 && m_ui->cbEffectShowActor->currentIndex() >= 0) - selectedParticipantId = m_ui->cbEffectShowActor->currentData().toInt(); + int selectedParticipantId = -1; + if (m_ui->cbEffectShowActor->count() > 0 && m_ui->cbEffectShowActor->currentIndex() >= 0) + selectedParticipantId = m_ui->cbEffectShowActor->currentData().toInt(); - m_ui->cbEffectShowActor->clear(); + m_ui->cbEffectShowActor->clear(); - const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); - int i = 0; - for (auto it = m_effectShowActors.begin(); it != m_effectShowActors.end(); ++it) - { - auto iParticipant = m_model->getEffectShowActorModel()->getIt(it.key()); - if (iParticipant == m_model->getEffectShowActorModel()->getItEnd()) - continue; - if (!iParticipant->equipmentNumber().is_set()) - continue; - if (!m_model->getEffectShowActorModel()->isMatchedByFilter(iParticipant->equipmentNumber().get(), filter)) - continue; + const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); + int i = 0; + for (auto it = m_effectShowActors.begin(); it != m_effectShowActors.end(); ++it) + { + auto iParticipant = m_model->getEffectShowActorModel()->getIt(it.key()); + if (iParticipant == m_model->getEffectShowActorModel()->getItEnd()) + continue; + if (!iParticipant->equipmentNumber().is_set()) + continue; + if (!m_model->getEffectShowActorModel()->isMatchedByFilter(iParticipant->equipmentNumber().get(), filter)) + continue; - m_ui->cbEffectShowActor->addItem(it.value(), it.key()); - if (selectedParticipantId == it.key()) - m_ui->cbEffectShowActor->setCurrentIndex(i++); - } + m_ui->cbEffectShowActor->addItem(it.value(), it.key()); + if (selectedParticipantId == it.key()) + m_ui->cbEffectShowActor->setCurrentIndex(i++); + } } -void EffectShowActorRelocationEdit::onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus &data, - const DataModification &modType) +void EffectShowActorRelocationEdit::onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus& data, + const DataModification& modType) { - Q_UNUSED(modType); - int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(data.esmParticipantId()); - m_effectShowActors = m_model->getParticipantList(); - const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); - if (m_model->getEffectShowActorModel()->isMatchedByFilter(equipmentNumber, filter)) - onEffectShowActorFilterChanged(-1); + Q_UNUSED(modType); + int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(data.esmParticipantId()); + m_effectShowActors = m_model->getParticipantList(); + const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); + if (m_model->getEffectShowActorModel()->isMatchedByFilter(equipmentNumber, filter)) + onEffectShowActorFilterChanged(-1); } void EffectShowActorRelocationEdit::retranslate() { - translate(m_ui, QString(), true, tr("Actor Relocation")); + translate(m_ui, QString(), true, tr("Actor Relocation")); } - -bool EffectShowActorRelocationEdit::init(LtsSession::LtsSession *session, - EffectShowModel *model, - int rowToCopy) +bool EffectShowActorRelocationEdit::init(LtsSession::LtsSession* session, EffectShowModel* model, int rowToCopy) { - DEBUG_LOG(m_logger) << "EffectShowActorRelocationEdit::init()"; + DEBUG_LOG(m_logger) << "EffectShowActorRelocationEdit::init()"; - if (!session) - { - ERROR_LOG(m_logger) << "EffectShowActorRelocationEdit::init() Invalid shared_ptr!"; - return false; - } - - if (!session->getDtc(m_dtc)) - return false; - if (!session->getFtc(m_ftc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - - m_model = model; - m_session = session; - - m_session->getForeignGuiInterface(m_sitMapGuiIfc); - if (m_sitMapGuiIfc) - connect(m_ui->pbPosition, &QPushButton::clicked, this, &EffectShowActorRelocationEdit::getPosition); - - connect(m_ui->pbClear, &QPushButton::clicked, - m_ui->cwCoordinate, &LtsCoordWidget::LtsCoordWidget::clear); - - m_effectShowActors = m_model->getParticipantList(); - - - int idx = 1; - m_ui->cbEffectShowActorFilter->addItem(tr(""), EffectShowActorModel::eFeature::NotSpecified); - for (const EffectShowActorModel::eFeature &feature : std::as_const(EffectShowActorModel::s_features)) - { - m_ui->cbEffectShowActorFilter->addItem(EffectShowActorModel::getFeatureName(feature), static_cast(feature)); - if (feature == EffectShowActorModel::eFeature::SmokeAndExplosion48) - m_ui->cbEffectShowActorFilter->setCurrentIndex(idx); - ++idx; - } - onEffectShowActorFilterChanged(-1); - - connect(m_ui->cbEffectShowActorFilter, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &EffectShowActorRelocationEdit::onEffectShowActorFilterChanged); - - - connect(m_model, &EffectShowModel::effectShowVehicleStatusChanged, - this, &EffectShowActorRelocationEdit::onEffectShowVehicleStatusChanged); - - - m_ui->dteTime->setMinimumTimeMSec(m_session->partitionTime()); - m_ui->dteTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - - - m_uiRequirements->addRequirement({m_ui->lblCoordinate, [this]() { return (!m_ui->cwCoordinate->coordinate().isNull()); }}); - m_uiRequirements->addRequirement({m_ui->lblTime, [this]() { return (m_ui->dteTime->msecsSinceEpoch() > m_session->partitionTime()); }}); - m_uiRequirements->addRequirement({m_ui->lblEffectShowActor, [this]() { return (m_ui->cbEffectShowActor->currentIndex() != -1); }}); - - if (rowToCopy >= 0) - { - const EffectShowActorRelocation © = m_model->getEffetShowActorRelocationModel()->getRowData(rowToCopy); - if (copy.id() > 0) + if (!session) { - m_ui->cwCoordinate->setCoordinate(copy.position().lon(), copy.position().lat()); - m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(copy.esmParticipantId())); - m_ui->leInfo->setText(QString::fromStdString(copy.info())); - if (copy.arrival_time().is_set()) - m_ui->dteTime->setMsecsSinceEpoch(copy.arrival_time().get()); - slotChangesMade(); + ERROR_LOG(m_logger) << "EffectShowActorRelocationEdit::init() Invalid shared_ptr!"; + return false; } - } - return true; + if (!session->getDtc(m_dtc)) + return false; + if (!session->getFtc(m_ftc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + + m_model = model; + m_session = session; + + m_session->getForeignGuiInterface(m_sitMapGuiIfc); + if (m_sitMapGuiIfc) + connect(m_ui->pbPosition, &QPushButton::clicked, this, &EffectShowActorRelocationEdit::getPosition); + + connect(m_ui->pbClear, &QPushButton::clicked, m_ui->cwCoordinate, &LtsCoordWidget::LtsCoordWidget::clear); + + m_effectShowActors = m_model->getParticipantList(); + + int idx = 1; + m_ui->cbEffectShowActorFilter->addItem(tr(""), EffectShowActorModel::eFeature::NotSpecified); + for (const EffectShowActorModel::eFeature& feature : std::as_const(EffectShowActorModel::s_features)) + { + m_ui->cbEffectShowActorFilter->addItem(EffectShowActorModel::getFeatureName(feature), + static_cast(feature)); + if (feature == EffectShowActorModel::eFeature::SmokeAndExplosion48) + m_ui->cbEffectShowActorFilter->setCurrentIndex(idx); + ++idx; + } + onEffectShowActorFilterChanged(-1); + + connect(m_ui->cbEffectShowActorFilter, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &EffectShowActorRelocationEdit::onEffectShowActorFilterChanged); + + connect(m_model, &EffectShowModel::effectShowVehicleStatusChanged, this, + &EffectShowActorRelocationEdit::onEffectShowVehicleStatusChanged); + + m_ui->dteTime->setMinimumTimeMSec(m_session->partitionTime()); + m_ui->dteTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + + m_uiRequirements->addRequirement( + {m_ui->lblCoordinate, [this]() { return (!m_ui->cwCoordinate->coordinate().isNull()); }}); + m_uiRequirements->addRequirement( + {m_ui->lblTime, [this]() { return (m_ui->dteTime->msecsSinceEpoch() > m_session->partitionTime()); }}); + m_uiRequirements->addRequirement( + {m_ui->lblEffectShowActor, [this]() { return (m_ui->cbEffectShowActor->currentIndex() != -1); }}); + + if (rowToCopy >= 0) + { + const EffectShowActorRelocation& copy = m_model->getEffetShowActorRelocationModel()->getRowData(rowToCopy); + if (copy.id() > 0) + { + m_ui->cwCoordinate->setCoordinate(copy.position().lon(), copy.position().lat()); + m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(copy.esmParticipantId())); + m_ui->leInfo->setText(QString::fromStdString(copy.info())); + if (copy.arrival_time().is_set()) + m_ui->dteTime->setMsecsSinceEpoch(copy.arrival_time().get()); + slotChangesMade(); + } + } + + return true; } - bool EffectShowActorRelocationEdit::apply() { - - return m_requestHelper->startSingleRequest([this]() - { - EffectShowActorRelocation data; - data.id(0); + return m_requestHelper->startSingleRequest([this]() { + EffectShowActorRelocation data; + data.id(0); - data.esmParticipantId(m_ui->cbEffectShowActor->currentData().toInt()); - data.position(Core::GeoPosition2D(m_ui->cwCoordinate->coordinate().x(), m_ui->cwCoordinate->coordinate().y())); - data.arrival_time().set(m_ui->dteTime->msecsSinceEpoch()); - data.info(m_ui->leInfo->text().toStdString()); + data.esmParticipantId(m_ui->cbEffectShowActor->currentData().toInt()); + data.position(Core::GeoPosition2D(m_ui->cwCoordinate->coordinate().x(), m_ui->cwCoordinate->coordinate().y())); + data.arrival_time().set(m_ui->dteTime->msecsSinceEpoch()); + data.info(m_ui->leInfo->text().toStdString()); - return m_ftc->effectShowActorRelocationModifyRequest(data, this); - }); + return m_ftc->effectShowActorRelocationModifyRequest(data, this); + }); } -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.h old mode 100755 new mode 100644 index 83e8b157a..0fd09e54f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_edit.h @@ -1,17 +1,15 @@ - #pragma once #include "esm_effect_show_model.h" -#include +#include #include +#include +#include +#include #include #include -#include -#include -#include - namespace Ui { @@ -26,45 +24,46 @@ class ForeignGuiInterface; namespace EffectShowManagement { - -class EffectShowActorRelocationEdit : public LtsWidgets::LtsDialog, - protected EffectShowManagement::Interface::Ftc::EffectShowActorRelocationModifyReplyHandler +class EffectShowActorRelocationEdit + : public LtsWidgets::LtsDialog, + protected EffectShowManagement::Interface::Ftc::EffectShowActorRelocationModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit EffectShowActorRelocationEdit(QWidget *parent = nullptr); - ~EffectShowActorRelocationEdit(); + public: + explicit EffectShowActorRelocationEdit(QWidget* parent = nullptr); + ~EffectShowActorRelocationEdit(); - bool init(LtsSession::LtsSession *session, - EffectShowModel *model, - int rowToCopy = -1); - bool apply() override; + bool init(LtsSession::LtsSession* session, EffectShowModel* model, int rowToCopy = -1); + bool apply() override; -private slots: - void getPosition(); - void onEffectShowActorFilterChanged(const int &idx); - void onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus &data, const DataModification &modType); + private slots: + void getPosition(); + void onEffectShowActorFilterChanged(const int& idx); + void onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus& data, const DataModification& modType); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onEffectShowActorRelocationModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } + void onEffectShowActorRelocationModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private: - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_ppmDtc; + private: + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_ppmDtc; - std::shared_ptr m_sitMapGuiIfc; + std::shared_ptr m_sitMapGuiIfc; - QMap m_effectShowActors; + QMap m_effectShowActors; - EffectShowModel *m_model; - LtsSession::LtsSession *m_session; - Ui::EffectShowActorRelocationEdit *m_ui; - LtsUtils::RequestHelper *m_requestHelper; + EffectShowModel* m_model; + LtsSession::LtsSession* m_session; + Ui::EffectShowActorRelocationEdit* m_ui; + LtsUtils::RequestHelper* m_requestHelper; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.cpp old mode 100755 new mode 100644 index 9d70ff1cd..b6e7e560a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.cpp @@ -1,146 +1,125 @@ - #include "esm_effect_show_actor_relocation_list.h" -#include "ui_esm_effect_show_actor_relocation_list.h" -#include "esm_effect_show_actor_relocation_edit.h" -#include +#include "esm_effect_show_actor_relocation_edit.h" +#include "ui_esm_effect_show_actor_relocation_list.h" + +#include #include #include namespace EffectShowManagement { -EffectShowActorRelocationList::EffectShowActorRelocationList(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_menuGroup(menuGroup) - , m_effectShowModel(nullptr) - , m_ftc(nullptr) - , m_session(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::EffectShowActorRelocationList) +EffectShowActorRelocationList::EffectShowActorRelocationList(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_menuGroup(menuGroup), + m_effectShowModel(nullptr), m_ftc(nullptr), m_session(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::EffectShowActorRelocationList) { - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &EffectShowActorRelocationList::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &EffectShowActorRelocationList::onSelectionChanged); - - QCheckBox *cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); - cbExpired->setProperty("const", true); - m_ui->widget->setCustomWidget(cbExpired); - connect(cbExpired, &QCheckBox::toggled, this, &EffectShowActorRelocationList::setShowExpired); + QCheckBox* cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); + cbExpired->setProperty("const", true); + m_ui->widget->setCustomWidget(cbExpired); + connect(cbExpired, &QCheckBox::toggled, this, &EffectShowActorRelocationList::setShowExpired); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, + &EffectShowActorRelocationList::onAddEffectShowActorRelocation); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, + &EffectShowActorRelocationList::onRemoveEffectShowActorRelocation); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EffectShowActorRelocationList::onPrint); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &EffectShowActorRelocationList::onAddEffectShowActorRelocation); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &EffectShowActorRelocationList::onRemoveEffectShowActorRelocation); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EffectShowActorRelocationList::onPrint); - - setOnlineHelpFilename(QStringLiteral("Situation-Effect_Show_Actor_Relocations")); - -} - + setOnlineHelpFilename(QStringLiteral("Situation-Effect_Show_Actor_Relocations")); +} EffectShowActorRelocationList::~EffectShowActorRelocationList() { - delete m_ui; -} - + delete m_ui; +} void EffectShowActorRelocationList::retranslate() { - translate(m_ui, tr("Actor Position Relocations")); + translate(m_ui, tr("Actor Position Relocations")); } - -bool EffectShowActorRelocationList::init(LtsSession::LtsSession *session) +bool EffectShowActorRelocationList::init(LtsSession::LtsSession* session) { - if (!session) - return false; + if (!session) + return false; - if (!session->getFtc(m_ftc)) - return false; + if (!session->getFtc(m_ftc)) + return false; - m_session = session; - m_effectShowModel = new EffectShowModel(this); - m_effectShowModel->initModel(session); - - m_proxyModel = new EffectShowActorRelocationProxyModel(this); - m_proxyModel->setSourceModel(m_effectShowModel->getEffetShowActorRelocationModel()); - m_ui->widget->setModel(m_proxyModel); + m_session = session; + m_effectShowModel = new EffectShowModel(this); + m_effectShowModel->initModel(session); + m_proxyModel = new EffectShowActorRelocationProxyModel(this); + m_proxyModel->setSourceModel(m_effectShowModel->getEffetShowActorRelocationModel()); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(EffectShowModel::Columns::Id); + m_ui->widget->hideColumn(EffectShowModel::Columns::Id); #endif - return true; -} - + return true; +} void EffectShowActorRelocationList::onSelectionChanged() { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, m_ui->widget->selectionModel()->selectedRows().size()); - -} - + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, + m_ui->widget->selectionModel()->selectedRows().size()); +} void EffectShowActorRelocationList::onAddEffectShowActorRelocation() { - DEBUG_LOG(m_logger) << "--- onAddEffectShowActorRelocation() "; - EffectShowActorRelocationEdit *dialog = new EffectShowActorRelocationEdit(this); - if (m_ui->widget->currentIndex().row() >= 0) - dialog->init(m_session, m_effectShowModel, m_ui->widget->currentIndex().row()); - else - dialog->init(m_session, m_effectShowModel, -1); - - addDialog(dialog, m_menuGroup, QLatin1String("esmEffectShowActorRelocation"), LtsWidgets::LayoutArea::eDialogTab); - -} + DEBUG_LOG(m_logger) << "--- onAddEffectShowActorRelocation() "; + EffectShowActorRelocationEdit* dialog = new EffectShowActorRelocationEdit(this); + if (m_ui->widget->currentIndex().row() >= 0) + dialog->init(m_session, m_effectShowModel, m_ui->widget->currentIndex().row()); + else + dialog->init(m_session, m_effectShowModel, -1); + addDialog(dialog, m_menuGroup, QLatin1String("esmEffectShowActorRelocation"), LtsWidgets::LayoutArea::eDialogTab); +} void EffectShowActorRelocationList::onRemoveEffectShowActorRelocation() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - EffectShowManagement::EffectShowActorRelocation esar = m_effectShowModel->getEffetShowActorRelocationModel()->getRowData(row); - - - - m_requestHelper->startSingleRequest([esar, this]() - { - const Core::RemoveElementRequest req(esar.id()); - return m_ftc->effectShowActorRelocationRemoveRequest(req, this); - }); - -} + EffectShowManagement::EffectShowActorRelocation esar = + m_effectShowModel->getEffetShowActorRelocationModel()->getRowData(row); + m_requestHelper->startSingleRequest([esar, this]() { + const Core::RemoveElementRequest req(esar.id()); + return m_ftc->effectShowActorRelocationRemoveRequest(req, this); + }); +} void EffectShowActorRelocationList::setShowExpired(bool show) { - m_proxyModel->setShowExpired(show); + m_proxyModel->setShowExpired(show); } - void EffectShowActorRelocationList::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } void EffectShowActorRelocationList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); -} + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); +} -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.h old mode 100755 new mode 100644 index 1b5adc500..c89d9280b --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_list.h @@ -1,65 +1,63 @@ - #pragma once -#include "esm_effect_show_model.h" #include "esm_effect_show_actor_relocation_model.h" +#include "esm_effect_show_model.h" #include #include -#include - -#include #include #include +#include +#include namespace Ui { class EffectShowActorRelocationList; } + namespace EffectShowManagement { - -class EffectShowActorRelocationList : public LtsWidgets::LtsDialog - , protected EffectShowManagement::Interface::Ftc::EffectShowActorRelocationRemoveReplyHandler +class EffectShowActorRelocationList + : public LtsWidgets::LtsDialog, + protected EffectShowManagement::Interface::Ftc::EffectShowActorRelocationRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit EffectShowActorRelocationList(const QString &menuGroup, QWidget *parent = nullptr); - ~EffectShowActorRelocationList(); - bool init(LtsSession::LtsSession *session); + public: + explicit EffectShowActorRelocationList(const QString& menuGroup, QWidget* parent = nullptr); + ~EffectShowActorRelocationList(); + bool init(LtsSession::LtsSession* session); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onAddEffectShowActorRelocation(); + void onRemoveEffectShowActorRelocation(); + void onPrint(); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onAddEffectShowActorRelocation(); - void onRemoveEffectShowActorRelocation(); - void onPrint(); - void tableColumnOrganiserSetting() override; + void onEffectShowActorRelocationRemoveReply(const Core::FunctionReplyObject& reply) override + { + m_requestHelper->requestReply(reply); + } - void onEffectShowActorRelocationRemoveReply(const Core::FunctionReplyObject &reply) override - { - m_requestHelper->requestReply(reply); - } + private slots: + void setShowExpired(bool show); -private slots: - void setShowExpired(bool show); + private: + QString m_menuGroup; + EffectShowModel* m_effectShowModel{nullptr}; + EffectShowActorRelocationProxyModel* m_proxyModel{nullptr}; -private: - QString m_menuGroup; - EffectShowModel *m_effectShowModel{nullptr}; - EffectShowActorRelocationProxyModel *m_proxyModel{nullptr}; - - std::shared_ptr m_ftc; - LtsSession::LtsSession *m_session{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; + std::shared_ptr m_ftc; + LtsSession::LtsSession* m_session{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; - Ui::EffectShowActorRelocationList *m_ui{nullptr}; + Ui::EffectShowActorRelocationList* m_ui{nullptr}; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_model.h old mode 100755 new mode 100644 index 67ece18ef..6480f0d39 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_actor_relocation_model.h @@ -1,11 +1,9 @@ - #pragma once #include #include - #include #include @@ -13,60 +11,62 @@ namespace EffectShowManagement { class EffectShowModel; - - -class EffectShowActorRelocationModel final : public LtsWidgets::LtsAbstractTableModel +class EffectShowActorRelocationModel final + : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Name, - Id, - ArrivalTime, - Position, - Info, - Status, - Answer - }; - explicit EffectShowActorRelocationModel(EffectShowModel *effectShowModel, QObject *parent); + Q_OBJECT + public: + enum Columns { Name, Id, ArrivalTime, Position, Info, Status, Answer }; - bool initModel(const std::shared_ptr &dtc); + explicit EffectShowActorRelocationModel(EffectShowModel* effectShowModel, QObject* parent); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool initModel(const std::shared_ptr& dtc); - QVector::const_iterator getItBegin() const { return m_vecData.begin(); } - QVector::const_iterator getItEnd() const { return m_vecData.end(); } + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -private: + QVector::const_iterator getItBegin() const + { + return m_vecData.begin(); + } -NGL::INGLLogger &m_logger; - std::shared_ptr m_dtc; + QVector::const_iterator getItEnd() const + { + return m_vecData.end(); + } - EffectShowModel *m_effectShowModel; - friend class EffectShowActorRelocationProxyModel; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_dtc; + + EffectShowModel* m_effectShowModel; + friend class EffectShowActorRelocationProxyModel; }; - class EffectShowActorRelocationProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; - bool showExpired() const { return m_showExpired; } + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; -public slots: - void setShowExpired(bool show); + bool showExpired() const + { + return m_showExpired; + } -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override final; -private: - bool checkFilter(int source_row) const; -private: - bool m_showExpired{false}; + public slots: + void setShowExpired(bool show); - EffectShowActorRelocationModel *m_sourceModel{nullptr}; + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override final; + + private: + bool checkFilter(int source_row) const; + + private: + bool m_showExpired{false}; + + EffectShowActorRelocationModel* m_sourceModel{nullptr}; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.cpp old mode 100755 new mode 100644 index b548d9e58..737d8d25d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.cpp @@ -1,234 +1,192 @@ - #include "esm_effect_show_edit.h" -#include "ui_esm_effect_show_list.h" -#include "ui_esm_effect_show_edit.h" -#include "esm_effect_show_actor_model.h" -#include -#include +#include "esm_effect_show_actor_model.h" +#include "ui_esm_effect_show_edit.h" +#include "ui_esm_effect_show_list.h" + #include -#include +#include +#include #include +#include namespace EffectShowManagement { -EffectShowEdit::EffectShowEdit(const EffectShow &effectShow, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ftc(nullptr) - , m_model(nullptr) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_effectShow(effectShow) - , m_ui(new Ui::EffectShowEdit) +EffectShowEdit::EffectShowEdit(const EffectShow& effectShow, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ftc(nullptr), m_model(nullptr), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_effectShow(effectShow), m_ui(new Ui::EffectShowEdit) { - m_ui->setupUi(this); + m_ui->setupUi(this); } - EffectShowEdit::~EffectShowEdit() { - delete m_ui; + delete m_ui; } - void EffectShowEdit::retranslate() { - translate(m_ui, tr("Edit Effect Show")); + translate(m_ui, tr("Edit Effect Show")); } - -bool EffectShowEdit::init(LtsSession::LtsSession *session, - EffectShowModel *model) +bool EffectShowEdit::init(LtsSession::LtsSession* session, EffectShowModel* model) { - m_session = session; - if (!session->getFtc(m_ftc)) - return false; - if (!session->getDtc(m_pdmDtc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - if (!session->getDtc(m_aesDtc)) - return false; - if (!session->getForeignGuiInterface(m_esmActorCbx)) - return false; + m_session = session; + if (!session->getFtc(m_ftc)) + return false; + if (!session->getDtc(m_pdmDtc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + if (!session->getDtc(m_aesDtc)) + return false; + if (!session->getForeignGuiInterface(m_esmActorCbx)) + return false; - DEBUG_LOG(m_logger) << "EffectShowEdit::init()"; - m_model = model; + DEBUG_LOG(m_logger) << "EffectShowEdit::init()"; + m_model = model; - AreaEffectSimulation::AesItem aesItem; - bool foundItem = m_aesDtc->aesItemFromId(m_effectShow.idAreaEffectSimulation(), aesItem); - DEBUG_LOG(m_logger) << ", found :" << foundItem - << ", idAreaEffectSimulation :" << m_effectShow.idAreaEffectSimulation() - << ", aesItem.id() :" << aesItem.id() - << ", esmParticipantId: " << m_effectShow.esmParticipantId(); + AreaEffectSimulation::AesItem aesItem; + bool foundItem = m_aesDtc->aesItemFromId(m_effectShow.idAreaEffectSimulation(), aesItem); + DEBUG_LOG(m_logger) << ", found :" << foundItem + << ", idAreaEffectSimulation :" << m_effectShow.idAreaEffectSimulation() + << ", aesItem.id() :" << aesItem.id() + << ", esmParticipantId: " << m_effectShow.esmParticipantId(); - if (!foundItem) - return false; + if (!foundItem) + return false; - m_isSmoke = m_pdmDtc->isSmoke(aesItem.chargeStruct().chargeTypeId(), - aesItem.chargeStruct().igniterTypeId(), - aesItem.chargeStruct().igniterFunctionId()); + m_isSmoke = m_pdmDtc->isSmoke(aesItem.chargeStruct().chargeTypeId(), aesItem.chargeStruct().igniterTypeId(), + aesItem.chargeStruct().igniterFunctionId()); - if (!m_isSmoke) - { - connect(m_ui->sbVolley, static_cast(&QSpinBox::valueChanged), this, [this](int val) + if (!m_isSmoke) { - m_ui->sbShotsInTotal->setMinimum(val); - if (m_ui->sbShotsInTotal->value() < val) - m_ui->sbShotsInTotal->setValue(val); - }); + connect(m_ui->sbVolley, static_cast(&QSpinBox::valueChanged), this, [this](int val) { + m_ui->sbShotsInTotal->setMinimum(val); + if (m_ui->sbShotsInTotal->value() < val) + m_ui->sbShotsInTotal->setValue(val); + }); - - m_ui->cbEffectShowActorFilter->addItem(tr(""), EffectShowActorModel::eFeature::NotSpecified); - m_ui->cbEffectShowActorFilter->addItem(EffectShowActorModel::getFeatureName(EffectShowActorModel::eFeature::SmokeAndExplosion48), - EffectShowActorModel::eFeature::SmokeAndExplosion48); - m_ui->cbEffectShowActorFilter->addItem(EffectShowActorModel::getFeatureName(EffectShowActorModel::eFeature::Explosion24), - EffectShowActorModel::eFeature::Explosion24); - m_ui->cbEffectShowActorFilter->setCurrentIndex(1); - onEffectShowActorFilterChanged(-1); - connect(m_ui->cbEffectShowActorFilter, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &EffectShowEdit::onEffectShowActorFilterChanged); - } - else - { - m_ui->lblEffectShowActorFilter->hide(); - m_ui->cbEffectShowActorFilter->hide(); - onEffectShowActorFilterChanged(-1); - } + m_ui->cbEffectShowActorFilter->addItem(tr(""), EffectShowActorModel::eFeature::NotSpecified); + m_ui->cbEffectShowActorFilter->addItem( + EffectShowActorModel::getFeatureName(EffectShowActorModel::eFeature::SmokeAndExplosion48), + EffectShowActorModel::eFeature::SmokeAndExplosion48); + m_ui->cbEffectShowActorFilter->addItem( + EffectShowActorModel::getFeatureName(EffectShowActorModel::eFeature::Explosion24), + EffectShowActorModel::eFeature::Explosion24); + m_ui->cbEffectShowActorFilter->setCurrentIndex(1); + onEffectShowActorFilterChanged(-1); + connect(m_ui->cbEffectShowActorFilter, QOverload::of(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &EffectShowEdit::onEffectShowActorFilterChanged); + } + else + { + m_ui->lblEffectShowActorFilter->hide(); + m_ui->cbEffectShowActorFilter->hide(); + onEffectShowActorFilterChanged(-1); + } - connect(m_model, &EffectShowModel::effectShowVehicleStatusChanged, - this, &EffectShowEdit::onEffectShowVehicleStatusChanged); + connect(m_model, &EffectShowModel::effectShowVehicleStatusChanged, this, + &EffectShowEdit::onEffectShowVehicleStatusChanged); - showEffectShow(); - m_ui->dteFire->setWithNowButton(false); - return true; + showEffectShow(); + m_ui->dteFire->setWithNowButton(false); + return true; } - bool EffectShowEdit::apply() { - - return m_requestHelper->startSingleRequest([this]() - { - m_effectShow.esmParticipantId(m_ui->cbEffectShowActor->currentData().toInt()); - if (!m_isSmoke) - { - m_effectShow.numOfVolley(m_ui->sbVolley->value()); - m_effectShow.shotsPerVolley(m_ui->sbShotsInTotal->value()); - } - return m_ftc->effectShowModifyRequest(m_effectShow, this); - }); -} + return m_requestHelper->startSingleRequest([this]() { + m_effectShow.esmParticipantId(m_ui->cbEffectShowActor->currentData().toInt()); + if (!m_isSmoke) + { + m_effectShow.numOfVolley(m_ui->sbVolley->value()); + m_effectShow.shotsPerVolley(m_ui->sbShotsInTotal->value()); + } + return m_ftc->effectShowModifyRequest(m_effectShow, this); + }); +} void EffectShowEdit::showEffectShow() { - m_ui->leName->setText(QString::fromStdString(m_effectShow.nameAreaEffectSimulation())); - - EffectShowVehicleStatus vehicleStatus; - const int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(m_effectShow.esmParticipantId()); - m_model->getVehicleStatus(equipmentNumber, vehicleStatus); - const int feature = m_ui->cbEffectShowActorFilter->findData(vehicleStatus.feature().underlying()); - switch (feature) - { - case EffectShowManagement::Feature_e::Explosion24: - case EffectShowManagement::Feature_e::NotSpecified: - m_ui->cbEffectShowActorFilter->setCurrentIndex(feature); - break; - default: - m_ui->cbEffectShowActorFilter->setCurrentIndex(1); - break; - } + m_ui->leName->setText(QString::fromStdString(m_effectShow.nameAreaEffectSimulation())); - if (m_effectShow.esmParticipantId() > 0) - m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(m_effectShow.esmParticipantId())); + EffectShowVehicleStatus vehicleStatus; + const int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(m_effectShow.esmParticipantId()); + m_model->getVehicleStatus(equipmentNumber, vehicleStatus); + const int feature = m_ui->cbEffectShowActorFilter->findData(vehicleStatus.feature().underlying()); + switch (feature) + { + case EffectShowManagement::Feature_e::Explosion24: + case EffectShowManagement::Feature_e::NotSpecified: + m_ui->cbEffectShowActorFilter->setCurrentIndex(feature); + break; + default: + m_ui->cbEffectShowActorFilter->setCurrentIndex(1); + break; + } - if (m_isSmoke) - { - m_ui->sbVolley->hide(); - m_ui->lblVolley->hide(); - m_ui->sbShotsInTotal->hide(); - m_ui->lblShots->hide(); - } - else - { - m_ui->lblVolley->setText(tr("Volley:")); - m_ui->lblShots->setText(tr("Shots in Total:")); - m_ui->sbVolley->setValue(m_effectShow.numOfVolley()); - m_ui->sbShotsInTotal->setValue(m_effectShow.shotsPerVolley()); - } - m_ui->dteFire->setMsecsSinceEpoch(m_effectShow.startTime().is_set() ? m_effectShow.startTime().get() : 0); - m_ui->leRemainingAmmunition->setText(m_model->getParticipantAmmunition(m_effectShow.esmParticipantId())); + if (m_effectShow.esmParticipantId() > 0) + m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(m_effectShow.esmParticipantId())); - connect(m_ui->cbEffectShowActor, static_cast(&QComboBox::currentIndexChanged), this, [this]() - { - m_ui->leRemainingAmmunition->setText(m_model->getParticipantAmmunition(m_ui->cbEffectShowActor->currentData().toInt())); - }); + if (m_isSmoke) + { + m_ui->sbVolley->hide(); + m_ui->lblVolley->hide(); + m_ui->sbShotsInTotal->hide(); + m_ui->lblShots->hide(); + } + else + { + m_ui->lblVolley->setText(tr("Volley:")); + m_ui->lblShots->setText(tr("Shots in Total:")); + m_ui->sbVolley->setValue(m_effectShow.numOfVolley()); + m_ui->sbShotsInTotal->setValue(m_effectShow.shotsPerVolley()); + } + m_ui->dteFire->setMsecsSinceEpoch(m_effectShow.startTime().is_set() ? m_effectShow.startTime().get() : 0); + m_ui->leRemainingAmmunition->setText(m_model->getParticipantAmmunition(m_effectShow.esmParticipantId())); + + connect(m_ui->cbEffectShowActor, static_cast(&QComboBox::currentIndexChanged), this, + [this]() { + m_ui->leRemainingAmmunition->setText( + m_model->getParticipantAmmunition(m_ui->cbEffectShowActor->currentData().toInt())); + }); } -void EffectShowEdit::updateActorComboBox(const Core::GeoPosition &coordGeo) +void EffectShowEdit::updateActorComboBox(const Core::GeoPosition& coordGeo) { - bool ok; + bool ok; - int esmParticipantId = m_ui->cbEffectShowActor->currentData().toInt(&ok); - DEBUG_LOG(m_logger) << "currentIndex: " << m_ui->cbEffectShowActor->currentIndex() - << ", currentText: " << m_ui->cbEffectShowActor->currentText() - << ", esmParticipantId: " << esmParticipantId - << ", ok: " << ok; - int featureFilter = m_ui->cbEffectShowActorFilter->currentData().toInt(); - m_esmActorCbx->fillActorComboBox(m_ui->cbEffectShowActor, coordGeo, m_isSmoke, featureFilter); - m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(esmParticipantId)); + int esmParticipantId = m_ui->cbEffectShowActor->currentData().toInt(&ok); + DEBUG_LOG(m_logger) << "currentIndex: " << m_ui->cbEffectShowActor->currentIndex() + << ", currentText: " << m_ui->cbEffectShowActor->currentText() + << ", esmParticipantId: " << esmParticipantId << ", ok: " << ok; + int featureFilter = m_ui->cbEffectShowActorFilter->currentData().toInt(); + m_esmActorCbx->fillActorComboBox(m_ui->cbEffectShowActor, coordGeo, m_isSmoke, featureFilter); + m_ui->cbEffectShowActor->setCurrentIndex(m_ui->cbEffectShowActor->findData(esmParticipantId)); } -void EffectShowEdit::onEffectShowActorFilterChanged(const int &idx) +void EffectShowEdit::onEffectShowActorFilterChanged(const int& idx) { - Q_UNUSED(idx); + Q_UNUSED(idx); - const Core::GeoPosition coordGeo(m_effectShow.position().lon(), m_effectShow.position().lat(), 0); - updateActorComboBox(coordGeo); - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + const Core::GeoPosition coordGeo(m_effectShow.position().lon(), m_effectShow.position().lat(), 0); + updateActorComboBox(coordGeo); } -void EffectShowEdit::onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus &data, const DataModification &modType) +void EffectShowEdit::onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus& data, + const DataModification& modType) { - Q_UNUSED(modType); - int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(data.esmParticipantId()); - const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); - if (m_model->getEffectShowActorModel()->isMatchedByFilter(equipmentNumber, filter)) - onEffectShowActorFilterChanged(-1); + Q_UNUSED(modType); + int equipmentNumber = m_ppmDtc->equipmentNumberByParticipantId(data.esmParticipantId()); + const int filter = m_ui->cbEffectShowActorFilter->currentData().toInt(); + if (m_model->getEffectShowActorModel()->isMatchedByFilter(equipmentNumber, filter)) + onEffectShowActorFilterChanged(-1); } -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.h old mode 100755 new mode 100644 index 40947a2ce..5583ca511 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_edit.h @@ -1,24 +1,21 @@ - #pragma once #include "esm_effect_show_model.h" -#include -#include #include -#include -#include -#include -#include - -#include -#include #include +#include #include - +#include +#include +#include +#include +#include #include #include +#include +#include namespace Ui { @@ -28,46 +25,48 @@ class EffectShowEdit; namespace EffectShowManagement { - class EffectShowEdit : public LtsWidgets::LtsDialog, - protected EffectShowManagement::Interface::Ftc::EffectShowModifyReplyHandler + protected EffectShowManagement::Interface::Ftc::EffectShowModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit EffectShowEdit(const EffectShow &effectShow, QWidget *parent = nullptr); - ~EffectShowEdit(); + public: + explicit EffectShowEdit(const EffectShow& effectShow, QWidget* parent = nullptr); + ~EffectShowEdit(); - bool init(LtsSession::LtsSession *session, - EffectShowModel *model); - bool apply() override; + bool init(LtsSession::LtsSession* session, EffectShowModel* model); + bool apply() override; -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void showEffectShow(); -NGL::INGLLogger &m_logger; - void retranslate() override; - void showEffectShow(); - void onEffectShowModifyReply(const Core::FunctionReplyObject &replyObject) override { m_requestHelper->requestReply(replyObject); } - void updateActorComboBox(const Core::GeoPosition &coordGeo); + void onEffectShowModifyReply(const Core::FunctionReplyObject& replyObject) override + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void onEffectShowActorFilterChanged(const int &idx); - void onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus &data, const DataModification &modType); + void updateActorComboBox(const Core::GeoPosition& coordGeo); -private: - LtsSession::LtsSession *m_session; - std::shared_ptr m_ftc; - std::shared_ptr m_aesDtc; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_esmActorCbx; + private slots: + void onEffectShowActorFilterChanged(const int& idx); + void onEffectShowVehicleStatusChanged(const EffectShowVehicleStatus& data, const DataModification& modType); - EffectShowModel *m_model; - LtsUtils::RequestHelper *m_requestHelper; - EffectShow m_effectShow; - bool m_isSmoke{false}; + private: + LtsSession::LtsSession* m_session; + std::shared_ptr m_ftc; + std::shared_ptr m_aesDtc; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_esmActorCbx; - Ui::EffectShowEdit *m_ui; + EffectShowModel* m_model; + LtsUtils::RequestHelper* m_requestHelper; + EffectShow m_effectShow; + bool m_isSmoke{false}; + + Ui::EffectShowEdit* m_ui; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.cpp old mode 100755 new mode 100644 index e645f0d65..98b3110b1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.cpp @@ -1,169 +1,143 @@ - #include "esm_effect_show_list.h" -#include "ui_esm_effect_show_list.h" + +#include "esm_effect_show_actor_model.h" #include "esm_effect_show_edit.h" #include "esm_effect_show_model.h" -#include "esm_effect_show_actor_model.h" -#include +#include "ui_esm_effect_show_list.h" +#include #include #include namespace EffectShowManagement { -EffectShowList::EffectShowList(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_menuGroup(menuGroup) - , m_model(nullptr) - , m_ftc(nullptr) - , m_session(nullptr) - , m_ui(new Ui::EffectShowList) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +EffectShowList::EffectShowList(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_menuGroup(menuGroup), m_model(nullptr), + m_ftc(nullptr), m_session(nullptr), m_ui(new Ui::EffectShowList), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + m_ui->setupUi(this); + m_ui->widget->setSelectionMode(QAbstractItemView::SingleSelection); + QCheckBox* cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); + cbExpired->setProperty("const", true); + m_ui->widget->setCustomWidget(cbExpired); + connect(cbExpired, &QCheckBox::toggled, this, &EffectShowList::setShowExpired); - - QCheckBox *cbExpired = new QCheckBox(tr("Show expired"), m_ui->widget); - cbExpired->setProperty("const", true); - m_ui->widget->setCustomWidget(cbExpired); - connect(cbExpired, &QCheckBox::toggled, this, &EffectShowList::setShowExpired); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &EffectShowList::onSelectionChanged); - - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &EffectShowList::onSelectionChanged); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &EffectShowList::onEditEffectShow); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &EffectShowList::onEditEffectShow); - - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &EffectShowList::onEditEffectShow); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &EffectShowList::onRemoveEffectShow); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EffectShowList::onPrint); - - setOnlineHelpFilename(QStringLiteral("Situation-Effect_Shows")); - -} + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &EffectShowList::onEditEffectShow); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &EffectShowList::onRemoveEffectShow); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &EffectShowList::onPrint); + setOnlineHelpFilename(QStringLiteral("Situation-Effect_Shows")); +} EffectShowList::~EffectShowList() { - delete m_ui; -} - + delete m_ui; +} void EffectShowList::retranslate() { - translate(m_ui, tr("Effect Representations")); + translate(m_ui, tr("Effect Representations")); } - -bool EffectShowList::init(LtsSession::LtsSession *session) +bool EffectShowList::init(LtsSession::LtsSession* session) { - if (!session) - return false; + if (!session) + return false; - m_session = session; - if (!m_session->getFtc(m_ftc)) - return false; + m_session = session; + if (!m_session->getFtc(m_ftc)) + return false; - m_model = new EffectShowModel(this); - m_model->initModel(session); + m_model = new EffectShowModel(this); + m_model->initModel(session); - m_proxyModel = new EffectShowProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_ui->widget->setModel(m_proxyModel); + m_proxyModel = new EffectShowProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(EffectShowModel::Columns::Id); + m_ui->widget->hideColumn(EffectShowModel::Columns::Id); #endif - return true; -} - + return true; +} void EffectShowList::onSelectionChanged() { - int rowCount = m_ui->widget->selectedRows().size(); - - bool enaEdit = false; - if (rowCount > 0) - { - int row = m_ui->widget->currentIndex().row(); - EffectShowManagement::EffectShow effectShow = m_model->getRowData(row); - enaEdit = effectShow.orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && - effectShow.orderConfirmation() != OrderConfirmation_e::Execution; - } - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, enaEdit); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, rowCount); - - -} + int rowCount = m_ui->widget->selectedRows().size(); + bool enaEdit = false; + if (rowCount > 0) + { + int row = m_ui->widget->currentIndex().row(); + EffectShowManagement::EffectShow effectShow = m_model->getRowData(row); + enaEdit = effectShow.orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && + effectShow.orderConfirmation() != OrderConfirmation_e::Execution; + } + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, enaEdit); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, rowCount); +} void EffectShowList::onEditEffectShow() { - const QModelIndex idx = m_ui->widget->currentIndex(); + const QModelIndex idx = m_ui->widget->currentIndex(); - int row = idx.row(); - if (row < 0) - return; + int row = idx.row(); + if (row < 0) + return; - EffectShowManagement::EffectShow effectShow = m_model->getRowData(row); + EffectShowManagement::EffectShow effectShow = m_model->getRowData(row); - DEBUG_LOG(m_logger) << "--- onEffectShow() " - << " id: " << effectShow.id() - << " position: " << effectShow.position(); - - - EffectShowEdit *dialog = new EffectShowEdit(effectShow, this); - dialog->init(m_session, m_model); - addDialog(dialog, m_menuGroup, QLatin1String("esmEffectShow") + QString::number(effectShow.id()), LtsWidgets::LayoutArea::eDialogTab); - -} + DEBUG_LOG(m_logger) << "--- onEffectShow() " + << " id: " << effectShow.id() << " position: " << effectShow.position(); + EffectShowEdit* dialog = new EffectShowEdit(effectShow, this); + dialog->init(m_session, m_model); + addDialog(dialog, m_menuGroup, QLatin1String("esmEffectShow") + QString::number(effectShow.id()), + LtsWidgets::LayoutArea::eDialogTab); +} void EffectShowList::onRemoveEffectShow() { - const QModelIndexList idxList = m_ui->widget->selectedRows(); + const QModelIndexList idxList = m_ui->widget->selectedRows(); - if (idxList.isEmpty()) - return; - int row = idxList.first().row(); + if (idxList.isEmpty()) + return; + int row = idxList.first().row(); - EffectShowManagement::EffectShow es = m_model->getRowData(row); - - - - m_requestHelper->startSingleRequest([es, this]() - { - const Core::RemoveElementRequest req(es.id()); - return m_ftc->effectShowRemoveRequest(req, this); - }); -} + EffectShowManagement::EffectShow es = m_model->getRowData(row); + m_requestHelper->startSingleRequest([es, this]() { + const Core::RemoveElementRequest req(es.id()); + return m_ftc->effectShowRemoveRequest(req, this); + }); +} void EffectShowList::setShowExpired(bool show) { - m_proxyModel->setShowExpired(show); + m_proxyModel->setShowExpired(show); } void EffectShowList::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); -} + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); +} void EffectShowList::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } - -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.h old mode 100755 new mode 100644 index 4f2771c15..e8db34f57 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_list.h @@ -1,24 +1,22 @@ - #pragma once +#include +#include +#include +#include +#include +#include +#include #include #include -#include - -#include -#include - -#include -#include -#include -#include namespace Ui { class EffectShowList; } + namespace EffectShowManagement { class EffectShowModel; @@ -26,43 +24,42 @@ class EffectShowProxyModel; class EffectShowActorModel; class EffectShowActorRelocationModel; - -class EffectShowList : public LtsWidgets::LtsDialog - , protected EffectShowManagement::Interface::Ftc::EffectShowRemoveReplyHandler +class EffectShowList : public LtsWidgets::LtsDialog, + protected EffectShowManagement::Interface::Ftc::EffectShowRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit EffectShowList(const QString &menuGroup, QWidget *parent = nullptr); - ~EffectShowList(); - bool init(LtsSession::LtsSession *session); + public: + explicit EffectShowList(const QString& menuGroup, QWidget* parent = nullptr); + ~EffectShowList(); + bool init(LtsSession::LtsSession* session); -private slots: - void setShowExpired(bool show); + private slots: + void setShowExpired(bool show); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + void onSelectionChanged(); + void onEditEffectShow(); + void onRemoveEffectShow(); + void onPrint(); + void tableColumnOrganiserSetting() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onSelectionChanged(); - void onEditEffectShow(); - void onRemoveEffectShow(); - void onPrint(); - void tableColumnOrganiserSetting() override; + void onEffectShowRemoveReply(const Core::FunctionReplyObject& reply) override + { + m_requestHelper->requestReply(reply); + } - void onEffectShowRemoveReply(const Core::FunctionReplyObject &reply) override - { - m_requestHelper->requestReply(reply); - } -private: - QString m_menuGroup; - EffectShowModel *m_model; - EffectShowProxyModel *m_proxyModel; - std::shared_ptr m_ftc; - LtsSession::LtsSession *m_session; - Ui::EffectShowList *m_ui; + private: + QString m_menuGroup; + EffectShowModel* m_model; + EffectShowProxyModel* m_proxyModel; + std::shared_ptr m_ftc; + LtsSession::LtsSession* m_session; + Ui::EffectShowList* m_ui; - LtsUtils::RequestHelper *m_requestHelper; + LtsUtils::RequestHelper* m_requestHelper; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.cpp old mode 100755 new mode 100644 index 5f5cb3c5d..a078f0d68 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.cpp @@ -1,515 +1,487 @@ - #include "esm_effect_show_model.h" + #include "esm_effect_show_actor_model.h" #include "esm_effect_show_actor_relocation_model.h" -#include -#include -#include -#include + #include +#include +#include +#include #include #include +#include #include namespace EffectShowManagement { - - -EffectShowModel::EffectShowModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +EffectShowModel::EffectShowModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Name AES"), tr("Id"), tr("Fire"), tr("Duration"), tr("Position"), tr("AesStatus"), tr("Actor"), + tr("Volley"), tr("Shots in total"), tr("Dimension [m]"), tr("Rotation"), tr("Status"), tr("Answer")}, + parent), + m_dtc(nullptr), m_effectShowActorProxyModel(nullptr), m_effectShowActorModel(nullptr), + m_effectShowActorRelocationModel(nullptr) { - tr("Name AES"), - tr("Id"), - tr("Fire"), - tr("Duration"), - tr("Position"), - tr("AesStatus"), - tr("Actor"), - tr("Volley"), - tr("Shots in total"), - tr("Dimension [m]"), - tr("Rotation"), - tr("Status"), - tr("Answer") -}, - parent) - , m_dtc(nullptr) - , m_effectShowActorProxyModel(nullptr) - , m_effectShowActorModel(nullptr) - , m_effectShowActorRelocationModel(nullptr) -{} +} EffectShowModel::~EffectShowModel() { - delete m_effectShowActorProxyModel; - delete m_effectShowActorModel; - delete m_effectShowActorRelocationModel; + delete m_effectShowActorProxyModel; + delete m_effectShowActorModel; + delete m_effectShowActorRelocationModel; } - -bool EffectShowModel::initModel(LtsSession::LtsSession *session) +bool EffectShowModel::initModel(LtsSession::LtsSession* session) { - if (!session->getDtc(m_dtc)) - return false; - if (!session->getDtc(m_dtcPpm)) - return false; - if (!session->getDtc(m_dtcAes)) - return false; + if (!session->getDtc(m_dtc)) + return false; + if (!session->getDtc(m_dtcPpm)) + return false; + if (!session->getDtc(m_dtcAes)) + return false; - connect(m_dtc.get(), &EffectShowManagement::Interface::Dtc::effectShowChanged, - this, &EffectShowModel::onDataChanged); - connect(m_dtc.get(), &EffectShowManagement::Interface::Dtc::effectShowVehicleStatusChanged, - this, &EffectShowModel::onEffectShowVehicleStatusChanged); + connect(m_dtc.get(), &EffectShowManagement::Interface::Dtc::effectShowChanged, this, + &EffectShowModel::onDataChanged); + connect(m_dtc.get(), &EffectShowManagement::Interface::Dtc::effectShowVehicleStatusChanged, this, + &EffectShowModel::onEffectShowVehicleStatusChanged); + m_dtc->effectShows([this](const EffectShowManagement::EffectShow& effectShow) { insertRow(effectShow); }); + m_effectShowVehicleStatus = m_dtc->effectShowVehicleStatuss(); - - m_dtc->effectShows([this](const EffectShowManagement::EffectShow & effectShow) { insertRow(effectShow); }); - m_effectShowVehicleStatus = m_dtc->effectShowVehicleStatuss(); + m_effectShowActorModel = new EffectShowActorModel(this, this); + m_effectShowActorProxyModel = new EffectShowActorProxyModel(m_effectShowActorModel, this, this); + m_effectShowActorModel->initModel(session); - m_effectShowActorModel = new EffectShowActorModel(this, this); - m_effectShowActorProxyModel = new EffectShowActorProxyModel(m_effectShowActorModel, this, this); - m_effectShowActorModel->initModel(session); + m_effectShowActorRelocationModel = new EffectShowActorRelocationModel(this, this); + m_effectShowActorRelocationModel->initModel(m_dtc); - m_effectShowActorRelocationModel = new EffectShowActorRelocationModel(this, this); - m_effectShowActorRelocationModel->initModel(m_dtc); + m_dtc->effectShowVehicleStatuss([this](const EffectShowManagement::EffectShowVehicleStatus& item) { + onEffectShowVehicleStatusChanged(item, DataModification::eAdded); + }); - m_dtc->effectShowVehicleStatuss([this](const EffectShowManagement::EffectShowVehicleStatus &item) { onEffectShowVehicleStatusChanged(item, DataModification::eAdded);}); - - return true; + return true; } - -QVariant EffectShowModel::data(const QModelIndex &index, int role) const +QVariant EffectShowModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole || !indexIsValid(index)) + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const EffectShowManagement::EffectShow& effectShow = m_vecData.at(index.row()); + AreaEffectSimulation::AesItem aesItem; + m_dtcAes->aesItemFromId(effectShow.idAreaEffectSimulation(), aesItem); + + switch (index.column()) + { + case Id: + return effectShow.id(); + case Name_AES: + return QString::fromStdString(effectShow.nameAreaEffectSimulation()); + case Duration: + return LtsWidgets::readableDuration(effectShow.duration()); + ; + case StartTime: + return effectShow.startTime().is_set() ? DTG::toStringMSec(effectShow.startTime().get()) + : QStringLiteral("---"); + case Position: { + const Core::GeoPosition2D& pos = effectShow.position(); + return LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); + } + case EffectShowActor: { + int id = effectShow.esmParticipantId(); + return (id > 0) ? getParticipantName(id) : QStringLiteral("---"); + } + case Volley: { + if (effectShow.typeOfAmmunition() == 5) + return QStringLiteral("--"); + else + return effectShow.numOfVolley(); + } + case ShotsInTotal: { + if (effectShow.typeOfAmmunition() == 5) + return QStringLiteral("--"); + else + return effectShow.shotsPerVolley(); + } + case Size: + return tr("%1 x %2").arg(QString::number(effectShow.areaWidth()), QString::number(effectShow.areaDepth())); + case Rotation: + return effectShow.areaRotation(); + case Status: + return EffectShowManagement::toString(effectShow.orderConfirmation()); + case Answer: + return QString::fromStdString(effectShow.answerText()); + case AesStatus: + return AreaEffectSimulation::toString(aesItem.effectStateId()); + } return QVariant(); - - const EffectShowManagement::EffectShow &effectShow = m_vecData.at(index.row()); - AreaEffectSimulation::AesItem aesItem; - m_dtcAes->aesItemFromId(effectShow.idAreaEffectSimulation(), aesItem); - - switch (index.column()) - { - case Id: - return effectShow.id(); - case Name_AES: - return QString::fromStdString(effectShow.nameAreaEffectSimulation()); - case Duration: - return LtsWidgets::readableDuration(effectShow.duration());; - case StartTime: - return effectShow.startTime().is_set() ? DTG::toStringMSec(effectShow.startTime().get()) : QStringLiteral("---"); - case Position: - { - const Core::GeoPosition2D &pos = effectShow.position(); - return LtsCoordTrans::mgrsFromGeographic(pos.lon(), pos.lat()); - } - case EffectShowActor: - { - int id = effectShow.esmParticipantId(); - return (id > 0) ? getParticipantName(id) : QStringLiteral("---"); - } - case Volley: - { - if (effectShow.typeOfAmmunition() == 5) - return QStringLiteral("--"); - else - return effectShow.numOfVolley(); - } - case ShotsInTotal: - { - if (effectShow.typeOfAmmunition() == 5) - return QStringLiteral("--"); - else - return effectShow.shotsPerVolley(); - } - case Size: - return tr("%1 x %2").arg(QString::number(effectShow.areaWidth()), QString::number(effectShow.areaDepth())); - case Rotation: - return effectShow.areaRotation(); - case Status: - return EffectShowManagement::toString(effectShow.orderConfirmation()); - case Answer: - return QString::fromStdString(effectShow.answerText()); - case AesStatus: - return AreaEffectSimulation::toString(aesItem.effectStateId()); - } - return QVariant(); } QMap EffectShowModel::getParticipantList() const { - QMap ret; - int numRow = m_effectShowActorProxyModel->rowCount(QModelIndex()); + QMap ret; + int numRow = m_effectShowActorProxyModel->rowCount(QModelIndex()); - for (int i = 0; i < numRow; ++i) - { - const ParticipantManagement::Participant part = m_effectShowActorModel->getRowData(m_effectShowActorProxyModel->mapToSource(m_effectShowActorProxyModel->index(i, 0)).row()); - if (hasVehicleReportedOperationalToday(part.equipmentNumber().get())) - ret.insert(part.id(), getParticipantName(part.id())); - } - return ret; + for (int i = 0; i < numRow; ++i) + { + const ParticipantManagement::Participant part = m_effectShowActorModel->getRowData( + m_effectShowActorProxyModel->mapToSource(m_effectShowActorProxyModel->index(i, 0)).row()); + if (hasVehicleReportedOperationalToday(part.equipmentNumber().get())) + ret.insert(part.id(), getParticipantName(part.id())); + } + return ret; } QMap EffectShowModel::getParticipantList(bool is_smoke) const { - QMap ret; - int numRow = m_effectShowActorProxyModel->rowCount(QModelIndex()); + QMap ret; + int numRow = m_effectShowActorProxyModel->rowCount(QModelIndex()); - for (int i = 0; i < numRow; ++i) - { - int realRow = m_effectShowActorProxyModel->mapToSource(m_effectShowActorProxyModel->index(i, 0)).row(); - const ParticipantManagement::Participant part = m_effectShowActorModel->getRowData(realRow); + for (int i = 0; i < numRow; ++i) + { + int realRow = m_effectShowActorProxyModel->mapToSource(m_effectShowActorProxyModel->index(i, 0)).row(); + const ParticipantManagement::Participant part = m_effectShowActorModel->getRowData(realRow); - if (!hasVehicleReportedOperationalToday(part.equipmentNumber().get())) - continue; + if (!hasVehicleReportedOperationalToday(part.equipmentNumber().get())) + continue; - EffectShowManagement::Feature_e feature = m_effectShowActorModel->getFeature(realRow); - if (feature != EffectShowManagement::Feature_e_def::NotSpecified && - ( - (feature == EffectShowManagement::Feature_e_def::Smoke && is_smoke) || - (feature != EffectShowManagement::Feature_e_def::Smoke && !is_smoke) - ) - ) - ret.insert(part.id(), getParticipantName(part.id())); - } - return ret; + EffectShowManagement::Feature_e feature = m_effectShowActorModel->getFeature(realRow); + if (feature != EffectShowManagement::Feature_e_def::NotSpecified && + ((feature == EffectShowManagement::Feature_e_def::Smoke && is_smoke) || + (feature != EffectShowManagement::Feature_e_def::Smoke && !is_smoke))) + ret.insert(part.id(), getParticipantName(part.id())); + } + return ret; } -QVector> EffectShowModel::getParticipantListByDistance(bool is_smoke, const Core::GeoPosition2D &origin) +QVector> EffectShowModel::getParticipantListByDistance(bool is_smoke, + const Core::GeoPosition2D& origin) { - QVector> ret; + QVector> ret; - - QMap participantList = getParticipantList(is_smoke); - - ret.reserve(participantList.size()); + QMap participantList = getParticipantList(is_smoke); - QMap distanceMapSorted; - for (const auto partId : participantList.keys()) - { + ret.reserve(participantList.size()); - int eqNr = m_dtcPpm->equipmentNumberByParticipantId(partId); - if (eqNr <= 0) - continue; - EffectShowManagement::EffectShowVehicleStatus vehicleStatus; - bool isVehicleStatus = getVehicleStatus(eqNr, vehicleStatus); - if (!isVehicleStatus) - continue; - const ParticipantManagement::ParticipantPosition &pos = m_dtcPpm->participantPosition(partId); - - - LtsCoordTrans::UtmCoordinate pPos = LtsCoordTrans::UtmCoordinate::fromGeographic(pos.pos().lon(), pos.pos().lat()); - LtsCoordTrans::UtmCoordinate pOrigin = LtsCoordTrans::UtmCoordinate::fromGeographic(origin.lon(), origin.lat()); - - double distance = LtsCoordTrans::distance(pPos, pOrigin); - - - - distanceMapSorted.insert(distance, partId); - - - QString currentAssigendEffectShows; - for (const auto &dat : m_vecData) + QMap distanceMapSorted; + for (const auto partId : participantList.keys()) { - if (dat.esmParticipantId() == partId) - { + + int eqNr = m_dtcPpm->equipmentNumberByParticipantId(partId); + if (eqNr <= 0) + continue; + EffectShowManagement::EffectShowVehicleStatus vehicleStatus; + bool isVehicleStatus = getVehicleStatus(eqNr, vehicleStatus); + if (!isVehicleStatus) + continue; + const ParticipantManagement::ParticipantPosition& pos = m_dtcPpm->participantPosition(partId); + + LtsCoordTrans::UtmCoordinate pPos = + LtsCoordTrans::UtmCoordinate::fromGeographic(pos.pos().lon(), pos.pos().lat()); + LtsCoordTrans::UtmCoordinate pOrigin = LtsCoordTrans::UtmCoordinate::fromGeographic(origin.lon(), origin.lat()); + + double distance = LtsCoordTrans::distance(pPos, pOrigin); + + distanceMapSorted.insert(distance, partId); + + QString currentAssigendEffectShows; + for (const auto& dat : m_vecData) + { + if (dat.esmParticipantId() == partId) + { + if (!currentAssigendEffectShows.isEmpty()) + currentAssigendEffectShows.append(QStringLiteral(", ")); + currentAssigendEffectShows.append(QString::fromStdString(dat.nameAreaEffectSimulation())); + } + } + + QString newString = participantList.value(partId); + newString.append(QStringLiteral(" ")); + newString.append( + tr("Mag: %1 | Avail: %2").arg(vehicleStatus.ammunitionMagazine()).arg(vehicleStatus.ammunitionAvailable())); + newString.append(tr(" | Dist: %1[m]").arg(QString::number(int(distance)))); if (!currentAssigendEffectShows.isEmpty()) - currentAssigendEffectShows.append(QStringLiteral(", ")); - currentAssigendEffectShows.append(QString::fromStdString(dat.nameAreaEffectSimulation())); - } + newString.append(tr(" | Assigned: %1").arg(currentAssigendEffectShows)); + + participantList.insert(partId, newString); } - - - - - - - QString newString = participantList.value(partId); - newString.append(QStringLiteral(" ")); - newString.append(tr("Mag: %1 | Avail: %2").arg(vehicleStatus.ammunitionMagazine()).arg(vehicleStatus.ammunitionAvailable())); - newString.append(tr(" | Dist: %1[m]").arg(QString::number(int(distance)))); - if (!currentAssigendEffectShows.isEmpty()) - newString.append(tr(" | Assigned: %1").arg(currentAssigendEffectShows)); - - participantList.insert(partId, newString); - } + QMapIterator it(distanceMapSorted); + while (it.hasNext()) + { + it.next(); + ret.append(QPair(it.value(), participantList.value(it.value()))); + } - QMapIterator it(distanceMapSorted); - while(it.hasNext()) - { - it.next(); - ret.append(QPair(it.value(), participantList.value(it.value()))); - } - - return ret; + return ret; } QString EffectShowModel::getParticipantName(int id) const { - auto it = m_effectShowActorModel->getIt(id); - if (it == m_effectShowActorModel->getItEnd()) return QString(); - QString eqNumber = QStringLiteral("-"); - if (it->equipmentNumber().is_set()) - eqNumber = QString::number(it->equipmentNumber().get()); - return QStringLiteral("%1 - %2 (%3)").arg(QString::fromStdString(it->designator())).arg(QString::fromStdString(it->tacticalIdentifier())).arg(eqNumber); + auto it = m_effectShowActorModel->getIt(id); + if (it == m_effectShowActorModel->getItEnd()) + return QString(); + QString eqNumber = QStringLiteral("-"); + if (it->equipmentNumber().is_set()) + eqNumber = QString::number(it->equipmentNumber().get()); + return QStringLiteral("%1 - %2 (%3)") + .arg(QString::fromStdString(it->designator())) + .arg(QString::fromStdString(it->tacticalIdentifier())) + .arg(eqNumber); } QString EffectShowModel::getParticipantAmmunition(int id) const { - auto it = m_effectShowActorModel->getIt(id); - if (it == m_effectShowActorModel->getItEnd()) return QString(); + auto it = m_effectShowActorModel->getIt(id); + if (it == m_effectShowActorModel->getItEnd()) + return QString(); - EffectShowManagement::EffectShowVehicleStatus vehicleStatus; - if (!getVehicleStatus(it->equipmentNumber().get(), vehicleStatus)) return QString(); + EffectShowManagement::EffectShowVehicleStatus vehicleStatus; + if (!getVehicleStatus(it->equipmentNumber().get(), vehicleStatus)) + return QString(); - QString res = QString::number(vehicleStatus.ammunitionMagazine()); - res.append(QLatin1String(" / ")); - res.append(QString::number(vehicleStatus.ammunitionAvailable())); - return res; + QString res = QString::number(vehicleStatus.ammunitionMagazine()); + res.append(QLatin1String(" / ")); + res.append(QString::number(vehicleStatus.ammunitionAvailable())); + return res; } - bool EffectShowModel::isVehicleStatus(int equipmentNum) const { - auto it = m_effectShowVehicleStatus.find(equipmentNum); - return (it != m_effectShowVehicleStatus.end()); + auto it = m_effectShowVehicleStatus.find(equipmentNum); + return (it != m_effectShowVehicleStatus.end()); } -bool EffectShowModel::getVehicleStatus(int equipmentNum, EffectShowManagement::EffectShowVehicleStatus &vehicleStatus) const +bool EffectShowModel::getVehicleStatus(int equipmentNum, + EffectShowManagement::EffectShowVehicleStatus& vehicleStatus) const { - auto it = m_effectShowVehicleStatus.find(equipmentNum); - if (it == m_effectShowVehicleStatus.end()) - return false; + auto it = m_effectShowVehicleStatus.find(equipmentNum); + if (it == m_effectShowVehicleStatus.end()) + return false; - vehicleStatus = it.value(); - return true; + vehicleStatus = it.value(); + return true; } bool EffectShowModel::hasVehicleReportedOperationalToday(int equipmentNum) const { - EffectShowVehicleStatus vehicleStatus; - getVehicleStatus(equipmentNum, vehicleStatus); + EffectShowVehicleStatus vehicleStatus; + getVehicleStatus(equipmentNum, vehicleStatus); - - if (vehicleStatus.operational()) - { - DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " - << vehicleStatus.esmParticipantId() << " is operational."; - return true; - } + if (vehicleStatus.operational()) + { + DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " + << vehicleStatus.esmParticipantId() << " is operational."; + return true; + } - - if (!m_effectShowVehicleLastTimeOperational.contains(equipmentNum)) - { - DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " - << vehicleStatus.esmParticipantId() << " has not reported operational at any time."; - return false; - } + if (!m_effectShowVehicleLastTimeOperational.contains(equipmentNum)) + { + DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " + << vehicleStatus.esmParticipantId() << " has not reported operational at any time."; + return false; + } - - bool bRet = QDateTime().addMSecs(m_effectShowVehicleLastTimeOperational[equipmentNum]).date() == QDate::currentDate(); - if (bRet) - DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " - << vehicleStatus.esmParticipantId() << " is not operational, but has reported operational today."; - else - DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " - << vehicleStatus.esmParticipantId() << " is not operational and has not reported operational today."; - return bRet; + bool bRet = + QDateTime().addMSecs(m_effectShowVehicleLastTimeOperational[equipmentNum]).date() == QDate::currentDate(); + if (bRet) + DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " + << vehicleStatus.esmParticipantId() + << " is not operational, but has reported operational today."; + else + DEBUG_LOG(m_logger) << "Effect show actor " << vehicleStatus.nameEffectShowActor() << " with participantId " + << vehicleStatus.esmParticipantId() + << " is not operational and has not reported operational today."; + return bRet; } QString EffectShowModel::getTimeAndPositionOfNextEffectShow(int idParticipant) const { - auto it = m_vecData.begin(); - if (it == m_vecData.end()) - return QString(); + auto it = m_vecData.begin(); + if (it == m_vecData.end()) + return QString(); - qint64 effectStart = 0; - int numOrder = 0; - Core::GeoPosition2D position; - while (it != m_vecData.end()) - { - if (it->orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && - it->esmParticipantId() == idParticipant) + qint64 effectStart = 0; + int numOrder = 0; + Core::GeoPosition2D position; + while (it != m_vecData.end()) { - ++numOrder; - qint64 start = it->startTime().is_set() ? it->startTime().get() : 0; + if (it->orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && it->esmParticipantId() == idParticipant) + { + ++numOrder; + qint64 start = it->startTime().is_set() ? it->startTime().get() : 0; - if (effectStart == 0) - { - effectStart = start; - position = it->position(); - } - else if (start < effectStart) - { - effectStart = start; - position = it->position(); - } + if (effectStart == 0) + { + effectStart = start; + position = it->position(); + } + else if (start < effectStart) + { + effectStart = start; + position = it->position(); + } + } + ++it; } - ++it; - } - if ((numOrder == 0) || ((numOrder > 1) && (effectStart == 0))) - return QString(); + if ((numOrder == 0) || ((numOrder > 1) && (effectStart == 0))) + return QString(); - QString res; - res = (effectStart != 0) ? DTG::toStringMSec(effectStart) : tr("---"); + QString res; + res = (effectStart != 0) ? DTG::toStringMSec(effectStart) : tr("---"); - res += QLatin1String(", "); - res += LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); + res += QLatin1String(", "); + res += LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); - return res; + return res; } QString EffectShowModel::getTimeAndPositionOfNextActorRelocation(int idParticipant) const { - auto it = m_effectShowActorRelocationModel->getItBegin(); - if (it == m_effectShowActorRelocationModel->getItEnd()) - return QString(); + auto it = m_effectShowActorRelocationModel->getItBegin(); + if (it == m_effectShowActorRelocationModel->getItEnd()) + return QString(); - qint64 arrivalTime = std::numeric_limits::max(); - Core::GeoPosition2D position; - bool found = false; + qint64 arrivalTime = std::numeric_limits::max(); + Core::GeoPosition2D position; + bool found = false; - while (it != m_effectShowActorRelocationModel->getItEnd()) - { - if (it->orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && - it->orderConfirmation() != OrderConfirmation_e::PositionReached && - it->orderConfirmation() != OrderConfirmation_e::Abort && - it->orderConfirmation() != OrderConfirmation_e::Nonacceptance && - it->esmParticipantId() == idParticipant) + while (it != m_effectShowActorRelocationModel->getItEnd()) { - if (it->arrival_time().get() < arrivalTime) - { - arrivalTime = it->arrival_time().get(); - position = it->position(); - found = true; - } + if (it->orderConfirmation() != OrderConfirmation_e::OrderCarriedOut && + it->orderConfirmation() != OrderConfirmation_e::PositionReached && + it->orderConfirmation() != OrderConfirmation_e::Abort && + it->orderConfirmation() != OrderConfirmation_e::Nonacceptance && it->esmParticipantId() == idParticipant) + { + if (it->arrival_time().get() < arrivalTime) + { + arrivalTime = it->arrival_time().get(); + position = it->position(); + found = true; + } + } + ++it; } - ++it; - } - if (!found) - return QString(); + if (!found) + return QString(); - QString res; - res = (arrivalTime != 0) ? DTG::toStringMSec(arrivalTime) : tr("---"); + QString res; + res = (arrivalTime != 0) ? DTG::toStringMSec(arrivalTime) : tr("---"); - res += QLatin1String(", "); - res += LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); + res += QLatin1String(", "); + res += LtsCoordTrans::mgrsFromGeographic(position.lon(), position.lat()); - return res; + return res; } void EffectShowModel::updateAll() { - this->update(); - m_effectShowActorModel->update(); - m_effectShowActorRelocationModel->update(); + this->update(); + m_effectShowActorModel->update(); + m_effectShowActorRelocationModel->update(); } -bool EffectShowModel::onEffectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus &data, DataModification modType) +bool EffectShowModel::onEffectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus& data, + DataModification modType) { - int equipmentNumber = m_dtcPpm->equipmentNumberByParticipantId(data.esmParticipantId()); + int equipmentNumber = m_dtcPpm->equipmentNumberByParticipantId(data.esmParticipantId()); - switch (modType) - { - case DataModification::eAdded: - case DataModification::eModified: - if (m_effectShowVehicleStatus.contains(equipmentNumber)) + switch (modType) { - if (m_effectShowVehicleStatus[equipmentNumber].operational() && !data.operational()) - m_effectShowVehicleLastTimeOperational[equipmentNumber] = data.sampleTime(); - } - else - m_effectShowVehicleLastTimeOperational[equipmentNumber] = 0; - m_effectShowVehicleStatus[equipmentNumber] = data; - break; + case DataModification::eAdded: + case DataModification::eModified: + if (m_effectShowVehicleStatus.contains(equipmentNumber)) + { + if (m_effectShowVehicleStatus[equipmentNumber].operational() && !data.operational()) + m_effectShowVehicleLastTimeOperational[equipmentNumber] = data.sampleTime(); + } + else + m_effectShowVehicleLastTimeOperational[equipmentNumber] = 0; + m_effectShowVehicleStatus[equipmentNumber] = data; + break; - case DataModification::eRemoved: - m_effectShowVehicleStatus.remove(equipmentNumber); - m_effectShowVehicleLastTimeOperational.remove(equipmentNumber); - break; - } + case DataModification::eRemoved: + m_effectShowVehicleStatus.remove(equipmentNumber); + m_effectShowVehicleLastTimeOperational.remove(equipmentNumber); + break; + } - updateAll(); - emit effectShowVehicleStatusChanged(data, modType); - return true; + updateAll(); + emit effectShowVehicleStatusChanged(data, modType); + return true; } -void EffectShowProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void EffectShowProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } void EffectShowProxyModel::setShowExpired(bool show) { - if (m_showExpired == show) - return; + if (m_showExpired == show) + return; - m_showExpired = show; - invalidateFilter(); + m_showExpired = show; + invalidateFilter(); } -bool EffectShowProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +bool EffectShowProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case EffectShowModel::StartTime: + if (dataLeft.startTime().is_set() && dataRight.startTime().is_set()) + return dataLeft.startTime().get() < dataRight.startTime().get(); + if (dataRight.startTime().is_set()) + return true; + if (dataLeft.startTime().is_set()) + return false; + return dataLeft.id() < dataRight.id(); + + case EffectShowModel::Name_AES: + case EffectShowModel::Id: + case EffectShowModel::Duration: + case EffectShowModel::Position: + case EffectShowModel::EffectShowActor: + case EffectShowModel::Volley: + case EffectShowModel::ShotsInTotal: + case EffectShowModel::Status: + case EffectShowModel::Answer: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case EffectShowModel::StartTime: - if (dataLeft.startTime().is_set() && dataRight.startTime().is_set()) - return dataLeft.startTime().get() < dataRight.startTime().get(); - if (dataRight.startTime().is_set()) - return true; - if (dataLeft.startTime().is_set()) - return false; - return dataLeft.id() < dataRight.id(); - - case EffectShowModel::Name_AES: - case EffectShowModel::Id: - case EffectShowModel::Duration: - case EffectShowModel::Position: - case EffectShowModel::EffectShowActor: - case EffectShowModel::Volley: - case EffectShowModel::ShotsInTotal: - case EffectShowModel::Status: - case EffectShowModel::Answer: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } -bool EffectShowProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool EffectShowProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - bool bRet = checkFilter(source_row); - if (!bRet) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + bool bRet = checkFilter(source_row); + if (!bRet) + return false; + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } bool EffectShowProxyModel::checkFilter(int source_row) const { - - if (showExpired()) - return true; + if (showExpired()) + return true; - const auto effectShowSource = m_sourceModel->getRowData(source_row); + const auto effectShowSource = m_sourceModel->getRowData(source_row); - - if (effectShowSource.orderConfirmation() != EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut) - return true; + if (effectShowSource.orderConfirmation() != EffectShowManagement::OrderConfirmation_e_def::OrderCarriedOut) + return true; - return false; + return false; } -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.h old mode 100755 new mode 100644 index 97dde4e0b..d38692a62 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/EffectShowManagement/Gui/esm_effect_show_model.h @@ -1,19 +1,17 @@ - #pragma once -#include #include #include #include - #include #include +#include namespace LtsSession { - class LtsSession; +class LtsSession; } namespace EffectShowManagement @@ -22,123 +20,118 @@ class EffectShowActorProxyModel; class EffectShowActorModel; class EffectShowActorRelocationModel; - - class EffectShowModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT -public: - enum Columns - { - Name_AES, - Id, - StartTime, - Duration, - Position, - AesStatus, - EffectShowActor, - Volley, - ShotsInTotal, - Size, - Rotation, - Status, - Answer - }; - explicit EffectShowModel(QObject *parent); - ~EffectShowModel(); + Q_OBJECT + public: + enum Columns { + Name_AES, + Id, + StartTime, + Duration, + Position, + AesStatus, + EffectShowActor, + Volley, + ShotsInTotal, + Size, + Rotation, + Status, + Answer + }; - bool initModel(LtsSession::LtsSession *session); + explicit EffectShowModel(QObject* parent); + ~EffectShowModel(); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + bool initModel(LtsSession::LtsSession* session); - EffectShowActorModel *getEffectShowActorModel() { return m_effectShowActorModel; } - EffectShowActorProxyModel *getEffectShowActorProxyModel() { return m_effectShowActorProxyModel; } - EffectShowActorRelocationModel *getEffetShowActorRelocationModel() { return m_effectShowActorRelocationModel; } + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - + EffectShowActorModel* getEffectShowActorModel() + { + return m_effectShowActorModel; + } - QMap getParticipantList() const; + EffectShowActorProxyModel* getEffectShowActorProxyModel() + { + return m_effectShowActorProxyModel; + } + EffectShowActorRelocationModel* getEffetShowActorRelocationModel() + { + return m_effectShowActorRelocationModel; + } - + QMap getParticipantList() const; - QMap getParticipantList(bool is_smoke) const; + QMap getParticipantList(bool is_smoke) const; - + QVector> getParticipantListByDistance(bool is_smoke, const Core::GeoPosition2D& origin); - QVector> getParticipantListByDistance(bool is_smoke, const Core::GeoPosition2D &origin); + QString getParticipantName(int id) const; - + QString getParticipantAmmunition(int id) const; - QString getParticipantName(int id) const; + bool isVehicleStatus(int equipmentNum) const; - + bool getVehicleStatus(int equipmentNum, EffectShowManagement::EffectShowVehicleStatus& vehicleStatus) const; - QString getParticipantAmmunition(int id) const; + bool hasVehicleReportedOperationalToday(int equipmentNum) const; - + QString getTimeAndPositionOfNextEffectShow(int idParticipant) const; - bool isVehicleStatus(int equipmentNum) const; - + QString getTimeAndPositionOfNextActorRelocation(int idParticipant) const; - bool getVehicleStatus(int equipmentNum, EffectShowManagement::EffectShowVehicleStatus &vehicleStatus) const; - + void updateAll(); - bool hasVehicleReportedOperationalToday(int equipmentNum) const; + private: + NGL::INGLLogger& m_logger; + bool onEffectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus& data, + DataModification modType); - + signals: + void effectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus&, const DataModification&); - QString getTimeAndPositionOfNextEffectShow(int idParticipant) const; - + private: + std::shared_ptr m_dtc; + std::shared_ptr m_dtcPpm; + std::shared_ptr m_dtcAes; - QString getTimeAndPositionOfNextActorRelocation(int idParticipant) const; + QMap m_effectShowVehicleStatus; + QMap m_effectShowVehicleLastTimeOperational; - + EffectShowActorProxyModel* m_effectShowActorProxyModel; + EffectShowActorModel* m_effectShowActorModel; + EffectShowActorRelocationModel* m_effectShowActorRelocationModel; - void updateAll(); - -private: - -NGL::INGLLogger &m_logger; - bool onEffectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus &data, DataModification modType); - -signals: - void effectShowVehicleStatusChanged(const EffectShowManagement::EffectShowVehicleStatus &, const DataModification &); - -private: - std::shared_ptr m_dtc; - std::shared_ptr m_dtcPpm; - std::shared_ptr m_dtcAes; - - QMap m_effectShowVehicleStatus; - QMap m_effectShowVehicleLastTimeOperational; - - EffectShowActorProxyModel *m_effectShowActorProxyModel; - EffectShowActorModel *m_effectShowActorModel; - EffectShowActorRelocationModel *m_effectShowActorRelocationModel; - - friend class EffectShowProxyModel; + friend class EffectShowProxyModel; }; class EffectShowProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; - bool showExpired() const { return m_showExpired; } + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; -public slots: - void setShowExpired(bool show); + bool showExpired() const + { + return m_showExpired; + } -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override final; -private: - bool checkFilter(int source_row) const; -private: - bool m_showExpired = false; + public slots: + void setShowExpired(bool show); - EffectShowModel *m_sourceModel = nullptr; + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override final; + + private: + bool checkFilter(int source_row) const; + + private: + bool m_showExpired = false; + + EffectShowModel* m_sourceModel = nullptr; }; -} +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.cpp old mode 100755 new mode 100644 index 3c188ccc3..5e49a7bab --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.cpp @@ -1,225 +1,218 @@ - #include "evl_topic_editor_model.h" +#include +#include #include #include -#include - -#include - namespace Evaluations { - - -TopicEditorEvaluationModel::TopicEditorEvaluationModel(QObject *parent) : NGLTreeModel(parent, new NGLTreeItem(QVariant()),, - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { tr("Id"), tr("Name"), tr("Weight"), tr("Start Time"), tr("Situation"), tr("Video"), tr("Audio") }) -{} - +TopicEditorEvaluationModel::TopicEditorEvaluationModel(QObject* parent) + : NGLTreeModel(parent, new NGLTreeItem(QVariant()), , + m_logger(NGL::NGLLoggerBootstrap::getLogger()){tr("Id"), tr("Name"), tr("Weight"), tr("Start Time"), + tr("Situation"), tr("Video"), tr("Audio")}) +{ +} QVariant TopicEditorEvaluationModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role == Qt::DisplayRole && orientation == Qt::Horizontal) - { - switch (section) + if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { - case ID: - return tr("Id"); - case WEIGHT: - return tr("Weight"); - case NAME: - return tr("Name"); - case START_TIME: - return tr("Start time"); - case SITUATION: - return tr("Situation"); - case VIDEO: - return tr("Video"); - case AUDIO: - return tr("Audio"); + switch (section) + { + case ID: + return tr("Id"); + case WEIGHT: + return tr("Weight"); + case NAME: + return tr("Name"); + case START_TIME: + return tr("Start time"); + case SITUATION: + return tr("Situation"); + case VIDEO: + return tr("Video"); + case AUDIO: + return tr("Audio"); + } } - } - return NGLTreeModel::headerData(section, orientation, role); + return NGLTreeModel::headerData(section, orientation, role); } - -QVariant TopicEditorEvaluationModel::data(const QModelIndex &index, int role) const +QVariant TopicEditorEvaluationModel::data(const QModelIndex& index, int role) const { - if (!(index.isValid() && (role == Qt::DisplayRole || role == Qt::UserRole))) + if (!(index.isValid() && (role == Qt::DisplayRole || role == Qt::UserRole))) + return QVariant(); + + NGLTreeItem* item = privateData(index); + if (item->data().canConvert()) + { + EvaluationCriterium crt = item->data().value(); + + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case NAME: + return QString::fromStdString(crt.name()); + case ID: + return crt.id(); + default: + break; + } + } + else if (role == Qt::UserRole) + return crt.id(); + } + else if (item->data().canConvert()) + { + + EvaluationElement elem = item->data().value(); + + if (role == Qt::DisplayRole) + { + switch (index.column()) + { + case ID: + return elem.id(); + case NAME: + return QString::fromStdString(elem.note()); + case WEIGHT: + return elem.rating(); + case SITUATION: + return elem.situation() ? tr("Yes") : tr("No"); + case AUDIO: + return elem.audio() ? tr("Yes") : tr("No"); + case VIDEO: + return elem.video() ? tr("Yes") : tr("No"); + case START_TIME: + return QDateTime::fromMSecsSinceEpoch(elem.timestamp()); + } + } + else if (role == Qt::UserRole) + return elem.id(); + } return QVariant(); - - NGLTreeItem *item = privateData(index); - if (item->data().canConvert()) - { - EvaluationCriterium crt = item->data().value(); - - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case NAME: - return QString::fromStdString(crt.name()); - case ID: - return crt.id(); - default: - break; - } - } - else if (role == Qt::UserRole) - return crt.id(); - } - else if (item->data().canConvert()) - { - - EvaluationElement elem = item->data().value(); - - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case ID: - return elem.id(); - case NAME: - return QString::fromStdString(elem.note()); - case WEIGHT: - return elem.rating(); - case SITUATION: - return elem.situation() ? tr("Yes") : tr("No"); - case AUDIO: - return elem.audio() ? tr("Yes") : tr("No"); - case VIDEO: - return elem.video() ? tr("Yes") : tr("No"); - case START_TIME: - return QDateTime::fromMSecsSinceEpoch(elem.timestamp()); - } - } - else if (role == Qt::UserRole) - return elem.id(); - } - return QVariant(); } - -Qt::ItemFlags TopicEditorEvaluationModel::flags(const QModelIndex &index) const +Qt::ItemFlags TopicEditorEvaluationModel::flags(const QModelIndex& index) const { - auto ret = NGLTreeModel::flags(index); + auto ret = NGLTreeModel::flags(index); - - NGLTreeItem *item = privateData(index); - if (item->data().canConvert()) - ret &= ~Qt::ItemIsSelectable; + NGLTreeItem* item = privateData(index); + if (item->data().canConvert()) + ret &= ~Qt::ItemIsSelectable; - return ret; + return ret; } - -bool TopicEditorEvaluationModel::initModel(const std::shared_ptr &dtc, int operatorId) +bool TopicEditorEvaluationModel::initModel(const std::shared_ptr& dtc, int operatorId) { - if (!dtc) - return false; - DEBUG_LOG(m_logger) << "initModel Folder"; - - NGLTreeModel::resetModel(); - - QHash parentItemIndexCache; - const QMap critMap = dtc->evaluationCriteriums(); - - const QMap elemMap = dtc->evaluationElements(); - - parentItemIndexCache.insert(0, QModelIndex()); - - for (QMap::const_iterator iter = critMap.constBegin(); - iter != critMap.constEnd(); ++iter) - { - int criteriumId = iter.key(); - - int parentId = 0; - EvaluationCriterium crit = iter.value(); - - if (crit.operatorId() != operatorId) - continue; - - if (!parentItemIndexCache.contains(parentId)) - { - ERROR_LOG(m_logger) << "Invalid folder structure"; - return false; - } - else - { - QModelIndex pIndex = parentItemIndexCache.value(parentId); - int rowPos = -1; - - QVariant data; - data.setValue(crit); - onInsertRow(rowPos, pIndex, data); - parentItemIndexCache.insert(criteriumId+10000, index(rowPos, 0, pIndex)); - DEBUG_LOG(m_logger) << "Added to tree (criterium id, parent id) : (" << criteriumId << ", " << parentId << ")"; - } - - for (QMap::const_iterator iter2 = elemMap.constBegin(); - iter2 != elemMap.constEnd(); ++iter2) - { - Evaluations::EvaluationElement elem = iter2.value(); - if (elem.criteriumId() != criteriumId) - continue; - - parentId = criteriumId + 10000; - - if (!parentItemIndexCache.contains(parentId)) - { - ERROR_LOG(m_logger) << "Invalid folder structure"; + if (!dtc) return false; - } - else - { - QModelIndex pIndex = parentItemIndexCache.value(parentId); - int rowPos = -1; + DEBUG_LOG(m_logger) << "initModel Folder"; - QVariant data; - data.setValue(elem); - onInsertRow(rowPos, pIndex, data); - int elementId = elem.id(); - parentItemIndexCache.insert(elementId,index(rowPos, 0, pIndex)); - DEBUG_LOG(m_logger) << "Added to tree (element id, parent id) : (" << elementId << ", " << parentId << ")"; - } + NGLTreeModel::resetModel(); + + QHash parentItemIndexCache; + const QMap critMap = dtc->evaluationCriteriums(); + + const QMap elemMap = dtc->evaluationElements(); + + parentItemIndexCache.insert(0, QModelIndex()); + + for (QMap::const_iterator iter = critMap.constBegin(); + iter != critMap.constEnd(); ++iter) + { + int criteriumId = iter.key(); + + int parentId = 0; + EvaluationCriterium crit = iter.value(); + + if (crit.operatorId() != operatorId) + continue; + + if (!parentItemIndexCache.contains(parentId)) + { + ERROR_LOG(m_logger) << "Invalid folder structure"; + return false; + } + else + { + QModelIndex pIndex = parentItemIndexCache.value(parentId); + int rowPos = -1; + + QVariant data; + data.setValue(crit); + onInsertRow(rowPos, pIndex, data); + parentItemIndexCache.insert(criteriumId + 10000, index(rowPos, 0, pIndex)); + DEBUG_LOG(m_logger) << "Added to tree (criterium id, parent id) : (" << criteriumId << ", " << parentId + << ")"; + } + + for (QMap::const_iterator iter2 = elemMap.constBegin(); + iter2 != elemMap.constEnd(); ++iter2) + { + Evaluations::EvaluationElement elem = iter2.value(); + if (elem.criteriumId() != criteriumId) + continue; + + parentId = criteriumId + 10000; + + if (!parentItemIndexCache.contains(parentId)) + { + ERROR_LOG(m_logger) << "Invalid folder structure"; + return false; + } + else + { + QModelIndex pIndex = parentItemIndexCache.value(parentId); + int rowPos = -1; + + QVariant data; + data.setValue(elem); + onInsertRow(rowPos, pIndex, data); + int elementId = elem.id(); + parentItemIndexCache.insert(elementId, index(rowPos, 0, pIndex)); + DEBUG_LOG(m_logger) << "Added to tree (element id, parent id) : (" << elementId << ", " << parentId + << ")"; + } + } } - } - return true; + return true; } - -bool TopicEditorEvaluationModel::onInsertRow(int &row, const QModelIndex &parent, const QVariant &data) +bool TopicEditorEvaluationModel::onInsertRow(int& row, const QModelIndex& parent, const QVariant& data) { - DEBUG_LOG(m_logger) << "onInsertRow"; + DEBUG_LOG(m_logger) << "onInsertRow"; - row = rowCount(parent); - NGLTreeItem *item = new NGLTreeItem(data, QIcon()); + row = rowCount(parent); + NGLTreeItem* item = new NGLTreeItem(data, QIcon()); - return NGLTreeModel::insertRow(row, parent, item); + return NGLTreeModel::insertRow(row, parent, item); } -EvaluationElement TopicEditorEvaluationModel::getEvaluationElement(const QModelIndex &index) const +EvaluationElement TopicEditorEvaluationModel::getEvaluationElement(const QModelIndex& index) const { - NGLTreeItem *item = privateData(index); - if (item->data().canConvert()) - return item->data().value(); + NGLTreeItem* item = privateData(index); + if (item->data().canConvert()) + return item->data().value(); - return EvaluationElement(); + return EvaluationElement(); } - -QModelIndex TopicEditorEvaluationModel::getIndex(const int &elementId) const +QModelIndex TopicEditorEvaluationModel::getIndex(const int& elementId) const { - QModelIndexList list = match(index(0, 0), Qt::UserRole, QVariant::fromValue(elementId), 1, Qt::MatchRecursive); + QModelIndexList list = match(index(0, 0), Qt::UserRole, QVariant::fromValue(elementId), 1, Qt::MatchRecursive); - if (!list.isEmpty()) - return list.first(); + if (!list.isEmpty()) + return list.first(); - return {}; + return {}; } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.h old mode 100755 new mode 100644 index 2a12b6b8b..4f31d5f0c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/evl_topic_editor_model.h @@ -1,60 +1,42 @@ - #pragma once -#include #include - +#include #include #include class QTableWidget; - - namespace Evaluations { class TopicEditorEvaluationModel : public NGLTreeModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - NAME = 0, - ID, - WEIGHT, - START_TIME, - SITUATION, - VIDEO, - AUDIO - }; + public: + enum Columns { NAME = 0, ID, WEIGHT, START_TIME, SITUATION, VIDEO, AUDIO }; - explicit TopicEditorEvaluationModel(QObject *parent); - ~TopicEditorEvaluationModel() = default; + explicit TopicEditorEvaluationModel(QObject* parent); + ~TopicEditorEvaluationModel() = default; - bool initModel(const std::shared_ptr &dtc, int operatorId); + bool initModel(const std::shared_ptr& dtc, int operatorId); - EvaluationElement getEvaluationElement(const QModelIndex &index) const; + EvaluationElement getEvaluationElement(const QModelIndex& index) const; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override final; - QVariant data(const QModelIndex &, int) const override final; - QModelIndex getIndex(const int &elementId) const; - Qt::ItemFlags flags(const QModelIndex &index) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override final; + QVariant data(const QModelIndex&, int) const override final; + QModelIndex getIndex(const int& elementId) const; + Qt::ItemFlags flags(const QModelIndex& index) const override; -public slots: - bool onInsertRow(int &row, const QModelIndex &parent, const QVariant &data); + public slots: + bool onInsertRow(int& row, const QModelIndex& parent, const QVariant& data); -private: - -NGL::INGLLogger &m_logger; + private: + NGL::INGLLogger& m_logger; }; -} +} // namespace Evaluations Q_DECLARE_METATYPE(Evaluations::EvaluationCriterium) Q_DECLARE_METATYPE(Evaluations::EvaluationElement) - - - - diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.cpp old mode 100755 new mode 100644 index 1dd45e99a..a2dc611bc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.cpp @@ -1,246 +1,229 @@ - #include "topic_editor.h" + #include "ui_topic_editor.h" #include #include #include #include -#include #include - #include #include #include - +#include namespace Evaluations { -EvaluationTopicEditor::EvaluationTopicEditor(LtsSession::LtsSession *session, QWidget *parent) - : TopicEditorBase::TopicEditor(parent) - , m_session(session) - , m_ui(new Ui::EvaluationTopicEditor) +EvaluationTopicEditor::EvaluationTopicEditor(LtsSession::LtsSession* session, QWidget* parent) + : TopicEditorBase::TopicEditor(parent), m_session(session), m_ui(new Ui::EvaluationTopicEditor) { - m_ui->setupUi(this); - init(m_ui->widget); - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Evaluation_Topic")); + m_ui->setupUi(this); + init(m_ui->widget); + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Evaluation_Topic")); - m_ui->cbxOperator->clear(); - m_ui->widget->setHidden(true); + m_ui->cbxOperator->clear(); + m_ui->widget->setHidden(true); - connect(m_ui->cbxOperator, static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), - this, &EvaluationTopicEditor::onOperatorChanged); + connect(m_ui->cbxOperator, + static_cast(&LtsWidgets::LtsComboBox::currentIndexChanged), this, + &EvaluationTopicEditor::onOperatorChanged); - m_model = new TopicEditorEvaluationModel(this); - m_ui->trvEvaluations->setModel(m_model); - m_ui->trvEvaluations->expandAll(); + m_model = new TopicEditorEvaluationModel(this); + m_ui->trvEvaluations->setModel(m_model); + m_ui->trvEvaluations->expandAll(); - m_ui->trvEvaluations->hideColumn(TopicEditorEvaluationModel::Columns::ID); + m_ui->trvEvaluations->hideColumn(TopicEditorEvaluationModel::Columns::ID); - - - QItemSelectionModel *selectionModel = m_ui->trvEvaluations->selectionModel(); - connect(selectionModel, &QItemSelectionModel::selectionChanged, - this, &EvaluationTopicEditor::onSelectionChanged); + QItemSelectionModel* selectionModel = m_ui->trvEvaluations->selectionModel(); + connect(selectionModel, &QItemSelectionModel::selectionChanged, this, &EvaluationTopicEditor::onSelectionChanged); } EvaluationTopicEditor::~EvaluationTopicEditor() { - delete m_ui; + delete m_ui; } - - - bool EvaluationTopicEditor::fetchInterfaces() { - if (!m_session->getDtc(m_evlDtc)) - { - ERROR_LOG(m_logger) << "Failed to retrieve Evl Dtc"; - return false; - } + if (!m_session->getDtc(m_evlDtc)) + { + ERROR_LOG(m_logger) << "Failed to retrieve Evl Dtc"; + return false; + } - if (!m_session->getForeignGuiInterface(m_opmCbxIfc)) - { - ERROR_LOG(m_logger) << "Failed to retrieve Evl ForeignGuiInterface"; - return false; - } + if (!m_session->getForeignGuiInterface(m_opmCbxIfc)) + { + ERROR_LOG(m_logger) << "Failed to retrieve Evl ForeignGuiInterface"; + return false; + } - m_model->initModel(m_evlDtc, m_operatorId); + m_model->initModel(m_evlDtc, m_operatorId); - - initOperatorComboBox(); + initOperatorComboBox(); - DEBUG_LOG(m_logger) << "fillOperatorComboBox m_operatorId = " << m_operatorId; - return true; + DEBUG_LOG(m_logger) << "fillOperatorComboBox m_operatorId = " << m_operatorId; + return true; } - - - void EvaluationTopicEditor::updateInternalData() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (!hasTopicDataProperties()) - return; + if (!hasTopicDataProperties()) + return; - m_operatorId = getTopicDataValue(QStringLiteral("operatorId")).toInt(); - DEBUG_LOG(m_logger) << "operator id = " << m_operatorId; + m_operatorId = getTopicDataValue(QStringLiteral("operatorId")).toInt(); + DEBUG_LOG(m_logger) << "operator id = " << m_operatorId; - m_ui->cbxOperator->setCurrentIndex(m_ui->cbxOperator->findData(m_operatorId)); - m_model->initModel(m_evlDtc, m_operatorId); + m_ui->cbxOperator->setCurrentIndex(m_ui->cbxOperator->findData(m_operatorId)); + m_model->initModel(m_evlDtc, m_operatorId); - m_evlElement.id(getTopicDataValue(QStringLiteral("elementId")).toDouble()); - DEBUG_LOG(m_logger) << "element id = " << m_evlElement.id(); - m_evlElement.timestamp(getTopicDataValue(QStringLiteral("start")).toDouble()); - m_evlElement.situation(getTopicDataValue(QStringLiteral("situation")).toBool()); - m_evlElement.audio(getTopicDataValue(QStringLiteral("audio")).toBool()); - m_evlElement.video(getTopicDataValue(QStringLiteral("video")).toBool()); + m_evlElement.id(getTopicDataValue(QStringLiteral("elementId")).toDouble()); + DEBUG_LOG(m_logger) << "element id = " << m_evlElement.id(); + m_evlElement.timestamp(getTopicDataValue(QStringLiteral("start")).toDouble()); + m_evlElement.situation(getTopicDataValue(QStringLiteral("situation")).toBool()); + m_evlElement.audio(getTopicDataValue(QStringLiteral("audio")).toBool()); + m_evlElement.video(getTopicDataValue(QStringLiteral("video")).toBool()); - selectElement(); + selectElement(); } void EvaluationTopicEditor::retranslate() { - translate(m_ui, tr("Evaluation Topic Editor")); + translate(m_ui, tr("Evaluation Topic Editor")); } - void EvaluationTopicEditor::selectElement() { - QModelIndex idx; - QItemSelectionModel *selectionModel = m_ui->trvEvaluations->selectionModel(); - if (m_evlElement.id() > 0) - idx = m_model->getIndex(m_evlElement.id()); - if (idx.isValid()) - selectionModel->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); - else - selectionModel->setCurrentIndex(m_model->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + QModelIndex idx; + QItemSelectionModel* selectionModel = m_ui->trvEvaluations->selectionModel(); + if (m_evlElement.id() > 0) + idx = m_model->getIndex(m_evlElement.id()); + if (idx.isValid()) + selectionModel->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + else + selectionModel->setCurrentIndex(m_model->index(0, 0), + QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void EvaluationTopicEditor::initOperatorComboBox() { - m_opmCbxIfc->fillOperatorComboBox(m_ui->cbxOperator); - m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - QMap evaluationCriteria = m_evlDtc->evaluationCriteriums(); - for (int index = m_ui->cbxOperator->count() - 1; index >= 0; --index) - { - int operatorId = m_ui->cbxOperator->itemData(index).toInt(); - - if (operatorId == m_operatorId) - continue; - - auto it = std::find_if(evaluationCriteria.constBegin(), evaluationCriteria.constEnd(), [this, operatorId](const EvaluationCriterium &ec) + m_opmCbxIfc->fillOperatorComboBox(m_ui->cbxOperator); + m_operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + QMap evaluationCriteria = m_evlDtc->evaluationCriteriums(); + for (int index = m_ui->cbxOperator->count() - 1; index >= 0; --index) { - return ec.operatorId() == operatorId; - }); - if (it == evaluationCriteria.constEnd()) - m_ui->cbxOperator->removeItem(index); - } - m_ui->cbxOperator->setCurrentIndex(m_ui->cbxOperator->findData(m_operatorId)); + int operatorId = m_ui->cbxOperator->itemData(index).toInt(); + + if (operatorId == m_operatorId) + continue; + + auto it = + std::find_if(evaluationCriteria.constBegin(), evaluationCriteria.constEnd(), + [this, operatorId](const EvaluationCriterium& ec) { return ec.operatorId() == operatorId; }); + if (it == evaluationCriteria.constEnd()) + m_ui->cbxOperator->removeItem(index); + } + m_ui->cbxOperator->setCurrentIndex(m_ui->cbxOperator->findData(m_operatorId)); } - - - bool EvaluationTopicEditor::apply2() { - setTopicDataProperty(QStringLiteral("operatorId"), m_operatorId); - setTopicDataProperty(QStringLiteral("elementId"), m_evlElement.id()); - setTopicDataProperty(QStringLiteral("start"), m_evlElement.timestamp()); - setTopicDataProperty(QStringLiteral("situation"), m_evlElement.situation()); - setTopicDataProperty(QStringLiteral("audio"), m_evlElement.audio()); - setTopicDataProperty(QStringLiteral("video"), m_evlElement.video()); + setTopicDataProperty(QStringLiteral("operatorId"), m_operatorId); + setTopicDataProperty(QStringLiteral("elementId"), m_evlElement.id()); + setTopicDataProperty(QStringLiteral("start"), m_evlElement.timestamp()); + setTopicDataProperty(QStringLiteral("situation"), m_evlElement.situation()); + setTopicDataProperty(QStringLiteral("audio"), m_evlElement.audio()); + setTopicDataProperty(QStringLiteral("video"), m_evlElement.video()); - DEBUG_LOG(m_logger) << "operator id = " << m_operatorId << ", element id = " << m_evlElement.id(); - DEBUG_LOG(m_logger) << "timestamp: " << m_evlElement.timestamp(); + DEBUG_LOG(m_logger) << "operator id = " << m_operatorId << ", element id = " << m_evlElement.id(); + DEBUG_LOG(m_logger) << "timestamp: " << m_evlElement.timestamp(); - if (m_evlElement.situation()) - { - TopicEditorBase::TopicData data; - data.topicType = TopicEditorBase::TopicType::Situation; - setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); - setTopicDataProperty(QStringLiteral("speed"), 1.0); - - if (m_evlElement.situationContent()) + if (m_evlElement.situation()) { - QJsonParseError error; - QJsonDocument doc(QJsonDocument::fromJson(QString::fromStdString(m_evlElement.situationContent().get()).toUtf8(), &error)); + TopicEditorBase::TopicData data; + data.topicType = TopicEditorBase::TopicType::Situation; + setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); + setTopicDataProperty(QStringLiteral("speed"), 1.0); - if (error.error == QJsonParseError::NoError) - { - QJsonObject root(doc.object()); - setTopicDataProperty(QStringLiteral("filters"), root[QStringLiteral("filters")]); - setTopicDataProperty(QStringLiteral("settings"), root[QStringLiteral("settings")]); - } - else - new LtsWidgets::LtsMessageDialogNew(this, tr("The selected marker has invalid filter and/or map settings.")); + if (m_evlElement.situationContent()) + { + QJsonParseError error; + QJsonDocument doc(QJsonDocument::fromJson( + QString::fromStdString(m_evlElement.situationContent().get()).toUtf8(), &error)); + + if (error.error == QJsonParseError::NoError) + { + QJsonObject root(doc.object()); + setTopicDataProperty(QStringLiteral("filters"), root[QStringLiteral("filters")]); + setTopicDataProperty(QStringLiteral("settings"), root[QStringLiteral("settings")]); + } + else + new LtsWidgets::LtsMessageDialogNew(this, + tr("The selected marker has invalid filter and/or map settings.")); + } + + data.duration = m_evlElement.duration(); + data.properties = m_topicData.properties; + + DEBUG_LOG(m_logger) << "topicData - properties: " + << QJsonDocument(m_topicData.properties).toJson(QJsonDocument::Compact); + + emit topicEditorRequested(data); } - data.duration = m_evlElement.duration(); - data.properties = m_topicData.properties; + if (m_evlElement.audio()) + { + TopicEditorBase::TopicData data; + data.topicType = TopicEditorBase::TopicType::Audio; + setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); + LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(m_evlElement.audioContent().get()); + setTopicDataProperty(QStringLiteral("stream"), jsonObj.value("actualStream")); + data.duration = m_evlElement.duration(); + data.properties = m_topicData.properties; + emit topicEditorRequested(data); + } - DEBUG_LOG(m_logger) << "topicData - properties: " << QJsonDocument(m_topicData.properties).toJson(QJsonDocument::Compact); + if (m_evlElement.video()) + { + LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(m_evlElement.videoContent().get()); + TopicEditorBase::TopicData data; + data.topicType = TopicEditorBase::TopicType::Video; + setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); + setTopicDataProperty(QStringLiteral("stream"), jsonObj.value("actualStream")); + data.duration = m_evlElement.duration(); + data.properties = m_topicData.properties; + emit topicEditorRequested(data); + } - emit topicEditorRequested(data); - } - - if (m_evlElement.audio()) - { - TopicEditorBase::TopicData data; - data.topicType = TopicEditorBase::TopicType::Audio; - setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); - LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(m_evlElement.audioContent().get()); - setTopicDataProperty(QStringLiteral("stream"), jsonObj.value("actualStream")); - data.duration = m_evlElement.duration(); - data.properties = m_topicData.properties; - emit topicEditorRequested(data); - } - - if (m_evlElement.video()) - { - LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(m_evlElement.videoContent().get()); - TopicEditorBase::TopicData data; - data.topicType = TopicEditorBase::TopicType::Video; - setTopicDataProperty(QStringLiteral("end"), m_evlElement.timestamp() + m_evlElement.duration() * 1000); - setTopicDataProperty(QStringLiteral("stream"), jsonObj.value("actualStream")); - data.duration = m_evlElement.duration(); - data.properties = m_topicData.properties; - emit topicEditorRequested(data); - } - - - return true; + return true; } - void EvaluationTopicEditor::onOperatorChanged() { - m_operatorId = m_ui->cbxOperator->currentData().toInt(); - DEBUG_LOG(m_logger) << "operator id = " << m_operatorId; + m_operatorId = m_ui->cbxOperator->currentData().toInt(); + DEBUG_LOG(m_logger) << "operator id = " << m_operatorId; - m_model->initModel(m_evlDtc, m_operatorId); - m_ui->trvEvaluations->expandAll(); + m_model->initModel(m_evlDtc, m_operatorId); + m_ui->trvEvaluations->expandAll(); } -void EvaluationTopicEditor::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) +void EvaluationTopicEditor::onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { - Q_UNUSED(selected); - Q_UNUSED(deselected); + Q_UNUSED(selected); + Q_UNUSED(deselected); - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - QModelIndex index = m_ui->trvEvaluations->currentIndex(); - m_evlElement = m_model->getEvaluationElement(index); - DEBUG_LOG(m_logger) << "element id = " << m_evlElement.id(); + QModelIndex index = m_ui->trvEvaluations->currentIndex(); + m_evlElement = m_model->getEvaluationElement(index); + DEBUG_LOG(m_logger) << "element id = " << m_evlElement.id(); - m_topicData.description = QString::number(m_evlElement.id()); - slotChangesMade(); + m_topicData.description = QString::number(m_evlElement.id()); + slotChangesMade(); } - -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.h old mode 100755 new mode 100644 index 775dfa9bd..5ad748bc3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/TopicEditor/topic_editor.h @@ -1,6 +1,5 @@ - #pragma once #include "evl_topic_editor_model.h" @@ -11,51 +10,54 @@ #include #include +namespace Ui +{ +class EvaluationTopicEditor; +} -namespace Ui { class EvaluationTopicEditor; } - -namespace LtsScriptTimeline { class TrackEntry; } - +namespace LtsScriptTimeline +{ +class TrackEntry; +} namespace Evaluations { class EvaluationTopicEditor : public TopicEditorBase::TopicEditor { - Q_OBJECT + Q_OBJECT -public: - explicit EvaluationTopicEditor(LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~EvaluationTopicEditor(); + public: + explicit EvaluationTopicEditor(LtsSession::LtsSession* session, QWidget* parent = nullptr); + ~EvaluationTopicEditor(); - void selected(); - bool fetchInterfaces(); + void selected(); + bool fetchInterfaces(); -private: + private: + NGL::INGLLogger& m_logger; + void updateInternalData() override final; + void retranslate() override final; -NGL::INGLLogger &m_logger; - void updateInternalData() override final; - void retranslate() override final; + void selectElement(); + void initOperatorComboBox(); - void selectElement(); - void initOperatorComboBox(); + private slots: + bool apply2() override final; -private slots: - bool apply2() override final; + void onOperatorChanged(); + void onSelectionChanged(const QItemSelection&, const QItemSelection&); - void onOperatorChanged(); - void onSelectionChanged(const QItemSelection & , const QItemSelection & ); + private: + LtsSession::LtsSession* m_session{nullptr}; + std::shared_ptr m_evlDtc{nullptr}; + std::shared_ptr m_opmCbxIfc{nullptr}; -private: - LtsSession::LtsSession *m_session{nullptr}; - std::shared_ptr m_evlDtc{nullptr}; - std::shared_ptr m_opmCbxIfc{nullptr}; + int m_operatorId{0}; + EvaluationElement m_evlElement; + TopicEditorEvaluationModel* m_model{nullptr}; - int m_operatorId{0}; - EvaluationElement m_evlElement; - TopicEditorEvaluationModel *m_model{nullptr}; - - Ui::EvaluationTopicEditor *m_ui{nullptr}; + Ui::EvaluationTopicEditor* m_ui{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.cpp old mode 100755 new mode 100644 index 9823dc2f3..d09305b74 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.cpp @@ -1,204 +1,204 @@ - #include "evl_dialog.h" -#include "ui_evl_dialog.h" -#include "evl_model.h" + #include "evl_edit_dialog.h" #include "evl_element_dialog.h" - -#include -#include +#include "evl_model.h" +#include "ui_evl_dialog.h" #include +#include +#include #include namespace Evaluations { -CriteriumDialog::CriteriumDialog(const QString &menuGroup, LtsSession::LtsSession *session, bool ownEvlElements, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_model(new CriteriumDialogModel(this)) - , m_proxyModel(new CriteriumFilterModel(this)) - , m_session(session) - , m_ui(new Ui::CriteriumDialog) - , m_menuGroup(menuGroup) - , m_ownEvaluationElements(ownEvlElements) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +CriteriumDialog::CriteriumDialog(const QString& menuGroup, LtsSession::LtsSession* session, bool ownEvlElements, + QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_model(new CriteriumDialogModel(this)), + m_proxyModel(new CriteriumFilterModel(this)), m_session(session), m_ui(new Ui::CriteriumDialog), + m_menuGroup(menuGroup), m_ownEvaluationElements(ownEvlElements), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - DEBUG_LOG(m_logger) << "CriteriumDialog ctor"; - m_ui->setupUi(this); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CriteriumDialog::onPrint); + DEBUG_LOG(m_logger) << "CriteriumDialog ctor"; + m_ui->setupUi(this); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Print, this, &CriteriumDialog::onPrint); - m_proxyModel->setSourceModel(m_model); + m_proxyModel->setSourceModel(m_model); - if (ownEvlElements) - setOnlineHelpFilename(QStringLiteral("Situation-Own_Evaluation_Criteria")); - else - setOnlineHelpFilename(QStringLiteral("Situation-All_Evaluation_Criteria")); + if (ownEvlElements) + setOnlineHelpFilename(QStringLiteral("Situation-Own_Evaluation_Criteria")); + else + setOnlineHelpFilename(QStringLiteral("Situation-All_Evaluation_Criteria")); } CriteriumDialog::~CriteriumDialog() { - delete m_ui; + delete m_ui; } void CriteriumDialog::retranslate() { - if (m_ownEvaluationElements) - translate(m_ui, tr("Own Evaluation Criteria")); - else - translate(m_ui, tr("All Evaluation Criteria")); + if (m_ownEvaluationElements) + translate(m_ui, tr("Own Evaluation Criteria")); + else + translate(m_ui, tr("All Evaluation Criteria")); } void CriteriumDialog::enaDisa() { - int selected = m_ui->widget->selectedRows().size(); + int selected = m_ui->widget->selectedRows().size(); - const QModelIndex srcIdx = m_ui->widget->currentIndex(); - int operatorId = m_model->getRowData(srcIdx.row()).operatorId(); + const QModelIndex srcIdx = m_ui->widget->currentIndex(); + int operatorId = m_model->getRowData(srcIdx.row()).operatorId(); - if (m_currentOperatorId == operatorId) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true && selected == 1); - else - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (selected == 1)); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (selected > 0)); + if (m_currentOperatorId == operatorId) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true && selected == 1); + else + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (selected == 1)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (selected > 0)); } + void CriteriumDialog::onPrint() { - LtsPrinting::printView(m_session, this, m_ui->widget->treeView() ); + LtsPrinting::printView(m_session, this, m_ui->widget->treeView()); } - void CriteriumDialog::editCriterium(int criteriumId) { - addDialog(LtsWidgets::initDialog(new CriteriumEditDialog(), - criteriumId, - m_session, m_dtc, m_ftc, m_opmCbxDtc), - m_menuGroup, QStringLiteral("CriteriumEditDialog%1").arg(criteriumId), LtsWidgets::LayoutArea::eDialogTab); + addDialog(LtsWidgets::initDialog(new CriteriumEditDialog(), criteriumId, m_session, m_dtc, m_ftc, m_opmCbxDtc), + m_menuGroup, QStringLiteral("CriteriumEditDialog%1").arg(criteriumId), + LtsWidgets::LayoutArea::eDialogTab); } void CriteriumDialog::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } void CriteriumDialog::slotAdd() { - DEBUG_LOG(m_logger) << "CriteriumDialog::slotAdd"; - editCriterium(0 ); + DEBUG_LOG(m_logger) << "CriteriumDialog::slotAdd"; + editCriterium(0); } void CriteriumDialog::slotEdit() { - DEBUG_LOG(m_logger) << "CriteriumDialog::slotEdit"; + DEBUG_LOG(m_logger) << "CriteriumDialog::slotEdit"; - const QModelIndex srcIdx = m_ui->widget->currentIndex(); - editCriterium(m_model->getRowData(srcIdx.row()).id() ); + const QModelIndex srcIdx = m_ui->widget->currentIndex(); + editCriterium(m_model->getRowData(srcIdx.row()).id()); } void CriteriumDialog::slotRemove() { - DEBUG_LOG(m_logger) << "CriteriumDialog::slotRemove"; - const QModelIndex selIndex = m_ui->widget->currentIndex(); - if (!selIndex.isValid()) - return; + DEBUG_LOG(m_logger) << "CriteriumDialog::slotRemove"; + const QModelIndex selIndex = m_ui->widget->currentIndex(); + if (!selIndex.isValid()) + return; - Core::RemoveElementRequest req(m_model->getRowData(selIndex.row()).id()); - DEBUG_LOG(m_logger) << "Removing criterium id = " << req.id(); - m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->evlCriteriumRemoveRequest(req, this); - }); + Core::RemoveElementRequest req(m_model->getRowData(selIndex.row()).id()); + DEBUG_LOG(m_logger) << "Removing criterium id = " << req.id(); + m_requestHelper->startSingleRequest([req, this]() { return m_ftc->evlCriteriumRemoveRequest(req, this); }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to remove criterium"; + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to remove criterium"; } - void CriteriumDialog::slotEditElements() { - const QModelIndex selIndex = m_ui->widget->currentIndex(); - if (!selIndex.isValid()) - return; + const QModelIndex selIndex = m_ui->widget->currentIndex(); + if (!selIndex.isValid()) + return; - int criteriumId = m_model->getRowData(selIndex.row()).id(); - addDialog(LtsWidgets::initDialog(new ElementDialog(), - criteriumId, - m_exerciseId, m_menuGroup, m_dtc, m_ftc, m_exmDtc, m_avmDataIfc, m_fltParticipantIfc, m_fltAesIfc, m_fltBuildingComponentIfc, m_session), - m_menuGroup, ElementDialog::dialogIdentifier() + QString::number(criteriumId), LtsWidgets::LayoutArea::eDialogTab); + int criteriumId = m_model->getRowData(selIndex.row()).id(); + addDialog(LtsWidgets::initDialog(new ElementDialog(), criteriumId, m_exerciseId, m_menuGroup, m_dtc, m_ftc, + m_exmDtc, m_avmDataIfc, m_fltParticipantIfc, m_fltAesIfc, + m_fltBuildingComponentIfc, m_session), + m_menuGroup, ElementDialog::dialogIdentifier() + QString::number(criteriumId), + LtsWidgets::LayoutArea::eDialogTab); } -bool CriteriumDialog::init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &opmDtc, - const std::shared_ptr &opmCbxDtc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - int exerciseId, - int currentOperatorId) +bool CriteriumDialog::init( + const std::shared_ptr& dtc, const std::shared_ptr& ftc, + const std::shared_ptr& opmDtc, + const std::shared_ptr& opmCbxDtc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + int exerciseId, int currentOperatorId) { - DEBUG_LOG(m_logger) << "CriteriumDialog::init"; - m_dtc = dtc; - m_ftc = ftc; - m_opmCbxDtc = opmCbxDtc; - m_exmDtc = exmDtc; - m_avmDataIfc = avmDataIfc; - m_fltParticipantIfc = fltParticipantIfc; - m_fltAesIfc = fltAesIfc; - m_fltBuildingComponentIfc = fltBuildingComponentIfc; - m_exerciseId = exerciseId; - m_currentOperatorId = currentOperatorId; + DEBUG_LOG(m_logger) << "CriteriumDialog::init"; + m_dtc = dtc; + m_ftc = ftc; + m_opmCbxDtc = opmCbxDtc; + m_exmDtc = exmDtc; + m_avmDataIfc = avmDataIfc; + m_fltParticipantIfc = fltParticipantIfc; + m_fltAesIfc = fltAesIfc; + m_fltBuildingComponentIfc = fltBuildingComponentIfc; + m_exerciseId = exerciseId; + m_currentOperatorId = currentOperatorId; - m_model->initModel(dtc, opmDtc); + m_model->initModel(dtc, opmDtc); - if (m_ownEvaluationElements) - m_proxyModel->setOperatorId(m_currentOperatorId); + if (m_ownEvaluationElements) + m_proxyModel->setOperatorId(m_currentOperatorId); - m_ui->widget->setModel(m_proxyModel); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(CriteriumDialogModel::Id); + m_ui->widget->hideColumn(CriteriumDialogModel::Id); #endif - m_ui->widget->setSortIndicator(CriteriumDialogModel::Name, Qt::AscendingOrder); + m_ui->widget->setSortIndicator(CriteriumDialogModel::Name, Qt::AscendingOrder); - QMap criteria = m_dtc->evaluationCriteriums(); + QMap criteria = m_dtc->evaluationCriteriums(); - for (auto i = criteria.constBegin(); i != criteria.constEnd(); ++i) - { - const EvaluationCriterium &p = (*i); - DEBUG_LOG(m_logger) << "Criterium: id = " << p.id() << ", name = " << p.name().c_str() << ", desc = " << p.description().c_str(); - } + for (auto i = criteria.constBegin(); i != criteria.constEnd(); ++i) + { + const EvaluationCriterium& p = (*i); + DEBUG_LOG(m_logger) << "Criterium: id = " << p.id() << ", name = " << p.name().c_str() + << ", desc = " << p.description().c_str(); + } - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &CriteriumDialog::enaDisa, Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &CriteriumDialog::enaDisa, + Qt::UniqueConnection); - if (!m_ownEvaluationElements) - { - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &CriteriumDialog::slotAdd, Qt::UniqueConnection); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &CriteriumDialog::slotEdit, Qt::UniqueConnection); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &CriteriumDialog::slotRemove, Qt::UniqueConnection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &CriteriumDialog::slotEdit, Qt::UniqueConnection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &CriteriumDialog::slotEdit, Qt::UniqueConnection); - } - else - { - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &CriteriumDialog::slotEditElements, Qt::UniqueConnection); - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Edit Elements")); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &CriteriumDialog::slotEditElements, Qt::UniqueConnection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &CriteriumDialog::slotEditElements, Qt::UniqueConnection); - } + if (!m_ownEvaluationElements) + { + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &CriteriumDialog::slotAdd, + Qt::UniqueConnection); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &CriteriumDialog::slotEdit, + Qt::UniqueConnection); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &CriteriumDialog::slotRemove, + Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &CriteriumDialog::slotEdit, + Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &CriteriumDialog::slotEdit, + Qt::UniqueConnection); + } + else + { + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &CriteriumDialog::slotEditElements, + Qt::UniqueConnection); + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Edit Elements")); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &CriteriumDialog::slotEditElements, + Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &CriteriumDialog::slotEditElements, + Qt::UniqueConnection); + } - enaDisa(); + enaDisa(); - return true; + return true; } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.h old mode 100755 new mode 100644 index 58170e2aa..72c69430f --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_dialog.h @@ -1,22 +1,19 @@ - #pragma once #include #include #include #include -#include - -#include #include - +#include +#include #include -#include -#include #include #include +#include +#include namespace Ui { @@ -33,65 +30,71 @@ namespace Evaluations class CriteriumDialogModel; class CriteriumFilterModel; -class CriteriumDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::EvlCriteriumModifyReplyHandler - , protected Interface::Ftc::EvlCriteriumRemoveReplyHandler +class CriteriumDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::EvlCriteriumModifyReplyHandler, + protected Interface::Ftc::EvlCriteriumRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit CriteriumDialog(const QString &menuGroup, LtsSession::LtsSession *session, bool ownEvlElements, QWidget *parent = nullptr); - ~CriteriumDialog(); + public: + explicit CriteriumDialog(const QString& menuGroup, LtsSession::LtsSession* session, bool ownEvlElements, + QWidget* parent = nullptr); + ~CriteriumDialog(); - bool init(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &opmDtc, - const std::shared_ptr &opmCbxDtc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - int exerciseId, - int currentOperatorId); + bool init(const std::shared_ptr& dtc, const std::shared_ptr& ftc, + const std::shared_ptr& opmDtc, + const std::shared_ptr& opmCbxDtc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + int exerciseId, int currentOperatorId); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onEvlCriteriumModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onEvlCriteriumRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onPrint(); + void onEvlCriteriumModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - void retranslate() override; - void editCriterium(int criteriumId); - void tableColumnOrganiserSetting() override; + void onEvlCriteriumRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - CriteriumDialogModel *m_model{nullptr}; - CriteriumFilterModel *m_proxyModel{nullptr}; - LtsSession::LtsSession *m_session{nullptr}; - Ui::CriteriumDialog *m_ui{nullptr}; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_opmDtc; - std::shared_ptr m_opmCbxDtc; - std::shared_ptr m_exmDtc; - std::shared_ptr m_avmDataIfc; - std::shared_ptr m_fltParticipantIfc; - std::shared_ptr m_fltAesIfc; - std::shared_ptr m_fltBuildingComponentIfc; - QString m_menuGroup; - int m_exerciseId{-1}; - int m_currentOperatorId{-1}; - bool m_ownEvaluationElements{false}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; -private slots: - void slotAdd(); - void slotEdit(); - void slotRemove(); - void enaDisa(); - void slotEditElements(); + void onPrint(); + private: + void retranslate() override; + void editCriterium(int criteriumId); + void tableColumnOrganiserSetting() override; + + CriteriumDialogModel* m_model{nullptr}; + CriteriumFilterModel* m_proxyModel{nullptr}; + LtsSession::LtsSession* m_session{nullptr}; + Ui::CriteriumDialog* m_ui{nullptr}; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_opmDtc; + std::shared_ptr m_opmCbxDtc; + std::shared_ptr m_exmDtc; + std::shared_ptr m_avmDataIfc; + std::shared_ptr m_fltParticipantIfc; + std::shared_ptr m_fltAesIfc; + std::shared_ptr m_fltBuildingComponentIfc; + QString m_menuGroup; + int m_exerciseId{-1}; + int m_currentOperatorId{-1}; + bool m_ownEvaluationElements{false}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + private slots: + void slotAdd(); + void slotEdit(); + void slotRemove(); + void enaDisa(); + void slotEditElements(); }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.cpp old mode 100755 new mode 100644 index cf7b23640..a7f971e28 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.cpp @@ -1,154 +1,145 @@ - #include "evl_edit_dialog.h" + #include "ui_evl_edit_dialog.h" +#include +#include #include #include -#include #include -#include - -#include #include +#include namespace Evaluations { -CriteriumEditDialog::CriteriumEditDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::CriteriumEditDialog) +CriteriumEditDialog::CriteriumEditDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkCancel), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::CriteriumEditDialog) { - DEBUG_LOG(m_logger) << "CriteriumEditDialog ctor"; + DEBUG_LOG(m_logger) << "CriteriumEditDialog ctor"; - m_ui->setupUi(this); + m_ui->setupUi(this); - m_uiRequirements->addRequirement({ m_ui->lblName, [this]() { return !m_ui->leName->text().isEmpty(); } }); + m_uiRequirements->addRequirement({m_ui->lblName, [this]() { return !m_ui->leName->text().isEmpty(); }}); } CriteriumEditDialog::~CriteriumEditDialog() { - delete m_ui; + delete m_ui; } void CriteriumEditDialog::retranslate() { - translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Criterium")); + translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Criterium")); } -bool CriteriumEditDialog::init(int criteriumId, - LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &opmCbxDtc) +bool CriteriumEditDialog::init(int criteriumId, LtsSession::LtsSession* session, + const std::shared_ptr& dtc, const std::shared_ptr& ftc, + const std::shared_ptr& opmCbxDtc) { - DEBUG_LOG(m_logger) << "CriteriumEditDialog::init"; - m_criteriumId = criteriumId; - m_dtc = dtc; - m_ftc = ftc; - m_session = session; + DEBUG_LOG(m_logger) << "CriteriumEditDialog::init"; + m_criteriumId = criteriumId; + m_dtc = dtc; + m_ftc = ftc; + m_session = session; - opmCbxDtc->fillOperatorComboBox(m_ui->cbxOperators); + opmCbxDtc->fillOperatorComboBox(m_ui->cbxOperators); - if (m_criteriumId > 0) - { - Evaluations::EvaluationCriterium eval = m_dtc->evaluationCriterium(m_criteriumId); - m_ui->leName->setText(QString::fromStdString(eval.name())); - m_ui->teDesc->setText(QString::fromStdString(eval.description())); + if (m_criteriumId > 0) + { + Evaluations::EvaluationCriterium eval = m_dtc->evaluationCriterium(m_criteriumId); + m_ui->leName->setText(QString::fromStdString(eval.name())); + m_ui->teDesc->setText(QString::fromStdString(eval.description())); - m_ui->cbxOperators->setCurrentIndex(m_ui->cbxOperators->findData(eval.operatorId())); - } - else - { - m_ui->cbxOperators->setCurrentIndex(m_ui->cbxOperators->findData(LtsSessionData::LtsSessionData::getInstance()->getOperatorId())); - } + m_ui->cbxOperators->setCurrentIndex(m_ui->cbxOperators->findData(eval.operatorId())); + } + else + { + m_ui->cbxOperators->setCurrentIndex( + m_ui->cbxOperators->findData(LtsSessionData::LtsSessionData::getInstance()->getOperatorId())); + } - m_ui->leName->setFocus(); + m_ui->leName->setFocus(); - - m_buttonBox->connectLibraryButton(this, &CriteriumEditDialog::onImportButtonClicked, - &CriteriumEditDialog::onExportButtonClicked); + m_buttonBox->connectLibraryButton(this, &CriteriumEditDialog::onImportButtonClicked, + &CriteriumEditDialog::onExportButtonClicked); - if (!m_session->getForeignGuiInterface(m_flmGui)) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); + if (!m_session->getForeignGuiInterface(m_flmGui)) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Library, false); - return true; + return true; } bool CriteriumEditDialog::apply() { - - EvlCriteriumModifyRequest req; - req.id(m_criteriumId); - req.name(m_ui->leName->text().toStdString()); - req.description(m_ui->teDesc->toPlainText().toStdString()); - req.operatorId(m_ui->cbxOperators->currentData().toInt()); - return m_requestHelper->startSingleRequest([this, req]() - { - return m_ftc->evlCriteriumModifyRequest(req, this); - }); + EvlCriteriumModifyRequest req; + req.id(m_criteriumId); + req.name(m_ui->leName->text().toStdString()); + req.description(m_ui->teDesc->toPlainText().toStdString()); + req.operatorId(m_ui->cbxOperators->currentData().toInt()); + + return m_requestHelper->startSingleRequest([this, req]() { return m_ftc->evlCriteriumModifyRequest(req, this); }); } QByteArray CriteriumEditDialog::UiToJson() { - QJsonObject obj; - obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit); - obj[QStringLiteral("Name")] = m_ui->leName->text(); - obj[QStringLiteral("Description")] = m_ui->teDesc->toPlainText(); - obj[QStringLiteral("OperatorId")] = m_ui->cbxOperators->currentData().toInt(); + QJsonObject obj; + obj[QStringLiteral("XmlType")] = FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit); + obj[QStringLiteral("Name")] = m_ui->leName->text(); + obj[QStringLiteral("Description")] = m_ui->teDesc->toPlainText(); + obj[QStringLiteral("OperatorId")] = m_ui->cbxOperators->currentData().toInt(); - return QJsonDocument(obj).toJson(QJsonDocument::Compact); -} + return QJsonDocument(obj).toJson(QJsonDocument::Compact); +} -void CriteriumEditDialog::jsonToUi(const QByteArray &content) +void CriteriumEditDialog::jsonToUi(const QByteArray& content) { - - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); - QString name = obj[QStringLiteral("Name")].toString(); - QString description = obj[QStringLiteral("Description")].toString();; - int operatorId = obj[QStringLiteral("OperatorId")].toInt(); + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); - m_ui->leName->setText(name); - m_ui->teDesc->setText(description); - m_ui->cbxOperators->setCurrentIndex(m_ui->cbxOperators->findData(operatorId)); -} + QString name = obj[QStringLiteral("Name")].toString(); + QString description = obj[QStringLiteral("Description")].toString(); + ; + int operatorId = obj[QStringLiteral("OperatorId")].toInt(); + + m_ui->leName->setText(name); + m_ui->teDesc->setText(description); + m_ui->cbxOperators->setCurrentIndex(m_ui->cbxOperators->findData(operatorId)); +} void CriteriumEditDialog::onExportButtonClicked() { - QByteArray byteArray = UiToJson(); + QByteArray byteArray = UiToJson(); - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, m_session->exerciseId(), byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void CriteriumEditDialog::onImportButtonClicked() { - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit)); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit))) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, m_session->exerciseId(), + FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit)); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); + if (!m_flmGui->isXmlType(content, FileManagement::toString(FileManagement::XmlType::EVLCriteriumEdit))) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + jsonToUi(content); + } } - else - { - jsonToUi(content); - } - } -} +} -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.h old mode 100755 new mode 100644 index aec14a418..6ec282b63 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_dialog.h @@ -1,18 +1,16 @@ - #pragma once -#include #include #include -#include -#include -#include +#include #include - -#include +#include +#include +#include #include +#include namespace LtsWidgets { @@ -27,44 +25,49 @@ class CriteriumEditDialog; namespace Evaluations { -class CriteriumEditDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::EvlCriteriumModifyReplyHandler - , protected Interface::Ftc::EvlCriteriumRemoveReplyHandler +class CriteriumEditDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::EvlCriteriumModifyReplyHandler, + protected Interface::Ftc::EvlCriteriumRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit CriteriumEditDialog(QWidget *parent = nullptr); - ~CriteriumEditDialog(); + public: + explicit CriteriumEditDialog(QWidget* parent = nullptr); + ~CriteriumEditDialog(); - bool init(int criteriumId, - LtsSession::LtsSession *session, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &opmCbxDtc); + bool init(int criteriumId, LtsSession::LtsSession* session, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& opmCbxDtc); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onEvlCriteriumModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onEvlCriteriumRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onEvlCriteriumModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void onExportButtonClicked(); - void onImportButtonClicked(); + void onEvlCriteriumRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - bool apply() override; - void retranslate() override; - QByteArray UiToJson(); - void jsonToUi(const QByteArray &content); + private slots: + void onExportButtonClicked(); + void onImportButtonClicked(); - LtsSession::LtsSession *m_session{nullptr}; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_flmGui; - int m_criteriumId{-1}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - Ui::CriteriumEditDialog *m_ui{nullptr}; + private: + bool apply() override; + void retranslate() override; + QByteArray UiToJson(); + void jsonToUi(const QByteArray& content); + + LtsSession::LtsSession* m_session{nullptr}; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_flmGui; + int m_criteriumId{-1}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + Ui::CriteriumEditDialog* m_ui{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.cpp old mode 100755 new mode 100644 index c2bd0df9f..36e79caa8 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.cpp @@ -1,328 +1,303 @@ - #include "evl_edit_element_dialog.h" -#include -#include "ui_evl_edit_element_dialog.h" -#include -#include -#include -#include -#include +#include "ui_evl_edit_element_dialog.h" #include #include +#include +#include #include #include -#include +#include +#include +#include #include -#include - #include -#include #include - +#include +#include +#include +#include namespace Evaluations { -ElementEditDialog::ElementEditDialog(QWidget *) - : LtsWidgets::LtsDialog(nullptr, LtsWidgets::ButtonCombination::OkCancel) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::ElementEditDialog) +ElementEditDialog::ElementEditDialog(QWidget*) + : LtsWidgets::LtsDialog(nullptr, LtsWidgets::ButtonCombination::OkCancel), + m_requestHelper(new LtsUtils::RequestHelper(this)), m_ui(new Ui::ElementEditDialog) { - DEBUG_LOG(m_logger) << "ElementEditDialog ctor"; + DEBUG_LOG(m_logger) << "ElementEditDialog ctor"; - m_ui->setupUi(this); + m_ui->setupUi(this); - connect(m_ui->cbSituation, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); - connect(m_ui->cbVideo, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); - connect(m_ui->cbAudio, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); + connect(m_ui->cbSituation, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); + connect(m_ui->cbVideo, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); + connect(m_ui->cbAudio, &QCheckBox::clicked, this, &ElementEditDialog::onCheckBoxClicked); - connect(m_ui->cbVideo, &QCheckBox::stateChanged, this, &ElementEditDialog::onVideoClicked); - connect(m_ui->cbAudio, &QCheckBox::stateChanged, this, &ElementEditDialog::onAudioClicked); + connect(m_ui->cbVideo, &QCheckBox::stateChanged, this, &ElementEditDialog::onVideoClicked); + connect(m_ui->cbAudio, &QCheckBox::stateChanged, this, &ElementEditDialog::onAudioClicked); - m_uiRequirements->addRequirement({m_ui->lblMedium, [this]() { return m_ui->cbSituation->isChecked() || - (m_ui->cbAudio->isChecked() && !m_audioStreams.isEmpty()) || - (m_ui->cbVideo->isChecked() && !m_videoStreams.isEmpty()); }, - tr("Select one or more media. If you have selected audio or video, make sure that a audio / video stream has been selected.") }); + m_uiRequirements->addRequirement({m_ui->lblMedium, + [this]() { + return m_ui->cbSituation->isChecked() || + (m_ui->cbAudio->isChecked() && !m_audioStreams.isEmpty()) || + (m_ui->cbVideo->isChecked() && !m_videoStreams.isEmpty()); + }, + tr("Select one or more media. If you have selected audio or video, make sure " + "that a audio / video stream has been selected.")}); } - ElementEditDialog::~ElementEditDialog() { - delete m_ui; + delete m_ui; } - void ElementEditDialog::retranslate() { - translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Criterium Element")); + translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Criterium Element")); } - -bool ElementEditDialog::init(int elementId, - int criteriumId, - int exerciseId, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - LtsSession::LtsSession *session) +bool ElementEditDialog::init( + int elementId, int criteriumId, int exerciseId, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + LtsSession::LtsSession* session) { - DEBUG_LOG(m_logger) << "ElementEditDialog::init"; - m_elementId = elementId; - m_criteriumId = criteriumId; - m_exerciseId = exerciseId; - m_dtc = dtc; - m_ftc = ftc; - m_exmDtc = exmDtc; - m_avmDataIfc = avmDataIfc; - m_fltParticipantIfc = fltParticipantIfc; - m_fltAesIfc = fltAesIfc; - m_fltBuildingComponentIfc = fltBuildingComponentIfc; - m_session = session; + DEBUG_LOG(m_logger) << "ElementEditDialog::init"; + m_elementId = elementId; + m_criteriumId = criteriumId; + m_exerciseId = exerciseId; + m_dtc = dtc; + m_ftc = ftc; + m_exmDtc = exmDtc; + m_avmDataIfc = avmDataIfc; + m_fltParticipantIfc = fltParticipantIfc; + m_fltAesIfc = fltAesIfc; + m_fltBuildingComponentIfc = fltBuildingComponentIfc; + m_session = session; - for (int i = 1; i <= 10; ++i) - m_ui->cbxRating->addItem(QString::number(i), i); + for (int i = 1; i <= 10; ++i) + m_ui->cbxRating->addItem(QString::number(i), i); - fillPhasesComboBox(); + fillPhasesComboBox(); - if (m_elementId > 0) - { - Evaluations::EvaluationElement eval = m_dtc->evaluationElement(m_elementId); - m_ui->cbxRating->setCurrentIndex(m_ui->cbxRating->findData(eval.rating())); - m_ui->teDesc->setText(QString::fromStdString(eval.note())); - m_ui->lblStartTime->setText(DTG::toStringMSec(eval.timestamp())); - ERROR_LOG(m_logger) << "set start time label to " << m_ui->lblStartTime->text(); - m_startTime = eval.timestamp(); + if (m_elementId > 0) + { + Evaluations::EvaluationElement eval = m_dtc->evaluationElement(m_elementId); + m_ui->cbxRating->setCurrentIndex(m_ui->cbxRating->findData(eval.rating())); + m_ui->teDesc->setText(QString::fromStdString(eval.note())); + m_ui->lblStartTime->setText(DTG::toStringMSec(eval.timestamp())); + ERROR_LOG(m_logger) << "set start time label to " << m_ui->lblStartTime->text(); + m_startTime = eval.timestamp(); - m_ui->cbSituation->setChecked(eval.situation()); - m_ui->cbVideo->setChecked(eval.video()); - m_ui->cbAudio->setChecked(eval.audio()); + m_ui->cbSituation->setChecked(eval.situation()); + m_ui->cbVideo->setChecked(eval.video()); + m_ui->cbAudio->setChecked(eval.audio()); - m_ui->cbxPhase->setCurrentIndex(m_ui->cbxPhase->findData(eval.phaseId())); - } + m_ui->cbxPhase->setCurrentIndex(m_ui->cbxPhase->findData(eval.phaseId())); + } - if (m_avmDataIfc && m_avmDataIfc->hasAvsSession()) - { - onAudioClicked(); - onVideoClicked(); - } - else - { - - - m_ui->cbxVideoChannel->setEnabled(false); - m_ui->cbxRadioCircuit->setEnabled(false); - } - - if (m_avmDataIfc && m_avmDataIfc->hasAvsSession()) - { - m_videoStreams = m_avmDataIfc->avaState()->currentLiveVideoStreams(); - - if ( m_videoStreams.size() > 0 ) - m_ui->cbVideo->setEnabled( true ); + if (m_avmDataIfc && m_avmDataIfc->hasAvsSession()) + { + onAudioClicked(); + onVideoClicked(); + } else - m_ui->cbVideo->setEnabled( false ); + { - m_audioStreams = m_avmDataIfc->avaState()->getRtProfile(); - - if ( m_audioStreams.size() > 0 ) - m_ui->cbAudio->setEnabled( true ); - else - m_ui->cbAudio->setEnabled( false ); - } - - return true; -} - - -void ElementEditDialog::onReturnPressed() -{ + m_ui->cbxVideoChannel->setEnabled(false); + m_ui->cbxRadioCircuit->setEnabled(false); + } + if (m_avmDataIfc && m_avmDataIfc->hasAvsSession()) + { + m_videoStreams = m_avmDataIfc->avaState()->currentLiveVideoStreams(); + if (m_videoStreams.size() > 0) + m_ui->cbVideo->setEnabled(true); + else + m_ui->cbVideo->setEnabled(false); + + m_audioStreams = m_avmDataIfc->avaState()->getRtProfile(); + + if (m_audioStreams.size() > 0) + m_ui->cbAudio->setEnabled(true); + else + m_ui->cbAudio->setEnabled(false); + } + + return true; } +void ElementEditDialog::onReturnPressed() {} bool ElementEditDialog::apply() { - - EvlElementModifyRequest req; - req.id(m_elementId); - req.criteriumId(m_criteriumId); - req.rating(m_ui->cbxRating->currentData().toInt()); - req.note(m_ui->teDesc->toPlainText().toStdString()); - req.timestamp(m_startTime); - req.duration((QDateTime::currentMSecsSinceEpoch() - m_startTime) / 1000); - req.phaseId(m_ui->cbxPhase->currentData().toInt()); - QJsonObject obj; - if (m_ui->cbSituation->isChecked()) - { - QJsonObject root; + EvlElementModifyRequest req; + req.id(m_elementId); + req.criteriumId(m_criteriumId); + req.rating(m_ui->cbxRating->currentData().toInt()); + req.note(m_ui->teDesc->toPlainText().toStdString()); + req.timestamp(m_startTime); + req.duration((QDateTime::currentMSecsSinceEpoch() - m_startTime) / 1000); + req.phaseId(m_ui->cbxPhase->currentData().toInt()); - std::shared_ptr sitMapIfc; - if (m_session->getForeignGuiInterface(sitMapIfc)) - root[QStringLiteral("settings")] = sitMapIfc->operatorMapSettings(); - else - ERROR_LOG(m_logger) << "sit map ifc not available, can't save map settings :("; + QJsonObject obj; + if (m_ui->cbSituation->isChecked()) + { + QJsonObject root; - root[QStringLiteral("filters")] = getFilterSettings(); + std::shared_ptr sitMapIfc; + if (m_session->getForeignGuiInterface(sitMapIfc)) + root[QStringLiteral("settings")] = sitMapIfc->operatorMapSettings(); + else + ERROR_LOG(m_logger) << "sit map ifc not available, can't save map settings :("; - req.situationContent().set(QJsonDocument(root).toJson().constData()); - } + root[QStringLiteral("filters")] = getFilterSettings(); - if (m_ui->cbVideo->isChecked() && m_ui->cbxVideoChannel->currentData().isValid()) - { - obj[QStringLiteral("actualStream")] = QJsonValue(m_ui->cbxVideoChannel->currentData().toString()); - obj[QStringLiteral("allStreams")] = QJsonValue(QString(m_videoStreams.join(QStringLiteral(", ")))); - req.videoContent().set(QJsonDocument(obj).toJson().constData()); - } + req.situationContent().set(QJsonDocument(root).toJson().constData()); + } - if (m_ui->cbAudio->isChecked() && !m_ui->cbxRadioCircuit->currentText().isNull()) - { - obj[QStringLiteral("actualStream")] = QJsonValue(m_ui->cbxRadioCircuit->currentText()); - obj[QStringLiteral("allStreams")] = QJsonValue(QString(m_audioStreams.join(QStringLiteral(", ")))); - req.audioContent().set(QJsonDocument(obj).toJson().constData()); - } + if (m_ui->cbVideo->isChecked() && m_ui->cbxVideoChannel->currentData().isValid()) + { + obj[QStringLiteral("actualStream")] = QJsonValue(m_ui->cbxVideoChannel->currentData().toString()); + obj[QStringLiteral("allStreams")] = QJsonValue(QString(m_videoStreams.join(QStringLiteral(", ")))); + req.videoContent().set(QJsonDocument(obj).toJson().constData()); + } - return m_requestHelper->startSingleRequest([this, req]() - { - return m_ftc->evlElementModifyRequest(req, this); - }); + if (m_ui->cbAudio->isChecked() && !m_ui->cbxRadioCircuit->currentText().isNull()) + { + obj[QStringLiteral("actualStream")] = QJsonValue(m_ui->cbxRadioCircuit->currentText()); + obj[QStringLiteral("allStreams")] = QJsonValue(QString(m_audioStreams.join(QStringLiteral(", ")))); + req.audioContent().set(QJsonDocument(obj).toJson().constData()); + } + + return m_requestHelper->startSingleRequest([this, req]() { return m_ftc->evlElementModifyRequest(req, this); }); } - void ElementEditDialog::fillPhasesComboBox() { - DEBUG_LOG(m_logger) << "fillPhasesComboBox"; - QSignalBlocker blocker(m_ui->cbxPhase); - m_ui->cbxPhase->clear(); - m_ui->cbxPhase->addItem(tr(""), 0); + DEBUG_LOG(m_logger) << "fillPhasesComboBox"; + QSignalBlocker blocker(m_ui->cbxPhase); + m_ui->cbxPhase->clear(); + m_ui->cbxPhase->addItem(tr(""), 0); - auto cb = [this] (const ExerciseManagement::ExercisePhase &ph) - { - if (ph.exerciseId() == m_exerciseId) - m_ui->cbxPhase->addItem(QString::fromStdString(ph.name()), ph.id()); - }; - m_exmDtc->exercisePhases(cb); + auto cb = [this](const ExerciseManagement::ExercisePhase& ph) { + if (ph.exerciseId() == m_exerciseId) + m_ui->cbxPhase->addItem(QString::fromStdString(ph.name()), ph.id()); + }; + m_exmDtc->exercisePhases(cb); - if (m_session->exerciseData()->phId > 0) - m_ui->cbxPhase->setCurrentIndex(m_ui->cbxPhase->findData(m_session->exerciseData()->phId)); + if (m_session->exerciseData()->phId > 0) + m_ui->cbxPhase->setCurrentIndex(m_ui->cbxPhase->findData(m_session->exerciseData()->phId)); } - void ElementEditDialog::onCheckBoxClicked() { - INFO_LOG(m_logger) << "onCheckBoxClicked"; - if (m_startTime > 0) - return; + INFO_LOG(m_logger) << "onCheckBoxClicked"; + if (m_startTime > 0) + return; - m_startTime = QDateTime::currentMSecsSinceEpoch(); - m_ui->lblStartTime->setText(DTG::toStringMSec(m_startTime)); + m_startTime = QDateTime::currentMSecsSinceEpoch(); + m_ui->lblStartTime->setText(DTG::toStringMSec(m_startTime)); } - void ElementEditDialog::onAudioClicked() { - Q_ASSERT(m_avmDataIfc && m_avmDataIfc->hasAvsSession()); - if (!m_avmDataIfc) - return; + Q_ASSERT(m_avmDataIfc && m_avmDataIfc->hasAvsSession()); + if (!m_avmDataIfc) + return; - m_audioStreams = m_avmDataIfc->avaState()->getRtProfile(); + m_audioStreams = m_avmDataIfc->avaState()->getRtProfile(); - QString currentText; - if (m_ui->cbxRadioCircuit->currentIndex() >= 0) - currentText = m_ui->cbxRadioCircuit->currentText(); + QString currentText; + if (m_ui->cbxRadioCircuit->currentIndex() >= 0) + currentText = m_ui->cbxRadioCircuit->currentText(); - m_ui->cbxRadioCircuit->clear(); + m_ui->cbxRadioCircuit->clear(); - for (const QString &audioChannel : std::as_const(m_audioStreams)) - m_ui->cbxRadioCircuit->addItem(audioChannel); + for (const QString& audioChannel : std::as_const(m_audioStreams)) + m_ui->cbxRadioCircuit->addItem(audioChannel); - m_ui->cbxRadioCircuit->setCurrentIndex(0); + m_ui->cbxRadioCircuit->setCurrentIndex(0); - int idx = m_ui->cbxRadioCircuit->findText(currentText); - if (idx >= 0) - m_ui->cbxRadioCircuit->setCurrentIndex(idx); + int idx = m_ui->cbxRadioCircuit->findText(currentText); + if (idx >= 0) + m_ui->cbxRadioCircuit->setCurrentIndex(idx); - if (m_ui->cbAudio->isChecked() && m_ui->cbxRadioCircuit->count() > 1) - m_ui->cbxRadioCircuit->setEnabled(true); - else - m_ui->cbxRadioCircuit->setEnabled(false); + if (m_ui->cbAudio->isChecked() && m_ui->cbxRadioCircuit->count() > 1) + m_ui->cbxRadioCircuit->setEnabled(true); + else + m_ui->cbxRadioCircuit->setEnabled(false); } - void ElementEditDialog::onVideoClicked() { - Q_ASSERT(m_avmDataIfc && m_avmDataIfc->hasAvsSession()); - if (!m_avmDataIfc) - return; + Q_ASSERT(m_avmDataIfc && m_avmDataIfc->hasAvsSession()); + if (!m_avmDataIfc) + return; - m_videoStreams = m_avmDataIfc->avaState()->currentLiveVideoStreams(); + m_videoStreams = m_avmDataIfc->avaState()->currentLiveVideoStreams(); - QVariant currentStream; - if (m_ui->cbxVideoChannel->currentIndex() >= 0) - currentStream = m_ui->cbxVideoChannel->currentData(); + QVariant currentStream; + if (m_ui->cbxVideoChannel->currentIndex() >= 0) + currentStream = m_ui->cbxVideoChannel->currentData(); - m_ui->cbxVideoChannel->clear(); + m_ui->cbxVideoChannel->clear(); - for (const QString &streamName : std::as_const(m_videoStreams)) - { - QString displayName = m_avmDataIfc->streamNameMapping()->displayName(streamName); - m_ui->cbxVideoChannel->addItem(displayName, streamName); - } - - for (int i = 0; i < m_ui->cbxVideoChannel->count(); ++i) - { - if ( m_ui->cbxVideoChannel->itemData(i).toString() == currentStream) + for (const QString& streamName : std::as_const(m_videoStreams)) { - m_ui->cbxVideoChannel->setCurrentIndex(i); - break; + QString displayName = m_avmDataIfc->streamNameMapping()->displayName(streamName); + m_ui->cbxVideoChannel->addItem(displayName, streamName); } - } - if (m_ui->cbVideo->isChecked() && m_ui->cbxVideoChannel->count() > 1) - m_ui->cbxVideoChannel->setEnabled(true); - else - m_ui->cbxVideoChannel->setEnabled(false); + for (int i = 0; i < m_ui->cbxVideoChannel->count(); ++i) + { + if (m_ui->cbxVideoChannel->itemData(i).toString() == currentStream) + { + m_ui->cbxVideoChannel->setCurrentIndex(i); + break; + } + } + + if (m_ui->cbVideo->isChecked() && m_ui->cbxVideoChannel->count() > 1) + m_ui->cbxVideoChannel->setEnabled(true); + else + m_ui->cbxVideoChannel->setEnabled(false); } - QJsonObject ElementEditDialog::getFilterSettings() { - const int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - QJsonObject jsonObj; + const int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + QJsonObject jsonObj; - { - - std::shared_ptr aesDisplayFilter = - m_fltAesIfc->aesFilterForOperator(operatorId, QString()); - jsonObj[QStringLiteral("AesFilterJson")] = aesDisplayFilter->filterToJson(); - } + { - { - - std::shared_ptr symbolAppearanceSettings = - m_fltParticipantIfc->symbolAppearanceForOperator(operatorId, QString()); - jsonObj[QStringLiteral("SymbolAppearanceJson")] = symbolAppearanceSettings->settingsToJson(); - } + std::shared_ptr aesDisplayFilter = + m_fltAesIfc->aesFilterForOperator(operatorId, QString()); + jsonObj[QStringLiteral("AesFilterJson")] = aesDisplayFilter->filterToJson(); + } - - if (m_fltBuildingComponentIfc) - { - - std::shared_ptr buildingComponentSettings = - m_fltBuildingComponentIfc->buildingComponentSettingsForOperator(operatorId, QString()); - jsonObj[QStringLiteral("BuildingComponentSettingsJson")] = buildingComponentSettings->bldCmpSettingsToJson(); - } + { + std::shared_ptr symbolAppearanceSettings = + m_fltParticipantIfc->symbolAppearanceForOperator(operatorId, QString()); + jsonObj[QStringLiteral("SymbolAppearanceJson")] = symbolAppearanceSettings->settingsToJson(); + } + if (m_fltBuildingComponentIfc) + { - return jsonObj; + std::shared_ptr buildingComponentSettings = + m_fltBuildingComponentIfc->buildingComponentSettingsForOperator(operatorId, QString()); + jsonObj[QStringLiteral("BuildingComponentSettingsJson")] = buildingComponentSettings->bldCmpSettingsToJson(); + } + + return jsonObj; } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.h old mode 100755 new mode 100644 index 5f213072a..062ac0cb8 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_edit_element_dialog.h @@ -1,21 +1,19 @@ - #pragma once -#include +#include #include #include -#include +#include #include -#include #include #include #include +#include #include #include - namespace LtsWidgets { class UiRequirementList; @@ -34,63 +32,67 @@ class LtsSession; namespace Evaluations { -class ElementEditDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::EvlElementModifyReplyHandler - , protected Interface::Ftc::EvlElementRemoveReplyHandler +class ElementEditDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::EvlElementModifyReplyHandler, + protected Interface::Ftc::EvlElementRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ElementEditDialog(QWidget *parent = nullptr); - ~ElementEditDialog(); + public: + explicit ElementEditDialog(QWidget* parent = nullptr); + ~ElementEditDialog(); - bool init(int elementId, - int criteriumId, - int exerciseId, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - LtsSession::LtsSession *session); + bool init(int elementId, int criteriumId, int exerciseId, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + LtsSession::LtsSession* session); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onEvlElementModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onEvlElementRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onEvlElementModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - QJsonObject getFilterSettings(); + void onEvlElementRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void onReturnPressed(); - void onCheckBoxClicked(); - void onAudioClicked(); - void onVideoClicked(); + QJsonObject getFilterSettings(); -private: - void retranslate() override; - bool apply() override; - void fillPhasesComboBox(); + private slots: + void onReturnPressed(); + void onCheckBoxClicked(); + void onAudioClicked(); + void onVideoClicked(); - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_exmDtc; - std::shared_ptr m_avmDataIfc; - std::shared_ptr m_fltParticipantIfc; - std::shared_ptr m_fltAesIfc; - std::shared_ptr m_fltBuildingComponentIfc; - std::shared_ptr m_fltDtc; - LtsSession::LtsSession *m_session{nullptr}; - int m_elementId{0}; - int m_criteriumId{-1}; - int m_exerciseId{-1}; - qint64 m_startTime { 0 }; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - Ui::ElementEditDialog *m_ui{nullptr}; - QStringList m_audioStreams; - QStringList m_videoStreams; + private: + void retranslate() override; + bool apply() override; + void fillPhasesComboBox(); + + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_exmDtc; + std::shared_ptr m_avmDataIfc; + std::shared_ptr m_fltParticipantIfc; + std::shared_ptr m_fltAesIfc; + std::shared_ptr m_fltBuildingComponentIfc; + std::shared_ptr m_fltDtc; + LtsSession::LtsSession* m_session{nullptr}; + int m_elementId{0}; + int m_criteriumId{-1}; + int m_exerciseId{-1}; + qint64 m_startTime{0}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + Ui::ElementEditDialog* m_ui{nullptr}; + QStringList m_audioStreams; + QStringList m_videoStreams; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.cpp old mode 100755 new mode 100644 index f5982c77c..46727eb55 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.cpp @@ -1,157 +1,151 @@ - #include "evl_element_dialog.h" -#include "ui_evl_element_dialog.h" -#include "evl_element_model.h" + #include "evl_edit_element_dialog.h" +#include "evl_element_model.h" +#include "ui_evl_element_dialog.h" -#include #include - +#include namespace Evaluations { -ElementDialog::ElementDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_model(new ElementDialogModel(this)) - , m_ui(new Ui::ElementDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ElementDialog::ElementDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_model(new ElementDialogModel(this)), + m_ui(new Ui::ElementDialog), m_requestHelper(new LtsUtils::RequestHelper(this)) { - DEBUG_LOG(m_logger) << "ElementDialog ctor"; - m_ui->setupUi(this); + DEBUG_LOG(m_logger) << "ElementDialog ctor"; + m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-Own_Evaluation_Criteria")); + setOnlineHelpFilename(QStringLiteral("Situation-Own_Evaluation_Criteria")); } ElementDialog::~ElementDialog() { - delete m_ui; + delete m_ui; } void ElementDialog::retranslate() { - translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Evaluation Elements")); + translate(m_ui, m_dtc->evaluationCriterium(m_criteriumId), tr("Evaluation Elements")); } void ElementDialog::enaDisa() { - int selected = m_ui->widget->selectedRows().size(); - - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (selected == 1)); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (selected > 0)); + int selected = m_ui->widget->selectedRows().size(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Add, true); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, (selected == 1)); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, (selected > 0)); } void ElementDialog::slotAdd() { - DEBUG_LOG(m_logger) << "ElementDialog::slotAdd"; + DEBUG_LOG(m_logger) << "ElementDialog::slotAdd"; - addElementEditDialog(); + addElementEditDialog(); } void ElementDialog::slotEdit() { - DEBUG_LOG(m_logger) << "ElementDialog::slotEdit"; + DEBUG_LOG(m_logger) << "ElementDialog::slotEdit"; - addElementEditDialog(m_model->getRowData(m_ui->widget->currentIndex().row()).id() ); + addElementEditDialog(m_model->getRowData(m_ui->widget->currentIndex().row()).id()); } - void ElementDialog::addElementEditDialog(int elementId) { - addDialog(LtsWidgets::initDialog(new ElementEditDialog(), - elementId, m_criteriumId, m_exerciseId, m_dtc, m_ftc, m_exmDtc, m_avmDataIfc, m_fltParticipantIfc, m_fltAesIfc, m_fltBuildingComponentIfc, m_session), - m_menuGroup, QStringLiteral("ElementEditDialog%1").arg(elementId), LtsWidgets::LayoutArea::eDialogTab); + addDialog(LtsWidgets::initDialog(new ElementEditDialog(), elementId, m_criteriumId, m_exerciseId, m_dtc, m_ftc, + m_exmDtc, m_avmDataIfc, m_fltParticipantIfc, m_fltAesIfc, + m_fltBuildingComponentIfc, m_session), + m_menuGroup, QStringLiteral("ElementEditDialog%1").arg(elementId), LtsWidgets::LayoutArea::eDialogTab); } void ElementDialog::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); -} + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); +} void ElementDialog::slotRemove() { - DEBUG_LOG(m_logger) << "ElementDialog::slotRemove"; - QModelIndex selIndex = m_ui->widget->currentIndex(); - if (!selIndex.isValid()) - return; + DEBUG_LOG(m_logger) << "ElementDialog::slotRemove"; + QModelIndex selIndex = m_ui->widget->currentIndex(); + if (!selIndex.isValid()) + return; - m_requestHelper->startSingleRequest([this]() - { - DEBUG_LOG(m_logger) << "Removing element id = " << m_model->getRowData(m_ui->widget->currentIndex().row()).id(); - return m_ftc->evlElementRemoveRequest(EvlElementRemoveRequest(m_model->getRowData(m_ui->widget->currentIndex().row()).id(), m_criteriumId), this); - }); + m_requestHelper->startSingleRequest([this]() { + DEBUG_LOG(m_logger) << "Removing element id = " << m_model->getRowData(m_ui->widget->currentIndex().row()).id(); + return m_ftc->evlElementRemoveRequest( + EvlElementRemoveRequest(m_model->getRowData(m_ui->widget->currentIndex().row()).id(), m_criteriumId), this); + }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to remove criterium"; + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to remove criterium"; } QString ElementDialog::dialogIdentifier() { - return QStringLiteral("Evl.EditElements"); + return QStringLiteral("Evl.EditElements"); } -bool ElementDialog::init(int criteriumId, - int exerciseId, - const QString &menuGroup, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - LtsSession::LtsSession *session) +bool ElementDialog::init( + int criteriumId, int exerciseId, const QString& menuGroup, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + LtsSession::LtsSession* session) { - DEBUG_LOG(m_logger) << "ElementDialog::init"; - m_criteriumId = criteriumId; - m_exerciseId = exerciseId; - m_dtc = dtc; - m_ftc = ftc; - m_exmDtc = exmDtc; - m_avmDataIfc = avmDataIfc; - m_fltParticipantIfc = fltParticipantIfc; - m_fltAesIfc = fltAesIfc; - m_fltBuildingComponentIfc = fltBuildingComponentIfc; - m_session = session; - m_menuGroup = menuGroup; + DEBUG_LOG(m_logger) << "ElementDialog::init"; + m_criteriumId = criteriumId; + m_exerciseId = exerciseId; + m_dtc = dtc; + m_ftc = ftc; + m_exmDtc = exmDtc; + m_avmDataIfc = avmDataIfc; + m_fltParticipantIfc = fltParticipantIfc; + m_fltAesIfc = fltAesIfc; + m_fltBuildingComponentIfc = fltBuildingComponentIfc; + m_session = session; + m_menuGroup = menuGroup; - m_model = new ElementDialogModel(this); + m_model = new ElementDialogModel(this); - m_model->initModel(dtc, exmDtc, avmDataIfc, criteriumId); + m_model->initModel(dtc, exmDtc, avmDataIfc, criteriumId); - m_proxyModel = new ElementDialogProxyModel(this); - m_proxyModel->setSourceModel(m_model); - m_proxyModel->setCriteriumId(m_criteriumId); - m_ui->widget->setModel(m_proxyModel); + m_proxyModel = new ElementDialogProxyModel(this); + m_proxyModel->setSourceModel(m_model); + m_proxyModel->setCriteriumId(m_criteriumId); + m_ui->widget->setModel(m_proxyModel); #ifndef LTS_DEBUG - m_ui->widget->hideColumn(ElementDialogModel::Id); + m_ui->widget->hideColumn(ElementDialogModel::Id); #endif - auto cb = [this](const Evaluations::EvaluationElement &e) - { - DEBUG_LOG(m_logger) << "Element: id = " << e.id() << ", medium = " << e.rating(); - }; - m_dtc->evaluationElements(cb); + auto cb = [this](const Evaluations::EvaluationElement& e) { + DEBUG_LOG(m_logger) << "Element: id = " << e.id() << ", medium = " << e.rating(); + }; + m_dtc->evaluationElements(cb); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ElementDialog::enaDisa, Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ElementDialog::enaDisa, + Qt::UniqueConnection); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ElementDialog::slotAdd, Qt::UniqueConnection); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ElementDialog::slotEdit, Qt::UniqueConnection); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ElementDialog::slotRemove, + Qt::UniqueConnection); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ElementDialog::slotAdd, Qt::UniqueConnection); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ElementDialog::slotEdit, Qt::UniqueConnection); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ElementDialog::slotRemove, Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &ElementDialog::slotEdit, + Qt::UniqueConnection); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &ElementDialog::slotEdit, + Qt::UniqueConnection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, &ElementDialog::slotEdit, Qt::UniqueConnection); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalEnterPressed, this, &ElementDialog::slotEdit, Qt::UniqueConnection); + enaDisa(); - enaDisa(); - - return true; + return true; } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.h old mode 100755 new mode 100644 index ad1c3866d..7a6a12917 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_dialog.h @@ -1,18 +1,17 @@ - #pragma once #include #include #include #include -#include -#include #include -#include +#include +#include #include #include +#include namespace Ui { @@ -30,61 +29,65 @@ namespace Evaluations class ElementDialogModel; class ElementDialogProxyModel; -class ElementDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::EvlElementModifyReplyHandler - , protected Interface::Ftc::EvlElementRemoveReplyHandler +class ElementDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::EvlElementModifyReplyHandler, + protected Interface::Ftc::EvlElementRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ElementDialog(QWidget *parent = nullptr); - ~ElementDialog(); + public: + explicit ElementDialog(QWidget* parent = nullptr); + ~ElementDialog(); - bool init(int criteriumId, - int exerciseId, const QString &menuGroup, - const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - const std::shared_ptr &fltParticipantIfc, - const std::shared_ptr &fltAesIfc, - const std::shared_ptr &fltBuildingComponentIfc, - LtsSession::LtsSession *session); + bool init(int criteriumId, int exerciseId, const QString& menuGroup, const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, + const std::shared_ptr& fltParticipantIfc, + const std::shared_ptr& fltAesIfc, + const std::shared_ptr& fltBuildingComponentIfc, + LtsSession::LtsSession* session); - static QString dialogIdentifier(); + static QString dialogIdentifier(); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onEvlElementModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onEvlElementRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onEvlElementModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - void retranslate() override; - void addElementEditDialog(int elementId = 0 ); - void tableColumnOrganiserSetting() override; + void onEvlElementRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - ElementDialogModel *m_model{nullptr}; - ElementDialogProxyModel *m_proxyModel{nullptr}; - Ui::ElementDialog *m_ui{nullptr}; - int m_criteriumId{-1}; - int m_exerciseId{-1}; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_exmDtc; - std::shared_ptr m_avmDataIfc; - std::shared_ptr m_fltParticipantIfc; - std::shared_ptr m_fltAesIfc; - std::shared_ptr m_fltBuildingComponentIfc; - LtsSession::LtsSession *m_session{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - QString m_menuGroup; -private slots: - void slotAdd(); - void slotEdit(); - void slotRemove(); - void enaDisa(); + private: + void retranslate() override; + void addElementEditDialog(int elementId = 0); + void tableColumnOrganiserSetting() override; + ElementDialogModel* m_model{nullptr}; + ElementDialogProxyModel* m_proxyModel{nullptr}; + Ui::ElementDialog* m_ui{nullptr}; + int m_criteriumId{-1}; + int m_exerciseId{-1}; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_exmDtc; + std::shared_ptr m_avmDataIfc; + std::shared_ptr m_fltParticipantIfc; + std::shared_ptr m_fltAesIfc; + std::shared_ptr m_fltBuildingComponentIfc; + LtsSession::LtsSession* m_session{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + QString m_menuGroup; + private slots: + void slotAdd(); + void slotEdit(); + void slotRemove(); + void enaDisa(); }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.cpp old mode 100755 new mode 100644 index f5048daef..3251d7b01 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.cpp @@ -1,160 +1,145 @@ - #include "evl_element_model.h" -#include -#include -#include #include +#include +#include +#include namespace Evaluations { -ElementDialogModel::ElementDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +ElementDialogModel::ElementDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Situation"), tr("Video"), tr("Audio"), tr("Start Time"), tr("Duration"), tr("Rating"), + tr("Radio Circuit"), tr("Video Channel"), tr("Note"), tr("Phase")}, + parent) { - tr("Id"), - tr("Situation"), - tr("Video"), - tr("Audio"), - tr("Start Time"), - tr("Duration"), - tr("Rating"), - tr("Radio Circuit"), - tr("Video Channel"), - tr("Note"), - tr("Phase") -}, -parent) -{} +} -bool ElementDialogModel::initModel(const std::shared_ptr &dtc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, +bool ElementDialogModel::initModel(const std::shared_ptr& dtc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, int criteriumId) { - m_exmDtc = exmDtc; - m_avmDataIfc = avmDataIfc; + m_exmDtc = exmDtc; + m_avmDataIfc = avmDataIfc; - connect(dtc.get(), &Interface::Dtc::evaluationElementChanged, - this, &ElementDialogModel::onDataChanged); + connect(dtc.get(), &Interface::Dtc::evaluationElementChanged, this, &ElementDialogModel::onDataChanged); - auto cb = [this, criteriumId](const EvaluationElement &e) - { - if (e.criteriumId() == criteriumId) - insertRow(e); - }; - dtc->evaluationElements(cb); + auto cb = [this, criteriumId](const EvaluationElement& e) { + if (e.criteriumId() == criteriumId) + insertRow(e); + }; + dtc->evaluationElements(cb); - INFO_LOG(m_logger) << "initModel - #EvalElements: " << m_vecData.size(); + INFO_LOG(m_logger) << "initModel - #EvalElements: " << m_vecData.size(); - return true; + return true; } - -QVariant ElementDialogModel::data(const QModelIndex &index, int role) const +QVariant ElementDialogModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole) || !indexIsValid(index)) + if ((role != Qt::DisplayRole) || !indexIsValid(index)) + return QVariant(); + + const Evaluations::EvaluationElement& eval = m_vecData.at(index.row()); + + switch (index.column()) + { + case Id: + return eval.id(); + case Situation: + return eval.situation() ? tr("Yes") : tr("No"); + case Video: + return eval.video() ? tr("Yes") : tr("No"); + case Audio: + return eval.audio() ? tr("Yes") : tr("No"); + case Timestamp: + return QDateTime::fromMSecsSinceEpoch(eval.timestamp()); + case Duration: + return eval.duration(); + case Rating: + return eval.rating(); + case RadioCircuit: + if (eval.audioContent().is_set()) + { + LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(eval.audioContent().get()); + return jsonObj.value("actualStream"); + } + else + return QString(); + case VideoChannel: + if (eval.videoContent().is_set()) + { + LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(eval.videoContent().get()); + QString streamName = jsonObj.value("actualStream"); + QString displayName = m_avmDataIfc->streamNameMapping()->displayName(streamName); + return displayName; + } + else + return QString(); + case Note: + return QString::fromStdString(eval.note()); + case Phase: + return QString::fromStdString(m_exmDtc->exercisePhase(eval.phaseId()).name()); + } + return QVariant(); - - const Evaluations::EvaluationElement &eval = m_vecData.at(index.row()); - - switch (index.column()) - { - case Id: - return eval.id(); - case Situation: - return eval.situation() ? tr("Yes") : tr("No"); - case Video: - return eval.video() ? tr("Yes") : tr("No"); - case Audio: - return eval.audio() ? tr("Yes") : tr("No"); - case Timestamp: - return QDateTime::fromMSecsSinceEpoch(eval.timestamp()); - case Duration: - return eval.duration(); - case Rating: - return eval.rating(); - case RadioCircuit: - if (eval.audioContent().is_set()) - { - LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(eval.audioContent().get()); - return jsonObj.value("actualStream"); - } - else - return QString(); - case VideoChannel: - if (eval.videoContent().is_set()) - { - LtsUtils::JsonObject jsonObj = LtsUtils::JsonObject::fromJson(eval.videoContent().get()); - QString streamName = jsonObj.value("actualStream"); - QString displayName = m_avmDataIfc->streamNameMapping()->displayName(streamName); - return displayName; - } - else - return QString(); - case Note: - return QString::fromStdString(eval.note()); - case Phase: - return QString::fromStdString(m_exmDtc->exercisePhase(eval.phaseId()).name()); - } - - return QVariant(); } -void ElementDialogProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void ElementDialogProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } -bool ElementDialogProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +bool ElementDialogProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case ElementDialogModel::Timestamp: + return dataLeft.timestamp() < dataRight.timestamp(); + case ElementDialogModel::Id: + case ElementDialogModel::Situation: + case ElementDialogModel::Video: + case ElementDialogModel::Audio: + + case ElementDialogModel::Duration: + case ElementDialogModel::Rating: + case ElementDialogModel::RadioCircuit: + case ElementDialogModel::VideoChannel: + case ElementDialogModel::Note: + case ElementDialogModel::Phase: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case ElementDialogModel::Timestamp: - return dataLeft.timestamp() < dataRight.timestamp(); - case ElementDialogModel::Id: - case ElementDialogModel::Situation: - case ElementDialogModel::Video: - case ElementDialogModel::Audio: - - case ElementDialogModel::Duration: - case ElementDialogModel::Rating: - case ElementDialogModel::RadioCircuit: - case ElementDialogModel::VideoChannel: - case ElementDialogModel::Note: - case ElementDialogModel::Phase: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } void ElementDialogProxyModel::setCriteriumId(int criteriumId) { - if (m_criteriumId == criteriumId) - return; - m_criteriumId = criteriumId; - invalidateFilter(); + if (m_criteriumId == criteriumId) + return; + m_criteriumId = criteriumId; + invalidateFilter(); } -bool ElementDialogProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool ElementDialogProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - if (m_criteriumId < 0 || !m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->m_vecData.size()) - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + if (m_criteriumId < 0 || !m_sourceModel || source_parent.isValid() || source_row < 0 || + source_row >= m_sourceModel->m_vecData.size()) + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - const auto &data = m_sourceModel->m_vecData.at(source_row); - if (data.criteriumId() != m_criteriumId) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + const auto& data = m_sourceModel->m_vecData.at(source_row); + if (data.criteriumId() != m_criteriumId) + return false; + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.h old mode 100755 new mode 100644 index 5e3c1a5d9..148d465bc --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_element_model.h @@ -1,69 +1,66 @@ - #pragma once #include #include #include -#include - #include #include +#include namespace Evaluations { class ElementDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Id = 0, - Situation, - Video, - Audio, - Timestamp, - Duration, - Rating, - RadioCircuit, - VideoChannel, - Note, - Phase - }; + public: + enum Columns { + Id = 0, + Situation, + Video, + Audio, + Timestamp, + Duration, + Rating, + RadioCircuit, + VideoChannel, + Note, + Phase + }; - explicit ElementDialogModel(QObject *parent = nullptr); - ~ElementDialogModel() = default; + explicit ElementDialogModel(QObject* parent = nullptr); + ~ElementDialogModel() = default; - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &exmDtc, - const std::shared_ptr &avmDataIfc, - int criteriumId); + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& exmDtc, + const std::shared_ptr& avmDataIfc, int criteriumId); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; -private: - -NGL::INGLLogger &m_logger; - std::shared_ptr m_avmDataIfc; - std::shared_ptr m_exmDtc; - friend class ElementDialogProxyModel; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_avmDataIfc; + std::shared_ptr m_exmDtc; + friend class ElementDialogProxyModel; }; class ElementDialogProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; - void setCriteriumId(int criteriumId); -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; -private: - ElementDialogModel *m_sourceModel{nullptr}; - int m_criteriumId{-1}; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + void setCriteriumId(int criteriumId); + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + + private: + ElementDialogModel* m_sourceModel{nullptr}; + int m_criteriumId{-1}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.cpp old mode 100755 new mode 100644 index 215205e98..e990ff6ac --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.cpp @@ -1,6 +1,5 @@ - #include "evl_model.h" #include @@ -8,78 +7,69 @@ namespace Evaluations { -CriteriumDialogModel::CriteriumDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +CriteriumDialogModel::CriteriumDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel({tr("Id"), tr("Name"), tr("Description"), tr("Operator")}, + parent) { - tr("Id"), - tr("Name"), - tr("Description"), - tr("Operator") -}, -parent) -{} - - -bool CriteriumDialogModel::initModel(const std::shared_ptr &dtc, - const std::shared_ptr &opmDtc - ) -{ - m_opmDtc = opmDtc; - connect(dtc.get(), &Interface::Dtc::evaluationCriteriumChanged, - this, &CriteriumDialogModel::onDataChanged); - dtc->evaluationCriteriums([this](const EvaluationCriterium & e) { insertRow(e); }); - - INFO_LOG(m_logger) << "initModel - #EvalCriteria: " << m_vecData.size(); - - return true; } - -QVariant CriteriumDialogModel::data(const QModelIndex &index, int role) const +bool CriteriumDialogModel::initModel(const std::shared_ptr& dtc, + const std::shared_ptr& opmDtc) { - if (role != Qt::DisplayRole || !indexIsValid(index)) + m_opmDtc = opmDtc; + connect(dtc.get(), &Interface::Dtc::evaluationCriteriumChanged, this, &CriteriumDialogModel::onDataChanged); + dtc->evaluationCriteriums([this](const EvaluationCriterium& e) { insertRow(e); }); + + INFO_LOG(m_logger) << "initModel - #EvalCriteria: " << m_vecData.size(); + + return true; +} + +QVariant CriteriumDialogModel::data(const QModelIndex& index, int role) const +{ + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const Evaluations::EvaluationCriterium& eval = m_vecData.at(index.row()); + switch (index.column()) + { + case Id: + return eval.id(); + case Name: + return QString::fromStdString(eval.name()); + case Description: + return QString::fromStdString(eval.description()); + case Operator: + return QString::fromStdString(m_opmDtc->user(eval.operatorId()).name()); + } + return QVariant(); - - const Evaluations::EvaluationCriterium &eval = m_vecData.at(index.row()); - switch (index.column()) - { - case Id: - return eval.id(); - case Name: - return QString::fromStdString(eval.name()); - case Description: - return QString::fromStdString(eval.description()); - case Operator: - return QString::fromStdString(m_opmDtc->user(eval.operatorId()).name()); - } - - return QVariant(); } - void CriteriumFilterModel::setOperatorId(int operatorId) { - if (m_operatorId == operatorId) - return; - m_operatorId = operatorId; - invalidateFilter(); + if (m_operatorId == operatorId) + return; + m_operatorId = operatorId; + invalidateFilter(); } -void CriteriumFilterModel::setSourceModel(QAbstractItemModel *sourceModel) +void CriteriumFilterModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } -bool CriteriumFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool CriteriumFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - if (m_operatorId < 0 || !m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->m_vecData.size()) + if (m_operatorId < 0 || !m_sourceModel || source_parent.isValid() || source_row < 0 || + source_row >= m_sourceModel->m_vecData.size()) + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + + const auto& data = m_sourceModel->m_vecData.at(source_row); + if (data.operatorId() != m_operatorId) + return false; return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - - const auto &data = m_sourceModel->m_vecData.at(source_row); - if (data.operatorId() != m_operatorId) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.h old mode 100755 new mode 100644 index 0d9a94f72..78167d73d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/CriteriumEdit/evl_model.h @@ -1,61 +1,53 @@ - #pragma once #include #include -#include - #include #include +#include namespace Evaluations { class CriteriumDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Id = 0, - Name, - Description, - Operator - }; + public: + enum Columns { Id = 0, Name, Description, Operator }; - explicit CriteriumDialogModel(QObject *parent = nullptr); - ~CriteriumDialogModel() = default; + explicit CriteriumDialogModel(QObject* parent = nullptr); + ~CriteriumDialogModel() = default; - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &opmDtc); + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& opmDtc); - QVariant data(const QModelIndex &, int) const override final; + QVariant data(const QModelIndex&, int) const override final; -protected: + protected: + NGL::INGLLogger& m_logger; - -NGL::INGLLogger &m_logger; -private: - std::shared_ptr m_opmDtc; - friend class CriteriumFilterModel; + private: + std::shared_ptr m_opmDtc; + friend class CriteriumFilterModel; }; class CriteriumFilterModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setOperatorId(int operatorId); - void setSourceModel(QAbstractItemModel *sourceModel) override; + void setOperatorId(int operatorId); + void setSourceModel(QAbstractItemModel* sourceModel) override; -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; -private: - CriteriumDialogModel *m_sourceModel{nullptr}; - int m_operatorId{-1}; + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + + private: + CriteriumDialogModel* m_sourceModel{nullptr}; + int m_operatorId{-1}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.cpp old mode 100755 new mode 100644 index 5ca5a39ca..e41105e52 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.cpp @@ -1,129 +1,116 @@ - - #include "san_nine_liner_dialog.h" -#include "ui_san_nine_liner_dialog.h" #include "san_nine_liner_dialog_model.h" #include "san_nine_liner_edit_dialog.h" +#include "ui_san_nine_liner_dialog.h" -#include #include #include - +#include namespace Evaluations { - - -SanNineLinerDialog::SanNineLinerDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::SanNineLinerDialog) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +SanNineLinerDialog::SanNineLinerDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_ui(new Ui::SanNineLinerDialog), + m_menuGroup(menuGroup), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-SanNineLiner")); + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Situation-SanNineLiner")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &SanNineLinerDialog::onAddSanNineLiner); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SanNineLinerDialog::onEditSanNineLiner); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &SanNineLinerDialog::onRemoveSanNineLiner); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &SanNineLinerDialog::onAddSanNineLiner); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &SanNineLinerDialog::onEditSanNineLiner); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &SanNineLinerDialog::onRemoveSanNineLiner); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &SanNineLinerDialog::onEditSanNineLiner); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &SanNineLinerDialog::onEditSanNineLiner); } SanNineLinerDialog::~SanNineLinerDialog() { - delete m_ui; + delete m_ui; } void SanNineLinerDialog::retranslate() { - translate(m_ui, tr("SanNineLiner")); + translate(m_ui, tr("SanNineLiner")); } void SanNineLinerDialog::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } -bool SanNineLinerDialog::init(LtsSession::LtsSessionDataDds *session) +bool SanNineLinerDialog::init(LtsSession::LtsSessionDataDds* session) { - m_session = session; - std::shared_ptr dtc; + m_session = session; + std::shared_ptr dtc; - if (!m_session->getDtc(dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; + if (!m_session->getDtc(dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; - m_model = new SanNineLinerDialogModel(this); - m_model->initModel(dtc); - auto proxy = new SanNineLinerProxyModel(this); - proxy->setSourceModel(m_model); + m_model = new SanNineLinerDialogModel(this); + m_model->initModel(dtc); + auto proxy = new SanNineLinerProxyModel(this); + proxy->setSourceModel(m_model); - m_ui->widget->setModel(proxy); + m_ui->widget->setModel(proxy); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &SanNineLinerDialog::enaDisa); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &SanNineLinerDialog::enaDisa); - enaDisa(); + enaDisa(); - - return true; + return true; } void SanNineLinerDialog::enaDisa() { - QModelIndexList selectedRows = m_ui->widget->selectedRows(); - const int cntSelectedRows = selectedRows.size(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - const QModelIndex curIdx = m_ui->widget->currentIndex(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, curIdx.isValid() && cntSelectedRows == 1); + QModelIndexList selectedRows = m_ui->widget->selectedRows(); + const int cntSelectedRows = selectedRows.size(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + const QModelIndex curIdx = m_ui->widget->currentIndex(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, curIdx.isValid() && cntSelectedRows == 1); } void SanNineLinerDialog::onAddSanNineLiner() { - SanNineLinerEditDialog *dialog = new SanNineLinerEditDialog(this); - dialog->init(m_session, m_menuGroup, 0 ); + SanNineLinerEditDialog* dialog = new SanNineLinerEditDialog(this); + dialog->init(m_session, m_menuGroup, 0); - addDialog(dialog, m_menuGroup, QStringLiteral("New SanNineLiner")); + addDialog(dialog, m_menuGroup, QStringLiteral("New SanNineLiner")); } void SanNineLinerDialog::onRemoveSanNineLiner() { - const QModelIndex curIdx = m_ui->widget->currentIndex(); - if (!curIdx.isValid()) - return; - const int sanNineLinerId = m_model->getRowData(curIdx.row()).id(); + const QModelIndex curIdx = m_ui->widget->currentIndex(); + if (!curIdx.isValid()) + return; + const int sanNineLinerId = m_model->getRowData(curIdx.row()).id(); - - Core::RemoveElementRequest req(sanNineLinerId); - m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->sanNineLinerRemoveRequest(req, this); - }); + Core::RemoveElementRequest req(sanNineLinerId); + m_requestHelper->startSingleRequest([req, this]() { return m_ftc->sanNineLinerRemoveRequest(req, this); }); } void SanNineLinerDialog::onEditSanNineLiner() { - const QModelIndex idx = m_ui->widget->currentIndex(); - const Evaluations::SanNineLiner san = m_model->getRowData(idx.row()); + const QModelIndex idx = m_ui->widget->currentIndex(); + const Evaluations::SanNineLiner san = m_model->getRowData(idx.row()); - if (san.id() <= 0) - return; - DEBUG_LOG(m_logger) << "current SanNineLinerId: " << san.id(); + if (san.id() <= 0) + return; + DEBUG_LOG(m_logger) << "current SanNineLinerId: " << san.id(); - SanNineLinerEditDialog *dialog = new SanNineLinerEditDialog(this); + SanNineLinerEditDialog* dialog = new SanNineLinerEditDialog(this); - dialog->init(m_session, m_menuGroup, san.id()); - const QString identifier = QStringLiteral("EditSanNineLiner%1").arg(san.id()); + dialog->init(m_session, m_menuGroup, san.id()); + const QString identifier = QStringLiteral("EditSanNineLiner%1").arg(san.id()); - addDialog(dialog, m_menuGroup, identifier); + addDialog(dialog, m_menuGroup, identifier); } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.h old mode 100755 new mode 100644 index d034dd54e..2fe131f5d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog.h @@ -1,13 +1,12 @@ - #pragma once #include #include -#include -#include #include +#include +#include namespace Ui { @@ -18,36 +17,39 @@ namespace Evaluations { class SanNineLinerDialogModel; - - -class SanNineLinerDialog : public LtsWidgets::LtsDialog - , protected Evaluations::Interface::Ftc::SanNineLinerRemoveReplyHandler +class SanNineLinerDialog : public LtsWidgets::LtsDialog, + protected Evaluations::Interface::Ftc::SanNineLinerRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit SanNineLinerDialog(const QString &menuGroup, QWidget *parent = nullptr); - ~SanNineLinerDialog(); + public: + explicit SanNineLinerDialog(const QString& menuGroup, QWidget* parent = nullptr); + ~SanNineLinerDialog(); - bool init(LtsSession::LtsSessionDataDds *session); + bool init(LtsSession::LtsSessionDataDds* session); -private slots: - void enaDisa(); - void onAddSanNineLiner(); - void onEditSanNineLiner(); - void onRemoveSanNineLiner(); + private slots: + void enaDisa(); + void onAddSanNineLiner(); + void onEditSanNineLiner(); + void onRemoveSanNineLiner(); -private: - NGL::INGLLogger &m_logger; - void retranslate() override; - void onSanNineLinerRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void tableColumnOrganiserSetting() override; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; - SanNineLinerDialogModel *m_model{nullptr}; - Ui::SanNineLinerDialog *m_ui{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; - std::shared_ptr m_ftc; - QString m_menuGroup; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; + void onSanNineLinerRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } + + void tableColumnOrganiserSetting() override; + + SanNineLinerDialogModel* m_model{nullptr}; + Ui::SanNineLinerDialog* m_ui{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + std::shared_ptr m_ftc; + QString m_menuGroup; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.cpp old mode 100755 new mode 100644 index 59adfb68f..8f6d788a3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.cpp @@ -1,83 +1,64 @@ - - #include "san_nine_liner_dialog_model.h" -#include -#include #include #include +#include +#include namespace Evaluations { - - - -SanNineLinerDialogModel::SanNineLinerDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Created"), - tr("Position"), - tr("Radio frequency / Call Sign / Suffix") - }, - parent) -{} - -bool SanNineLinerDialogModel::initModel(const std::shared_ptr &dtc) +SanNineLinerDialogModel::SanNineLinerDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Created"), tr("Position"), tr("Radio frequency / Call Sign / Suffix")}, parent) { - m_evlDtc = dtc; - - connect(m_evlDtc.get(), &Evaluations::Interface::Dtc::sanNineLinerChanged, - this, &SanNineLinerDialogModel::onDataChanged); - - - m_evlDtc->sanNineLiners([this](const Evaluations::SanNineLiner &san) - { - insertRow(san); - }); - - INFO_LOG(m_logger) << "initModel - #sanNineLiner: " << m_vecData.size(); - return true; } - -QVariant SanNineLinerDialogModel::data(const QModelIndex &index, int role) const +bool SanNineLinerDialogModel::initModel(const std::shared_ptr& dtc) { - if (role != Qt::DisplayRole || !indexIsValid(index)) + m_evlDtc = dtc; + + connect(m_evlDtc.get(), &Evaluations::Interface::Dtc::sanNineLinerChanged, this, + &SanNineLinerDialogModel::onDataChanged); + + m_evlDtc->sanNineLiners([this](const Evaluations::SanNineLiner& san) { insertRow(san); }); + + INFO_LOG(m_logger) << "initModel - #sanNineLiner: " << m_vecData.size(); + return true; +} + +QVariant SanNineLinerDialogModel::data(const QModelIndex& index, int role) const +{ + if (role != Qt::DisplayRole || !indexIsValid(index)) + return QVariant(); + + const Evaluations::SanNineLiner& san = m_vecData.at(index.row()); + + switch (index.column()) + { + case SanNineLinerDialogModel::Columns::Id: + return san.id(); + case SanNineLinerDialogModel::Columns::Created: + return QDateTime::fromMSecsSinceEpoch(san.lastModified()); + case SanNineLinerDialogModel::Columns::Position: { + if (std::isnan(san.line1_position().lat()) || std::isnan(san.line1_position().lon())) + return tr("---"); + return LtsCoordTrans::mgrsFromGeographic(san.line1_position().lon(), san.line1_position().lat()); + } + case SanNineLinerDialogModel::Columns::RadioFrequencyCallSignSuffix: + return QString::fromStdString(san.line2_RadioFrequencyCallSignSuffix()); + default: + return QVariant(); + } return QVariant(); - - const Evaluations::SanNineLiner &san = m_vecData.at(index.row()); - - switch (index.column()) - { - case SanNineLinerDialogModel::Columns::Id: - return san.id(); - case SanNineLinerDialogModel::Columns::Created: - return QDateTime::fromMSecsSinceEpoch(san.lastModified()); - case SanNineLinerDialogModel::Columns::Position: - { - if (std::isnan(san.line1_position().lat()) || std::isnan(san.line1_position().lon())) - return tr("---"); - return LtsCoordTrans::mgrsFromGeographic(san.line1_position().lon(), san.line1_position().lat()); - } - case SanNineLinerDialogModel::Columns::RadioFrequencyCallSignSuffix: - return QString::fromStdString(san.line2_RadioFrequencyCallSignSuffix()); - default: - return QVariant(); - } - return QVariant(); } - - - - -void SanNineLinerProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void SanNineLinerProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } - -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.h old mode 100755 new mode 100644 index 55b18b9cf..5671c8b08 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_dialog_model.h @@ -1,52 +1,43 @@ - #pragma once +#include #include #include #include -#include namespace Evaluations { - - - class SanNineLinerDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Id, - Created, - Position, - RadioFrequencyCallSignSuffix - }; + public: + enum Columns { Id, Created, Position, RadioFrequencyCallSignSuffix }; - explicit SanNineLinerDialogModel(QObject *parent = nullptr); - bool initModel(const std::shared_ptr &dtc); + explicit SanNineLinerDialogModel(QObject* parent = nullptr); + bool initModel(const std::shared_ptr& dtc); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; -private: - NGL::INGLLogger &m_logger; - std::shared_ptr m_evlDtc; - friend class SanNineLinerProxyModel; + private: + NGL::INGLLogger& m_logger; + std::shared_ptr m_evlDtc; + friend class SanNineLinerProxyModel; }; class SanNineLinerProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -private: - NGL::INGLLogger &m_logger; - SanNineLinerDialogModel *m_sourceModel{nullptr}; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + private: + NGL::INGLLogger& m_logger; + SanNineLinerDialogModel* m_sourceModel{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.cpp old mode 100755 new mode 100644 index 7ec7a0f57..180ee23cf --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.cpp @@ -1,326 +1,300 @@ - - #include "san_nine_liner_edit_dialog.h" -#include + #include "ui_san_nine_liner_edit_dialog.h" -#include -#include -#include - -#include #include +#include +#include +#include #include -#include #include - +#include +#include +#include +#include #include #include - -#include - -#include +#include namespace Evaluations { - - -SanNineLinerEditDialog::SanNineLinerEditDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::SanNineLinerEditDialog) - , m_validator(new QIntValidator(this)) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +SanNineLinerEditDialog::SanNineLinerEditDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ui(new Ui::SanNineLinerEditDialog), + m_validator(new QIntValidator(this)), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_validator->setRange(0, 99); + m_validator->setRange(0, 99); - m_ui->le3A->setValidator(m_validator); - m_ui->le3B->setValidator(m_validator); - m_ui->le3C->setValidator(m_validator); - m_ui->le3D->setValidator(m_validator); - m_ui->le3E->setValidator(m_validator); - m_ui->le4A->setValidator(m_validator); - m_ui->le4B->setValidator(m_validator); - m_ui->le4C->setValidator(m_validator); - m_ui->le4D->setValidator(m_validator); - m_ui->le5A->setValidator(m_validator); - m_ui->le5B->setValidator(m_validator); - m_ui->le8A->setValidator(m_validator); - m_ui->le8B->setValidator(m_validator); - m_ui->le8C->setValidator(m_validator); - m_ui->le8D->setValidator(m_validator); - m_ui->le8E->setValidator(m_validator); + m_ui->le3A->setValidator(m_validator); + m_ui->le3B->setValidator(m_validator); + m_ui->le3C->setValidator(m_validator); + m_ui->le3D->setValidator(m_validator); + m_ui->le3E->setValidator(m_validator); + m_ui->le4A->setValidator(m_validator); + m_ui->le4B->setValidator(m_validator); + m_ui->le4C->setValidator(m_validator); + m_ui->le4D->setValidator(m_validator); + m_ui->le5A->setValidator(m_validator); + m_ui->le5B->setValidator(m_validator); + m_ui->le8A->setValidator(m_validator); + m_ui->le8B->setValidator(m_validator); + m_ui->le8C->setValidator(m_validator); + m_ui->le8D->setValidator(m_validator); + m_ui->le8E->setValidator(m_validator); - connect(m_ui->pbClear, &QPushButton::clicked, - m_ui->positionEdit, &LtsCoordWidget::LtsCoordWidget::clear); + connect(m_ui->pbClear, &QPushButton::clicked, m_ui->positionEdit, &LtsCoordWidget::LtsCoordWidget::clear); } - SanNineLinerEditDialog::~SanNineLinerEditDialog() { - delete m_ui; + delete m_ui; } - void SanNineLinerEditDialog::retranslate() { - translate(m_ui, QLatin1String("SanNineLiner"), m_sanNineLinerId, QLatin1String("Custom"), tr("SanNineLiner Edit")); + translate(m_ui, QLatin1String("SanNineLiner"), m_sanNineLinerId, QLatin1String("Custom"), tr("SanNineLiner Edit")); } - -bool SanNineLinerEditDialog::init(LtsSession::LtsSessionDataDds *session, - const QString &menuGroup, - const int sanNineLinerId) +bool SanNineLinerEditDialog::init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup, + const int sanNineLinerId) { - m_session = session; - m_menuGroup = menuGroup; - m_sanNineLinerId = sanNineLinerId; + m_session = session; + m_menuGroup = menuGroup; + m_sanNineLinerId = sanNineLinerId; - if (!m_session->getDtc(m_dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; + if (!m_session->getDtc(m_dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; - m_session->getForeignGuiInterface(m_sitMapGuiIfc); + m_session->getForeignGuiInterface(m_sitMapGuiIfc); - if (m_sitMapGuiIfc) - connect(m_ui->pbPosition, &QPushButton::clicked, this, &SanNineLinerEditDialog::getPosition); - else - m_ui->pbPosition->setEnabled(false); + if (m_sitMapGuiIfc) + connect(m_ui->pbPosition, &QPushButton::clicked, this, &SanNineLinerEditDialog::getPosition); + else + m_ui->pbPosition->setEnabled(false); - m_ui->dtTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + m_ui->dtTime->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - Evaluations::SanNineLiner data = m_dtc->sanNineLiner(sanNineLinerId); + Evaluations::SanNineLiner data = m_dtc->sanNineLiner(sanNineLinerId); - - if (data.id() > 0) - { - m_ui->dtTime->setMsecsSinceEpoch(data.lastModified()); - m_ui->leRadioFrequencyCallSignSuffix->setText(QString::fromStdString(data.line2_RadioFrequencyCallSignSuffix())); - QPointF position(data.line1_position().lon(), data.line1_position().lat()); - if (!position.isNull()) - m_ui->positionEdit->setCoordinate(position); - - - QVector linesCategory = SanCategoryLine::fromJson(data.lines(), data.id()); - - INFO_LOG(m_logger) << "linesCategory size: " << linesCategory.size(); - - for (const Database::SanCategoryLine &cl : std::as_const(linesCategory)) + if (data.id() > 0) { - - QString leName = QStringLiteral("le") + QString::number(cl.line) + cl.category; - QLineEdit *leLineAmount = findChild(leName); - if (leLineAmount) - { - INFO_LOG(m_logger) << "leName: " << leName << ", amount: " << cl.amount; - leLineAmount->setText(QString::number(cl.amount)); + m_ui->dtTime->setMsecsSinceEpoch(data.lastModified()); + m_ui->leRadioFrequencyCallSignSuffix->setText( + QString::fromStdString(data.line2_RadioFrequencyCallSignSuffix())); + QPointF position(data.line1_position().lon(), data.line1_position().lat()); + if (!position.isNull()) + m_ui->positionEdit->setCoordinate(position); - continue; - } + QVector linesCategory = SanCategoryLine::fromJson(data.lines(), data.id()); - - QString rbName = QStringLiteral("rb") + QString::number(cl.line) + cl.category; - QRadioButton *rbCategory = findChild(rbName); - if (rbCategory) - { - INFO_LOG(m_logger) << "rbName: " << rbName; - rbCategory->setChecked(true); - continue; - } + INFO_LOG(m_logger) << "linesCategory size: " << linesCategory.size(); - + for (const Database::SanCategoryLine& cl : std::as_const(linesCategory)) + { - QString cbxName = QStringLiteral("cbx") + QString::number(cl.line) + cl.category + (cl.category == QStringLiteral("N") ? QStringLiteral("u") : QString()); - QCheckBox *cbxCategory = findChild(cbxName); - if (cbxCategory) - { - INFO_LOG(m_logger) << "cbxName: " << cbxName; - cbxCategory->setChecked(true); - } + QString leName = QStringLiteral("le") + QString::number(cl.line) + cl.category; + QLineEdit* leLineAmount = findChild(leName); + if (leLineAmount) + { + INFO_LOG(m_logger) << "leName: " << leName << ", amount: " << cl.amount; + leLineAmount->setText(QString::number(cl.amount)); + + continue; + } + + QString rbName = QStringLiteral("rb") + QString::number(cl.line) + cl.category; + QRadioButton* rbCategory = findChild(rbName); + if (rbCategory) + { + INFO_LOG(m_logger) << "rbName: " << rbName; + rbCategory->setChecked(true); + continue; + } + + QString cbxName = QStringLiteral("cbx") + QString::number(cl.line) + cl.category + + (cl.category == QStringLiteral("N") ? QStringLiteral("u") : QString()); + QCheckBox* cbxCategory = findChild(cbxName); + if (cbxCategory) + { + INFO_LOG(m_logger) << "cbxName: " << cbxName; + cbxCategory->setChecked(true); + } + } } - - } - else - { - m_ui->dtTime->setMsecsSinceEpoch(m_session->partitionTime()); - } - setOnlineHelpFilename(QStringLiteral("Situation-SanNineLiner")); - enaDisa(); - return true; + else + { + m_ui->dtTime->setMsecsSinceEpoch(m_session->partitionTime()); + } + setOnlineHelpFilename(QStringLiteral("Situation-SanNineLiner")); + enaDisa(); + return true; } - void SanNineLinerEditDialog::enaDisa() { - m_ui->lblLine1_DE->hide(); - m_ui->lblLine2_DE->hide(); - m_ui->lblLine3_DE->hide(); - m_ui->lblLine4_DE->hide(); - m_ui->lblLine5_DE->hide(); - m_ui->lblLine6_DE->hide(); - m_ui->lblLine7_DE->hide(); - m_ui->lblLine8_DE->hide(); - m_ui->lblLine9_DE->hide(); - if (NGL::translationLocale() == "de_DE") - { - m_ui->lblLine1_DE->show(); - m_ui->lblLine2_DE->show(); - m_ui->gbLine3->setTitle(m_ui->gbLine3->title()+m_ui->lblLine3_DE->text()); - m_ui->gbLine4->setTitle(m_ui->gbLine4->title()+m_ui->lblLine4_DE->text()); - m_ui->gbLine5->setTitle(m_ui->gbLine5->title()+m_ui->lblLine5_DE->text()); - m_ui->gbLine6->setTitle(m_ui->gbLine6->title()+m_ui->lblLine6_DE->text()); - m_ui->gbLine7->setTitle(m_ui->gbLine7->title()+m_ui->lblLine7_DE->text()); - m_ui->gbLine8->setTitle(m_ui->gbLine8->title()+m_ui->lblLine8_DE->text()); - m_ui->gbLine9->setTitle(m_ui->gbLine9->title()+m_ui->lblLine9_DE->text()); - } + m_ui->lblLine1_DE->hide(); + m_ui->lblLine2_DE->hide(); + m_ui->lblLine3_DE->hide(); + m_ui->lblLine4_DE->hide(); + m_ui->lblLine5_DE->hide(); + m_ui->lblLine6_DE->hide(); + m_ui->lblLine7_DE->hide(); + m_ui->lblLine8_DE->hide(); + m_ui->lblLine9_DE->hide(); + if (NGL::translationLocale() == "de_DE") + { + m_ui->lblLine1_DE->show(); + m_ui->lblLine2_DE->show(); + m_ui->gbLine3->setTitle(m_ui->gbLine3->title() + m_ui->lblLine3_DE->text()); + m_ui->gbLine4->setTitle(m_ui->gbLine4->title() + m_ui->lblLine4_DE->text()); + m_ui->gbLine5->setTitle(m_ui->gbLine5->title() + m_ui->lblLine5_DE->text()); + m_ui->gbLine6->setTitle(m_ui->gbLine6->title() + m_ui->lblLine6_DE->text()); + m_ui->gbLine7->setTitle(m_ui->gbLine7->title() + m_ui->lblLine7_DE->text()); + m_ui->gbLine8->setTitle(m_ui->gbLine8->title() + m_ui->lblLine8_DE->text()); + m_ui->gbLine9->setTitle(m_ui->gbLine9->title() + m_ui->lblLine9_DE->text()); + } } - -bool SanNineLinerEditDialog::apply() +bool SanNineLinerEditDialog::apply() { - SanNineLinerModifyRequest request; - request.id(m_sanNineLinerId); + SanNineLinerModifyRequest request; + request.id(m_sanNineLinerId); - - request.id(m_sanNineLinerId); - request.lastModified(m_ui->dtTime->msecsSinceEpoch()); - const Core::GeoPosition2D pos(m_ui->positionEdit->coordinate().x(), m_ui->positionEdit->coordinate().y()); - request.line1_position(pos); - request.line2_radioFrequencyCallSignSuffix(m_ui->leRadioFrequencyCallSignSuffix->text().toStdString()); + request.id(m_sanNineLinerId); + request.lastModified(m_ui->dtTime->msecsSinceEpoch()); + const Core::GeoPosition2D pos(m_ui->positionEdit->coordinate().x(), m_ui->positionEdit->coordinate().y()); + request.line1_position(pos); + request.line2_radioFrequencyCallSignSuffix(m_ui->leRadioFrequencyCallSignSuffix->text().toStdString()); - m_vecCategoryLine.clear(); - - int line = 3; - - setCategoryLine(line, QStringLiteral("A"), m_ui->le3A); - setCategoryLine(line, QStringLiteral("B"), m_ui->le3B); - setCategoryLine(line, QStringLiteral("C"), m_ui->le3C); - setCategoryLine(line, QStringLiteral("D"), m_ui->le3D); - setCategoryLine(line, QStringLiteral("E"), m_ui->le3E); - - line = 4; - setCategoryLine(line, QStringLiteral("A"), m_ui->le4A); - setCategoryLine(line, QStringLiteral("B"), m_ui->le4B); - setCategoryLine(line, QStringLiteral("C"), m_ui->le4C); - setCategoryLine(line, QStringLiteral("D"), m_ui->le4D); - - line = 5; - setCategoryLine(line, QStringLiteral("A"), m_ui->le5A); - setCategoryLine(line, QStringLiteral("B"), m_ui->le5B); - - line = 6; - setCategoryLine(line, QStringLiteral("A"), m_ui->rb6A); - setCategoryLine(line, QStringLiteral("B"), m_ui->rb6B); - - line = 7; - setCategoryLine(line, QStringLiteral("A"), m_ui->cbx7A); - setCategoryLine(line, QStringLiteral("B"), m_ui->cbx7B); - setCategoryLine(line, QStringLiteral("C"), m_ui->cbx7C); - setCategoryLine(line, QStringLiteral("D"), m_ui->cbx7D); - setCategoryLine(line, QStringLiteral("E"), m_ui->cbx7E); - - line = 8; - setCategoryLine(line, QStringLiteral("A"), m_ui->le8A); - setCategoryLine(line, QStringLiteral("B"), m_ui->le8B); - setCategoryLine(line, QStringLiteral("C"), m_ui->le8C); - setCategoryLine(line, QStringLiteral("D"), m_ui->le8D); - setCategoryLine(line, QStringLiteral("E"), m_ui->le8E); - - line = 9; - setCategoryLine(line, QStringLiteral("N"), m_ui->cbx9Nu); - setCategoryLine(line, QStringLiteral("B"), m_ui->cbx9B); - setCategoryLine(line, QStringLiteral("C"), m_ui->cbx9C); - setCategoryLine(line, QStringLiteral("None"), m_ui->cbx9None); + m_vecCategoryLine.clear(); - QJsonDocument doc = SanCategoryLine::toJson(m_vecCategoryLine); - request.lines(doc.toJson().toStdString()); + int line = 3; - if (!m_requestHelper->startSingleRequest([this, request]() - { - return m_ftc->sanNineLinerModifyRequest(request, this); - })) - return false; + setCategoryLine(line, QStringLiteral("A"), m_ui->le3A); + setCategoryLine(line, QStringLiteral("B"), m_ui->le3B); + setCategoryLine(line, QStringLiteral("C"), m_ui->le3C); + setCategoryLine(line, QStringLiteral("D"), m_ui->le3D); + setCategoryLine(line, QStringLiteral("E"), m_ui->le3E); - if (request.id() <= 0) - { - m_sanNineLinerId = m_requestHelper->getRepliedId(); - ERROR_LOG(m_logger) << "Created new san nine liner with id " << m_sanNineLinerId; - } + line = 4; + setCategoryLine(line, QStringLiteral("A"), m_ui->le4A); + setCategoryLine(line, QStringLiteral("B"), m_ui->le4B); + setCategoryLine(line, QStringLiteral("C"), m_ui->le4C); + setCategoryLine(line, QStringLiteral("D"), m_ui->le4D); + line = 5; + setCategoryLine(line, QStringLiteral("A"), m_ui->le5A); + setCategoryLine(line, QStringLiteral("B"), m_ui->le5B); + line = 6; + setCategoryLine(line, QStringLiteral("A"), m_ui->rb6A); + setCategoryLine(line, QStringLiteral("B"), m_ui->rb6B); - return true; + line = 7; + setCategoryLine(line, QStringLiteral("A"), m_ui->cbx7A); + setCategoryLine(line, QStringLiteral("B"), m_ui->cbx7B); + setCategoryLine(line, QStringLiteral("C"), m_ui->cbx7C); + setCategoryLine(line, QStringLiteral("D"), m_ui->cbx7D); + setCategoryLine(line, QStringLiteral("E"), m_ui->cbx7E); + + line = 8; + setCategoryLine(line, QStringLiteral("A"), m_ui->le8A); + setCategoryLine(line, QStringLiteral("B"), m_ui->le8B); + setCategoryLine(line, QStringLiteral("C"), m_ui->le8C); + setCategoryLine(line, QStringLiteral("D"), m_ui->le8D); + setCategoryLine(line, QStringLiteral("E"), m_ui->le8E); + + line = 9; + setCategoryLine(line, QStringLiteral("N"), m_ui->cbx9Nu); + setCategoryLine(line, QStringLiteral("B"), m_ui->cbx9B); + setCategoryLine(line, QStringLiteral("C"), m_ui->cbx9C); + setCategoryLine(line, QStringLiteral("None"), m_ui->cbx9None); + + QJsonDocument doc = SanCategoryLine::toJson(m_vecCategoryLine); + request.lines(doc.toJson().toStdString()); + + if (!m_requestHelper->startSingleRequest( + [this, request]() { return m_ftc->sanNineLinerModifyRequest(request, this); })) + return false; + + if (request.id() <= 0) + { + m_sanNineLinerId = m_requestHelper->getRepliedId(); + ERROR_LOG(m_logger) << "Created new san nine liner with id " << m_sanNineLinerId; + } + + return true; } bool SanNineLinerEditDialog::has2DMap() { - if (!m_sitMapGuiIfc) - return false; - if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); - return false; - } - return true; + if (!m_sitMapGuiIfc) + return false; + if (m_sitMapGuiIfc->mapMode() != SituationMap::MapMode::MapMode_2D) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Only available in 2D mode")); + return false; + } + return true; } void SanNineLinerEditDialog::getPosition() { - if (!has2DMap()) - return; - - m_sitMapGuiIfc->getCoordinate(this, SLOT(onCoordinate(QPointF)), nullptr); + if (!has2DMap()) + return; + m_sitMapGuiIfc->getCoordinate(this, SLOT(onCoordinate(QPointF)), nullptr); } -void SanNineLinerEditDialog::onCoordinate(const QPointF ¢erPoint) +void SanNineLinerEditDialog::onCoordinate(const QPointF& centerPoint) { - m_ui->positionEdit->setCoordinate(centerPoint); + m_ui->positionEdit->setCoordinate(centerPoint); } -void SanNineLinerEditDialog::setCategoryLine( int line, const QString &category, QLineEdit* leAmount) +void SanNineLinerEditDialog::setCategoryLine(int line, const QString& category, QLineEdit* leAmount) { - Database::SanCategoryLine cl; + Database::SanCategoryLine cl; - cl.nineLinerId = m_sanNineLinerId; - cl.line = line; - cl.category = category; - cl.amount = leAmount->text().toInt(); + cl.nineLinerId = m_sanNineLinerId; + cl.line = line; + cl.category = category; + cl.amount = leAmount->text().toInt(); - if (cl.amount > 0) - m_vecCategoryLine.push_back(std::move(cl)); + if (cl.amount > 0) + m_vecCategoryLine.push_back(std::move(cl)); } -void SanNineLinerEditDialog::setCategoryLine( int line, const QString &category, QRadioButton *rb) +void SanNineLinerEditDialog::setCategoryLine(int line, const QString& category, QRadioButton* rb) { - Database::SanCategoryLine cl; + Database::SanCategoryLine cl; - cl.nineLinerId = m_sanNineLinerId; - cl.line = line; - cl.category = category; - cl.amount = 0; + cl.nineLinerId = m_sanNineLinerId; + cl.line = line; + cl.category = category; + cl.amount = 0; - if (rb->isChecked()) - m_vecCategoryLine.push_back(std::move(cl)); + if (rb->isChecked()) + m_vecCategoryLine.push_back(std::move(cl)); } -void SanNineLinerEditDialog::setCategoryLine(int line, const QString &category, QCheckBox *cbx) +void SanNineLinerEditDialog::setCategoryLine(int line, const QString& category, QCheckBox* cbx) { - Database::SanCategoryLine cl; + Database::SanCategoryLine cl; - cl.nineLinerId = m_sanNineLinerId; - cl.line = line; - cl.category = category; - cl.amount = 0; + cl.nineLinerId = m_sanNineLinerId; + cl.line = line; + cl.category = category; + cl.amount = 0; - if (cbx->isChecked()) - m_vecCategoryLine.push_back(std::move(cl)); + if (cbx->isChecked()) + m_vecCategoryLine.push_back(std::move(cl)); } -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.h old mode 100755 new mode 100644 index a7c0cae9d..5a47b0778 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SanNineLinerEdit/san_nine_liner_edit_dialog.h @@ -1,16 +1,14 @@ - #pragma once -#include -#include -#include -#include -#include -#include - #include +#include +#include +#include +#include +#include +#include namespace Ui { @@ -19,7 +17,7 @@ class SanNineLinerEditDialog; namespace SituationMap { - class ForeignGuiInterface; +class ForeignGuiInterface; } class QIntValidator; @@ -27,58 +25,55 @@ class QIntValidator; namespace Evaluations { - - - -class SanNineLinerEditDialog final : public LtsWidgets::LtsDialog - , protected Evaluations::Interface::Ftc::SanNineLinerModifyReplyHandler +class SanNineLinerEditDialog final : public LtsWidgets::LtsDialog, + protected Evaluations::Interface::Ftc::SanNineLinerModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit SanNineLinerEditDialog(QWidget *parent = nullptr); + public: + explicit SanNineLinerEditDialog(QWidget* parent = nullptr); - bool init(LtsSession::LtsSessionDataDds *session, - const QString &menuGroup, - const int sanNineLinerId); + bool init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup, const int sanNineLinerId); - ~SanNineLinerEditDialog(); + ~SanNineLinerEditDialog(); -protected: + protected: + NGL::INGLLogger& m_logger; - NGL::INGLLogger &m_logger; - void onSanNineLinerModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onSanNineLinerModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void onCoordinate(const QPointF ¢erPoint); - void getPosition(); + private slots: + void onCoordinate(const QPointF& centerPoint); + void getPosition(); + signals: + void sendData(const Evaluations::SanNineLiner& data); -signals: - void sendData(const Evaluations::SanNineLiner &data); + private: + void retranslate() override; + bool apply() override final; + bool has2DMap(); -private: - void retranslate() override; - bool apply() override final; - bool has2DMap(); + void setCategoryLine(int line, const QString& category, QLineEdit* leAmount); + void setCategoryLine(int line, const QString& category, QRadioButton* rb); + void setCategoryLine(int line, const QString& category, QCheckBox* cbx); - void setCategoryLine(int line, const QString &category, QLineEdit* leAmount); - void setCategoryLine( int line, const QString &category, QRadioButton *rb); - void setCategoryLine( int line, const QString &category, QCheckBox *cbx); + void enaDisa(); - void enaDisa(); + Ui::SanNineLinerEditDialog* m_ui{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + int m_sanNineLinerId{0}; + std::vector m_vecCategoryLine; - Ui::SanNineLinerEditDialog *m_ui{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; - int m_sanNineLinerId{0}; - std::vector m_vecCategoryLine; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_sitMapGuiIfc; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_sitMapGuiIfc; - - QString m_menuGroup; - QIntValidator *m_validator{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; + QString m_menuGroup; + QIntValidator* m_validator{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_comments.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_comments.h old mode 100755 new mode 100644 index c1f2d9a0d..0166d5b38 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_comments.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_comments.h @@ -1,11 +1,10 @@ - #pragma once -#include -#include #include +#include +#include #include namespace Ui @@ -20,33 +19,30 @@ class EvlCommentDataViewProxyModel; class EvlCommentsView : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT -public: + public: + EvlCommentsView(const std::shared_ptr& evlDtc, + const std::shared_ptr& opmDtc, QWidget* parent = nullptr); + ~EvlCommentsView(); - EvlCommentsView(const std::shared_ptr &evlDtc, - const std::shared_ptr &opmDtc, - QWidget *parent = nullptr); - ~EvlCommentsView(); + private slots: + void onLtsDataView_DoubleClicked(); + void onCommentChanged(const Evaluations::EvaluationComment& data, DataModification modType); -private slots: - void onLtsDataView_DoubleClicked(); - void onCommentChanged(const Evaluations::EvaluationComment &data, DataModification modType); + private: + NGL::INGLLogger& m_logger; + bool insertComment(const Evaluations::EvaluationComment& c); + void retranslate() override; + bool eventFilter(QObject* object, QEvent* event) override; + void tableColumnOrganiserSetting() override; -private: + Ui::EvlCommentsDialog* m_ui{nullptr}; -NGL::INGLLogger &m_logger; - bool insertComment(const Evaluations::EvaluationComment &c); - void retranslate() override; - bool eventFilter(QObject *object, QEvent *event) override; - void tableColumnOrganiserSetting() override; + std::shared_ptr m_evlDtc; + std::shared_ptr m_opmDtc; - Ui::EvlCommentsDialog *m_ui{nullptr}; - - std::shared_ptr m_evlDtc; - std::shared_ptr m_opmDtc; - - EvlCommentDataViewModel *m_model{nullptr}; - EvlCommentDataViewProxyModel *m_proxyModel{nullptr}; + EvlCommentDataViewModel* m_model{nullptr}; + EvlCommentDataViewProxyModel* m_proxyModel{nullptr}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.cpp old mode 100755 new mode 100644 index c1b192250..85e0d21ab --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.cpp @@ -1,1245 +1,1145 @@ - #include "evl_edit_schema.h" -#include "ui_evl_edit_schema.h" + #include "evl_new_comment_dialog.h" +#include "ui_evl_edit_schema.h" -#include #include - -#include -#include +#include #include #include +#include +#include #include namespace Evaluations { - - -static void beautifyTreeView(QTreeView *tv, QAbstractItemModel *pModel, const QModelIndex &parent = QModelIndex(), bool keepExpanded = true) +static void beautifyTreeView(QTreeView* tv, QAbstractItemModel* pModel, const QModelIndex& parent = QModelIndex(), + bool keepExpanded = true) { - if (!parent.isValid()) - tv->expandAll(); - else - tv->expand(parent); - - int colCount = pModel->columnCount(parent); - for (int i = 0; i < colCount; ++i) - tv->resizeColumnToContents(i); - - tv->header()->resizeSection(0, tv->columnWidth(0) + tv->iconSize().width() + 10); - - - if (!keepExpanded) - { if (!parent.isValid()) - tv->collapseAll(); + tv->expandAll(); else - tv->collapse(parent); - } + tv->expand(parent); + + int colCount = pModel->columnCount(parent); + for (int i = 0; i < colCount; ++i) + tv->resizeColumnToContents(i); + + tv->header()->resizeSection(0, tv->columnWidth(0) + tv->iconSize().width() + 10); + + if (!keepExpanded) + { + if (!parent.isValid()) + tv->collapseAll(); + else + tv->collapse(parent); + } } - - - - - -void expandNodeChildren(QTreeView *pTreeView, const QModelIndex &index, bool expand) +void expandNodeChildren(QTreeView* pTreeView, const QModelIndex& index, bool expand) { - if (!index.isValid()) - return; + if (!index.isValid()) + return; - int childCount = index.model()->rowCount(index); - for (int i = 0; i < childCount; i++) - { - const QModelIndex &child = index.model()->index(i, 0, index); - - expandNodeChildren(pTreeView, child, expand); - } + int childCount = index.model()->rowCount(index); + for (int i = 0; i < childCount; i++) + { + const QModelIndex& child = index.model()->index(i, 0, index); - if (expand) - pTreeView->expand(index); - else - pTreeView->collapse(index); + expandNodeChildren(pTreeView, child, expand); + } + + if (expand) + pTreeView->expand(index); + else + pTreeView->collapse(index); } - - -EditSchemaDialog::EditSchemaDialog(bool ocMode, bool runningOnTablet, LtsSession::LtsSession *session, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ocMode(ocMode) - , m_runningOnTablet(runningOnTablet) - , m_session(session) - , m_requestHelper(new LtsUtils::RequestHelper(this)) - , m_ui(new Ui::EditSchemaDialog) +EditSchemaDialog::EditSchemaDialog(bool ocMode, bool runningOnTablet, LtsSession::LtsSession* session, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ocMode(ocMode), + m_runningOnTablet(runningOnTablet), m_session(session), m_requestHelper(new LtsUtils::RequestHelper(this)), + m_ui(new Ui::EditSchemaDialog) { - m_ui->setupUi(this); + m_ui->setupUi(this); - if (ocMode) - setOnlineHelpFilename(QStringLiteral("OC-Exercise_Evaluations")); - else - setOnlineHelpFilename(QStringLiteral("Situation-O-C_Evaluation_Schemes")); + if (ocMode) + setOnlineHelpFilename(QStringLiteral("OC-Exercise_Evaluations")); + else + setOnlineHelpFilename(QStringLiteral("Situation-O-C_Evaluation_Schemes")); } - -bool EditSchemaDialog::init(const std::shared_ptr &ocFtc, - const std::shared_ptr &evlFtc, - const std::shared_ptr &evlDtc, - const std::shared_ptr &opmDtc, - const std::shared_ptr &flmFtc, - const std::shared_ptr &flmDtc, - const std::shared_ptr &flmGui) +bool EditSchemaDialog::init(const std::shared_ptr& ocFtc, + const std::shared_ptr& evlFtc, + const std::shared_ptr& evlDtc, + const std::shared_ptr& opmDtc, + const std::shared_ptr& flmFtc, + const std::shared_ptr& flmDtc, + const std::shared_ptr& flmGui) { - m_ocFtc = ocFtc; - m_evlFtc = evlFtc; - m_evlDtc = evlDtc; - m_opmDtc = opmDtc; + m_ocFtc = ocFtc; + m_evlFtc = evlFtc; + m_evlDtc = evlDtc; + m_opmDtc = opmDtc; - m_flmFtc = flmFtc; - m_flmDtc = flmDtc; - m_flmGui = flmGui; + m_flmFtc = flmFtc; + m_flmDtc = flmDtc; + m_flmGui = flmGui; - m_pModel = new TreeModelSchema(this, m_logger); - m_ui->m_treeViewSchema->setModel(m_pModel); - m_ui->m_treeViewSchema->installEventFilter(this); + m_pModel = new TreeModelSchema(this, m_logger); + m_ui->m_treeViewSchema->setModel(m_pModel); + m_ui->m_treeViewSchema->installEventFilter(this); - connect(m_ui->m_treeViewSchema->selectionModel(), &QItemSelectionModel::currentChanged, this, &EditSchemaDialog::onTreeViewModelIndexChanged); - connect(m_ui->m_treeViewSchema, &QTreeView::customContextMenuRequested, this, &EditSchemaDialog::onShowContextMenu); - connect(m_ui->m_treeViewSchema, &QTreeView::doubleClicked, this, &EditSchemaDialog::onTreeViewDoubleClicked); + connect(m_ui->m_treeViewSchema->selectionModel(), &QItemSelectionModel::currentChanged, this, + &EditSchemaDialog::onTreeViewModelIndexChanged); + connect(m_ui->m_treeViewSchema, &QTreeView::customContextMenuRequested, this, &EditSchemaDialog::onShowContextMenu); + connect(m_ui->m_treeViewSchema, &QTreeView::doubleClicked, this, &EditSchemaDialog::onTreeViewDoubleClicked); - - connect(m_evlDtc.get(), &Evaluations::Interface::Dtc::evaluationSchemaChanged, this, &EditSchemaDialog::onNotifyAboutSchema, Qt::UniqueConnection); + connect(m_evlDtc.get(), &Evaluations::Interface::Dtc::evaluationSchemaChanged, this, + &EditSchemaDialog::onNotifyAboutSchema, Qt::UniqueConnection); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); - if (m_ocMode) - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Apply")); + if (m_ocMode) + { + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Apply")); - m_ui->m_treeViewSchema->setDragEnabled(false); - connect(m_ui->m_pushButton_SendComment, &QPushButton::clicked, this, &EditSchemaDialog::onSendComment); - connect(m_ui->m_pushButton_SendAllComments, &QPushButton::clicked, this, &EditSchemaDialog::onSendAllComments); - connect(m_ui->m_pushButton_NewComment, &QPushButton::clicked, this, &EditSchemaDialog::onAddNewComment); - connect(m_ui->m_pushButton_EditComment, &QPushButton::clicked, this, &EditSchemaDialog::onTreeViewDoubleClicked); - connect(m_ui->m_pushButton_RemoveComment, &QPushButton::clicked, this, &EditSchemaDialog::onRemoveSelectedElement); - connect(m_ui->m_pushButton_RequestSchema, &QPushButton::clicked, this, &EditSchemaDialog::onRequestSchema); + m_ui->m_treeViewSchema->setDragEnabled(false); + connect(m_ui->m_pushButton_SendComment, &QPushButton::clicked, this, &EditSchemaDialog::onSendComment); + connect(m_ui->m_pushButton_SendAllComments, &QPushButton::clicked, this, &EditSchemaDialog::onSendAllComments); + connect(m_ui->m_pushButton_NewComment, &QPushButton::clicked, this, &EditSchemaDialog::onAddNewComment); + connect(m_ui->m_pushButton_EditComment, &QPushButton::clicked, this, + &EditSchemaDialog::onTreeViewDoubleClicked); + connect(m_ui->m_pushButton_RemoveComment, &QPushButton::clicked, this, + &EditSchemaDialog::onRemoveSelectedElement); + connect(m_ui->m_pushButton_RequestSchema, &QPushButton::clicked, this, &EditSchemaDialog::onRequestSchema); - m_ui->m_pushButton_SendComment->setEnabled(false); - m_ui->m_pushButton_SendAllComments->setEnabled(false); - m_ui->m_pushButton_NewComment->setEnabled(false); - m_ui->m_pushButton_EditComment->setEnabled(false); - m_ui->m_pushButton_RemoveComment->setEnabled(false); + m_ui->m_pushButton_SendComment->setEnabled(false); + m_ui->m_pushButton_SendAllComments->setEnabled(false); + m_ui->m_pushButton_NewComment->setEnabled(false); + m_ui->m_pushButton_EditComment->setEnabled(false); + m_ui->m_pushButton_RemoveComment->setEnabled(false); - m_ui->m_pushButton_CreateNewSchema->hide(); - m_ui->m_pushButton_AddElement->hide(); - m_ui->m_pushButton_AddFolder->hide(); - m_ui->m_pushButton_AddRootFolder->hide(); - m_ui->m_pushButton_Modify->hide(); - m_ui->m_pushButton_Remove->hide(); + m_ui->m_pushButton_CreateNewSchema->hide(); + m_ui->m_pushButton_AddElement->hide(); + m_ui->m_pushButton_AddFolder->hide(); + m_ui->m_pushButton_AddRootFolder->hide(); + m_ui->m_pushButton_Modify->hide(); + m_ui->m_pushButton_Remove->hide(); - m_ui->m_pushButton_SendSchema->hide(); - m_ui->m_pushButton_LoadSchemaDebug->hide(); - m_ui->m_pushButton_SaveToLibrary->hide(); - m_ui->m_pushButton_LoadFromLibrary->hide(); - m_ui->line->hide(); - m_ui->line_2->hide(); - } - else - { - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Save")); + m_ui->m_pushButton_SendSchema->hide(); + m_ui->m_pushButton_LoadSchemaDebug->hide(); + m_ui->m_pushButton_SaveToLibrary->hide(); + m_ui->m_pushButton_LoadFromLibrary->hide(); + m_ui->line->hide(); + m_ui->line_2->hide(); + } + else + { + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->setText(tr("Save")); - connect(m_pModel, &TreeModelSchema::signalSuccessfulDropPerformed, this, &EditSchemaDialog::onDropActionFinished); - connect(m_pModel, &TreeModelSchema::signalTriedToDropFolderToElement, this, &EditSchemaDialog::onTriedToDropFolderToElement); + connect(m_pModel, &TreeModelSchema::signalSuccessfulDropPerformed, this, + &EditSchemaDialog::onDropActionFinished); + connect(m_pModel, &TreeModelSchema::signalTriedToDropFolderToElement, this, + &EditSchemaDialog::onTriedToDropFolderToElement); - connect(m_ui->m_pushButton_SaveToLibrary, &QPushButton::clicked, this, &EditSchemaDialog::onSaveToLibrary); - connect(m_ui->m_pushButton_LoadFromLibrary, &QPushButton::clicked, this, &EditSchemaDialog::onLoadFromLibrary); - connect(m_ui->m_pushButton_SendSchema, &QPushButton::clicked, this, &EditSchemaDialog::onSendSchema); - connect(m_ui->m_pushButton_LoadSchemaDebug, &QPushButton::clicked, this, &EditSchemaDialog::DebugonLoadSchema); + connect(m_ui->m_pushButton_SaveToLibrary, &QPushButton::clicked, this, &EditSchemaDialog::onSaveToLibrary); + connect(m_ui->m_pushButton_LoadFromLibrary, &QPushButton::clicked, this, &EditSchemaDialog::onLoadFromLibrary); + connect(m_ui->m_pushButton_SendSchema, &QPushButton::clicked, this, &EditSchemaDialog::onSendSchema); + connect(m_ui->m_pushButton_LoadSchemaDebug, &QPushButton::clicked, this, &EditSchemaDialog::DebugonLoadSchema); - connect(m_ui->m_pushButton_CreateNewSchema, &QPushButton::clicked, this, &EditSchemaDialog::onCreateNewSchema); - connect(m_ui->m_pushButton_AddElement, &QPushButton::clicked, this, &EditSchemaDialog::onAddElement); - connect(m_ui->m_pushButton_AddFolder, &QPushButton::clicked, this, &EditSchemaDialog::onAddFolder); - connect(m_ui->m_pushButton_AddRootFolder, &QPushButton::clicked, this, &EditSchemaDialog::onAddRootFolder); - connect(m_ui->m_pushButton_Modify, &QPushButton::clicked, this, &EditSchemaDialog::onModifySelectedEntry); - connect(m_ui->m_pushButton_Remove, &QPushButton::clicked, this, &EditSchemaDialog::onRemoveSelectedElement); + connect(m_ui->m_pushButton_CreateNewSchema, &QPushButton::clicked, this, &EditSchemaDialog::onCreateNewSchema); + connect(m_ui->m_pushButton_AddElement, &QPushButton::clicked, this, &EditSchemaDialog::onAddElement); + connect(m_ui->m_pushButton_AddFolder, &QPushButton::clicked, this, &EditSchemaDialog::onAddFolder); + connect(m_ui->m_pushButton_AddRootFolder, &QPushButton::clicked, this, &EditSchemaDialog::onAddRootFolder); + connect(m_ui->m_pushButton_Modify, &QPushButton::clicked, this, &EditSchemaDialog::onModifySelectedEntry); + connect(m_ui->m_pushButton_Remove, &QPushButton::clicked, this, &EditSchemaDialog::onRemoveSelectedElement); - m_ui->m_pushButton_NewComment->hide(); - m_ui->m_pushButton_SendComment->hide(); - m_ui->m_pushButton_SendAllComments->hide(); - m_ui->m_pushButton_EditComment->hide(); - m_ui->m_pushButton_RemoveComment->hide(); - m_ui->m_pushButton_RequestSchema->hide(); + m_ui->m_pushButton_NewComment->hide(); + m_ui->m_pushButton_SendComment->hide(); + m_ui->m_pushButton_SendAllComments->hide(); + m_ui->m_pushButton_EditComment->hide(); + m_ui->m_pushButton_RemoveComment->hide(); + m_ui->m_pushButton_RequestSchema->hide(); - m_ui->m_labelComments->hide(); + m_ui->m_labelComments->hide(); - m_ui->line_3->hide(); - m_ui->line_4->hide(); + m_ui->line_3->hide(); + m_ui->line_4->hide(); #ifdef LTS_DEBUG - #else - m_ui->m_pushButton_LoadSchemaDebug->hide(); + m_ui->m_pushButton_LoadSchemaDebug->hide(); #endif - } + } - loadLatestSchema(); - onTreeViewModelIndexChanged(QModelIndex()); - return true; + loadLatestSchema(); + onTreeViewModelIndexChanged(QModelIndex()); + return true; } - - - void EditSchemaDialog::loadLatestSchema() { - m_mapSchemata = m_evlDtc->evaluationSchemas(); + m_mapSchemata = m_evlDtc->evaluationSchemas(); - if (!m_mapSchemata.size()) - { - FATAL_LOG(m_logger) << "No evaluation schema available! Something is really wrong, there should always be at least one default evaluation schema available (created by the evaluation service)!"; - return; - } - - if (m_ocMode) - { - - auto itE = m_mapSchemata.cend(); - auto itB = m_mapSchemata.cbegin(); - - while (itE != itB) + if (!m_mapSchemata.size()) { - --itE; - - if ((*itE).sendToTa()) - { - loadSchema((*itE).id()); - break; - } + FATAL_LOG(m_logger) << "No evaluation schema available! Something is really wrong, there should always be at " + "least one default evaluation schema available (created by the evaluation service)!"; + return; } - - const QMap mapComments = m_evlDtc->evaluationComments(); - - for (const Evaluations::EvaluationComment &c : mapComments) + if (m_ocMode) { - if (c.schemaId() != m_loadedSchemaId) - continue; - if (c.senderOperatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId()) - continue; + auto itE = m_mapSchemata.cend(); + auto itB = m_mapSchemata.cbegin(); - ItemComment comment(QString::fromStdString(c.text()), - c.senderOperatorId(), - c.receiverOperatorId().is_set() ? c.receiverOperatorId().get() : 0, - c.elementId(), - QDateTime::fromMSecsSinceEpoch(c.ts())); - m_pModel->insertComment(comment); + while (itE != itB) + { + --itE; + + if ((*itE).sendToTa()) + { + loadSchema((*itE).id()); + break; + } + } + + const QMap mapComments = m_evlDtc->evaluationComments(); + + for (const Evaluations::EvaluationComment& c : mapComments) + { + if (c.schemaId() != m_loadedSchemaId) + continue; + + if (c.senderOperatorId() != LtsSessionData::LtsSessionData::getInstance()->getOperatorId()) + continue; + + ItemComment comment(QString::fromStdString(c.text()), c.senderOperatorId(), + c.receiverOperatorId().is_set() ? c.receiverOperatorId().get() : 0, c.elementId(), + QDateTime::fromMSecsSinceEpoch(c.ts())); + m_pModel->insertComment(comment); + } + + updateCommentLabel(); } - - updateCommentLabel(); - - } - else - loadSchema(m_mapSchemata.last().id()); + else + loadSchema(m_mapSchemata.last().id()); } - void EditSchemaDialog::handleUnsentComments() { - if (m_pModel->cntSentComments() != m_pModel->cntComments()) - { - LtsWidgets::Button button = - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("There are unsent comments within the currently loaded schema. Do you wish to send them before requesting a new schema?"), - tr("Warning"), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); + if (m_pModel->cntSentComments() != m_pModel->cntComments()) + { + LtsWidgets::Button button = LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("There are unsent comments within the currently loaded schema. Do you wish to send them before " + "requesting a new schema?"), + tr("Warning"), LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); - if (button == LtsWidgets::Button::Yes) - onSendAllComments(); - } + if (button == LtsWidgets::Button::Yes) + onSendAllComments(); + } } - void EditSchemaDialog::onRequestSchema() { - - bool con = true; + bool con = true; - if (!con) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("No Tetra radio, request failed!")); - return; - } - - handleUnsentComments(); - - loadLatestSchema(); - - - - m_ui->m_pushButton_RequestSchema->setEnabled(false); - - QTimer::singleShot(3000, this, [this]() - { - m_ui->m_pushButton_RequestSchema->setEnabled(true); - }); -} - - -void EditSchemaDialog::onNotifyAboutSchema(const Evaluations::EvaluationSchema &data, DataModification modType) -{ - if (m_ocMode && !data.sendToTa()) - return; - - QJsonParseError jError; - const QJsonDocument doc(QJsonDocument::fromJson(data.schemadata().c_str(), &jError)); - - if (jError.error != QJsonParseError::NoError) - { - WARNING_LOG(m_logger) << "Could not parse schema with database id " << data.id(); - return; - } - - if (m_loadedSchemaId == data.id()) - return; - - - - if (doc == m_pModel->toJsonDocument()) - { - - m_loadedSchemaId = data.id(); - retranslate(); - return; - } - - if (modType == DataModification::eAdded || modType == DataModification::eModified) - { - LtsWidgets::Button button = - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("A new schema is available. Do you wish to load this schema?"), - tr("Information"), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); - - if (button == LtsWidgets::Button::Yes) + if (!con) { - handleUnsentComments(); - - m_loadedSchemaId = data.id(); - m_pModel->fromQJsonDocument(doc); - expandNodeChildren(m_ui->m_treeViewSchema, QModelIndex(), true); - updateCommentLabel(); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("No Tetra radio, request failed!")); + return; } - } + + handleUnsentComments(); + + loadLatestSchema(); + + m_ui->m_pushButton_RequestSchema->setEnabled(false); + + QTimer::singleShot(3000, this, [this]() { m_ui->m_pushButton_RequestSchema->setEnabled(true); }); } - -void EditSchemaDialog::loadSchema(qint32 schemaId) +void EditSchemaDialog::onNotifyAboutSchema(const Evaluations::EvaluationSchema& data, DataModification modType) { - if (m_mapSchemata.size()) - { + if (m_ocMode && !data.sendToTa()) + return; + QJsonParseError jError; - const QJsonDocument doc(QJsonDocument::fromJson(m_mapSchemata[schemaId].schemadata().c_str(), &jError)); + const QJsonDocument doc(QJsonDocument::fromJson(data.schemadata().c_str(), &jError)); if (jError.error != QJsonParseError::NoError) { - WARNING_LOG(m_logger) << "Could not load schema with database id " << m_mapSchemata.last().id(); - return; + WARNING_LOG(m_logger) << "Could not parse schema with database id " << data.id(); + return; } - m_loadedSchemaId = schemaId; - m_pModel->fromQJsonDocument(doc); - beautifyTreeView(m_ui->m_treeViewSchema, m_pModel); + if (m_loadedSchemaId == data.id()) + return; - + if (doc == m_pModel->toJsonDocument()) + { - } + m_loadedSchemaId = data.id(); + retranslate(); + return; + } + + if (modType == DataModification::eAdded || modType == DataModification::eModified) + { + LtsWidgets::Button button = LtsWidgets::LtsMessageDialog::showMessage( + this, tr("A new schema is available. Do you wish to load this schema?"), tr("Information"), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); + + if (button == LtsWidgets::Button::Yes) + { + handleUnsentComments(); + + m_loadedSchemaId = data.id(); + m_pModel->fromQJsonDocument(doc); + expandNodeChildren(m_ui->m_treeViewSchema, QModelIndex(), true); + updateCommentLabel(); + } + } } +void EditSchemaDialog::loadSchema(qint32 schemaId) +{ + if (m_mapSchemata.size()) + { + QJsonParseError jError; + const QJsonDocument doc(QJsonDocument::fromJson(m_mapSchemata[schemaId].schemadata().c_str(), &jError)); + + if (jError.error != QJsonParseError::NoError) + { + WARNING_LOG(m_logger) << "Could not load schema with database id " << m_mapSchemata.last().id(); + return; + } + + m_loadedSchemaId = schemaId; + m_pModel->fromQJsonDocument(doc); + beautifyTreeView(m_ui->m_treeViewSchema, m_pModel); + } +} void EditSchemaDialog::DebugonLoadSchema() { - if (!m_mapSchemata.size()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("(DEBUG) No schemes in db available.")); - return; - } + if (!m_mapSchemata.size()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, QStringLiteral("(DEBUG) No schemes in db available.")); + return; + } - m_mapSchemata = m_evlDtc->evaluationSchemas(); - qint32 id = QInputDialog::getInt(this, QStringLiteral("Insert database id of desired schema"), QStringLiteral("Database id"), m_mapSchemata.last().id(), m_mapSchemata.first().id(), m_mapSchemata.last().id()); - loadSchema(id); + m_mapSchemata = m_evlDtc->evaluationSchemas(); + qint32 id = QInputDialog::getInt(this, QStringLiteral("Insert database id of desired schema"), + QStringLiteral("Database id"), m_mapSchemata.last().id(), + m_mapSchemata.first().id(), m_mapSchemata.last().id()); + loadSchema(id); } - -bool EditSchemaDialog::eventFilter(QObject *object, QEvent *event) +bool EditSchemaDialog::eventFilter(QObject* object, QEvent* event) { - if (object == m_ui->m_treeViewSchema && event->type() == QEvent::KeyPress) - { - QKeyEvent *pKeyEvent = static_cast(event); + if (object == m_ui->m_treeViewSchema && event->type() == QEvent::KeyPress) + { + QKeyEvent* pKeyEvent = static_cast(event); - if (pKeyEvent->key() == Qt::Key_Delete) - onRemoveSelectedElement(); - } + if (pKeyEvent->key() == Qt::Key_Delete) + onRemoveSelectedElement(); + } - return LtsWidgets::LtsDialog::eventFilter(object, event); + return LtsWidgets::LtsDialog::eventFilter(object, event); } - void EditSchemaDialog::onAddFolder() { - addEntry(true); + addEntry(true); } - void EditSchemaDialog::onAddRootFolder() { - addEntry(true, true); + addEntry(true, true); } - void EditSchemaDialog::onAddElement() { - addEntry(false); + addEntry(false); } - void EditSchemaDialog::addEntry(bool isFolder, bool isNewRoot) { - bool inputNotCancelled; - QString strText = QInputDialog::getText(this, tr("EXCON"), isFolder ? tr("Folder name:") : tr("Element name:"), QLineEdit::Normal, isFolder ? tr("New Folder") : tr("New element"), &inputNotCancelled); - if (!inputNotCancelled) - return; + bool inputNotCancelled; + QString strText = + QInputDialog::getText(this, tr("EXCON"), isFolder ? tr("Folder name:") : tr("Element name:"), QLineEdit::Normal, + isFolder ? tr("New Folder") : tr("New element"), &inputNotCancelled); + if (!inputNotCancelled) + return; - if (strText.isEmpty()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("You have to enter a description.")); - return; - } + if (strText.isEmpty()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("You have to enter a description.")); + return; + } - ElementData e(strText, isFolder); + ElementData e(strText, isFolder); - const QModelIndex idx = isNewRoot ? QModelIndex() : m_ui->m_treeViewSchema->currentIndex(); - m_pModel->insertElementData(idx, e); - beautifyTreeView(m_ui->m_treeViewSchema, m_pModel, idx); - slotChangesMade(); + const QModelIndex idx = isNewRoot ? QModelIndex() : m_ui->m_treeViewSchema->currentIndex(); + m_pModel->insertElementData(idx, e); + beautifyTreeView(m_ui->m_treeViewSchema, m_pModel, idx); + slotChangesMade(); } - void EditSchemaDialog::onRemoveSelectedElement() { - const QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + const QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - if (!idx.isValid()) - return; + if (!idx.isValid()) + return; - - - if (m_ocMode) - removeComment(idx); - else - removeEntry(idx); + if (m_ocMode) + removeComment(idx); + else + removeEntry(idx); } - -void EditSchemaDialog::removeEntry(const QModelIndex &idx) +void EditSchemaDialog::removeEntry(const QModelIndex& idx) { - bool isLastRoot = ((!idx.parent().isValid()) && (m_pModel->rowCount() == 1)); + bool isLastRoot = ((!idx.parent().isValid()) && (m_pModel->rowCount() == 1)); - if (isLastRoot) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("You can not remove the last root node.")); - return; - } + if (isLastRoot) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("You can not remove the last root node.")); + return; + } - LtsWidgets::Button button = LtsWidgets::Button::Yes; + LtsWidgets::Button button = LtsWidgets::Button::Yes; - if (m_pModel->hasChildren(idx)) - { - button = LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Selected folder contains elements. Do you really want to remove the selected folder?"), - tr("Information"), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); - } + if (m_pModel->hasChildren(idx)) + { + button = LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Selected folder contains elements. Do you really want to remove the selected folder?"), + tr("Information"), LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); + } - if (button == LtsWidgets::Button::Yes) - { - m_pModel->removeRow(idx, true); - slotChangesMade(); - } + if (button == LtsWidgets::Button::Yes) + { + m_pModel->removeRow(idx, true); + slotChangesMade(); + } } - -void EditSchemaDialog::removeComment(const QModelIndex &idx) +void EditSchemaDialog::removeComment(const QModelIndex& idx) { - - QVariant v = m_pModel->dataAsVariant(idx); - if (v.canConvert()) - { - ItemComment c = v.value(); - if (c.isSent()) - return; + QVariant v = m_pModel->dataAsVariant(idx); + if (v.canConvert()) + { + ItemComment c = v.value(); - m_pModel->removeComment(idx); - updateCommentLabel(); - } + if (c.isSent()) + return; + + m_pModel->removeComment(idx); + updateCommentLabel(); + } } - void EditSchemaDialog::saveSchema(bool sendToTa) { - EvlSchemaModifyRequest req; + EvlSchemaModifyRequest req; - bool schemaChanged = hasUnsavedChanges(); - req.id(schemaChanged ? 0 : m_loadedSchemaId); - req.sendToTa(sendToTa); + bool schemaChanged = hasUnsavedChanges(); + req.id(schemaChanged ? 0 : m_loadedSchemaId); + req.sendToTa(sendToTa); - QJsonDocument doc = m_pModel->toJsonDocument(); - req.schemadata(doc.toJson().constData()); + QJsonDocument doc = m_pModel->toJsonDocument(); + req.schemadata(doc.toJson().constData()); + m_requestHelper->addRequest([this, req, schemaChanged]() { + bool success = m_evlFtc->evlSchemaModifyRequest(req, this); - m_requestHelper->addRequest([this, req, schemaChanged]() - { - bool success = m_evlFtc->evlSchemaModifyRequest(req, this); + if (success && schemaChanged) + __unchange__(); - if (success && schemaChanged) - __unchange__(); + return success; + }); - return success; - }); - - m_requestHelper->startRequests(); + m_requestHelper->startRequests(); } - void EditSchemaDialog::onSendSchema() { - saveSchema(true); + saveSchema(true); } - void EditSchemaDialog::onCreateNewSchema() { - if (hasUnsavedChanges()) - { - LtsWidgets::Button button = - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Current schema has been modified. Do you want to save these changes?"), - tr("Information"), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); + if (hasUnsavedChanges()) + { + LtsWidgets::Button button = LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Current schema has been modified. Do you want to save these changes?"), tr("Information"), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); - if (button == LtsWidgets::Button::Yes) - apply(); - } + if (button == LtsWidgets::Button::Yes) + apply(); + } - - bool inputNotCancelled; - QString strFolderName = QInputDialog::getText(this, tr("EXCON"), tr("New root folder name:"), QLineEdit::Normal, tr(""), &inputNotCancelled); + bool inputNotCancelled; + QString strFolderName = QInputDialog::getText(this, tr("EXCON"), tr("New root folder name:"), QLineEdit::Normal, + tr(""), &inputNotCancelled); - if (strFolderName.isEmpty()) - strFolderName = tr(""); + if (strFolderName.isEmpty()) + strFolderName = tr(""); - m_pModel->resetModel(); + m_pModel->resetModel(); - QModelIndex root; - ElementData e(strFolderName); - m_pModel->insertElementData(root, e); - slotChangesMade(); + QModelIndex root; + ElementData e(strFolderName); + m_pModel->insertElementData(root, e); + slotChangesMade(); } - EditSchemaDialog::~EditSchemaDialog() { - delete m_ui; + delete m_ui; } - void EditSchemaDialog::retranslate() { - translate(m_ui, QString::number(m_loadedSchemaId), (m_loadedSchemaId < 1), m_ocMode ? tr("O/C Evaluations") : tr("O/C Evaluation Schemes")); + translate(m_ui, QString::number(m_loadedSchemaId), (m_loadedSchemaId < 1), + m_ocMode ? tr("O/C Evaluations") : tr("O/C Evaluation Schemes")); } - void EditSchemaDialog::onSendAllComments() { - QModelIndex root; - m_pModel->iterateModel(root, [this](const QModelIndex & idx, const QVariant & v) - { - Q_UNUSED(v); - sendComment(idx); - }); + QModelIndex root; + m_pModel->iterateModel(root, [this](const QModelIndex& idx, const QVariant& v) { + Q_UNUSED(v); + sendComment(idx); + }); - updateCommentLabel(); + updateCommentLabel(); } - void EditSchemaDialog::onSendComment() { - QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - sendComment(idx); + QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + sendComment(idx); } - -EvlCommentModifyRequest EditSchemaDialog::createEvlCommentModifyRequest(const ItemComment &c) const +EvlCommentModifyRequest EditSchemaDialog::createEvlCommentModifyRequest(const ItemComment& c) const { - EvlCommentModifyRequest req; - req.id(0); - req.ts(c.getTimeStamp().toMSecsSinceEpoch()); - req.senderOperatorId(c.senderId()); + EvlCommentModifyRequest req; + req.id(0); + req.ts(c.getTimeStamp().toMSecsSinceEpoch()); + req.senderOperatorId(c.senderId()); - if (c.hasReceiverId()) - req.receiverOperatorId(c.receiverId()); + if (c.hasReceiverId()) + req.receiverOperatorId(c.receiverId()); - req.text(c.getText().toStdString()); + req.text(c.getText().toStdString()); - req.hierarchy(c.getHierarchy().toStdString()); - req.schemaId(m_loadedSchemaId); - req.elementId(c.elementId()); - return req; + req.hierarchy(c.getHierarchy().toStdString()); + req.schemaId(m_loadedSchemaId); + req.elementId(c.elementId()); + return req; } - -OcSituationClient::SendEvaluationRequest EditSchemaDialog::createSendEvaluationRequest(const ItemComment &c) const +OcSituationClient::SendEvaluationRequest EditSchemaDialog::createSendEvaluationRequest(const ItemComment& c) const { - OcSituationClient::SendEvaluationRequest req; - req.timeStamp(c.getTimeStamp().toMSecsSinceEpoch()); - req.senderOperatorId(c.senderId()); + OcSituationClient::SendEvaluationRequest req; + req.timeStamp(c.getTimeStamp().toMSecsSinceEpoch()); + req.senderOperatorId(c.senderId()); - if (c.hasReceiverId()) - req.receiverOperatorId(c.receiverId()); + if (c.hasReceiverId()) + req.receiverOperatorId(c.receiverId()); - req.text(c.getText().toStdString()); + req.text(c.getText().toStdString()); - req.hierarchy(c.getHierarchy().toStdString()); - req.schemaId(m_loadedSchemaId); - - return req; + req.hierarchy(c.getHierarchy().toStdString()); + req.schemaId(m_loadedSchemaId); + + return req; } - -void EditSchemaDialog::markCommentAsSent(const QPersistentModelIndex &idx) +void EditSchemaDialog::markCommentAsSent(const QPersistentModelIndex& idx) { - QVariant v = m_pModel->dataAsVariant(idx); - ItemComment c = v.value(); - - c.markAsSent(); - m_pModel->updateComment(idx, c); - - - EvlCommentModifyRequest req = createEvlCommentModifyRequest(c); - m_requestHelper->addRequest([this, req]() - { - return m_evlFtc->evlCommentModifyRequest(req, this); - }); - - updateCommentLabel(); - m_ui->m_pushButton_SendComment->setEnabled(false); - m_ui->m_pushButton_EditComment->setEnabled(false); - m_ui->m_pushButton_RemoveComment->setEnabled(false); -} - - -void EditSchemaDialog::onSendEvaluationReply(const Core::FunctionReplyObject &replyObject) -{ - m_requestHelper->requestReply(replyObject); - - if (!replyObject.error()) - { - - markCommentAsSent(m_vecCommentsInSendState.front()); - - m_requestHelper->startRequests(); - } - - m_vecCommentsInSendState.pop_front(); -} - - -void EditSchemaDialog::sendComment(const QModelIndex &idx) -{ - QVariant v = m_pModel->dataAsVariant(idx); - - if (v.canConvert()) - { + QVariant v = m_pModel->dataAsVariant(idx); ItemComment c = v.value(); - if (c.isSent()) - return; + c.markAsSent(); + m_pModel->updateComment(idx, c); - - if (!m_runningOnTablet) - { - markCommentAsSent(idx); - return; - } + EvlCommentModifyRequest req = createEvlCommentModifyRequest(c); + m_requestHelper->addRequest([this, req]() { return m_evlFtc->evlCommentModifyRequest(req, this); }); - OcSituationClient::SendEvaluationRequest req = createSendEvaluationRequest(c); - - m_requestHelper->addRequest([this, &idx, req]() - { - bool commentSent = m_ocFtc->sendEvaluationRequest(req, this); - - if (commentSent) - { - - m_vecCommentsInSendState.push_back(idx); - } - - return commentSent; - }); - - - - - - m_requestHelper->startRequests(); - } + updateCommentLabel(); + m_ui->m_pushButton_SendComment->setEnabled(false); + m_ui->m_pushButton_EditComment->setEnabled(false); + m_ui->m_pushButton_RemoveComment->setEnabled(false); } +void EditSchemaDialog::onSendEvaluationReply(const Core::FunctionReplyObject& replyObject) +{ + m_requestHelper->requestReply(replyObject); + + if (!replyObject.error()) + { + + markCommentAsSent(m_vecCommentsInSendState.front()); + + m_requestHelper->startRequests(); + } + + m_vecCommentsInSendState.pop_front(); +} + +void EditSchemaDialog::sendComment(const QModelIndex& idx) +{ + QVariant v = m_pModel->dataAsVariant(idx); + + if (v.canConvert()) + { + ItemComment c = v.value(); + + if (c.isSent()) + return; + + if (!m_runningOnTablet) + { + markCommentAsSent(idx); + return; + } + + OcSituationClient::SendEvaluationRequest req = createSendEvaluationRequest(c); + + m_requestHelper->addRequest([this, &idx, req]() { + bool commentSent = m_ocFtc->sendEvaluationRequest(req, this); + + if (commentSent) + { + + m_vecCommentsInSendState.push_back(idx); + } + + return commentSent; + }); + + m_requestHelper->startRequests(); + } +} void EditSchemaDialog::updateCommentLabel() { - m_ui->m_labelComments->setText(QString(tr("Sent comments: %1/%2")).arg(QString::number(m_pModel->cntSentComments()), QString::number(m_pModel->cntComments()))); - m_ui->m_pushButton_SendAllComments->setEnabled(m_pModel->cntSentComments() < m_pModel->cntComments()); + m_ui->m_labelComments->setText( + QString(tr("Sent comments: %1/%2")) + .arg(QString::number(m_pModel->cntSentComments()), QString::number(m_pModel->cntComments()))); + m_ui->m_pushButton_SendAllComments->setEnabled(m_pModel->cntSentComments() < m_pModel->cntComments()); - if (m_pModel->cntSentComments() == m_pModel->cntComments()) - __unchange__(); + if (m_pModel->cntSentComments() == m_pModel->cntComments()) + __unchange__(); } - void EditSchemaDialog::onAddNewComment() { - if (m_commentDlg) - m_commentDlg->deleteLater(); + if (m_commentDlg) + m_commentDlg->deleteLater(); - m_commentDlg = new EvlNewCommentDialog(m_opmDtc, this); - connect(m_commentDlg, &EvlNewCommentDialog::accepted, this, &EditSchemaDialog::onCommentAccepted); - m_commentDlg->show(); + m_commentDlg = new EvlNewCommentDialog(m_opmDtc, this); + connect(m_commentDlg, &EvlNewCommentDialog::accepted, this, &EditSchemaDialog::onCommentAccepted); + m_commentDlg->show(); } - void EditSchemaDialog::onCommentAccepted() { - { - if (m_commentDlg->comment().isEmpty()) { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("No text entered. Comment has not been added!")); - return; + if (m_commentDlg->comment().isEmpty()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("No text entered. Comment has not been added!")); + return; + } + + QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + + QVector vecHierachy = m_pModel->getSelectedIndexHierarchy(idx); + QString strHierarchy; + + for (int i = 0; i < vecHierachy.size() - 1; ++i) + strHierarchy += vecHierachy[i] + QStringLiteral(", "); + strHierarchy += vecHierachy.last(); + + ElementData e = m_pModel->getSelectedIndexDataAsElement(idx); + ItemComment c(m_commentDlg->comment(), LtsSessionData::LtsSessionData::getInstance()->getOperatorId(), + m_commentDlg->selectedReceiverId(), e.m_id, strHierarchy); + + QModelIndex idxNewComment = m_pModel->insertComment(idx, c); + + if (m_commentDlg->autoSend()) + sendComment(idxNewComment); + + updateCommentLabel(); + slotChangesMade(); } - - QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - - QVector vecHierachy = m_pModel->getSelectedIndexHierarchy(idx); - QString strHierarchy; - - for (int i = 0; i < vecHierachy.size() - 1; ++i) - strHierarchy += vecHierachy[i] + QStringLiteral(", "); - strHierarchy += vecHierachy.last(); - - ElementData e = m_pModel->getSelectedIndexDataAsElement(idx); - ItemComment c(m_commentDlg->comment(), LtsSessionData::LtsSessionData::getInstance()->getOperatorId(), m_commentDlg->selectedReceiverId(), e.m_id, strHierarchy); - - QModelIndex idxNewComment = m_pModel->insertComment(idx, c); - - if (m_commentDlg->autoSend()) - sendComment(idxNewComment); - - updateCommentLabel(); - slotChangesMade(); - } } - void EditSchemaDialog::onTreeViewDoubleClicked() { - if (m_ocMode) - onEditComment(); - else - onModifySelectedEntry(); + if (m_ocMode) + onEditComment(); + else + onModifySelectedEntry(); } - void EditSchemaDialog::onEditComment() { - QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - QVariant v = m_pModel->dataAsVariant(idx); + QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + QVariant v = m_pModel->dataAsVariant(idx); - if (v.canConvert()) - { - ItemComment c = v.value(); + if (v.canConvert()) + { + ItemComment c = v.value(); - if (c.isSent()) - return; + if (c.isSent()) + return; - if (m_commentDlg) - m_commentDlg->deleteLater(); + if (m_commentDlg) + m_commentDlg->deleteLater(); - m_commentDlg = new EvlNewCommentDialog(m_opmDtc, this); - m_commentDlg->setAsEditComment(c.getText()); - connect(m_commentDlg, &EvlNewCommentDialog::accepted, this, &EditSchemaDialog::onCommentEditAccepted); - m_commentDlg->show(); - - } + m_commentDlg = new EvlNewCommentDialog(m_opmDtc, this); + m_commentDlg->setAsEditComment(c.getText()); + connect(m_commentDlg, &EvlNewCommentDialog::accepted, this, &EditSchemaDialog::onCommentEditAccepted); + m_commentDlg->show(); + } } void EditSchemaDialog::onCommentEditAccepted() { - QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - QVariant v = m_pModel->dataAsVariant(idx); - if (v.canConvert()) - { - ItemComment c = v.value(); - c.setText(m_commentDlg->comment()); - m_pModel->updateComment(idx, c); - } + QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + QVariant v = m_pModel->dataAsVariant(idx); + if (v.canConvert()) + { + ItemComment c = v.value(); + c.setText(m_commentDlg->comment()); + m_pModel->updateComment(idx, c); + } } void EditSchemaDialog::onModifySelectedEntry() { - QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); - ElementData e = m_pModel->getSelectedIndexDataAsElement(idx); + QModelIndex idx = m_ui->m_treeViewSchema->currentIndex(); + ElementData e = m_pModel->getSelectedIndexDataAsElement(idx); - bool inputNotCancelled; - QString strText = QInputDialog::getText(this, tr("EXCON"), e.isFolder() ? tr("Modify folder name:") : tr("Modify element name:"), QLineEdit::Normal, e.getText(), &inputNotCancelled); - if (!inputNotCancelled) - return; - - if (strText.isEmpty()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("You have to enter a description.")); - return; - } - - e.setText(strText); - m_pModel->updateElementData(idx, e); - slotChangesMade(); -} - - -void EditSchemaDialog::onTreeViewModelIndexChanged(const QModelIndex &curr) -{ - bool indexValid = curr.isValid(); - - if (m_ocMode) - { - m_ui->m_pushButton_SendComment->setEnabled(false); - m_ui->m_pushButton_NewComment->setEnabled(false); - m_ui->m_pushButton_EditComment->setEnabled(false); - m_ui->m_pushButton_RemoveComment->setEnabled(false); - - if (indexValid) - { - QVariant v = m_pModel->dataAsVariant(curr); - - if (v.canConvert()) - m_ui->m_pushButton_NewComment->setEnabled(!v.value().isFolder()); - else if (v.canConvert()) - { - if (!v.value().isSent()) - { - m_ui->m_pushButton_SendComment->setEnabled(true); - m_ui->m_pushButton_EditComment->setEnabled(true); - m_ui->m_pushButton_RemoveComment->setEnabled(true); - } - } - } - } - else - { - ElementData e = m_pModel->getSelectedIndexDataAsElement(curr); - - m_ui->m_pushButton_AddElement->setEnabled(indexValid && e.isFolder()); - m_ui->m_pushButton_AddFolder->setEnabled(indexValid && e.isFolder()); - m_ui->m_pushButton_Modify->setEnabled(indexValid); - m_ui->m_pushButton_Remove->setEnabled(indexValid); - - if (indexValid) - m_ui->m_treeViewSchema->selectionModel()->setCurrentIndex(curr, QItemSelectionModel::SelectCurrent); - } -} - - -void EditSchemaDialog::onTriedToDropFolderToElement() -{ - LtsWidgets::LtsMessageDialog::showMessage(this, tr("It is not possible to append folders to elements.")); -} - - -void EditSchemaDialog::onDropActionFinished(const QModelIndex &parent) -{ - beautifyTreeView(m_ui->m_treeViewSchema, m_pModel, parent); - slotChangesMade(); -} - - -bool EditSchemaDialog::apply() -{ - if (m_ocMode) - onSendAllComments(); - else - { - LtsWidgets::Button button = LtsWidgets::LtsMessageDialog::showMessage(this, tr("Do you want to update the training area?"), QString(), - LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes | LtsWidgets::Button::No); - - bool sendToTA = (button == LtsWidgets::Button::Yes); - saveSchema(sendToTA); - } - return true; -} - - -void EditSchemaDialog::onLoadFromLibrary() -{ - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::EvaluationSchema}, m_session->exerciseId()); - if (fileId > 0) - { - QJsonParseError jError; - const QJsonDocument doc(QJsonDocument::fromJson(content, &jError)); - if (jError.error != QJsonParseError::NoError) - { - WARNING_LOG(m_logger) << "Could not parse schema !"; - return; - } - if (!m_pModel->fromQJsonDocument(doc)) - { - WARNING_LOG(m_logger) << "Could not load schema !"; - return; - } - - beautifyTreeView(m_ui->m_treeViewSchema, m_pModel); - slotChangesMade(); - } - else - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Loading schema from library failed!")); - } -} - - -bool EditSchemaDialog::onSaveToLibrary() -{ - QByteArray byteArray = m_pModel->toJsonDocument().toJson(); - - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::EvaluationSchema, m_session->exerciseId(), byteArray); - if (fileId > 0) - { - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - return true; - } - else - ERROR_LOG(m_logger) << "Could not save file in library "; - - return false; -} - -void EditSchemaDialog::onShowContextMenu(const QPoint &position) -{ - QTreeView *tv = qobject_cast(sender()); - if (!tv) - return; - const QModelIndex idx = tv->currentIndex(); - if (!idx.isValid()) - return; - - QMenu menu; - - if (!m_ocMode) - { - ElementData d = m_pModel->getSelectedIndexDataAsElement(idx); - - if (d.isFolder()) - { - QAction *pActionAddElement = new QAction(tr("Add element"), &menu); - connect(pActionAddElement, &QAction::triggered, this, &EditSchemaDialog::onAddElement); - menu.addAction(pActionAddElement); - - QAction *pActionAddFolder = new QAction(tr("Add folder"), &menu); - connect(pActionAddFolder, &QAction::triggered, this, &EditSchemaDialog::onAddFolder); - menu.addAction(pActionAddFolder); - } - - QAction *pActionRemove = new QAction(tr("Remove"), &menu); - connect(pActionRemove, &QAction::triggered, this, &EditSchemaDialog::onRemoveSelectedElement); - menu.addAction(pActionRemove); - } - else - { - QVariant v = m_pModel->dataAsVariant(idx); - - if (v.canConvert() && !v.value().isFolder()) - { - QAction *pActionNewComment = new QAction(tr("New comment"), &menu); - connect(pActionNewComment, &QAction::triggered, this, &EditSchemaDialog::onAddNewComment); - menu.addAction(pActionNewComment); - } - else if (v.canConvert()) - { - ItemComment c = v.value(); - if (c.isSent()) + bool inputNotCancelled; + QString strText = + QInputDialog::getText(this, tr("EXCON"), e.isFolder() ? tr("Modify folder name:") : tr("Modify element name:"), + QLineEdit::Normal, e.getText(), &inputNotCancelled); + if (!inputNotCancelled) return; - QAction *pActionSendComment = new QAction(tr("Send comment"), &menu); - connect(pActionSendComment, &QAction::triggered, this, &EditSchemaDialog::onSendComment); - menu.addAction(pActionSendComment); - - QAction *pActionEditComment = new QAction(tr("Edit comment"), &menu); - connect(pActionEditComment, &QAction::triggered, this, &EditSchemaDialog::onEditComment); - menu.addAction(pActionEditComment); - - QAction *pActionRemove = new QAction(tr("Remove comment"), &menu); - connect(pActionRemove, &QAction::triggered, this, &EditSchemaDialog::onRemoveSelectedElement); - menu.addAction(pActionRemove); - } - } - - - if (m_pModel->rowCount(idx) != 0) - { - menu.addSeparator(); - - if (tv->isExpanded(idx)) + if (strText.isEmpty()) { - QAction *collapseAction = new QAction(tr("Collapse"), &menu); - connect(collapseAction, &QAction::triggered, this, [tv, idx]() { tv->collapse(idx);}); - menu.addAction(collapseAction); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("You have to enter a description.")); + return; + } - QAction *collapseAllAction = new QAction(tr("Collapse all"), &menu); - connect(collapseAllAction, &QAction::triggered, this, [tv, idx]() { expandNodeChildren(tv, idx, false); }); - menu.addAction(collapseAllAction); + e.setText(strText); + m_pModel->updateElementData(idx, e); + slotChangesMade(); +} + +void EditSchemaDialog::onTreeViewModelIndexChanged(const QModelIndex& curr) +{ + bool indexValid = curr.isValid(); + + if (m_ocMode) + { + m_ui->m_pushButton_SendComment->setEnabled(false); + m_ui->m_pushButton_NewComment->setEnabled(false); + m_ui->m_pushButton_EditComment->setEnabled(false); + m_ui->m_pushButton_RemoveComment->setEnabled(false); + + if (indexValid) + { + QVariant v = m_pModel->dataAsVariant(curr); + + if (v.canConvert()) + m_ui->m_pushButton_NewComment->setEnabled(!v.value().isFolder()); + else if (v.canConvert()) + { + if (!v.value().isSent()) + { + m_ui->m_pushButton_SendComment->setEnabled(true); + m_ui->m_pushButton_EditComment->setEnabled(true); + m_ui->m_pushButton_RemoveComment->setEnabled(true); + } + } + } } else { - QAction *expandAction = new QAction(tr("Expand"), &menu); - connect(expandAction, &QAction::triggered, this, [tv, idx]() { tv->expand(idx);}); - menu.addAction(expandAction); + ElementData e = m_pModel->getSelectedIndexDataAsElement(curr); + + m_ui->m_pushButton_AddElement->setEnabled(indexValid && e.isFolder()); + m_ui->m_pushButton_AddFolder->setEnabled(indexValid && e.isFolder()); + m_ui->m_pushButton_Modify->setEnabled(indexValid); + m_ui->m_pushButton_Remove->setEnabled(indexValid); + + if (indexValid) + m_ui->m_treeViewSchema->selectionModel()->setCurrentIndex(curr, QItemSelectionModel::SelectCurrent); } - - QAction *expandAllAction = new QAction(tr("Expand all"), &menu); - connect(expandAllAction, &QAction::triggered, this, [tv, idx]() { expandNodeChildren(tv, idx, true); }); - menu.addAction(expandAllAction); - } - - menu.exec(tv->viewport()->mapToGlobal(position)); } +void EditSchemaDialog::onTriedToDropFolderToElement() +{ + LtsWidgets::LtsMessageDialog::showMessage(this, tr("It is not possible to append folders to elements.")); +} +void EditSchemaDialog::onDropActionFinished(const QModelIndex& parent) +{ + beautifyTreeView(m_ui->m_treeViewSchema, m_pModel, parent); + slotChangesMade(); +} + +bool EditSchemaDialog::apply() +{ + if (m_ocMode) + onSendAllComments(); + else + { + LtsWidgets::Button button = LtsWidgets::LtsMessageDialog::showMessage( + this, tr("Do you want to update the training area?"), QString(), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No); + + bool sendToTA = (button == LtsWidgets::Button::Yes); + saveSchema(sendToTA); + } + return true; +} + +void EditSchemaDialog::onLoadFromLibrary() +{ + QByteArray content; + int fileId = + m_flmGui->loadFileContent(this, content, {FileManagement::FileType::EvaluationSchema}, m_session->exerciseId()); + if (fileId > 0) + { + QJsonParseError jError; + const QJsonDocument doc(QJsonDocument::fromJson(content, &jError)); + if (jError.error != QJsonParseError::NoError) + { + WARNING_LOG(m_logger) << "Could not parse schema !"; + return; + } + if (!m_pModel->fromQJsonDocument(doc)) + { + WARNING_LOG(m_logger) << "Could not load schema !"; + return; + } + + beautifyTreeView(m_ui->m_treeViewSchema, m_pModel); + slotChangesMade(); + } + else + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Loading schema from library failed!")); + } +} + +bool EditSchemaDialog::onSaveToLibrary() +{ + QByteArray byteArray = m_pModel->toJsonDocument().toJson(); + + int fileId = + m_flmGui->saveFileContent(this, FileManagement::FileType::EvaluationSchema, m_session->exerciseId(), byteArray); + if (fileId > 0) + { + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + return true; + } + else + ERROR_LOG(m_logger) << "Could not save file in library "; + + return false; +} + +void EditSchemaDialog::onShowContextMenu(const QPoint& position) +{ + QTreeView* tv = qobject_cast(sender()); + if (!tv) + return; + const QModelIndex idx = tv->currentIndex(); + if (!idx.isValid()) + return; + + QMenu menu; + + if (!m_ocMode) + { + ElementData d = m_pModel->getSelectedIndexDataAsElement(idx); + + if (d.isFolder()) + { + QAction* pActionAddElement = new QAction(tr("Add element"), &menu); + connect(pActionAddElement, &QAction::triggered, this, &EditSchemaDialog::onAddElement); + menu.addAction(pActionAddElement); + + QAction* pActionAddFolder = new QAction(tr("Add folder"), &menu); + connect(pActionAddFolder, &QAction::triggered, this, &EditSchemaDialog::onAddFolder); + menu.addAction(pActionAddFolder); + } + + QAction* pActionRemove = new QAction(tr("Remove"), &menu); + connect(pActionRemove, &QAction::triggered, this, &EditSchemaDialog::onRemoveSelectedElement); + menu.addAction(pActionRemove); + } + else + { + QVariant v = m_pModel->dataAsVariant(idx); + + if (v.canConvert() && !v.value().isFolder()) + { + QAction* pActionNewComment = new QAction(tr("New comment"), &menu); + connect(pActionNewComment, &QAction::triggered, this, &EditSchemaDialog::onAddNewComment); + menu.addAction(pActionNewComment); + } + else if (v.canConvert()) + { + ItemComment c = v.value(); + if (c.isSent()) + return; + + QAction* pActionSendComment = new QAction(tr("Send comment"), &menu); + connect(pActionSendComment, &QAction::triggered, this, &EditSchemaDialog::onSendComment); + menu.addAction(pActionSendComment); + + QAction* pActionEditComment = new QAction(tr("Edit comment"), &menu); + connect(pActionEditComment, &QAction::triggered, this, &EditSchemaDialog::onEditComment); + menu.addAction(pActionEditComment); + + QAction* pActionRemove = new QAction(tr("Remove comment"), &menu); + connect(pActionRemove, &QAction::triggered, this, &EditSchemaDialog::onRemoveSelectedElement); + menu.addAction(pActionRemove); + } + } + + if (m_pModel->rowCount(idx) != 0) + { + menu.addSeparator(); + + if (tv->isExpanded(idx)) + { + QAction* collapseAction = new QAction(tr("Collapse"), &menu); + connect(collapseAction, &QAction::triggered, this, [tv, idx]() { tv->collapse(idx); }); + menu.addAction(collapseAction); + + QAction* collapseAllAction = new QAction(tr("Collapse all"), &menu); + connect(collapseAllAction, &QAction::triggered, this, [tv, idx]() { expandNodeChildren(tv, idx, false); }); + menu.addAction(collapseAllAction); + } + else + { + QAction* expandAction = new QAction(tr("Expand"), &menu); + connect(expandAction, &QAction::triggered, this, [tv, idx]() { tv->expand(idx); }); + menu.addAction(expandAction); + } + + QAction* expandAllAction = new QAction(tr("Expand all"), &menu); + connect(expandAllAction, &QAction::triggered, this, [tv, idx]() { expandNodeChildren(tv, idx, true); }); + menu.addAction(expandAllAction); + } + + menu.exec(tv->viewport()->mapToGlobal(position)); +} void EditSchemaDialog::createExampleSchema() { - QModelIndex root; + QModelIndex root; - - ElementData e(QStringLiteral("Dokumentation")); - QModelIndex idxDoku = m_pModel->insertElementData(root, e); + ElementData e(QStringLiteral("Dokumentation")); + QModelIndex idxDoku = m_pModel->insertElementData(root, e); + e.setText(QStringLiteral("Taktik")); + QModelIndex idxDokuTaktik = m_pModel->insertElementData(idxDoku, e); + e.setText(QStringLiteral("Stellungen")); + QModelIndex idxDokuTaktikStellungen = m_pModel->insertElementData(idxDokuTaktik, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Erkundung")); + m_pModel->insertElementData(idxDokuTaktikStellungen, e); + e.setText(QStringLiteral("Ausbau")); + m_pModel->insertElementData(idxDokuTaktikStellungen, e); - - e.setText(QStringLiteral("Taktik")); - QModelIndex idxDokuTaktik = m_pModel->insertElementData(idxDoku, e); - e.setText(QStringLiteral("Stellungen")); - QModelIndex idxDokuTaktikStellungen = m_pModel->insertElementData(idxDokuTaktik, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Erkundung")); - m_pModel->insertElementData(idxDokuTaktikStellungen, e); - e.setText(QStringLiteral("Ausbau")); - m_pModel->insertElementData(idxDokuTaktikStellungen, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Verhalten")); + QModelIndex idxDokuTaktikVerhalten = m_pModel->insertElementData(idxDokuTaktik, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Geländeausnutzung")); + m_pModel->insertElementData(idxDokuTaktikVerhalten, e); + e.setText(QStringLiteral("Tarnung")); + m_pModel->insertElementData(idxDokuTaktikVerhalten, e); + e.setText(QStringLiteral("Geräuschdisziplin")); + m_pModel->insertElementData(idxDokuTaktikVerhalten, e); + e.setText(QStringLiteral("Beleuchtungsdisziplin")); + m_pModel->insertElementData(idxDokuTaktikVerhalten, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Verbindung")); + QModelIndex idxDokuTaktikVerbindung = m_pModel->insertElementData(idxDokuTaktik, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Verbindung halten")); + m_pModel->insertElementData(idxDokuTaktikVerbindung, e); + e.setText(QStringLiteral("Zeichendurchgabe")); + m_pModel->insertElementData(idxDokuTaktikVerbindung, e); - e.markAsFolder(true); - e.setText(QStringLiteral("Verhalten")); - QModelIndex idxDokuTaktikVerhalten = m_pModel->insertElementData(idxDokuTaktik, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Geländeausnutzung")); - m_pModel->insertElementData(idxDokuTaktikVerhalten, e); - e.setText(QStringLiteral("Tarnung")); - m_pModel->insertElementData(idxDokuTaktikVerhalten, e); - e.setText(QStringLiteral("Geräuschdisziplin")); - m_pModel->insertElementData(idxDokuTaktikVerhalten, e); - e.setText(QStringLiteral("Beleuchtungsdisziplin")); - m_pModel->insertElementData(idxDokuTaktikVerhalten, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Befehle und Meldungen")); + QModelIndex idxBefMeld = m_pModel->insertElementData(idxDoku, e); - e.markAsFolder(true); - e.setText(QStringLiteral("Verbindung")); - QModelIndex idxDokuTaktikVerbindung = m_pModel->insertElementData(idxDokuTaktik, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Verbindung halten")); - m_pModel->insertElementData(idxDokuTaktikVerbindung, e); - e.setText(QStringLiteral("Zeichendurchgabe")); - m_pModel->insertElementData(idxDokuTaktikVerbindung, e); + e.setText(QStringLiteral("Befehlsgebung")); + QModelIndex idxBefGeb = m_pModel->insertElementData(idxBefMeld, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Mündliche Befehlsausgaben")); + m_pModel->insertElementData(idxBefGeb, e); + e.setText(QStringLiteral("Absprachen")); + m_pModel->insertElementData(idxBefGeb, e); + e.setText(QStringLiteral("Ergebnisvortrag")); + m_pModel->insertElementData(idxBefGeb, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Befehle und Meldungen")); - QModelIndex idxBefMeld = m_pModel->insertElementData(idxDoku, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Verteilung und Zuführung")); + QModelIndex idxVerZuf = m_pModel->insertElementData(idxBefMeld, e); - e.setText(QStringLiteral("Befehlsgebung")); - QModelIndex idxBefGeb = m_pModel->insertElementData(idxBefMeld, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Befehle")); + m_pModel->insertElementData(idxVerZuf, e); + e.setText(QStringLiteral("Pläne")); + m_pModel->insertElementData(idxVerZuf, e); + e.setText(QStringLiteral("Meldungen")); + m_pModel->insertElementData(idxVerZuf, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Mündliche Befehlsausgaben")); - m_pModel->insertElementData(idxBefGeb, e); - e.setText(QStringLiteral("Absprachen")); - m_pModel->insertElementData(idxBefGeb, e); - e.setText(QStringLiteral("Ergebnisvortrag")); - m_pModel->insertElementData(idxBefGeb, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Logistische Versorgung")); + QModelIndex idxLogVer = m_pModel->insertElementData(idxDoku, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Betriebsstoff")); + m_pModel->insertElementData(idxLogVer, e); + e.setText(QStringLiteral("Munition")); + m_pModel->insertElementData(idxLogVer, e); + e.setText(QStringLiteral("Verpflegung")); + m_pModel->insertElementData(idxLogVer, e); + e.setText(QStringLiteral("NVG")); + m_pModel->insertElementData(idxLogVer, e); + e.setText(QStringLiteral("EVG")); + m_pModel->insertElementData(idxLogVer, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Sanitätsdienst")); + QModelIndex idxSani = m_pModel->insertElementData(idxDoku, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Versorgung")); + m_pModel->insertElementData(idxSani, e); + e.setText(QStringLiteral("Kameradenhilfe")); + m_pModel->insertElementData(idxSani, e); - e.markAsFolder(true); - e.setText(QStringLiteral("Verteilung und Zuführung")); - QModelIndex idxVerZuf = m_pModel->insertElementData(idxBefMeld, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Instandsetzung")); + QModelIndex idxInstand = m_pModel->insertElementData(idxDoku, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Bergung")); + m_pModel->insertElementData(idxInstand, e); + e.setText(QStringLiteral("Instandsetzung")); + m_pModel->insertElementData(idxInstand, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Befehle")); - m_pModel->insertElementData(idxVerZuf, e); - e.setText(QStringLiteral("Pläne")); - m_pModel->insertElementData(idxVerZuf, e); - e.setText(QStringLiteral("Meldungen")); - m_pModel->insertElementData(idxVerZuf, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Beurteilung")); + QModelIndex idxEval = m_pModel->insertElementData(root, e); + e.setText(QStringLiteral("Taktik")); + QModelIndex idxEvlTakt = m_pModel->insertElementData(idxEval, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Logistische Versorgung")); - QModelIndex idxLogVer = m_pModel->insertElementData(idxDoku, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Betriebsstoff")); - m_pModel->insertElementData(idxLogVer, e); - e.setText(QStringLiteral("Munition")); - m_pModel->insertElementData(idxLogVer, e); - e.setText(QStringLiteral("Verpflegung")); - m_pModel->insertElementData(idxLogVer, e); - e.setText(QStringLiteral("NVG")); - m_pModel->insertElementData(idxLogVer, e); - e.setText(QStringLiteral("EVG")); - m_pModel->insertElementData(idxLogVer, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Führung")); + QModelIndex idxEvlTaktFuehr = m_pModel->insertElementData(idxEvlTakt, e); + e.markAsFolder(false); + e.setText(QStringLiteral("gut")); + m_pModel->insertElementData(idxEvlTaktFuehr, e); + e.setText(QStringLiteral("mittel")); + m_pModel->insertElementData(idxEvlTaktFuehr, e); + e.setText(QStringLiteral("schlecht")); + m_pModel->insertElementData(idxEvlTaktFuehr, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Planung")); + QModelIndex idxEvlTaktPlan = m_pModel->insertElementData(idxEvlTakt, e); + e.markAsFolder(false); + e.setText(QStringLiteral("gut")); + m_pModel->insertElementData(idxEvlTaktPlan, e); + e.setText(QStringLiteral("planlos")); + m_pModel->insertElementData(idxEvlTaktPlan, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Sanitätsdienst")); - QModelIndex idxSani = m_pModel->insertElementData(idxDoku, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Versorgung")); - m_pModel->insertElementData(idxSani, e); - e.setText(QStringLiteral("Kameradenhilfe")); - m_pModel->insertElementData(idxSani, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Koordination")); + QModelIndex idxEvlTaktKoord = m_pModel->insertElementData(idxEvlTakt, e); + e.markAsFolder(false); + e.setText(QStringLiteral("vorhanden")); + m_pModel->insertElementData(idxEvlTaktKoord, e); + e.setText(QStringLiteral("nicht vorhanden")); + m_pModel->insertElementData(idxEvlTaktKoord, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Feindlage")); + QModelIndex idxEvlTaktFeind = m_pModel->insertElementData(idxEvlTakt, e); + e.markAsFolder(false); + e.setText(QStringLiteral("berücksichtigt")); + m_pModel->insertElementData(idxEvlTaktFeind, e); + e.setText(QStringLiteral("falsch eingeschätzt")); + m_pModel->insertElementData(idxEvlTaktFeind, e); + e.setText(QStringLiteral("nicht erkannt")); + m_pModel->insertElementData(idxEvlTaktFeind, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Instandsetzung")); - QModelIndex idxInstand = m_pModel->insertElementData(idxDoku, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Bergung")); - m_pModel->insertElementData(idxInstand, e); - e.setText(QStringLiteral("Instandsetzung")); - m_pModel->insertElementData(idxInstand, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Meldewesen")); + QModelIndex idxEvlMeld = m_pModel->insertElementData(idxEval, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Bataillon zu Brigade")); + m_pModel->insertElementData(idxEvlMeld, e); + e.setText(QStringLiteral("Ebene Teileinheit")); + m_pModel->insertElementData(idxEvlMeld, e); + e.setText(QStringLiteral("Effektivität")); + m_pModel->insertElementData(idxEvlMeld, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Sperren")); + QModelIndex idxEvlSperr = m_pModel->insertElementData(idxEval, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Verlegen")); + m_pModel->insertElementData(idxEvlSperr, e); + e.setText(QStringLiteral("Räumen")); + m_pModel->insertElementData(idxEvlSperr, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Beurteilung")); - QModelIndex idxEval = m_pModel->insertElementData(root, e); + e.markAsFolder(true); + e.setText(QStringLiteral("ABC-Abwehr")); + QModelIndex idxEvlABC = m_pModel->insertElementData(idxEval, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Schutz")); + m_pModel->insertElementData(idxEvlABC, e); + e.setText(QStringLiteral("Aufklärung")); + m_pModel->insertElementData(idxEvlABC, e); - - - e.setText(QStringLiteral("Taktik")); - QModelIndex idxEvlTakt = m_pModel->insertElementData(idxEval, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Führung")); - QModelIndex idxEvlTaktFuehr = m_pModel->insertElementData(idxEvlTakt, e); - e.markAsFolder(false); - e.setText(QStringLiteral("gut")); - m_pModel->insertElementData(idxEvlTaktFuehr, e); - e.setText(QStringLiteral("mittel")); - m_pModel->insertElementData(idxEvlTaktFuehr, e); - e.setText(QStringLiteral("schlecht")); - m_pModel->insertElementData(idxEvlTaktFuehr, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Planung")); - QModelIndex idxEvlTaktPlan = m_pModel->insertElementData(idxEvlTakt, e); - e.markAsFolder(false); - e.setText(QStringLiteral("gut")); - m_pModel->insertElementData(idxEvlTaktPlan, e); - e.setText(QStringLiteral("planlos")); - m_pModel->insertElementData(idxEvlTaktPlan, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Koordination")); - QModelIndex idxEvlTaktKoord = m_pModel->insertElementData(idxEvlTakt, e); - e.markAsFolder(false); - e.setText(QStringLiteral("vorhanden")); - m_pModel->insertElementData(idxEvlTaktKoord, e); - e.setText(QStringLiteral("nicht vorhanden")); - m_pModel->insertElementData(idxEvlTaktKoord, e); - - e.markAsFolder(true); - e.setText(QStringLiteral("Feindlage")); - QModelIndex idxEvlTaktFeind = m_pModel->insertElementData(idxEvlTakt, e); - e.markAsFolder(false); - e.setText(QStringLiteral("berücksichtigt")); - m_pModel->insertElementData(idxEvlTaktFeind, e); - e.setText(QStringLiteral("falsch eingeschätzt")); - m_pModel->insertElementData(idxEvlTaktFeind, e); - e.setText(QStringLiteral("nicht erkannt")); - m_pModel->insertElementData(idxEvlTaktFeind, e); - - - - e.markAsFolder(true); - e.setText(QStringLiteral("Meldewesen")); - QModelIndex idxEvlMeld = m_pModel->insertElementData(idxEval, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Bataillon zu Brigade")); - m_pModel->insertElementData(idxEvlMeld, e); - e.setText(QStringLiteral("Ebene Teileinheit")); - m_pModel->insertElementData(idxEvlMeld, e); - e.setText(QStringLiteral("Effektivität")); - m_pModel->insertElementData(idxEvlMeld, e); - - - - e.markAsFolder(true); - e.setText(QStringLiteral("Sperren")); - QModelIndex idxEvlSperr = m_pModel->insertElementData(idxEval, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Verlegen")); - m_pModel->insertElementData(idxEvlSperr, e); - e.setText(QStringLiteral("Räumen")); - m_pModel->insertElementData(idxEvlSperr, e); - - - - e.markAsFolder(true); - e.setText(QStringLiteral("ABC-Abwehr")); - QModelIndex idxEvlABC = m_pModel->insertElementData(idxEval, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Schutz")); - m_pModel->insertElementData(idxEvlABC, e); - e.setText(QStringLiteral("Aufklärung")); - m_pModel->insertElementData(idxEvlABC, e); - - - - e.markAsFolder(true); - e.setText(QStringLiteral("Hilfsmaßnahmen")); - QModelIndex idxEvlHilf = m_pModel->insertElementData(idxEval, e); - e.markAsFolder(false); - e.setText(QStringLiteral("Versorgungsabläufe")); - m_pModel->insertElementData(idxEvlHilf, e); - e.setText(QStringLiteral("Instandsetzung")); - m_pModel->insertElementData(idxEvlHilf, e); - e.setText(QStringLiteral("Sanitätsdienst")); - m_pModel->insertElementData(idxEvlHilf, e); + e.markAsFolder(true); + e.setText(QStringLiteral("Hilfsmaßnahmen")); + QModelIndex idxEvlHilf = m_pModel->insertElementData(idxEval, e); + e.markAsFolder(false); + e.setText(QStringLiteral("Versorgungsabläufe")); + m_pModel->insertElementData(idxEvlHilf, e); + e.setText(QStringLiteral("Instandsetzung")); + m_pModel->insertElementData(idxEvlHilf, e); + e.setText(QStringLiteral("Sanitätsdienst")); + m_pModel->insertElementData(idxEvlHilf, e); } -} - +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.h old mode 100755 new mode 100644 index 1402be97b..285f93a1a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_schema.h @@ -2,137 +2,142 @@ #pragma once -#include +#include "evl_edit_treemodel_schema.h" + #include #include -#include +#include #include #include -#include -#include -#include -#include -#include #include - -#include "evl_edit_treemodel_schema.h" +#include +#include +#include +#include +#include +#include namespace Ui { class EditSchemaDialog; } - namespace Evaluations { class EvlNewCommentDialog; -class EditSchemaDialog : public LtsWidgets::LtsDialog - , protected Interface::Ftc::EvlCommentModifyReplyHandler - , protected Interface::Ftc::EvlSchemaModifyReplyHandler - , protected FileManagement::Interface::Ftc::FileContentModifyReplyHandler - , protected OcSituationClient::Interface::Ftc::SendEvaluationReplyHandler +class EditSchemaDialog : public LtsWidgets::LtsDialog, + protected Interface::Ftc::EvlCommentModifyReplyHandler, + protected Interface::Ftc::EvlSchemaModifyReplyHandler, + protected FileManagement::Interface::Ftc::FileContentModifyReplyHandler, + protected OcSituationClient::Interface::Ftc::SendEvaluationReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit EditSchemaDialog(bool ocMode, bool runningOnTablet, LtsSession::LtsSession *session, QWidget *parent = nullptr); - ~EditSchemaDialog(); + public: + explicit EditSchemaDialog(bool ocMode, bool runningOnTablet, LtsSession::LtsSession* session, + QWidget* parent = nullptr); + ~EditSchemaDialog(); - bool init(const std::shared_ptr &ocFtc, - const std::shared_ptr &evlFtc, - const std::shared_ptr &evlDtc, - const std::shared_ptr &opmDtc, - const std::shared_ptr &flmFtc, - const std::shared_ptr &flmDtc, - const std::shared_ptr &flmGui); - void retranslate() override; + bool init(const std::shared_ptr& ocFtc, + const std::shared_ptr& evlFtc, const std::shared_ptr& evlDtc, + const std::shared_ptr& opmDtc, + const std::shared_ptr& flmFtc, + const std::shared_ptr& flmDtc, + const std::shared_ptr& flmGui); + void retranslate() override; -private: + private: + NGL::INGLLogger& m_logger; + void onSendEvaluationReply(const Core::FunctionReplyObject& replyObject) override final; -NGL::INGLLogger &m_logger; - void onSendEvaluationReply(const Core::FunctionReplyObject &replyObject) override final; + void onEvlCommentModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - void onEvlCommentModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onEvlSchemaModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onEvlSchemaModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - - void onFileContentModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject);} + void onFileContentModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void onRequestSchema(); - void onNotifyAboutSchema(const Evaluations::EvaluationSchema &data, DataModification modType); - void onAddNewComment(); - void onCommentAccepted(); - void onCommentEditAccepted(); - void onSendComment(); - void onSendAllComments(); + private slots: + void onRequestSchema(); + void onNotifyAboutSchema(const Evaluations::EvaluationSchema& data, DataModification modType); + void onAddNewComment(); + void onCommentAccepted(); + void onCommentEditAccepted(); + void onSendComment(); + void onSendAllComments(); - void onTreeViewDoubleClicked(); - void onEditComment(); - void onModifySelectedEntry(); - void onTreeViewModelIndexChanged(const QModelIndex &curr); - void onTriedToDropFolderToElement(); - void onDropActionFinished(const QModelIndex &parent); - void onShowContextMenu(const QPoint &position); + void onTreeViewDoubleClicked(); + void onEditComment(); + void onModifySelectedEntry(); + void onTreeViewModelIndexChanged(const QModelIndex& curr); + void onTriedToDropFolderToElement(); + void onDropActionFinished(const QModelIndex& parent); + void onShowContextMenu(const QPoint& position); - bool onSaveToLibrary(); - void onLoadFromLibrary(); - void onAddElement(); - void onAddFolder(); - void onAddRootFolder(); + bool onSaveToLibrary(); + void onLoadFromLibrary(); + void onAddElement(); + void onAddFolder(); + void onAddRootFolder(); - void onCreateNewSchema(); - void onRemoveSelectedElement(); + void onCreateNewSchema(); + void onRemoveSelectedElement(); - void DebugonLoadSchema(); - void onSendSchema(); + void DebugonLoadSchema(); + void onSendSchema(); -private: - void loadLatestSchema(); - void handleUnsentComments(); - void updateCommentLabel(); - void markCommentAsSent(const QPersistentModelIndex &idx); + private: + void loadLatestSchema(); + void handleUnsentComments(); + void updateCommentLabel(); + void markCommentAsSent(const QPersistentModelIndex& idx); - - EvlCommentModifyRequest createEvlCommentModifyRequest(const ItemComment &c) const; - OcSituationClient::SendEvaluationRequest createSendEvaluationRequest(const ItemComment &c) const; - QVector m_vecCommentsInSendState; + EvlCommentModifyRequest createEvlCommentModifyRequest(const ItemComment& c) const; + OcSituationClient::SendEvaluationRequest createSendEvaluationRequest(const ItemComment& c) const; + QVector m_vecCommentsInSendState; - bool eventFilter(QObject *object, QEvent *event) override; - void addEntry(bool isFolder, bool isNewRoot = false); + bool eventFilter(QObject* object, QEvent* event) override; + void addEntry(bool isFolder, bool isNewRoot = false); - void removeEntry(const QModelIndex &idx); - void removeComment(const QModelIndex &idx); - void sendComment(const QModelIndex &idx); + void removeEntry(const QModelIndex& idx); + void removeComment(const QModelIndex& idx); + void sendComment(const QModelIndex& idx); - void createExampleSchema(); - void loadSchema(qint32 schemaId); - void saveSchema(bool sendToTa); - bool apply() override; + void createExampleSchema(); + void loadSchema(qint32 schemaId); + void saveSchema(bool sendToTa); + bool apply() override; - bool m_ocMode{false}; - bool m_runningOnTablet{false}; - TreeModelSchema *m_pModel{nullptr}; + bool m_ocMode{false}; + bool m_runningOnTablet{false}; + TreeModelSchema* m_pModel{nullptr}; - QMap m_mapSchemata; - qint32 m_loadedSchemaId{0}; + QMap m_mapSchemata; + qint32 m_loadedSchemaId{0}; - std::shared_ptr m_ocFtc; - std::shared_ptr m_evlDtc; - std::shared_ptr m_evlFtc; - std::shared_ptr m_opmDtc; + std::shared_ptr m_ocFtc; + std::shared_ptr m_evlDtc; + std::shared_ptr m_evlFtc; + std::shared_ptr m_opmDtc; - std::shared_ptr m_flmFtc; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmGui; + std::shared_ptr m_flmFtc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmGui; - QString m_lastFileName; - Evaluations::EvlNewCommentDialog *m_commentDlg{nullptr}; - LtsSession::LtsSession *m_session{nullptr}; + QString m_lastFileName; + Evaluations::EvlNewCommentDialog* m_commentDlg{nullptr}; + LtsSession::LtsSession* m_session{nullptr}; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - Ui::EditSchemaDialog *m_ui{nullptr}; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + Ui::EditSchemaDialog* m_ui{nullptr}; }; -} - +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_general.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_general.h old mode 100755 new mode 100644 index 15136cf1f..c9053ffc3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_general.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_general.h @@ -1,33 +1,33 @@ - #pragma once -#include -#include -#include #include "evl_edit_schema_element_data.h" +#include +#include +#include + namespace Evaluations { class TreeModelGeneral : public NGLTreeModel { - Q_OBJECT -public: - TreeModelGeneral(QObject *parent, - NGL::INGLLogger &logger); + Q_OBJECT + public: + TreeModelGeneral(QObject* parent, NGL::INGLLogger& logger); - void iterateModel(const QModelIndex &parent, const std::function &fCallback, bool recursive = true) const; + void iterateModel(const QModelIndex& parent, + const std::function& fCallback, + bool recursive = true) const; - QVariant dataAsVariant(const QModelIndex &index) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant dataAsVariant(const QModelIndex& index) const; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - QModelIndex insertRow(const QModelIndex &parent, const QVariant &data, const QIcon &icon); - bool updateRow(const QModelIndex &index, const QVariant &data, const QIcon &icon); - void removeRow(const QModelIndex &idx, bool deleteRootAllowed = false); + QModelIndex insertRow(const QModelIndex& parent, const QVariant& data, const QIcon& icon); + bool updateRow(const QModelIndex& index, const QVariant& data, const QIcon& icon); + void removeRow(const QModelIndex& idx, bool deleteRootAllowed = false); -protected: - -NGL::INGLLogger &m_logger; + protected: + NGL::INGLLogger& m_logger; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_schema.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_schema.cpp old mode 100755 new mode 100644 index 34d13f2fe..f506fa248 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_schema.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_edit_treemodel_schema.cpp @@ -1,302 +1,281 @@ - #include "evl_edit_treemodel_schema.h" -#include #include #include +#include namespace Evaluations { -TreeModelSchema::TreeModelSchema(QObject *parent, NGL::INGLLogger &logger) - : TreeModelGeneral(parent, logger) +TreeModelSchema::TreeModelSchema(QObject* parent, NGL::INGLLogger& logger) : TreeModelGeneral(parent, logger) { - qRegisterMetaTypeStreamOperators(); + qRegisterMetaTypeStreamOperators(); } - void TreeModelSchema::resetModel() { - TreeModelGeneral::resetModel(); - m_elementId = 1; - m_cntComments = 0; - m_cntSentComments = 0; + TreeModelGeneral::resetModel(); + m_elementId = 1; + m_cntComments = 0; + m_cntSentComments = 0; } - -bool TreeModelSchema::dropMimeData(const QMimeData *data, Qt::DropAction action, - int row, int column, const QModelIndex &parent) +bool TreeModelSchema::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - - ElementData p = getSelectedIndexDataAsElement(parent); + ElementData p = getSelectedIndexDataAsElement(parent); - if (!p.isFolder()) - { - emit signalTriedToDropFolderToElement(); - return false; - } - - bool success = TreeModelGeneral::dropMimeData(data, action, row, column, parent); - - if (success) - { - - - int parentId = getSelectedIndexDataAsElement(parent).m_id; - iterateModel(parent, [this, parentId](const QModelIndex & idx, const QVariant & v) + if (!p.isFolder()) { - Evaluations::ElementData e = v.value(); - e.m_parentId = parentId; - updateElementData(idx, e); - }, false); + emit signalTriedToDropFolderToElement(); + return false; + } - refreshAllIcons(); - emit signalSuccessfulDropPerformed(parent); - } + bool success = TreeModelGeneral::dropMimeData(data, action, row, column, parent); - return success; + if (success) + { + + int parentId = getSelectedIndexDataAsElement(parent).m_id; + iterateModel( + parent, + [this, parentId](const QModelIndex& idx, const QVariant& v) { + Evaluations::ElementData e = v.value(); + e.m_parentId = parentId; + updateElementData(idx, e); + }, + false); + + refreshAllIcons(); + emit signalSuccessfulDropPerformed(parent); + } + + return success; } - -QVariant TreeModelSchema::data(const QModelIndex &index, int role) const +QVariant TreeModelSchema::data(const QModelIndex& index, int role) const { - QVariant v = TreeModelGeneral::data(index, role); + QVariant v = TreeModelGeneral::data(index, role); + + if (v.isNull()) + return v; + + if (v.canConvert()) + { + Evaluations::ElementData e = v.value(); + return e.getText(); + } + else if (v.canConvert()) + { + Evaluations::ItemComment c = v.value(); + QString str(DTG::toStringMSec(c.getTimeStamp().toMSecsSinceEpoch())); + str += QLatin1Char(' '); + str += c.getText(); + return str; + } - if (v.isNull()) return v; - - if (v.canConvert()) - { - Evaluations::ElementData e = v.value(); - return e.getText(); - } - else if (v.canConvert()) - { - Evaluations::ItemComment c = v.value(); - QString str(DTG::toStringMSec(c.getTimeStamp().toMSecsSinceEpoch())); - str += QLatin1Char(' '); - str += c.getText(); - return str; - } - - return v; } - -ElementData TreeModelSchema::getSelectedIndexDataAsElement(const QModelIndex &idx) const +ElementData TreeModelSchema::getSelectedIndexDataAsElement(const QModelIndex& idx) const { - if (!idx.isValid()) - ElementData(); + if (!idx.isValid()) + ElementData(); - QVariant v = TreeModelGeneral::dataAsVariant(idx); - return v.value(); + QVariant v = TreeModelGeneral::dataAsVariant(idx); + return v.value(); } - -QVector TreeModelSchema::getSelectedIndexHierarchy(const QModelIndex &idx) const +QVector TreeModelSchema::getSelectedIndexHierarchy(const QModelIndex& idx) const { - if (!idx.isValid()) - QString(); + if (!idx.isValid()) + QString(); - QVector vecHierarchy; + QVector vecHierarchy; - QModelIndex iterIdx = idx; + QModelIndex iterIdx = idx; + + while (iterIdx.parent() != QModelIndex()) + { + Evaluations::ElementData e = getSelectedIndexDataAsElement(iterIdx); + vecHierarchy.push_front(e.getText()); + + iterIdx = iterIdx.parent(); + } - while (iterIdx.parent() != QModelIndex()) - { Evaluations::ElementData e = getSelectedIndexDataAsElement(iterIdx); vecHierarchy.push_front(e.getText()); - iterIdx = iterIdx.parent(); - } - - Evaluations::ElementData e = getSelectedIndexDataAsElement(iterIdx); - vecHierarchy.push_front(e.getText()); - - return vecHierarchy; + return vecHierarchy; } - QJsonDocument TreeModelSchema::toJsonDocument() const { - QJsonArray arr; + QJsonArray arr; - QModelIndex root; - iterateModel(root, [this, &arr](const QModelIndex & idx, const QVariant & v) - { - Q_UNUSED(idx); - Evaluations::ElementData e = v.value(); - INFO_LOG(m_logger) << "toJsonDocument: Name: " << e.getText() << ", elementId: " << e.m_id << ", parent id: " << e.m_parentId; + QModelIndex root; + iterateModel(root, [this, &arr](const QModelIndex& idx, const QVariant& v) { + Q_UNUSED(idx); + Evaluations::ElementData e = v.value(); + INFO_LOG(m_logger) << "toJsonDocument: Name: " << e.getText() << ", elementId: " << e.m_id + << ", parent id: " << e.m_parentId; - QJsonObject obj; - obj[QStringLiteral("id")] = e.m_id; - obj[QStringLiteral("parentId")] = e.m_parentId; - obj[QStringLiteral("text")] = e.getText(); - obj[QStringLiteral("state")] = int(e.getState()); + QJsonObject obj; + obj[QStringLiteral("id")] = e.m_id; + obj[QStringLiteral("parentId")] = e.m_parentId; + obj[QStringLiteral("text")] = e.getText(); + obj[QStringLiteral("state")] = int(e.getState()); - arr.append(obj); - }); - - QJsonDocument doc(arr); - return doc; -} - - -bool TreeModelSchema::fromQJsonDocument(const QJsonDocument &doc) -{ - resetModel(); - - const QJsonArray arr(doc.array()); - - if (!arr.size()) - return false; - - QHash mapId2Index; - - for (const QJsonValue &val : arr) - { - const QJsonObject obj = val.toObject(); - - ElementData d(obj[QStringLiteral("text")].toString()); - d.m_id = obj[QStringLiteral("id")].toInt(); - d.m_parentId = obj[QStringLiteral("parentId")].toInt(); - d.switchState((ElementData::State)obj[QStringLiteral("state")].toInt()); - - QPersistentModelIndex parent = (d.m_parentId == 0) ? QPersistentModelIndex() : mapId2Index[d.m_parentId]; - QModelIndex newIdx = TreeModelGeneral::insertRow(parent, QVariant::fromValue(d), d.getIcon()); - - mapId2Index[d.m_id] = newIdx; - - - - m_elementId = std::max(m_elementId, d.m_id); - INFO_LOG(m_logger) << "fromQJsonDocument: " << d.getText() << ", own id = " << d.m_id << ", parent id = " << d.m_parentId; - } - - ++m_elementId; - return true; -} - - -QModelIndex TreeModelSchema::insertComment(const QModelIndex &parent, const ItemComment &data) -{ - QModelIndex idx = TreeModelGeneral::insertRow(parent, QVariant::fromValue(data), data.getIcon()); - - if (idx.isValid()) - { - ++m_cntComments; - - if (data.isSent()) - ++m_cntSentComments; - - refreshElementDataIconState(parent); - } - - return idx; -} - - -void TreeModelSchema::insertComment(const ItemComment &data) -{ - QModelIndex root = QModelIndex(); - iterateModel(root, [&data, this](const QModelIndex & idx, const QVariant & v) - { - if (v.canConvert()) - { - ElementData e = v.value(); - if (e.m_id == data.elementId()) - TreeModelSchema::insertComment(idx, data); - } - }); -} - - -bool TreeModelSchema::updateComment(const QModelIndex &index, const ItemComment &data) -{ - bool success = TreeModelGeneral::updateRow(index, QVariant::fromValue(data), data.getIcon()); - - if (success) - { - if (data.isSent()) - ++m_cntSentComments; - - refreshElementDataIconState(index.parent()); - } - - return success; -} - - -void TreeModelSchema::removeComment(const QModelIndex &idx) -{ - if (!idx.isValid()) - return; - - --m_cntComments; - QModelIndex idxParentElement = idx.parent(); - removeRow(idx); - refreshElementDataIconState(idxParentElement); -} - - -QModelIndex TreeModelSchema::insertElementData(const QModelIndex &parent, const ElementData &data) -{ - ElementData d(data); - d.m_id = m_elementId++; - d.m_parentId = !parent.isValid() ? 0 : getSelectedIndexDataAsElement(parent).m_id; - - return TreeModelGeneral::insertRow(parent, QVariant::fromValue(d), d.getIcon()); -} - - -bool TreeModelSchema::updateElementData(const QModelIndex &index, const ElementData &data) -{ - return TreeModelGeneral::updateRow(index, QVariant::fromValue(data), data.getIcon()); -} - - -void TreeModelSchema::refreshElementDataIconState(const QModelIndex &idx) -{ - ElementData e = getSelectedIndexDataAsElement(idx); - - if (e.isFolder()) - return; - - if (!rowCount(idx)) - e.switchState(ElementData::State::ElementWithoutComments); - else - { - bool hasUnsentComments = false; - iterateModel(idx, [&hasUnsentComments](const QModelIndex & idx, const QVariant & v) - { - Q_UNUSED(idx); - const Evaluations::ItemComment d = v.value(); - if (!d.isSent()) - hasUnsentComments = true; + arr.append(obj); }); - e.switchState(hasUnsentComments ? ElementData::State::ElementWithUnsentComments : ElementData::State::ElementAllCommentsSent); - } - - TreeModelGeneral::updateRow(idx, QVariant::fromValue(e), e.getIcon()); + QJsonDocument doc(arr); + return doc; } +bool TreeModelSchema::fromQJsonDocument(const QJsonDocument& doc) +{ + resetModel(); + + const QJsonArray arr(doc.array()); + + if (!arr.size()) + return false; + + QHash mapId2Index; + + for (const QJsonValue& val : arr) + { + const QJsonObject obj = val.toObject(); + + ElementData d(obj[QStringLiteral("text")].toString()); + d.m_id = obj[QStringLiteral("id")].toInt(); + d.m_parentId = obj[QStringLiteral("parentId")].toInt(); + d.switchState((ElementData::State)obj[QStringLiteral("state")].toInt()); + + QPersistentModelIndex parent = (d.m_parentId == 0) ? QPersistentModelIndex() : mapId2Index[d.m_parentId]; + QModelIndex newIdx = TreeModelGeneral::insertRow(parent, QVariant::fromValue(d), d.getIcon()); + + mapId2Index[d.m_id] = newIdx; + + m_elementId = std::max(m_elementId, d.m_id); + INFO_LOG(m_logger) << "fromQJsonDocument: " << d.getText() << ", own id = " << d.m_id + << ", parent id = " << d.m_parentId; + } + + ++m_elementId; + return true; +} + +QModelIndex TreeModelSchema::insertComment(const QModelIndex& parent, const ItemComment& data) +{ + QModelIndex idx = TreeModelGeneral::insertRow(parent, QVariant::fromValue(data), data.getIcon()); + + if (idx.isValid()) + { + ++m_cntComments; + + if (data.isSent()) + ++m_cntSentComments; + + refreshElementDataIconState(parent); + } + + return idx; +} + +void TreeModelSchema::insertComment(const ItemComment& data) +{ + QModelIndex root = QModelIndex(); + iterateModel(root, [&data, this](const QModelIndex& idx, const QVariant& v) { + if (v.canConvert()) + { + ElementData e = v.value(); + if (e.m_id == data.elementId()) + TreeModelSchema::insertComment(idx, data); + } + }); +} + +bool TreeModelSchema::updateComment(const QModelIndex& index, const ItemComment& data) +{ + bool success = TreeModelGeneral::updateRow(index, QVariant::fromValue(data), data.getIcon()); + + if (success) + { + if (data.isSent()) + ++m_cntSentComments; + + refreshElementDataIconState(index.parent()); + } + + return success; +} + +void TreeModelSchema::removeComment(const QModelIndex& idx) +{ + if (!idx.isValid()) + return; + + --m_cntComments; + QModelIndex idxParentElement = idx.parent(); + removeRow(idx); + refreshElementDataIconState(idxParentElement); +} + +QModelIndex TreeModelSchema::insertElementData(const QModelIndex& parent, const ElementData& data) +{ + ElementData d(data); + d.m_id = m_elementId++; + d.m_parentId = !parent.isValid() ? 0 : getSelectedIndexDataAsElement(parent).m_id; + + return TreeModelGeneral::insertRow(parent, QVariant::fromValue(d), d.getIcon()); +} + +bool TreeModelSchema::updateElementData(const QModelIndex& index, const ElementData& data) +{ + return TreeModelGeneral::updateRow(index, QVariant::fromValue(data), data.getIcon()); +} + +void TreeModelSchema::refreshElementDataIconState(const QModelIndex& idx) +{ + ElementData e = getSelectedIndexDataAsElement(idx); + + if (e.isFolder()) + return; + + if (!rowCount(idx)) + e.switchState(ElementData::State::ElementWithoutComments); + else + { + bool hasUnsentComments = false; + iterateModel(idx, [&hasUnsentComments](const QModelIndex& idx, const QVariant& v) { + Q_UNUSED(idx); + const Evaluations::ItemComment d = v.value(); + if (!d.isSent()) + hasUnsentComments = true; + }); + + e.switchState(hasUnsentComments ? ElementData::State::ElementWithUnsentComments + : ElementData::State::ElementAllCommentsSent); + } + + TreeModelGeneral::updateRow(idx, QVariant::fromValue(e), e.getIcon()); +} void TreeModelSchema::refreshAllIcons() { - QModelIndex root; - iterateModel(root, [this](const QModelIndex & idx, const QVariant & v) - { - Evaluations::ElementData d = v.value(); - d.refreshIcon(); + QModelIndex root; + iterateModel(root, [this](const QModelIndex& idx, const QVariant& v) { + Evaluations::ElementData d = v.value(); + d.refreshIcon(); - NGLTreeItem *item = privateData(idx); - item->setIcon(d.getIcon()); - }); + NGLTreeItem* item = privateData(idx); + item->setIcon(d.getIcon()); + }); - emit dataChanged(QModelIndex(), QModelIndex()); + emit dataChanged(QModelIndex(), QModelIndex()); } -} - +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.cpp old mode 100755 new mode 100644 index 233e071ba..e68d953a2 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.cpp @@ -1,94 +1,92 @@ +#include "evl_new_comment_dialog.h" + #include "ui_evl_new_comment_dialog.h" -#include "evl_new_comment_dialog.h" #include #include namespace Evaluations { -EvlNewCommentDialog::EvlNewCommentDialog(const std::shared_ptr &opmDtc, - QWidget *parent) : QDialog(parent), - m_ui(new Ui::EvlNewCommentDialog), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { - m_ui->setupUi(this); - setWindowFlags(Qt::Tool); - m_ui->m_ltsComboBox_ReceiverOperator->addItem(tr("All (Default)"), 0); +EvlNewCommentDialog::EvlNewCommentDialog(const std::shared_ptr& opmDtc, + QWidget* parent) + : QDialog(parent), m_ui(new Ui::EvlNewCommentDialog), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ + m_ui->setupUi(this); + setWindowFlags(Qt::Tool); + m_ui->m_ltsComboBox_ReceiverOperator->addItem(tr("All (Default)"), 0); - auto cbUser = [this](const OperatorManagement::User &user) - { - m_ui->m_ltsComboBox_ReceiverOperator->addItem(QString::fromStdString(user.name()), user.id()); - }; - opmDtc->users(cbUser); + auto cbUser = [this](const OperatorManagement::User& user) { + m_ui->m_ltsComboBox_ReceiverOperator->addItem(QString::fromStdString(user.name()), user.id()); + }; + opmDtc->users(cbUser); - connect(m_ui->m_pushButton_AddComment, &QPushButton::clicked, this, &QDialog::accept); - connect(m_ui->m_pushButton_Cancel, &QPushButton::clicked, this, &QDialog::reject); - connect(m_ui->m_plainTextEdit_Comment, &QPlainTextEdit::textChanged, this, &EvlNewCommentDialog::onTextChanged); + connect(m_ui->m_pushButton_AddComment, &QPushButton::clicked, this, &QDialog::accept); + connect(m_ui->m_pushButton_Cancel, &QPushButton::clicked, this, &QDialog::reject); + connect(m_ui->m_plainTextEdit_Comment, &QPlainTextEdit::textChanged, this, &EvlNewCommentDialog::onTextChanged); - m_ui->m_checkBox_SendComment->setChecked(LtsUtils::OperatorSettings::getInstance()->value(QStringLiteral("Evaluations"), QStringLiteral("setAutoSendComments"), false).toBool()); + m_ui->m_checkBox_SendComment->setChecked( + LtsUtils::OperatorSettings::getInstance() + ->value(QStringLiteral("Evaluations"), QStringLiteral("setAutoSendComments"), false) + .toBool()); - onTextChanged(); + onTextChanged(); } - EvlNewCommentDialog::~EvlNewCommentDialog() { - LtsUtils::OperatorSettings::getInstance()->setValue(QStringLiteral("Evaluations"), QStringLiteral("setAutoSendComments"), m_ui->m_checkBox_SendComment->isChecked()); - delete m_ui; + LtsUtils::OperatorSettings::getInstance()->setValue(QStringLiteral("Evaluations"), + QStringLiteral("setAutoSendComments"), + m_ui->m_checkBox_SendComment->isChecked()); + delete m_ui; } - void EvlNewCommentDialog::onTextChanged() { - QString plainText(m_ui->m_plainTextEdit_Comment->toPlainText()); - int currentUsedChars = plainText.toUtf8().size(); - bool bNeedSetNew = false; + QString plainText(m_ui->m_plainTextEdit_Comment->toPlainText()); + int currentUsedChars = plainText.toUtf8().size(); + bool bNeedSetNew = false; - while (currentUsedChars > m_maxChars) - { - plainText.chop(1); - currentUsedChars = plainText.toUtf8().size(); - bNeedSetNew = true; - } + while (currentUsedChars > m_maxChars) + { + plainText.chop(1); + currentUsedChars = plainText.toUtf8().size(); + bNeedSetNew = true; + } - - if (bNeedSetNew) - { - m_ui->m_plainTextEdit_Comment->setPlainText(plainText); - m_ui->m_plainTextEdit_Comment->moveCursor(QTextCursor::End); - } + if (bNeedSetNew) + { + m_ui->m_plainTextEdit_Comment->setPlainText(plainText); + m_ui->m_plainTextEdit_Comment->moveCursor(QTextCursor::End); + } - m_ui->m_label_CharsLeft->setText(tr("Characters left: %1").arg(m_maxChars - currentUsedChars)); + m_ui->m_label_CharsLeft->setText(tr("Characters left: %1").arg(m_maxChars - currentUsedChars)); } - bool EvlNewCommentDialog::autoSend() const { - return m_ui->m_checkBox_SendComment->isChecked(); + return m_ui->m_checkBox_SendComment->isChecked(); } - QString EvlNewCommentDialog::comment() const { - return m_ui->m_plainTextEdit_Comment->toPlainText(); + return m_ui->m_plainTextEdit_Comment->toPlainText(); } - int EvlNewCommentDialog::selectedReceiverId() const { - return m_ui->m_ltsComboBox_ReceiverOperator->currentData().toInt(); + return m_ui->m_ltsComboBox_ReceiverOperator->currentData().toInt(); } -void EvlNewCommentDialog::setAsEditComment(const QString &text) +void EvlNewCommentDialog::setAsEditComment(const QString& text) { - m_ui->m_plainTextEdit_Comment->setPlainText(text); - m_ui->m_label_CharsLeft->hide(); - m_ui->label->hide(); - m_ui->m_ltsComboBox_ReceiverOperator->hide(); - m_ui->m_checkBox_SendComment->hide(); + m_ui->m_plainTextEdit_Comment->setPlainText(text); + m_ui->m_label_CharsLeft->hide(); + m_ui->label->hide(); + m_ui->m_ltsComboBox_ReceiverOperator->hide(); + m_ui->m_checkBox_SendComment->hide(); - m_ui->m_pushButton_AddComment->setText(tr("Edit Comment")); + m_ui->m_pushButton_AddComment->setText(tr("Edit Comment")); } -} - +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.h old mode 100755 new mode 100644 index a0bca7769..f0547adc1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/Evaluations/Gui/SchemaEdit/evl_new_comment_dialog.h @@ -1,6 +1,5 @@ - #pragma once #include @@ -11,30 +10,28 @@ namespace Ui class EvlNewCommentDialog; } - namespace Evaluations { class EvlNewCommentDialog : public QDialog { - Q_OBJECT + Q_OBJECT -public: - explicit EvlNewCommentDialog(const std::shared_ptr &opmDtc, - QWidget *parent = nullptr); - ~EvlNewCommentDialog(); + public: + explicit EvlNewCommentDialog(const std::shared_ptr& opmDtc, + QWidget* parent = nullptr); + ~EvlNewCommentDialog(); - bool autoSend() const; - QString comment() const; - int selectedReceiverId() const; - void setAsEditComment(const QString &text); + bool autoSend() const; + QString comment() const; + int selectedReceiverId() const; + void setAsEditComment(const QString& text); -private slots: - void onTextChanged(); + private slots: + void onTextChanged(); -private: - -NGL::INGLLogger &m_logger; - Ui::EvlNewCommentDialog *m_ui{nullptr}; - const int m_maxChars{255}; + private: + NGL::INGLLogger& m_logger; + Ui::EvlNewCommentDialog* m_ui{nullptr}; + const int m_maxChars{255}; }; -} +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.cpp old mode 100755 new mode 100644 index 932aa8a94..3e7629ded --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.cpp @@ -1,178 +1,161 @@ - - #include "exm_dialog.h" -#include "ui_exm_dialog.h" - -#include "exm_dialog_model.h" -#include "exm_edit_dialog.h" #include "CustomViews/exm_exercise.h" +#include "exm_dialog_model.h" +#include "exm_edit_dialog.h" +#include "ui_exm_dialog.h" -#include -#include -#include -#include #include #include - +#include +#include +#include +#include namespace ExerciseManagement { - - -ExerciseManagementDialog::ExerciseManagementDialog(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_model(nullptr) - , m_ui(new Ui::ExerciseManagementDialog) - , m_session(nullptr) - , m_ftc(nullptr) - , m_menuGroup(menuGroup) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ExerciseManagementDialog::ExerciseManagementDialog(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), m_model(nullptr), + m_ui(new Ui::ExerciseManagementDialog), m_session(nullptr), m_ftc(nullptr), m_menuGroup(menuGroup), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Administrator-Exercises")); + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Administrator-Exercises")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ExerciseManagementDialog::onAddExercise); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementDialog::onEditExercise); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ExerciseManagementDialog::onRemoveExercise); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ExerciseManagementDialog::onAddExercise); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementDialog::onEditExercise); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ExerciseManagementDialog::onRemoveExercise); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ExerciseManagementDialog::onEditExercise); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ExerciseManagementDialog::onEditExercise); } ExerciseManagementDialog::~ExerciseManagementDialog() { - delete m_ui; + delete m_ui; } void ExerciseManagementDialog::retranslate() { - translate(m_ui, tr("Exercises")); + translate(m_ui, tr("Exercises")); } void ExerciseManagementDialog::tableColumnOrganiserSetting() { - - m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); + + m_ui->widget->setColumnsOrganiserEnabled(identifier(), true); } -bool ExerciseManagementDialog::init(LtsSession::LtsSessionDataDds *session) +bool ExerciseManagementDialog::init(LtsSession::LtsSessionDataDds* session) { - m_session = session; - std::shared_ptr dtc; - std::shared_ptr asmDtc; - std::shared_ptr pdmDtc; + m_session = session; + std::shared_ptr dtc; + std::shared_ptr asmDtc; + std::shared_ptr pdmDtc; - if (!m_session->getDtc(dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; - if (!m_session->getDtc(pdmDtc)) - return false; - if (!m_session->getDtc(asmDtc)) - return false; - if (!m_session->getDtc(m_flmDtc)) - return false; - if (!m_session->getFtc(m_flmFtc)) - return false; + if (!m_session->getDtc(dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; + if (!m_session->getDtc(pdmDtc)) + return false; + if (!m_session->getDtc(asmDtc)) + return false; + if (!m_session->getDtc(m_flmDtc)) + return false; + if (!m_session->getFtc(m_flmFtc)) + return false; - m_flmDtc->enableAll(); + m_flmDtc->enableAll(); - m_model = new ExerciseManagementDialogModel(this); - m_model->initModel(dtc, m_ftc, asmDtc, pdmDtc, true); - auto proxy = new ExerciseManagementProxyModel(this); - proxy->setSourceModel(m_model); - proxy->setAdminExerciseVisible(false); - proxy->setVisibleExerciseIds({-1}); + m_model = new ExerciseManagementDialogModel(this); + m_model->initModel(dtc, m_ftc, asmDtc, pdmDtc, true); + auto proxy = new ExerciseManagementProxyModel(this); + proxy->setSourceModel(m_model); + proxy->setAdminExerciseVisible(false); + proxy->setVisibleExerciseIds({-1}); - m_ui->widget->setModel(proxy, [this]() { return new CustomViewExercise(this); }); - m_ui->widget->hideColumn(ExerciseManagementDialogModel::Image); - const bool hasLinkedExercises = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), - QStringLiteral("CanBeLinked")); - const bool hasHlaInterface = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), - QStringLiteral("HasHlaInterface")); - m_ui->widget->setColumnHidden(ExerciseManagementDialogModel::LinkedId, !hasLinkedExercises); - m_ui->widget->setColumnHidden(ExerciseManagementDialogModel::HasHlaInterface, !hasHlaInterface); + m_ui->widget->setModel(proxy, [this]() { return new CustomViewExercise(this); }); + m_ui->widget->hideColumn(ExerciseManagementDialogModel::Image); + const bool hasLinkedExercises = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), QStringLiteral("CanBeLinked")); + const bool hasHlaInterface = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), QStringLiteral("HasHlaInterface")); + m_ui->widget->setColumnHidden(ExerciseManagementDialogModel::LinkedId, !hasLinkedExercises); + m_ui->widget->setColumnHidden(ExerciseManagementDialogModel::HasHlaInterface, !hasHlaInterface); - connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ExerciseManagementDialog::enaDisa); + connect(m_ui->widget, &LtsDataView::LtsDataView::signalSelectionChanged, this, &ExerciseManagementDialog::enaDisa); - enaDisa(); + enaDisa(); - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), - QStringLiteral("enableEditPhases")).toBool(); - if (!enableEditPhases) - m_ui->widget->hideColumn(ExerciseManagementDialogModel::ActivePhase); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); + if (!enableEditPhases) + m_ui->widget->hideColumn(ExerciseManagementDialogModel::ActivePhase); - return true; + return true; } void ExerciseManagementDialog::enaDisa() { - QModelIndexList selectedRows = m_ui->widget->selectedRows(); - const int cntSelectedRows = selectedRows.size(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - const QModelIndex curIdx = m_ui->widget->currentIndex(); - const ExerciseManagement::ExerciseState state = m_model->getRowData(curIdx.row()).state(); - const bool isRemovable = (state == ExerciseManagement::ExerciseState::Unknown || - state == ExerciseManagement::ExerciseState::Created || - state == ExerciseManagement::ExerciseState::Stopped || - state == ExerciseManagement::ExerciseState::Terminated); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, curIdx.isValid() && isRemovable); + QModelIndexList selectedRows = m_ui->widget->selectedRows(); + const int cntSelectedRows = selectedRows.size(); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + const QModelIndex curIdx = m_ui->widget->currentIndex(); + const ExerciseManagement::ExerciseState state = m_model->getRowData(curIdx.row()).state(); + const bool isRemovable = + (state == ExerciseManagement::ExerciseState::Unknown || state == ExerciseManagement::ExerciseState::Created || + state == ExerciseManagement::ExerciseState::Stopped || state == ExerciseManagement::ExerciseState::Terminated); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, curIdx.isValid() && isRemovable); } void ExerciseManagementDialog::onAddExercise() { - ExerciseManagementEditDialog *dialog = new ExerciseManagementEditDialog(this); - dialog->init(m_session, m_menuGroup, -1 ); + ExerciseManagementEditDialog* dialog = new ExerciseManagementEditDialog(this); + dialog->init(m_session, m_menuGroup, -1); - addDialog(dialog, m_menuGroup, QStringLiteral("NewExercise")); + addDialog(dialog, m_menuGroup, QStringLiteral("NewExercise")); } void ExerciseManagementDialog::onRemoveExercise() { - const QModelIndex curIdx = m_ui->widget->currentIndex(); - if (!curIdx.isValid()) - return; - const int exId = m_model->getRowData(curIdx.row()).id(); - const int folderId = m_flmDtc->getExerciseFolderId(exId); + const QModelIndex curIdx = m_ui->widget->currentIndex(); + if (!curIdx.isValid()) + return; + const int exId = m_model->getRowData(curIdx.row()).id(); + const int folderId = m_flmDtc->getExerciseFolderId(exId); - if (folderId > 0) - { - Core::RemoveElementRequest req(folderId); - m_requestHelper->startSingleRequest([req, this]() + if (folderId > 0) { - return m_flmFtc->folderRemoveRequest(req, this); - }); - } + Core::RemoveElementRequest req(folderId); + m_requestHelper->startSingleRequest([req, this]() { return m_flmFtc->folderRemoveRequest(req, this); }); + } - ExerciseManagement::ExerciseRemoveRequest req(exId, false); - m_requestHelper->startSingleRequest([req, this]() - { - m_ftc->enableExerciseRemove(); - return m_ftc->exerciseRemoveRequest(req, this); - }); + ExerciseManagement::ExerciseRemoveRequest req(exId, false); + m_requestHelper->startSingleRequest([req, this]() { + m_ftc->enableExerciseRemove(); + return m_ftc->exerciseRemoveRequest(req, this); + }); } void ExerciseManagementDialog::onEditExercise() { - const QModelIndex idx = m_ui->widget->currentIndex(); - const Exercise ex = m_model->getRowData(idx.row()); + const QModelIndex idx = m_ui->widget->currentIndex(); + const Exercise ex = m_model->getRowData(idx.row()); - if (ex.id() <= 0) - return; - DEBUG_LOG(m_logger) << "current EXId: " << ex.id(); + if (ex.id() <= 0) + return; + DEBUG_LOG(m_logger) << "current EXId: " << ex.id(); - ExerciseManagementEditDialog *dialog = new ExerciseManagementEditDialog(this); + ExerciseManagementEditDialog* dialog = new ExerciseManagementEditDialog(this); - dialog->init(m_session, m_menuGroup, ex.id()); - const QString identifier = QStringLiteral("EditExercise%1").arg(ex.id()); + dialog->init(m_session, m_menuGroup, ex.id()); + const QString identifier = QStringLiteral("EditExercise%1").arg(ex.id()); - addDialog(dialog, m_menuGroup, identifier); + addDialog(dialog, m_menuGroup, identifier); } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.h old mode 100755 new mode 100644 index 0374c3d7f..3f0444a4a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog.h @@ -1,16 +1,15 @@ - #pragma once -#include #include +#include #include -#include -#include -#include #include #include +#include +#include +#include namespace Ui { @@ -21,41 +20,47 @@ namespace ExerciseManagement { class ExerciseManagementDialogModel; - - -class ExerciseManagementDialog : public LtsWidgets::LtsDialog - , protected ExerciseManagement::Interface::Ftc::ExerciseRemoveReplyHandler - , protected FileManagement::Interface::Ftc::FolderRemoveReplyHandler +class ExerciseManagementDialog : public LtsWidgets::LtsDialog, + protected ExerciseManagement::Interface::Ftc::ExerciseRemoveReplyHandler, + protected FileManagement::Interface::Ftc::FolderRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ExerciseManagementDialog(const QString &menuGroup, QWidget *parent = nullptr); - ~ExerciseManagementDialog(); + public: + explicit ExerciseManagementDialog(const QString& menuGroup, QWidget* parent = nullptr); + ~ExerciseManagementDialog(); - bool init(LtsSession::LtsSessionDataDds *session); + bool init(LtsSession::LtsSessionDataDds* session); -private slots: - void enaDisa(); - void onAddExercise(); - void onEditExercise(); - void onRemoveExercise(); + private slots: + void enaDisa(); + void onAddExercise(); + void onEditExercise(); + void onRemoveExercise(); -private: + private: + NGL::INGLLogger& m_logger; + void retranslate() override; -NGL::INGLLogger &m_logger; - void retranslate() override; - void onExerciseRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onFolderRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void tableColumnOrganiserSetting() override; + void onExerciseRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - ExerciseManagementDialogModel *m_model; - Ui::ExerciseManagementDialog *m_ui; - LtsSession::LtsSessionDataDds *m_session; - std::shared_ptr m_ftc; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; - QString m_menuGroup; - LtsUtils::RequestHelper *m_requestHelper; + void onFolderRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } + + void tableColumnOrganiserSetting() override; + + ExerciseManagementDialogModel* m_model; + Ui::ExerciseManagementDialog* m_ui; + LtsSession::LtsSessionDataDds* m_session; + std::shared_ptr m_ftc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; + QString m_menuGroup; + LtsUtils::RequestHelper* m_requestHelper; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.cpp old mode 100755 new mode 100644 index dde63d7e5..4148d80f3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.cpp @@ -1,309 +1,284 @@ - - #include "exm_dialog_model.h" -#include -#include #include +#include #include +#include namespace ExerciseManagement { - - - -ExerciseManagementDialogModel::ExerciseManagementDialogModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Id"), - tr("Name"), - tr("Training Area"), - tr("Begin"), - tr("End"), - tr("Started"), - tr("Stopped"), - tr("Status"), - tr("Radio Group"), - tr("Active Phase"), - tr("Created"), - tr("Time Zone"), - tr("Forces"), - tr("Description"), - tr("Linked Exercise"), - tr("Transferred"), - tr("HLA"), - tr("Image")}, - parent) - , m_exmDtc(nullptr) - , m_asmDtc(nullptr) - , m_pdmDtc(nullptr) -{} - -bool ExerciseManagementDialogModel::initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &asmDtc, - const std::shared_ptr &pdmDtc, - bool addAdminExercise, - bool preloadExerciseImages) +ExerciseManagementDialogModel::ExerciseManagementDialogModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Id"), tr("Name"), tr("Training Area"), tr("Begin"), tr("End"), tr("Started"), tr("Stopped"), + tr("Status"), tr("Radio Group"), tr("Active Phase"), tr("Created"), tr("Time Zone"), tr("Forces"), + tr("Description"), tr("Linked Exercise"), tr("Transferred"), tr("HLA"), tr("Image")}, + parent), + m_exmDtc(nullptr), m_asmDtc(nullptr), m_pdmDtc(nullptr) { - m_exmDtc = dtc; - m_exmFtc = ftc; - m_asmDtc = asmDtc; - m_pdmDtc = pdmDtc; - - connect(m_exmDtc.get(), &ExerciseManagement::Interface::Dtc::exerciseChanged, - this, [this, preloadExerciseImages](const ExerciseManagement::Exercise &ex, DataModification mod) - { - onDataChanged(ex, mod); - - if (mod != DataModification::eAdded) - return; - - if (preloadExerciseImages) - addImagePreload(ex.id()); - }); - - if (addAdminExercise) - { - - ExerciseManagement::Exercise adminExercise; - adminExercise.name(tr("Superordinate Config / Administration").toStdString()); - adminExercise.id(0); - - insertRow(adminExercise); - } - - - m_exmDtc->exercises([this, preloadExerciseImages](const ExerciseManagement::Exercise &ex) - { - insertRow(ex); - - if (preloadExerciseImages) - addImagePreload(ex.id()); - }); - - INFO_LOG(m_logger) << "initModel - #exercises: " << m_vecData.size(); - return true; } - -int ExerciseManagementDialogModel::getId(const ExerciseManagement::Exercise &data) const +bool ExerciseManagementDialogModel::initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& asmDtc, + const std::shared_ptr& pdmDtc, + bool addAdminExercise, bool preloadExerciseImages) { - return data.id(); + m_exmDtc = dtc; + m_exmFtc = ftc; + m_asmDtc = asmDtc; + m_pdmDtc = pdmDtc; + + connect(m_exmDtc.get(), &ExerciseManagement::Interface::Dtc::exerciseChanged, this, + [this, preloadExerciseImages](const ExerciseManagement::Exercise& ex, DataModification mod) { + onDataChanged(ex, mod); + + if (mod != DataModification::eAdded) + return; + + if (preloadExerciseImages) + addImagePreload(ex.id()); + }); + + if (addAdminExercise) + { + + ExerciseManagement::Exercise adminExercise; + adminExercise.name(tr("Superordinate Config / Administration").toStdString()); + adminExercise.id(0); + + insertRow(adminExercise); + } + + m_exmDtc->exercises([this, preloadExerciseImages](const ExerciseManagement::Exercise& ex) { + insertRow(ex); + + if (preloadExerciseImages) + addImagePreload(ex.id()); + }); + + INFO_LOG(m_logger) << "initModel - #exercises: " << m_vecData.size(); + return true; } - -void ExerciseManagementDialogModel::addImagePreload(int32_t exId) +int ExerciseManagementDialogModel::getId(const ExerciseManagement::Exercise& data) const { - if (m_exerciseImages.contains(exId)) - return; - - m_preloadImages += exId; - - if (m_imagePreloadPending) - return; - - m_imagePreloadPending = true; - preloadNextImage(); + return data.id(); } +void ExerciseManagementDialogModel::addImagePreload(int32_t exId) +{ + if (m_exerciseImages.contains(exId)) + return; + + m_preloadImages += exId; + + if (m_imagePreloadPending) + return; + + m_imagePreloadPending = true; + preloadNextImage(); +} void ExerciseManagementDialogModel::preloadNextImage() { - if (m_preloadImages.isEmpty()) - return; + if (m_preloadImages.isEmpty()) + return; - m_exmFtc->enableGetExerciseImage(); - m_exmFtc->getExerciseImageRequest(GetExerciseImageRequest(m_preloadImages.takeFirst(), m_imageSize.height(), m_imageSize.width(), false), - createGetExerciseImageRequester()); + m_exmFtc->enableGetExerciseImage(); + m_exmFtc->getExerciseImageRequest( + GetExerciseImageRequest(m_preloadImages.takeFirst(), m_imageSize.height(), m_imageSize.width(), false), + createGetExerciseImageRequester()); } - -GetExerciseImageRequester *ExerciseManagementDialogModel::createGetExerciseImageRequester() +GetExerciseImageRequester* ExerciseManagementDialogModel::createGetExerciseImageRequester() { - auto r = GetExerciseImageRequester::createGetExerciseImageRequester(); - connect(r, &GetExerciseImageRequester::signalDone, - this, [this, r]() - { - m_imagePreloadPending = false; + auto r = GetExerciseImageRequester::createGetExerciseImageRequester(); + connect(r, &GetExerciseImageRequester::signalDone, this, [this, r]() { + m_imagePreloadPending = false; - const GetExerciseImageReply &reply(r->reply()); + const GetExerciseImageReply& reply(r->reply()); - if (reply.errorString().empty()) - { - m_exerciseImages.insert(reply.id(), LtsUtils::toQByteArray(reply.imageData())); + if (reply.errorString().empty()) + { + m_exerciseImages.insert(reply.id(), LtsUtils::toQByteArray(reply.imageData())); - - QModelIndex idx(findIndexForId(reply.id(), 0)); - emit dataChanged(idx, idx, { Qt::DisplayRole }); - } - else - { - QString msg(QString::fromStdString(reply.errorString())); - for (const std::string &arg : std::as_const(reply.errorParams())) - msg = msg.arg(QString::fromStdString(arg)); + QModelIndex idx(findIndexForId(reply.id(), 0)); + emit dataChanged(idx, idx, {Qt::DisplayRole}); + } + else + { + QString msg(QString::fromStdString(reply.errorString())); + for (const std::string& arg : std::as_const(reply.errorParams())) + msg = msg.arg(QString::fromStdString(arg)); - ERROR_LOG(m_logger) << "image preload failed: " << msg; - } + ERROR_LOG(m_logger) << "image preload failed: " << msg; + } - QTimer::singleShot(1, this, &ExerciseManagementDialogModel::preloadNextImage); - }); + QTimer::singleShot(1, this, &ExerciseManagementDialogModel::preloadNextImage); + }); - return r; + return r; } - -void ExerciseManagementDialogModel::setImageSizeConstraints(const QSize &size) +void ExerciseManagementDialogModel::setImageSizeConstraints(const QSize& size) { - m_imageSize = size; + m_imageSize = size; } - -QVariant ExerciseManagementDialogModel::data(const QModelIndex &index, int role) const +QVariant ExerciseManagementDialogModel::data(const QModelIndex& index, int role) const { - if ((role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::TextColorRole) || !indexIsValid(index)) - return QVariant(); - - const ExerciseManagement::Exercise &ex = m_vecData.at(index.row()); - - if (role == Qt::DisplayRole) - { - switch (index.column()) - { - case ExerciseManagementDialogModel::Columns::Name: - return QString::fromStdString(ex.name()); - case ExerciseManagementDialogModel::Columns::TrainingArea: - { - const AssetManagement::TrainingArea ta = m_asmDtc->trainingArea(ex.trainingAreaId()); - return QString::fromStdString(ta.name()); - } - case ExerciseManagementDialogModel::Columns::Begin: - return QDateTime::fromMSecsSinceEpoch(ex.beginTime()); - case ExerciseManagementDialogModel::Columns::End: - return QDateTime::fromMSecsSinceEpoch(ex.endTime()); - case ExerciseManagementDialogModel::Columns::Started: - return QDateTime::fromMSecsSinceEpoch(ex.startTime()); - case ExerciseManagementDialogModel::Columns::Stopped: - return QDateTime::fromMSecsSinceEpoch(ex.stopTime()); - case ExerciseManagementDialogModel::Columns::Status: - return ExerciseManagement::toString(ex.state()); - case ExerciseManagementDialogModel::Columns::RadioGroup: - if (ex.radioGroupId().is_set()) - return m_pdmDtc->trRadioGroupName(ex.radioGroupId().get()); - return QStringLiteral(" - "); - case ExerciseManagementDialogModel::Columns::ActivePhase: - return QString::fromStdString(m_exmDtc->exercisePhase(ex.activePhaseId()).name()); - case ExerciseManagementDialogModel::Columns::Created: - return QDateTime::fromMSecsSinceEpoch(ex.created()); - case ExerciseManagementDialogModel::Columns::TimeZone: - return (ex.defaultTimeZone() == 0) ? QStringLiteral("-") : QString(QLatin1Char(ex.defaultTimeZone())); - case ExerciseManagementDialogModel::Columns::Forces: - return QString::fromStdString(ex.forces()); - case ExerciseManagementDialogModel::Columns::Description: - return QString::fromStdString(ex.description()); - case ExerciseManagementDialogModel::Columns::Image: - return m_exerciseImages.value(ex.id()); - case ExerciseManagementDialogModel::Columns::Id: - return ex.id(); - case ExerciseManagementDialogModel::Columns::LinkedId: - { - if (ex.linkedExerciseId() == 0) + if ((role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::TextColorRole) || !indexIsValid(index)) return QVariant(); - const int row = findRowForId(ex.linkedExerciseId()); - if (row < 0) - return QStringLiteral("????? - %1").arg(ex.linkedExerciseId()); - return QString(QString::fromStdString(m_vecData.at(row).name()) + - QStringLiteral(" (%1)").arg(ex.linkedExerciseId())); - } - case ExerciseManagementDialogModel::Columns::Transferred: - return ex.transferred() ? tr("Yes") : tr("No"); - case ExerciseManagementDialogModel::Columns::HasHlaInterface: - return ex.hasHlaInterface() ? tr("Yes") : tr("No"); - } - } - else if (role == Qt::UserRole) - { - if (ex.id() == 0) - return 0; - switch (ex.state().underlying()) + + const ExerciseManagement::Exercise& ex = m_vecData.at(index.row()); + + if (role == Qt::DisplayRole) { - case ExerciseState::Unknown: return 6; - case ExerciseState::Created: return 3; - case ExerciseState::Started: return 1; - case ExerciseState::Paused: return 2; - case ExerciseState::Stopped: return 4; - case ExerciseState::Terminated: return 5; + switch (index.column()) + { + case ExerciseManagementDialogModel::Columns::Name: + return QString::fromStdString(ex.name()); + case ExerciseManagementDialogModel::Columns::TrainingArea: { + const AssetManagement::TrainingArea ta = m_asmDtc->trainingArea(ex.trainingAreaId()); + return QString::fromStdString(ta.name()); + } + case ExerciseManagementDialogModel::Columns::Begin: + return QDateTime::fromMSecsSinceEpoch(ex.beginTime()); + case ExerciseManagementDialogModel::Columns::End: + return QDateTime::fromMSecsSinceEpoch(ex.endTime()); + case ExerciseManagementDialogModel::Columns::Started: + return QDateTime::fromMSecsSinceEpoch(ex.startTime()); + case ExerciseManagementDialogModel::Columns::Stopped: + return QDateTime::fromMSecsSinceEpoch(ex.stopTime()); + case ExerciseManagementDialogModel::Columns::Status: + return ExerciseManagement::toString(ex.state()); + case ExerciseManagementDialogModel::Columns::RadioGroup: + if (ex.radioGroupId().is_set()) + return m_pdmDtc->trRadioGroupName(ex.radioGroupId().get()); + return QStringLiteral(" - "); + case ExerciseManagementDialogModel::Columns::ActivePhase: + return QString::fromStdString(m_exmDtc->exercisePhase(ex.activePhaseId()).name()); + case ExerciseManagementDialogModel::Columns::Created: + return QDateTime::fromMSecsSinceEpoch(ex.created()); + case ExerciseManagementDialogModel::Columns::TimeZone: + return (ex.defaultTimeZone() == 0) ? QStringLiteral("-") : QString(QLatin1Char(ex.defaultTimeZone())); + case ExerciseManagementDialogModel::Columns::Forces: + return QString::fromStdString(ex.forces()); + case ExerciseManagementDialogModel::Columns::Description: + return QString::fromStdString(ex.description()); + case ExerciseManagementDialogModel::Columns::Image: + return m_exerciseImages.value(ex.id()); + case ExerciseManagementDialogModel::Columns::Id: + return ex.id(); + case ExerciseManagementDialogModel::Columns::LinkedId: { + if (ex.linkedExerciseId() == 0) + return QVariant(); + const int row = findRowForId(ex.linkedExerciseId()); + if (row < 0) + return QStringLiteral("????? - %1").arg(ex.linkedExerciseId()); + return QString(QString::fromStdString(m_vecData.at(row).name()) + + QStringLiteral(" (%1)").arg(ex.linkedExerciseId())); + } + case ExerciseManagementDialogModel::Columns::Transferred: + return ex.transferred() ? tr("Yes") : tr("No"); + case ExerciseManagementDialogModel::Columns::HasHlaInterface: + return ex.hasHlaInterface() ? tr("Yes") : tr("No"); + } } - return 99; - } - else if (role == Qt::TextColorRole) - { - if (index.column() == ExerciseManagementDialogModel::Columns::Status) + else if (role == Qt::UserRole) { - switch (ex.state().underlying()) - { - case ExerciseState::Unknown: return QColor(Qt::black); - case ExerciseState::Created: return QColor(Qt::cyan); - case ExerciseState::Started: return QColor(Qt::darkGreen); - case ExerciseState::Paused: return QColor(Qt::darkYellow); - case ExerciseState::Stopped: return QColor(Qt::magenta); - case ExerciseState::Terminated: return QColor(Qt::red); - } + if (ex.id() == 0) + return 0; + switch (ex.state().underlying()) + { + case ExerciseState::Unknown: + return 6; + case ExerciseState::Created: + return 3; + case ExerciseState::Started: + return 1; + case ExerciseState::Paused: + return 2; + case ExerciseState::Stopped: + return 4; + case ExerciseState::Terminated: + return 5; + } + return 99; } - } - return QVariant(); + else if (role == Qt::TextColorRole) + { + if (index.column() == ExerciseManagementDialogModel::Columns::Status) + { + switch (ex.state().underlying()) + { + case ExerciseState::Unknown: + return QColor(Qt::black); + case ExerciseState::Created: + return QColor(Qt::cyan); + case ExerciseState::Started: + return QColor(Qt::darkGreen); + case ExerciseState::Paused: + return QColor(Qt::darkYellow); + case ExerciseState::Stopped: + return QColor(Qt::magenta); + case ExerciseState::Terminated: + return QColor(Qt::red); + } + } + } + return QVariant(); } - - - void ExerciseManagementProxyModel::setAdminExerciseVisible(bool bAdminVisible) { - if (m_bAdminVisible == bAdminVisible) - return; - m_bAdminVisible = bAdminVisible; - invalidateFilter(); + if (m_bAdminVisible == bAdminVisible) + return; + m_bAdminVisible = bAdminVisible; + invalidateFilter(); } -void ExerciseManagementProxyModel::setVisibleExerciseIds(const QVector &exIds) +void ExerciseManagementProxyModel::setVisibleExerciseIds(const QVector& exIds) { - if (m_exIds == exIds) - return; - m_exIds = exIds; - invalidateFilter(); + if (m_exIds == exIds) + return; + m_exIds = exIds; + invalidateFilter(); } -void ExerciseManagementProxyModel::setVisibleExerciseStates(const QVector &visibleStates) +void ExerciseManagementProxyModel::setVisibleExerciseStates(const QVector& visibleStates) { - if (m_visibleStates == visibleStates) - return; - m_visibleStates = visibleStates; - invalidateFilter(); + if (m_visibleStates == visibleStates) + return; + m_visibleStates = visibleStates; + invalidateFilter(); } -void ExerciseManagementProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void ExerciseManagementProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } -bool ExerciseManagementProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const +bool ExerciseManagementProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const { - if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->m_vecData.size()) + if (!m_sourceModel || source_parent.isValid() || source_row < 0 || source_row >= m_sourceModel->m_vecData.size()) + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + const auto& ex = m_sourceModel->m_vecData.at(source_row); + if (ex.id() == 0) + { + if (!m_bAdminVisible) + return false; + return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); + } + if (!m_exIds.contains(ex.id()) && !m_exIds.contains(-1)) + return false; + if (!m_visibleStates.contains(ex.state()) && !m_visibleStates.isEmpty()) + return false; return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - const auto &ex = m_sourceModel->m_vecData.at(source_row); - if (ex.id() == 0) - { - if (!m_bAdminVisible) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); - } - if (!m_exIds.contains(ex.id()) && !m_exIds.contains(-1)) - return false; - if (!m_visibleStates.contains(ex.state()) && !m_visibleStates.isEmpty()) - return false; - return LtsWidgets::LtsColumnFilterProxyModel::filterAcceptsRow(source_row, source_parent); } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.h old mode 100755 new mode 100644 index 81e4107b9..7f84775da --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_dialog_model.h @@ -1,148 +1,134 @@ - #pragma once -#include -#include -#include #include #include #include +#include +#include +#include #include - namespace ExerciseManagement { -class AbstractRequester - : public QObject +class AbstractRequester : public QObject { - Q_OBJECT -public: - AbstractRequester() - : QObject(nullptr) - {} + Q_OBJECT + public: + AbstractRequester() : QObject(nullptr) {} -signals: - void signalDone(); + signals: + void signalDone(); }; - - -class GetExerciseImageRequester - : public AbstractRequester - , public ExerciseManagement::Interface::Ftc::GetExerciseImageReplyHandler +class GetExerciseImageRequester : public AbstractRequester, + public ExerciseManagement::Interface::Ftc::GetExerciseImageReplyHandler { - Q_OBJECT + Q_OBJECT -private: + private: + NGL::INGLLogger& m_logger; + GetExerciseImageRequester() = default; -NGL::INGLLogger &m_logger; - GetExerciseImageRequester() = default; + public: + static GetExerciseImageRequester* createGetExerciseImageRequester() + { + return new GetExerciseImageRequester; + } -public: - static GetExerciseImageRequester *createGetExerciseImageRequester() - { - return new GetExerciseImageRequester; - } + const GetExerciseImageReply& reply() const + { + return m_reply; + } - const GetExerciseImageReply &reply() const - { - return m_reply; - } + void onGetExerciseImageReply(const GetExerciseImageReply& reply) override final + { + m_reply = reply; + emit signalDone(); + deleteLater(); + } - void onGetExerciseImageReply(const GetExerciseImageReply &reply) override final - { - m_reply = reply; - emit signalDone(); - deleteLater(); - } - -private: - GetExerciseImageReply m_reply; + private: + GetExerciseImageReply m_reply; }; - - - - -class ExerciseManagementDialogModel final - : public LtsWidgets::LtsAbstractTableModel +class ExerciseManagementDialogModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Id, - Name, - TrainingArea, - Begin, - End, - Started, - Stopped, - Status, - RadioGroup, - ActivePhase, - Created, - TimeZone, - Forces, - Description, - LinkedId, - Transferred, - HasHlaInterface, - Image - }; + public: + enum Columns { + Id, + Name, + TrainingArea, + Begin, + End, + Started, + Stopped, + Status, + RadioGroup, + ActivePhase, + Created, + TimeZone, + Forces, + Description, + LinkedId, + Transferred, + HasHlaInterface, + Image + }; - explicit ExerciseManagementDialogModel(QObject *parent = nullptr); - bool initModel(const std::shared_ptr &dtc, - const std::shared_ptr &ftc, - const std::shared_ptr &asmDtc, - const std::shared_ptr &pdmDtc, - bool addAdminExercise = false, - bool preloadExerciseImages = false); + explicit ExerciseManagementDialogModel(QObject* parent = nullptr); + bool initModel(const std::shared_ptr& dtc, + const std::shared_ptr& ftc, + const std::shared_ptr& asmDtc, + const std::shared_ptr& pdmDtc, bool addAdminExercise = false, + bool preloadExerciseImages = false); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; - void addImagePreload(int32_t exId); - void setImageSizeConstraints(const QSize &size); + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; + void addImagePreload(int32_t exId); + void setImageSizeConstraints(const QSize& size); -protected: - int getId(const ExerciseManagement::Exercise &data) const override final; + protected: + int getId(const ExerciseManagement::Exercise& data) const override final; -private slots: - void preloadNextImage(); + private slots: + void preloadNextImage(); -private: - GetExerciseImageRequester *createGetExerciseImageRequester(); + private: + GetExerciseImageRequester* createGetExerciseImageRequester(); - std::shared_ptr m_exmDtc; - std::shared_ptr m_exmFtc; - std::shared_ptr m_asmDtc; - std::shared_ptr m_pdmDtc; - QVector m_preloadImages; - QMap m_exerciseImages; - bool m_imagePreloadPending { false }; - QSize m_imageSize; - friend class ExerciseManagementProxyModel; + std::shared_ptr m_exmDtc; + std::shared_ptr m_exmFtc; + std::shared_ptr m_asmDtc; + std::shared_ptr m_pdmDtc; + QVector m_preloadImages; + QMap m_exerciseImages; + bool m_imagePreloadPending{false}; + QSize m_imageSize; + friend class ExerciseManagementProxyModel; }; class ExerciseManagementProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setAdminExerciseVisible(bool bAdminVisible); - void setVisibleExerciseStates(const QVector &visibleStates); - void setVisibleExerciseIds(const QVector &exIds); - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; -private: - ExerciseManagementDialogModel *m_sourceModel = nullptr; - QVector m_exIds; - QVector m_visibleStates; - bool m_bAdminVisible = false; + void setAdminExerciseVisible(bool bAdminVisible); + void setVisibleExerciseStates(const QVector& visibleStates); + void setVisibleExerciseIds(const QVector& exIds); + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; + + private: + ExerciseManagementDialogModel* m_sourceModel = nullptr; + QVector m_exIds; + QVector m_visibleStates; + bool m_bAdminVisible = false; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.cpp old mode 100755 new mode 100644 index e92cad06e..254b56ba1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.cpp @@ -1,1269 +1,1175 @@ - - #include "exm_edit_dialog.h" -#include -#include "ui_exm_edit_dialog.h" -#include "exm_edit_phase_dialog.h" -#include "exm_phase_model.h" -#include "exm_operator_model.h" -#include "exm_dialog_model.h" -#include "exm_edit_party_dialog.h" -#include +#include "exm_dialog_model.h" +#include "exm_edit_party_dialog.h" +#include "exm_edit_phase_dialog.h" +#include "exm_operator_model.h" +#include "exm_phase_model.h" +#include "ui_exm_edit_dialog.h" + +#include +#include #include #include #include -#include +#include #include #include -#include -#include - #include #include #include #include #include - +#include +#include namespace ExerciseManagement { - - -ExerciseManagementEditDialog::ExerciseManagementEditDialog(QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::ExerciseManagementEditDialog) - , m_currentState(ExerciseState::Unknown) - , m_menuGroup() - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ExerciseManagementEditDialog::ExerciseManagementEditDialog(QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::ExerciseManagementEditDialog), m_currentState(ExerciseState::Unknown), m_menuGroup(), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); - - connect(m_ui->imageEditor, &LtsWidgets::LtsImageEditor::signalClicked, - this, &ExerciseManagementEditDialog::slotChangeImage); + connect(m_ui->imageEditor, &LtsWidgets::LtsImageEditor::signalClicked, this, + &ExerciseManagementEditDialog::slotChangeImage); - m_ui->dvOperators->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->dvOperators, &LtsDataView::LtsDataView::customContextMenuRequested, this, &ExerciseManagementEditDialog::onContextMenuRequested); + m_ui->dvOperators->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->dvOperators, &LtsDataView::LtsDataView::customContextMenuRequested, this, + &ExerciseManagementEditDialog::onContextMenuRequested); - - m_ui->lbSymbolFilltype->setVisible(false); - m_ui->cbSymbolFilltype->setVisible(false); + m_ui->lbSymbolFilltype->setVisible(false); + m_ui->cbSymbolFilltype->setVisible(false); - for(int tz = 'Y'; tz <= 'Z'; ++tz) - m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); - for(int tz = 'A'; tz <= 'F'; ++tz) - m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); + for (int tz = 'Y'; tz <= 'Z'; ++tz) + m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); + for (int tz = 'A'; tz <= 'F'; ++tz) + m_ui->cbTimeZone->addItem(QString(QChar(tz)), tz); - const bool hasLinkedExercises = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), - QStringLiteral("CanBeLinked")); - const bool hasHlaInterface = LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), - QStringLiteral("HasHlaInterface")); - m_ui->cbLinkedExercise->setVisible(hasLinkedExercises); - m_ui->lblLinkedExercise->setVisible(hasLinkedExercises); - m_ui->cbStartHlaInterface->setVisible(hasHlaInterface); + const bool hasLinkedExercises = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), QStringLiteral("CanBeLinked")); + const bool hasHlaInterface = + LtsUtils::ProjectSettings::isFunctionEnabled(QStringLiteral("Exercises"), QStringLiteral("HasHlaInterface")); + m_ui->cbLinkedExercise->setVisible(hasLinkedExercises); + m_ui->lblLinkedExercise->setVisible(hasLinkedExercises); + m_ui->cbStartHlaInterface->setVisible(hasHlaInterface); } - ExerciseManagementEditDialog::~ExerciseManagementEditDialog() { - delete m_ui; + delete m_ui; } - void ExerciseManagementEditDialog::retranslate() { - - translate(m_ui, m_dtc->exercise(m_exerciseId), tr("Exercise")); - - m_uiRequirements->clear(); - m_uiRequirements->addRequirement( { m_ui->lblName, [this]() { return (!m_ui->leName->text().isEmpty()); } } ); - m_uiRequirements->addRequirement( { m_ui->lblStart, [this]() { return (!m_ui->dtBegin->isEmpty()); } } ); - m_uiRequirements->addRequirement( { m_ui->lblEnd, [this]() { return (!m_ui->dtEnd->isEmpty() && (m_ui->dtEnd->msecsSinceEpoch() > m_ui->dtBegin->msecsSinceEpoch())); }, tr("The end time must be bigger than the start time") }); + translate(m_ui, m_dtc->exercise(m_exerciseId), tr("Exercise")); - m_ui->btbDvOperators->setText(LtsWidgets::DialogButton::Edit, tr("Edit Visible Parties")); - m_buttonBox->setText(LtsWidgets::DialogButton::Export, tr("Save to library")); - m_buttonBox->setText(LtsWidgets::DialogButton::Import, tr("Load from library")); - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Create Folders")); + m_uiRequirements->clear(); + m_uiRequirements->addRequirement({m_ui->lblName, [this]() { return (!m_ui->leName->text().isEmpty()); }}); + m_uiRequirements->addRequirement({m_ui->lblStart, [this]() { return (!m_ui->dtBegin->isEmpty()); }}); + m_uiRequirements->addRequirement({m_ui->lblEnd, + [this]() { + return (!m_ui->dtEnd->isEmpty() && + (m_ui->dtEnd->msecsSinceEpoch() > m_ui->dtBegin->msecsSinceEpoch())); + }, + tr("The end time must be bigger than the start time")}); + + m_ui->btbDvOperators->setText(LtsWidgets::DialogButton::Edit, tr("Edit Visible Parties")); + m_buttonBox->setText(LtsWidgets::DialogButton::Export, tr("Save to library")); + m_buttonBox->setText(LtsWidgets::DialogButton::Import, tr("Load from library")); + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Create Folders")); } - -bool ExerciseManagementEditDialog::init(LtsSession::LtsSessionDataDds *session, - const QString &menuGroup, +bool ExerciseManagementEditDialog::init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup, const int exerciseId) { - m_session = session; - m_menuGroup = menuGroup; - m_exerciseId = exerciseId; + m_session = session; + m_menuGroup = menuGroup; + m_exerciseId = exerciseId; - if (!m_session->getDtc(m_dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; - if (!m_session->getDtc(m_pdmDtc)) - return false; - if (!m_session->getDtc(m_asmDtc)) - return false; - if (!m_session->getDtc(m_opmDtc)) - return false; - if (!m_session->getDtc(m_flmDtc)) - return false; - if (!m_session->getFtc(m_flmFtc)) - return false; + if (!m_session->getDtc(m_dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; + if (!m_session->getDtc(m_pdmDtc)) + return false; + if (!m_session->getDtc(m_asmDtc)) + return false; + if (!m_session->getDtc(m_opmDtc)) + return false; + if (!m_session->getDtc(m_flmDtc)) + return false; + if (!m_session->getFtc(m_flmFtc)) + return false; - ExerciseManagement::Exercise data = m_dtc->exercise(exerciseId); - m_currentState = data.state(); - m_ui->dtBegin->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - m_ui->dtEnd->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + ExerciseManagement::Exercise data = m_dtc->exercise(exerciseId); + m_currentState = data.state(); + m_ui->dtBegin->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); + m_ui->dtEnd->setRetrieveCurrentTimeCallback([this]() { return m_session->partitionTime(); }); - m_phaseModel = new ExercisePhaseModel(this); - m_phaseModel->initModel(m_exerciseId, m_dtc); - m_phaseProxyModel = new ExercisePhaseProxyModel(this); - m_phaseProxyModel->setSourceModel(m_phaseModel); + m_phaseModel = new ExercisePhaseModel(this); + m_phaseModel->initModel(m_exerciseId, m_dtc); + m_phaseProxyModel = new ExercisePhaseProxyModel(this); + m_phaseProxyModel->setSourceModel(m_phaseModel); - m_operatorModel = new ExerciseOperatorModel(m_session, m_exerciseId, this); - connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, this, &ExerciseManagementEditDialog::slotChangesMade); + m_operatorModel = new ExerciseOperatorModel(m_session, m_exerciseId, this); + connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, this, &ExerciseManagementEditDialog::slotChangesMade); - - if (data.id() > 0) - { - m_ui->leName->setText(QString::fromStdString(data.name())); - m_ui->dtBegin->setTimezone(data.defaultTimeZone()); - m_ui->dtBegin->setMsecsSinceEpoch(data.beginTime()); - m_ui->dtEnd->setTimezone(data.defaultTimeZone()); - m_ui->dtEnd->setMsecsSinceEpoch(data.endTime()); + if (data.id() > 0) + { + m_ui->leName->setText(QString::fromStdString(data.name())); + m_ui->dtBegin->setTimezone(data.defaultTimeZone()); + m_ui->dtBegin->setMsecsSinceEpoch(data.beginTime()); + m_ui->dtEnd->setTimezone(data.defaultTimeZone()); + m_ui->dtEnd->setMsecsSinceEpoch(data.endTime()); - m_ui->pteDescription->setPlainText(QString::fromStdString(data.description())); - m_ui->pteForces->setPlainText(QString::fromStdString(data.forces())); - m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData(data.defaultTimeZone())); - m_ui->cbStartHlaInterface->setChecked(data.hasHlaInterface()); - } - else - { - m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData('Z')); - m_ui->dtBegin->setMsecsSinceEpoch(m_session->partitionTime()); - m_ui->dtEnd->setMsecsSinceEpoch(m_session->partitionTime() + 1000 * 60 * 60 * 24); - - } - - - - m_ui->dvPhases->setModel(m_phaseProxyModel); - m_ui->dvPhases->hideColumn(ExercisePhaseModel::Description); - m_ui->dvPhases->hideColumn(ExercisePhaseModel::ExerciseId); - m_ui->dvPhases->seamless(); - m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Add, this, &ExerciseManagementEditDialog::onAddExercisePhase); - m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementEditDialog::onEditExercisePhase); - m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Remove, this, &ExerciseManagementEditDialog::onRemoveExercisePhase); - - m_ui->dvOperators->setModel(m_operatorModel); - m_ui->dvOperators->seamless(); - - m_ui->btbDvOperators->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementEditDialog::onEditVisibleParties); - connect(m_ui->dvOperators, &LtsDataView::LtsDataView::signalDoubleClicked, this, &ExerciseManagementEditDialog::onEditVisibleParties); - - - m_ui->btbDvOperators->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); - m_ui->btbDvOperators->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - - connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, - this, &ExerciseManagementEditDialog::enaDisaOperatorsButtons); - connect(m_ui->dvOperators, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ExerciseManagementEditDialog::enaDisaOperatorsButtons); - enaDisaOperatorsButtons(); - - - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Apply)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Help)->setVisible(false); - - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), - QStringLiteral("enableEditPhases")).toBool(); - if (!enableEditPhases) - { - m_ui->lblPhases->hide(); - m_ui->dvPhases->hide(); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Add)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Edit)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Remove)->setVisible(false); - m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - - m_ui->lblActivePhase->hide(); - m_ui->cbActivePhase->hide(); - } - - connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ExerciseManagementEditDialog::onEditExercisePhase); - connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ExerciseManagementEditDialog::enaDisaPhaseButtons); - connect(m_ui->cbTimeZone, &QComboBox::currentTextChanged, - this, &ExerciseManagementEditDialog::onTimeZoneChanged); - - enaDisaPhaseButtons(); - - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Export, this, &ExerciseManagementEditDialog::onExport); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Import, this, &ExerciseManagementEditDialog::onImport); - - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &ExerciseManagementEditDialog::onCreateFolders); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - - if (!session->getForeignGuiInterface(m_flmGui)) - { - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Import, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Export, false); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - } - - - fillAllCbx(); - - - m_ui->cbState->setEnabled(m_ui->cbState->count() > 1); - - - connect(m_dtc.get(), &Interface::Dtc::exercisePhaseChanged, this, &ExerciseManagementEditDialog::onExercisePhaseChanged); - m_ui->cbActivePhase->setCurrentIndex(m_ui->cbActivePhase->findData(QVariant(data.activePhaseId()))); - - - connect(m_dtc.get(), &Interface::Dtc::exerciseChanged, this, &ExerciseManagementEditDialog::onExerciseChanged); - m_initialRadioGroupId.clear(); - if (data.radioGroupId().is_set()) - { - int curIdx = m_ui->cbRadioGroup->findData(QVariant(data.radioGroupId().get())); - if (curIdx < 0) - curIdx = 0; + m_ui->pteDescription->setPlainText(QString::fromStdString(data.description())); + m_ui->pteForces->setPlainText(QString::fromStdString(data.forces())); + m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData(data.defaultTimeZone())); + m_ui->cbStartHlaInterface->setChecked(data.hasHlaInterface()); + } else - m_initialRadioGroupId = data.radioGroupId().get(); - m_ui->cbRadioGroup->setCurrentIndex(curIdx); - } - m_ui->cbVisibleInWarehouse->setChecked(data.sendToWMS()); - m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(data.linkedExerciseId())); + { + m_ui->cbTimeZone->setCurrentIndex(m_ui->cbTimeZone->findData('Z')); + m_ui->dtBegin->setMsecsSinceEpoch(m_session->partitionTime()); + m_ui->dtEnd->setMsecsSinceEpoch(m_session->partitionTime() + 1000 * 60 * 60 * 24); + } - - if (data.trainingAreaId() > 0) - { - int idx = m_ui->cbTrainingArea->findData(QVariant(data.trainingAreaId())); - m_ui->cbTrainingArea->setCurrentIndex(idx); - } + m_ui->dvPhases->setModel(m_phaseProxyModel); + m_ui->dvPhases->hideColumn(ExercisePhaseModel::Description); + m_ui->dvPhases->hideColumn(ExercisePhaseModel::ExerciseId); + m_ui->dvPhases->seamless(); + m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Add, this, + &ExerciseManagementEditDialog::onAddExercisePhase); + m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Edit, this, + &ExerciseManagementEditDialog::onEditExercisePhase); + m_ui->btbDvPhases->connectButton(LtsWidgets::DialogButton::Remove, this, + &ExerciseManagementEditDialog::onRemoveExercisePhase); - if (m_exerciseId < 1) - { - - m_ui->lblState->hide(); - m_ui->cbState->hide(); + m_ui->dvOperators->setModel(m_operatorModel); + m_ui->dvOperators->seamless(); - - - + m_ui->btbDvOperators->connectButton(LtsWidgets::DialogButton::Edit, this, + &ExerciseManagementEditDialog::onEditVisibleParties); + connect(m_ui->dvOperators, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ExerciseManagementEditDialog::onEditVisibleParties); - - - + m_ui->btbDvOperators->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); + m_ui->btbDvOperators->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - - m_ui->cbActivePhase->hide(); - m_ui->lblActivePhase->hide(); + connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, this, + &ExerciseManagementEditDialog::enaDisaOperatorsButtons); + connect(m_ui->dvOperators, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &ExerciseManagementEditDialog::enaDisaOperatorsButtons); + enaDisaOperatorsButtons(); - - m_ui->dvPhases->hide(); - m_ui->lblPhases->hide(); - m_ui->btbDvPhases->hide(); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Ok)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Apply)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Help)->setVisible(false); - - m_ui->line->hide(); - + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); + if (!enableEditPhases) + { + m_ui->lblPhases->hide(); + m_ui->dvPhases->hide(); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Add)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Edit)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Remove)->setVisible(false); + m_ui->btbDvPhases->getButton(LtsWidgets::DialogButton::Close)->setVisible(false); - QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); - if (!QFile(projectLogoFilename).exists()) - projectLogoFilename = QStringLiteral(":/project/logo.png"); + m_ui->lblActivePhase->hide(); + m_ui->cbActivePhase->hide(); + } - m_ui->imageEditor->setPixmap(QPixmap(projectLogoFilename)); - m_pictureChanged = true; - } + connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ExerciseManagementEditDialog::onEditExercisePhase); + connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &ExerciseManagementEditDialog::enaDisaPhaseButtons); + connect(m_ui->cbTimeZone, &QComboBox::currentTextChanged, this, &ExerciseManagementEditDialog::onTimeZoneChanged); - if (m_exerciseId < 0) - setOnlineHelpFilename(QStringLiteral("Administrator-Add_Exercise")); - else - setOnlineHelpFilename(QStringLiteral("Administrator-Edit_Exercise")); + enaDisaPhaseButtons(); - enaDisa(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Export, this, &ExerciseManagementEditDialog::onExport); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Import, this, &ExerciseManagementEditDialog::onImport); - - requestImage(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, this, &ExerciseManagementEditDialog::onCreateFolders); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - return true; + if (!session->getForeignGuiInterface(m_flmGui)) + { + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Import, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Export, false); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + } + + fillAllCbx(); + + m_ui->cbState->setEnabled(m_ui->cbState->count() > 1); + + connect(m_dtc.get(), &Interface::Dtc::exercisePhaseChanged, this, + &ExerciseManagementEditDialog::onExercisePhaseChanged); + m_ui->cbActivePhase->setCurrentIndex(m_ui->cbActivePhase->findData(QVariant(data.activePhaseId()))); + + connect(m_dtc.get(), &Interface::Dtc::exerciseChanged, this, &ExerciseManagementEditDialog::onExerciseChanged); + m_initialRadioGroupId.clear(); + if (data.radioGroupId().is_set()) + { + int curIdx = m_ui->cbRadioGroup->findData(QVariant(data.radioGroupId().get())); + if (curIdx < 0) + curIdx = 0; + else + m_initialRadioGroupId = data.radioGroupId().get(); + m_ui->cbRadioGroup->setCurrentIndex(curIdx); + } + m_ui->cbVisibleInWarehouse->setChecked(data.sendToWMS()); + m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(data.linkedExerciseId())); + + if (data.trainingAreaId() > 0) + { + int idx = m_ui->cbTrainingArea->findData(QVariant(data.trainingAreaId())); + m_ui->cbTrainingArea->setCurrentIndex(idx); + } + + if (m_exerciseId < 1) + { + + m_ui->lblState->hide(); + m_ui->cbState->hide(); + + m_ui->cbActivePhase->hide(); + m_ui->lblActivePhase->hide(); + + m_ui->dvPhases->hide(); + m_ui->lblPhases->hide(); + m_ui->btbDvPhases->hide(); + + m_ui->line->hide(); + + QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); + if (!QFile(projectLogoFilename).exists()) + projectLogoFilename = QStringLiteral(":/project/logo.png"); + + m_ui->imageEditor->setPixmap(QPixmap(projectLogoFilename)); + m_pictureChanged = true; + } + + if (m_exerciseId < 0) + setOnlineHelpFilename(QStringLiteral("Administrator-Add_Exercise")); + else + setOnlineHelpFilename(QStringLiteral("Administrator-Edit_Exercise")); + + enaDisa(); + + requestImage(); + + return true; } - void ExerciseManagementEditDialog::requestImage() { - GetExerciseImageRequester *requester = GetExerciseImageRequester::createGetExerciseImageRequester(); + GetExerciseImageRequester* requester = GetExerciseImageRequester::createGetExerciseImageRequester(); - connect(requester, &GetExerciseImageRequester::signalDone, - this, [this, requester]() - { - onGetExerciseImageReply(requester->reply()); - }); + connect(requester, &GetExerciseImageRequester::signalDone, this, + [this, requester]() { onGetExerciseImageReply(requester->reply()); }); - m_ftc->enableGetExerciseImage(); - m_ftc->getExerciseImageRequest(GetExerciseImageRequest(m_exerciseId, m_ui->imageEditor->height(), m_ui->imageEditor->width(), false), requester); + m_ftc->enableGetExerciseImage(); + m_ftc->getExerciseImageRequest( + GetExerciseImageRequest(m_exerciseId, m_ui->imageEditor->height(), m_ui->imageEditor->width(), false), + requester); } - -void ExerciseManagementEditDialog::onGetExerciseImageReply(const GetExerciseImageReply &reply) +void ExerciseManagementEditDialog::onGetExerciseImageReply(const GetExerciseImageReply& reply) { - if (reply.errorString().empty()) - { - m_ui->imageEditor->setPixmap(LtsUtils::getPixmap(reply.imageData())); - return; - } + if (reply.errorString().empty()) + { + m_ui->imageEditor->setPixmap(LtsUtils::getPixmap(reply.imageData())); + return; + } - QString msg(QString::fromStdString(reply.errorString())); - for (const std::string &arg : std::as_const(reply.errorParams())) - msg = msg.arg(QString::fromStdString(arg)); + QString msg(QString::fromStdString(reply.errorString())); + for (const std::string& arg : std::as_const(reply.errorParams())) + msg = msg.arg(QString::fromStdString(arg)); - ERROR_LOG(m_logger) << "loading exercise image failed: " << msg; - + ERROR_LOG(m_logger) << "loading exercise image failed: " << msg; - - QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); - if (!QFile(projectLogoFilename).exists()) - projectLogoFilename = QStringLiteral(":/project/logo.png"); + QString projectLogoFilename(QStringLiteral(":project/login_logo.png")); + if (!QFile(projectLogoFilename).exists()) + projectLogoFilename = QStringLiteral(":/project/logo.png"); - m_ui->imageEditor->setPixmap(QPixmap(projectLogoFilename)); + m_ui->imageEditor->setPixmap(QPixmap(projectLogoFilename)); } void ExerciseManagementEditDialog::onTimeZoneChanged() { - QChar tz = m_ui->cbTimeZone->currentData().toChar(); + QChar tz = m_ui->cbTimeZone->currentData().toChar(); - m_ui->dtBegin->setTimezone(tz.toLatin1()); - m_ui->dtEnd->setTimezone(tz.toLatin1()); + m_ui->dtBegin->setTimezone(tz.toLatin1()); + m_ui->dtEnd->setTimezone(tz.toLatin1()); } -bool ExerciseManagementEditDialog::hasVisibleParties(const std::vector vpbe) const +bool ExerciseManagementEditDialog::hasVisibleParties( + const std::vector vpbe) const { - for (const auto &pbe : vpbe) - { - if (pbe.exerciseId() != m_exerciseId) - continue; + for (const auto& pbe : vpbe) + { + if (pbe.exerciseId() != m_exerciseId) + continue; - return pbe.visibleParties().is_set(); - } - return false; + return pbe.visibleParties().is_set(); + } + return false; } void ExerciseManagementEditDialog::enaDisaOperatorsButtons() { - const QModelIndex idx = m_ui->dvOperators->currentIndex(); - if (!idx.isValid()) - { - m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - return; - } - const QPair row = m_operatorModel->getRowData(idx.row()); - bool visibleParties = hasVisibleParties(row.second.visiblePartiesByExercise()); - bool isChecked = row.first; + const QModelIndex idx = m_ui->dvOperators->currentIndex(); + if (!idx.isValid()) + { + m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + return; + } + const QPair row = m_operatorModel->getRowData(idx.row()); + bool visibleParties = hasVisibleParties(row.second.visiblePartiesByExercise()); + bool isChecked = row.first; - if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ExerciseOperatorEdit)) - m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, (visibleParties && isChecked)); - else - m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ExerciseOperatorEdit)) + m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, (visibleParties && isChecked)); + else + m_ui->btbDvOperators->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); } void ExerciseManagementEditDialog::enaDisaPhaseButtons() { - QModelIndexList selectedRows = m_ui->dvPhases->selectedRows(); - const int cntSelectedRows = selectedRows.size(); + QModelIndexList selectedRows = m_ui->dvPhases->selectedRows(); + const int cntSelectedRows = selectedRows.size(); - if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ExercisePhaseEdit)) - { - m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); - } - else - { - m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Add, false); - m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); - m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); - } + if (LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::ExercisePhaseEdit)) + { + m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); + } + else + { + m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Add, false); + m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Edit, false); + m_ui->btbDvPhases->setButtonEnabled(LtsWidgets::DialogButton::Remove, false); + } } void ExerciseManagementEditDialog::onAddExercisePhase() { - ExerciseManagementPhaseEditDialog *dialog = new ExerciseManagementPhaseEditDialog(this); - dialog->init(m_session, m_exerciseId, -1 ); + ExerciseManagementPhaseEditDialog* dialog = new ExerciseManagementPhaseEditDialog(this); + dialog->init(m_session, m_exerciseId, -1); - addDialog(dialog, m_menuGroup, QLatin1String("NewExercisePhase"), LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, QLatin1String("NewExercisePhase"), LtsWidgets::LayoutArea::eDialogTab); } void ExerciseManagementEditDialog::onRemoveExercisePhase() { - const int phId = m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id(); - const int folderId = m_flmDtc->getPhaseFolderId(m_exerciseId, phId); + const int phId = m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id(); + const int folderId = m_flmDtc->getPhaseFolderId(m_exerciseId, phId); - if (folderId > 0) - { - Core::RemoveElementRequest req(folderId); - m_requestHelper->startSingleRequest([req, this]() + if (folderId > 0) { - return m_flmFtc->folderRemoveRequest(req, this); - }); - } + Core::RemoveElementRequest req(folderId); + m_requestHelper->startSingleRequest([req, this]() { return m_flmFtc->folderRemoveRequest(req, this); }); + } - Core::RemoveElementRequest req(m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id()); - m_requestHelper->startSingleRequest([req, this]() - { - m_ftc->enableExercisePhaseRemove(); - return m_ftc->exercisePhaseRemoveRequest(req, this); - }); + Core::RemoveElementRequest req(m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id()); + m_requestHelper->startSingleRequest([req, this]() { + m_ftc->enableExercisePhaseRemove(); + return m_ftc->exercisePhaseRemoveRequest(req, this); + }); } void ExerciseManagementEditDialog::onEditVisibleParties() { - if (m_exerciseId == -1) - return; + if (m_exerciseId == -1) + return; - const QModelIndex idx = m_ui->dvOperators->currentIndex(); - const QPair row = m_operatorModel->getRowData(idx.row()); - const int operatorId = row.second.id(); - bool isChecked = row.first; - bool visibleParties = hasVisibleParties(row.second.visiblePartiesByExercise()); + const QModelIndex idx = m_ui->dvOperators->currentIndex(); + const QPair row = m_operatorModel->getRowData(idx.row()); + const int operatorId = row.second.id(); + bool isChecked = row.first; + bool visibleParties = hasVisibleParties(row.second.visiblePartiesByExercise()); - if (operatorId <= 0 || isChecked == false || !visibleParties) - return; - DEBUG_LOG(m_logger) << "current Operator Id: " << operatorId; + if (operatorId <= 0 || isChecked == false || !visibleParties) + return; + DEBUG_LOG(m_logger) << "current Operator Id: " << operatorId; + ExerciseEditPartyDialog* dialog = new ExerciseEditPartyDialog(operatorId, m_exerciseId, m_menuGroup, this); - ExerciseEditPartyDialog *dialog = new ExerciseEditPartyDialog(operatorId, m_exerciseId, m_menuGroup, this); + if (!dialog->init(m_session)) + return; - if (!dialog->init(m_session)) - return; - - const QString identifier = QLatin1String("EditParties") + QString::number(operatorId) + QString::number(m_exerciseId); - addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); + const QString identifier = + QLatin1String("EditParties") + QString::number(operatorId) + QString::number(m_exerciseId); + addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); } void ExerciseManagementEditDialog::onEditExercisePhase() { - const QModelIndex idx = m_ui->dvPhases->currentIndex(); - const ExercisePhase exPhase = m_phaseModel->getRowData(idx.row()); + const QModelIndex idx = m_ui->dvPhases->currentIndex(); + const ExercisePhase exPhase = m_phaseModel->getRowData(idx.row()); - if (exPhase.id() <= 0) - return; - DEBUG_LOG(m_logger) << "current exPhase Id: " << exPhase.id(); + if (exPhase.id() <= 0) + return; + DEBUG_LOG(m_logger) << "current exPhase Id: " << exPhase.id(); - ExerciseManagementPhaseEditDialog *dialog = new ExerciseManagementPhaseEditDialog(this); + ExerciseManagementPhaseEditDialog* dialog = new ExerciseManagementPhaseEditDialog(this); - dialog->init(m_session, m_exerciseId, exPhase.id()); - const QString identifier = QLatin1String("EditExercisePhase") + QString::number(exPhase.id()); + dialog->init(m_session, m_exerciseId, exPhase.id()); + const QString identifier = QLatin1String("EditExercisePhase") + QString::number(exPhase.id()); - addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); } void ExerciseManagementEditDialog::onExport() { - DEBUG_LOG(m_logger) << "onExport"; + DEBUG_LOG(m_logger) << "onExport"; - const QByteArray byteArray = exerciseToJson(); - DEBUG_LOG(m_logger) << "Exporting: " << byteArray; + const QByteArray byteArray = exerciseToJson(); + DEBUG_LOG(m_logger) << "Exporting: " << byteArray; - int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, 0, byteArray); - if (fileId > 0) - DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; - else - ERROR_LOG(m_logger) << "Could not save file in library "; + int fileId = m_flmGui->saveFileContent(this, FileManagement::FileType::Xml, 0, byteArray); + if (fileId > 0) + DEBUG_LOG(m_logger) << "Saved file with id = " << fileId; + else + ERROR_LOG(m_logger) << "Could not save file in library "; } void ExerciseManagementEditDialog::onImport() { - DEBUG_LOG(m_logger) << "onImport"; + DEBUG_LOG(m_logger) << "onImport"; - QByteArray content; - int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, 0, JsonKeys::XMLTYPEVALUE()); - if (fileId > 0) - { - if (!m_flmGui->isXmlType(content, JsonKeys::XMLTYPEVALUE())) + QByteArray content; + int fileId = m_flmGui->loadFileContent(this, content, {FileManagement::FileType::Xml}, 0, JsonKeys::XMLTYPEVALUE()); + if (fileId > 0) { - QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); - LtsWidgets::LtsMessageDialog::showMessage(this, - tr("Invalid xml file content"), - windowTitle(), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes, - texts); - } - else - { - ExerciseModifyRequest req = jsonToExercise(content); - DEBUG_LOG(m_logger) << "Importing: " << req; + if (!m_flmGui->isXmlType(content, JsonKeys::XMLTYPEVALUE())) + { + QHash texts({{LtsWidgets::Button::Yes, tr("Ok")}}); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Invalid xml file content"), windowTitle(), + LtsWidgets::Behaviour::Modal, LtsWidgets::Button::Yes, texts); + } + else + { + ExerciseModifyRequest req = jsonToExercise(content); + DEBUG_LOG(m_logger) << "Importing: " << req; - m_ui->pteForces->setPlainText(QString::fromStdString(req.forces())); - m_ui->pteDescription->setPlainText(QString::fromStdString(req.description())); + m_ui->pteForces->setPlainText(QString::fromStdString(req.forces())); + m_ui->pteDescription->setPlainText(QString::fromStdString(req.description())); + } } - } - return; + return; } void ExerciseManagementEditDialog::slotChangeImage() { - if (!m_ui->imageEditor->pixmap().isNull()) - { - if (LtsWidgets::LtsMessageDialog::showMessage(this, tr("Yes - overwrite image.
" - "Cancel - do not overwrite image.
"), - tr("Do you really want to overwrite the current image?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel) != LtsWidgets::Button::Yes) - return; - } + if (!m_ui->imageEditor->pixmap().isNull()) + { + if (LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Yes - overwrite image.
" + "Cancel - do not overwrite image.
"), + tr("Do you really want to overwrite the current image?"), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::Cancel) != LtsWidgets::Button::Yes) + return; + } - const QStringList filter ({ - tr("Images (*.jpg *.jpeg *.png)") - }); - QString fileName = QFileDialog::getOpenFileName(this, - tr("Select new image for this exercise"), - QString(), - filter.join(QStringLiteral(";;"))); + const QStringList filter({tr("Images (*.jpg *.jpeg *.png)")}); + QString fileName = QFileDialog::getOpenFileName(this, tr("Select new image for this exercise"), QString(), + filter.join(QStringLiteral(";;"))); - if (fileName.isEmpty()) - return; + if (fileName.isEmpty()) + return; - QPixmap pixmap; - if (!pixmap.load(fileName)) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Cannot load image '%1'").arg(fileName)); - return; - } + QPixmap pixmap; + if (!pixmap.load(fileName)) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Cannot load image '%1'").arg(fileName)); + return; + } - QSize newImgSize(200, 200); - QRect requestedRect(QPoint(0, 0), newImgSize); - QRect pictureRect(QPoint(0, 0), pixmap.size()); + QSize newImgSize(200, 200); + QRect requestedRect(QPoint(0, 0), newImgSize); + QRect pictureRect(QPoint(0, 0), pixmap.size()); - if (pictureRect.contains(requestedRect)) - pixmap = pixmap.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation); + if (pictureRect.contains(requestedRect)) + pixmap = pixmap.scaled(200, 200, Qt::KeepAspectRatio, Qt::SmoothTransformation); - m_ui->imageEditor->setPixmap(pixmap); + m_ui->imageEditor->setPixmap(pixmap); - m_pictureChanged = true; - slotChangesMade(); + m_pictureChanged = true; + slotChangesMade(); } void ExerciseManagementEditDialog::imageModifyError() { - if (m_exerciseId > 0) - m_ui->imageEditor->setPixmap(QPixmap()); + if (m_exerciseId > 0) + m_ui->imageEditor->setPixmap(QPixmap()); - - requestImage(); + requestImage(); } -void ExerciseManagementEditDialog::onExerciseChanged(const ExerciseManagement::Exercise &data, DataModification modType) +void ExerciseManagementEditDialog::onExerciseChanged(const ExerciseManagement::Exercise& data, DataModification modType) { - Q_UNUSED(modType) - if (data.id() == m_exerciseId) - { - const bool wasModified = hasUnsavedChanges(); - m_currentState = data.state(); - enaDisa(); - fillStateCbx(); - m_ui->cbVisibleInWarehouse->setChecked(data.sendToWMS()); - m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(data.linkedExerciseId())); - if (!wasModified) - __unchange__(); - } - else - fillRadioGroupCbx(); + Q_UNUSED(modType) + if (data.id() == m_exerciseId) + { + const bool wasModified = hasUnsavedChanges(); + m_currentState = data.state(); + enaDisa(); + fillStateCbx(); + m_ui->cbVisibleInWarehouse->setChecked(data.sendToWMS()); + m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(data.linkedExerciseId())); + if (!wasModified) + __unchange__(); + } + else + fillRadioGroupCbx(); } -void ExerciseManagementEditDialog::onExercisePhaseChanged(const ExerciseManagement::ExercisePhase &data, DataModification modType) +void ExerciseManagementEditDialog::onExercisePhaseChanged(const ExerciseManagement::ExercisePhase& data, + DataModification modType) { - Q_UNUSED(modType) - if (data.exerciseId() == m_exerciseId) - fillActivePhaseCbx(); + Q_UNUSED(modType) + if (data.exerciseId() == m_exerciseId) + fillActivePhaseCbx(); } void ExerciseManagementEditDialog::enaDisa() { - const bool wmsChecked = m_ui->cbVisibleInWarehouse->isChecked(); - const bool exerciseIsRunning = (m_currentState == ExerciseManagement::ExerciseState::Started || - m_currentState == ExerciseManagement::ExerciseState::Paused); - const bool exerciseIsFinished = (m_currentState == ExerciseManagement::ExerciseState::Stopped || - m_currentState == ExerciseManagement::ExerciseState::Terminated); - bool radioGroupAssignable = !exerciseIsFinished; - if (radioGroupAssignable && exerciseIsRunning) - radioGroupAssignable = m_initialRadioGroupId.isNull(); - if (radioGroupAssignable) - radioGroupAssignable = (m_ui->cbRadioGroup->count() > 1); + const bool wmsChecked = m_ui->cbVisibleInWarehouse->isChecked(); + const bool exerciseIsRunning = (m_currentState == ExerciseManagement::ExerciseState::Started || + m_currentState == ExerciseManagement::ExerciseState::Paused); + const bool exerciseIsFinished = (m_currentState == ExerciseManagement::ExerciseState::Stopped || + m_currentState == ExerciseManagement::ExerciseState::Terminated); + bool radioGroupAssignable = !exerciseIsFinished; + if (radioGroupAssignable && exerciseIsRunning) + radioGroupAssignable = m_initialRadioGroupId.isNull(); + if (radioGroupAssignable) + radioGroupAssignable = (m_ui->cbRadioGroup->count() > 1); - m_ui->cbVisibleInWarehouse->setEnabled(!exerciseIsRunning || !wmsChecked); - m_ui->cbLinkedExercise->setEnabled(!exerciseIsRunning && m_exerciseId > 0); - m_ui->cbRadioGroup->setEnabled(radioGroupAssignable); - m_ui->cbTrainingArea->setEnabled(!exerciseIsRunning && !exerciseIsFinished); - if (getExerciseFolder() <= 0) - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); - else - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + m_ui->cbVisibleInWarehouse->setEnabled(!exerciseIsRunning || !wmsChecked); + m_ui->cbLinkedExercise->setEnabled(!exerciseIsRunning && m_exerciseId > 0); + m_ui->cbRadioGroup->setEnabled(radioGroupAssignable); + m_ui->cbTrainingArea->setEnabled(!exerciseIsRunning && !exerciseIsFinished); + if (getExerciseFolder() <= 0) + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, true); + else + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); } - void ExerciseManagementEditDialog::fillStateCbx() { - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableExerciseTerminatedToStopped = ps->value(QStringLiteral("exm"), - QStringLiteral("enableExerciseTerminatedToStopped")).toBool(); + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableExerciseTerminatedToStopped = + ps->value(QStringLiteral("exm"), QStringLiteral("enableExerciseTerminatedToStopped")).toBool(); - - m_ui->cbState->clear(); - switch (m_currentState.underlying()) - { - case ExerciseState::Created: - m_ui->cbState->addItem(tr("Created"), ExerciseState::Created); - m_ui->cbState->addItem(tr("Start"), ExerciseState::Started); - break; - case ExerciseState::Started: - m_ui->cbState->addItem(tr("Started"), ExerciseState::Started); - m_ui->cbState->addItem(tr("Pause"), ExerciseState::Paused); - m_ui->cbState->addItem(tr("Stop"), ExerciseState::Stopped); - break; - case ExerciseState::Paused: - m_ui->cbState->addItem(tr("Paused"), ExerciseState::Paused); - m_ui->cbState->addItem(tr("Resume"), ExerciseState::Started); - m_ui->cbState->addItem(tr("Stop"), ExerciseState::Stopped); - break; - case ExerciseState::Stopped: - m_ui->cbState->addItem(tr("Stopped"), ExerciseState::Stopped); - m_ui->cbState->addItem(tr("Terminated"), ExerciseState::Terminated); - break; - case ExerciseState::Terminated: - m_ui->cbState->addItem(tr("Terminated"), ExerciseState::Terminated); - if (enableExerciseTerminatedToStopped) - m_ui->cbState->addItem(tr("Stopped"), ExerciseState::Stopped); - break; - case ExerciseState::Unknown: - m_ui->cbState->addItem(tr("Unknown"), ExerciseState::Unknown); - break; - } + m_ui->cbState->clear(); + switch (m_currentState.underlying()) + { + case ExerciseState::Created: + m_ui->cbState->addItem(tr("Created"), ExerciseState::Created); + m_ui->cbState->addItem(tr("Start"), ExerciseState::Started); + break; + case ExerciseState::Started: + m_ui->cbState->addItem(tr("Started"), ExerciseState::Started); + m_ui->cbState->addItem(tr("Pause"), ExerciseState::Paused); + m_ui->cbState->addItem(tr("Stop"), ExerciseState::Stopped); + break; + case ExerciseState::Paused: + m_ui->cbState->addItem(tr("Paused"), ExerciseState::Paused); + m_ui->cbState->addItem(tr("Resume"), ExerciseState::Started); + m_ui->cbState->addItem(tr("Stop"), ExerciseState::Stopped); + break; + case ExerciseState::Stopped: + m_ui->cbState->addItem(tr("Stopped"), ExerciseState::Stopped); + m_ui->cbState->addItem(tr("Terminated"), ExerciseState::Terminated); + break; + case ExerciseState::Terminated: + m_ui->cbState->addItem(tr("Terminated"), ExerciseState::Terminated); + if (enableExerciseTerminatedToStopped) + m_ui->cbState->addItem(tr("Stopped"), ExerciseState::Stopped); + break; + case ExerciseState::Unknown: + m_ui->cbState->addItem(tr("Unknown"), ExerciseState::Unknown); + break; + } } void ExerciseManagementEditDialog::fillTrainingAreaCbx() { - - int curIdxTa = m_ui->cbTrainingArea->currentIndex(); - m_ui->cbTrainingArea->clear(); - auto cb = [this](const AssetManagement::TrainingArea &ta) - { - m_ui->cbTrainingArea->addItem(QString::fromStdString(ta.name()), QVariant(ta.id())); - }; - m_asmDtc->trainingAreas(cb); - m_ui->cbTrainingArea->model()->sort(0); - if (curIdxTa >= 0) - m_ui->cbTrainingArea->setCurrentIndex(curIdxTa); + int curIdxTa = m_ui->cbTrainingArea->currentIndex(); + m_ui->cbTrainingArea->clear(); + auto cb = [this](const AssetManagement::TrainingArea& ta) { + m_ui->cbTrainingArea->addItem(QString::fromStdString(ta.name()), QVariant(ta.id())); + }; + m_asmDtc->trainingAreas(cb); + m_ui->cbTrainingArea->model()->sort(0); + + if (curIdxTa >= 0) + m_ui->cbTrainingArea->setCurrentIndex(curIdxTa); } void ExerciseManagementEditDialog::fillActivePhaseCbx() { - - int curIdxActPh = m_ui->cbActivePhase->currentIndex(); - m_ui->cbActivePhase->clear(); - auto cb = [this](const ExerciseManagement::ExercisePhase &phase) - { - if (m_exerciseId == phase.exerciseId()) - m_ui->cbActivePhase->addItem(QString::fromStdString(phase.name()), QVariant(phase.id())); - }; - m_dtc->exercisePhases(cb); - m_ui->cbActivePhase->setEnabled(m_ui->cbActivePhase->count() > 1); - if (curIdxActPh >= 0) - m_ui->cbActivePhase->setCurrentIndex(curIdxActPh); + int curIdxActPh = m_ui->cbActivePhase->currentIndex(); + m_ui->cbActivePhase->clear(); + auto cb = [this](const ExerciseManagement::ExercisePhase& phase) { + if (m_exerciseId == phase.exerciseId()) + m_ui->cbActivePhase->addItem(QString::fromStdString(phase.name()), QVariant(phase.id())); + }; + m_dtc->exercisePhases(cb); + m_ui->cbActivePhase->setEnabled(m_ui->cbActivePhase->count() > 1); + + if (curIdxActPh >= 0) + m_ui->cbActivePhase->setCurrentIndex(curIdxActPh); } void ExerciseManagementEditDialog::fillRadioGroupCbx() { - - const bool wasModified = hasUnsavedChanges(); - int curRadioGroupId = m_ui->cbRadioGroup->currentData().toInt(); - m_ui->cbRadioGroup->clear(); - - m_ui->cbRadioGroup->addItem(tr("No Radio Group"), QVariant(0)); + const bool wasModified = hasUnsavedChanges(); + int curRadioGroupId = m_ui->cbRadioGroup->currentData().toInt(); + m_ui->cbRadioGroup->clear(); - - const QMap mapEx = m_dtc->exercises(); - QMap mapRadioGrp = m_pdmDtc->radioGroups(); - for (auto it = mapEx.begin(); it != mapEx.end(); ++it) - if (it.value().id() != m_exerciseId) - if (it.value().radioGroupId().is_set()) - mapRadioGrp.remove(it.value().radioGroupId().get()); + m_ui->cbRadioGroup->addItem(tr("No Radio Group"), QVariant(0)); - - for (auto it = mapRadioGrp.begin(); it != mapRadioGrp.end(); ++it) - { - const auto &radioGroup = it.value(); - if (!radioGroup.base_group()) - m_ui->cbRadioGroup->addItem(m_pdmDtc->trRadioGroupName(radioGroup.id()), radioGroup.id()); - } + const QMap mapEx = m_dtc->exercises(); + QMap mapRadioGrp = m_pdmDtc->radioGroups(); + for (auto it = mapEx.begin(); it != mapEx.end(); ++it) + if (it.value().id() != m_exerciseId) + if (it.value().radioGroupId().is_set()) + mapRadioGrp.remove(it.value().radioGroupId().get()); - m_ui->cbTrainingArea->model()->sort(0); - m_ui->cbRadioGroup->setEnabled(m_ui->cbRadioGroup->count() > 1); - - if (curRadioGroupId >= 0) - { - int newIdx = m_ui->cbRadioGroup->findData(curRadioGroupId); - if (newIdx >= 0) + for (auto it = mapRadioGrp.begin(); it != mapRadioGrp.end(); ++it) { - m_ui->cbRadioGroup->setCurrentIndex(newIdx); - if (!wasModified) - __unchange__(); + const auto& radioGroup = it.value(); + if (!radioGroup.base_group()) + m_ui->cbRadioGroup->addItem(m_pdmDtc->trRadioGroupName(radioGroup.id()), radioGroup.id()); + } + + m_ui->cbTrainingArea->model()->sort(0); + m_ui->cbRadioGroup->setEnabled(m_ui->cbRadioGroup->count() > 1); + + if (curRadioGroupId >= 0) + { + int newIdx = m_ui->cbRadioGroup->findData(curRadioGroupId); + if (newIdx >= 0) + { + m_ui->cbRadioGroup->setCurrentIndex(newIdx); + if (!wasModified) + __unchange__(); + } } - } } void ExerciseManagementEditDialog::fillLinkedExercisesCbx() { - int curId = m_ui->cbLinkedExercise->currentData().toInt(); - m_ui->cbLinkedExercise->clear(); - auto cb = [this](const Exercise &ex) - { - if (ex.state() != ExerciseManagement::ExerciseState::Created && ex.linkedExerciseId() != m_exerciseId) - return; - if (ex.id() == m_exerciseId) - return; - m_ui->cbLinkedExercise->addItem(QString::fromStdString(ex.name()), ex.id()); - }; - m_dtc->exercises(cb); - m_ui->cbLinkedExercise->addItem(tr("---"), 0); + int curId = m_ui->cbLinkedExercise->currentData().toInt(); + m_ui->cbLinkedExercise->clear(); + auto cb = [this](const Exercise& ex) { + if (ex.state() != ExerciseManagement::ExerciseState::Created && ex.linkedExerciseId() != m_exerciseId) + return; + if (ex.id() == m_exerciseId) + return; + m_ui->cbLinkedExercise->addItem(QString::fromStdString(ex.name()), ex.id()); + }; + m_dtc->exercises(cb); + m_ui->cbLinkedExercise->addItem(tr("---"), 0); - if (curId < 0) - curId = 0; - m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(curId)); + if (curId < 0) + curId = 0; + m_ui->cbLinkedExercise->setCurrentIndex(m_ui->cbLinkedExercise->findData(curId)); } - void ExerciseManagementEditDialog::fillAllCbx() { - fillStateCbx(); - fillTrainingAreaCbx(); - fillActivePhaseCbx(); - fillRadioGroupCbx(); - fillLinkedExercisesCbx(); + fillStateCbx(); + fillTrainingAreaCbx(); + fillActivePhaseCbx(); + fillRadioGroupCbx(); + fillLinkedExercisesCbx(); } -template -bool ExerciseManagementEditDialog::removeElement(std::vector &vec, T elem) +template bool ExerciseManagementEditDialog::removeElement(std::vector& vec, T elem) { - for (auto it = vec.begin(); it != vec.end(); ++it) - { - if (*it == elem) + for (auto it = vec.begin(); it != vec.end(); ++it) { - vec.erase(it); - return true; - } - } - return false; -} - -bool ExerciseManagementEditDialog::apply() -{ - bool retVal = true; - - bool isAlreadyUnchangeable = unchangeable(); - __unchange__(); - if (!isAlreadyUnchangeable) - setUnchangeable(true); - - if (m_exerciseId > 0) - { - ExerciseState state = static_cast(m_ui->cbState->currentData().toInt()); - ExerciseManagement::Exercise data = m_dtc->exercise(m_exerciseId); - if (state == ExerciseState_def::Stopped && data.state() != ExerciseState_def::Stopped) - { - if (LtsWidgets::LtsMessageDialog::showMessage(this, QString(), - tr("Are you sure you want to stop the exercise?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - - retVal = false; - - } - else if (state == ExerciseState_def::Terminated && data.state() != ExerciseState_def::Terminated) - { - if (LtsWidgets::LtsMessageDialog::showMessage(this, QString(), - tr("Are you sure you want to terminate the exercise?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - - retVal = false; - } - - if (retVal) - { - ExerciseModifyRequest request; - - request.id(m_exerciseId); - request.beginTime(m_ui->dtBegin->msecsSinceEpoch()); - request.endTime(m_ui->dtEnd->msecsSinceEpoch()); - request.name(m_ui->leName->text().toStdString()); - request.sendToWMS(m_ui->cbVisibleInWarehouse->isChecked()); - request.linkedExerciseId(m_ui->cbLinkedExercise->currentData().toInt()); - request.trainingAreaId(m_ui->cbTrainingArea->currentData().toInt()); - int radioGroup = m_ui->cbRadioGroup->currentData().toInt(); - if (radioGroup != 0) - { - m_initialRadioGroupId = radioGroup; - request.radioGroupId(radioGroup); - } - - request.symbolFillTypeId(0); - request.activePhaseId(m_ui->cbActivePhase->currentData().toInt()); - request.defaultTimeZone(m_ui->cbTimeZone->currentData().toChar().toLatin1()); - request.forces(m_ui->pteForces->toPlainText().toStdString()); - request.description(m_ui->pteDescription->toPlainText().toStdString()); - request.hasHlaInterface(m_ui->cbStartHlaInterface->isChecked()); - request.newState(static_cast(m_ui->cbState->currentData().toInt())); - request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - request.workstationId(LtsSessionData::LtsSessionData::getInstance()->getWorkstationId()); - - - if (data.startTime() > 0) - request.startTime(data.startTime()); - if (data.stopTime() > 0) - request.stopTime(data.stopTime()); - - if (!m_requestHelper->startSingleRequest([this, request]() - { - m_ftc->enableExerciseModify(); - return m_ftc->exerciseModifyRequest(request, this); - })) - retVal = false; - - if (m_pictureChanged) - { - ExerciseImageModifyRequest exImgRequest(m_exerciseId, LtsUtils::fromPixmap(getPixmap())); - m_requestHelper->startSingleRequest([this, exImgRequest]() + if (*it == elem) { - m_ftc->enableExerciseImageModify(); - return m_ftc->exerciseImageModifyRequest(exImgRequest, this); - }); - } - - sendModifiedOperators(m_exerciseId); + vec.erase(it); + return true; + } } + return false; +} - - +bool ExerciseManagementEditDialog::apply() +{ + bool retVal = true; - - } - else - { - ExerciseCreateRequest request; - request.beginTime(m_ui->dtBegin->msecsSinceEpoch()); - request.endTime(m_ui->dtEnd->msecsSinceEpoch()); - request.name(m_ui->leName->text().toStdString()); - request.sendToWMS(m_ui->cbVisibleInWarehouse->isChecked()); - request.linkedExerciseId(m_ui->cbLinkedExercise->currentData().toInt()); - request.trainingAreaId(m_ui->cbTrainingArea->currentData().toInt()); - int radioGroup = m_ui->cbRadioGroup->currentData().toInt(); - if (radioGroup != 0) - request.radioGroupId(radioGroup); + bool isAlreadyUnchangeable = unchangeable(); + __unchange__(); + if (!isAlreadyUnchangeable) + setUnchangeable(true); - - request.symbolFillTypeId(0); - request.defaultTimeZone(m_ui->cbTimeZone->currentData().toChar().toLatin1()); - request.forces(m_ui->pteForces->toPlainText().toStdString()); - request.description(m_ui->pteDescription->toPlainText().toStdString()); - request.hasHlaInterface(m_ui->cbStartHlaInterface->isChecked()); - - - if (!m_requestHelper->startSingleRequest([this, request]() + if (m_exerciseId > 0) { - m_ftc->enableExerciseCreate(); - return m_ftc->exerciseCreateRequest(request, this); - })) - retVal = false; + ExerciseState state = static_cast(m_ui->cbState->currentData().toInt()); + ExerciseManagement::Exercise data = m_dtc->exercise(m_exerciseId); + if (state == ExerciseState_def::Stopped && data.state() != ExerciseState_def::Stopped) + { + if (LtsWidgets::LtsMessageDialog::showMessage( + this, QString(), tr("Are you sure you want to stop the exercise?"), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - int newExId = m_requestHelper->getRepliedId(); + retVal = false; + } + else if (state == ExerciseState_def::Terminated && data.state() != ExerciseState_def::Terminated) + { + if (LtsWidgets::LtsMessageDialog::showMessage( + this, QString(), tr("Are you sure you want to terminate the exercise?"), + LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - DEBUG_LOG(m_logger) << "Created new exercise with id " << newExId; + retVal = false; + } - if (newExId > 0) - { - ExerciseImageModifyRequest exImgRequest(newExId, - LtsUtils::fromPixmap(getPixmap())); - if (!m_requestHelper->startSingleRequest([this, exImgRequest]() - { - m_ftc->enableExerciseImageModify(); - return m_ftc->exerciseImageModifyRequest(exImgRequest, this); - })) - { - WARNING_LOG(m_logger) << "Unable to set default exercise picture"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Unable to set default exercise picture")); - } + if (retVal) + { + ExerciseModifyRequest request; - - sendModifiedOperators(newExId); + request.id(m_exerciseId); + request.beginTime(m_ui->dtBegin->msecsSinceEpoch()); + request.endTime(m_ui->dtEnd->msecsSinceEpoch()); + request.name(m_ui->leName->text().toStdString()); + request.sendToWMS(m_ui->cbVisibleInWarehouse->isChecked()); + request.linkedExerciseId(m_ui->cbLinkedExercise->currentData().toInt()); + request.trainingAreaId(m_ui->cbTrainingArea->currentData().toInt()); + int radioGroup = m_ui->cbRadioGroup->currentData().toInt(); + if (radioGroup != 0) + { + m_initialRadioGroupId = radioGroup; + request.radioGroupId(radioGroup); + } - - if (!createFolders(newExId)) - { - WARNING_LOG(m_logger) << "Unable to create exercise folders in document library."; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Unable to create exercise folders in document library.")); - } + request.symbolFillTypeId(0); + request.activePhaseId(m_ui->cbActivePhase->currentData().toInt()); + request.defaultTimeZone(m_ui->cbTimeZone->currentData().toChar().toLatin1()); + request.forces(m_ui->pteForces->toPlainText().toStdString()); + request.description(m_ui->pteDescription->toPlainText().toStdString()); + request.hasHlaInterface(m_ui->cbStartHlaInterface->isChecked()); + request.newState(static_cast(m_ui->cbState->currentData().toInt())); + request.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + request.workstationId(LtsSessionData::LtsSessionData::getInstance()->getWorkstationId()); + if (data.startTime() > 0) + request.startTime(data.startTime()); + if (data.stopTime() > 0) + request.stopTime(data.stopTime()); + + if (!m_requestHelper->startSingleRequest([this, request]() { + m_ftc->enableExerciseModify(); + return m_ftc->exerciseModifyRequest(request, this); + })) + retVal = false; + + if (m_pictureChanged) + { + ExerciseImageModifyRequest exImgRequest(m_exerciseId, LtsUtils::fromPixmap(getPixmap())); + m_requestHelper->startSingleRequest([this, exImgRequest]() { + m_ftc->enableExerciseImageModify(); + return m_ftc->exerciseImageModifyRequest(exImgRequest, this); + }); + } + + sendModifiedOperators(m_exerciseId); + } } else - retVal = false; + { + ExerciseCreateRequest request; + request.beginTime(m_ui->dtBegin->msecsSinceEpoch()); + request.endTime(m_ui->dtEnd->msecsSinceEpoch()); + request.name(m_ui->leName->text().toStdString()); + request.sendToWMS(m_ui->cbVisibleInWarehouse->isChecked()); + request.linkedExerciseId(m_ui->cbLinkedExercise->currentData().toInt()); + request.trainingAreaId(m_ui->cbTrainingArea->currentData().toInt()); + int radioGroup = m_ui->cbRadioGroup->currentData().toInt(); + if (radioGroup != 0) + request.radioGroupId(radioGroup); - - } + request.symbolFillTypeId(0); + request.defaultTimeZone(m_ui->cbTimeZone->currentData().toChar().toLatin1()); + request.forces(m_ui->pteForces->toPlainText().toStdString()); + request.description(m_ui->pteDescription->toPlainText().toStdString()); + request.hasHlaInterface(m_ui->cbStartHlaInterface->isChecked()); - if (!isAlreadyUnchangeable) - setUnchangeable(false); + if (!m_requestHelper->startSingleRequest([this, request]() { + m_ftc->enableExerciseCreate(); + return m_ftc->exerciseCreateRequest(request, this); + })) + retVal = false; - return retVal; + int newExId = m_requestHelper->getRepliedId(); + + DEBUG_LOG(m_logger) << "Created new exercise with id " << newExId; + + if (newExId > 0) + { + ExerciseImageModifyRequest exImgRequest(newExId, LtsUtils::fromPixmap(getPixmap())); + if (!m_requestHelper->startSingleRequest([this, exImgRequest]() { + m_ftc->enableExerciseImageModify(); + return m_ftc->exerciseImageModifyRequest(exImgRequest, this); + })) + { + WARNING_LOG(m_logger) << "Unable to set default exercise picture"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Unable to set default exercise picture")); + } + + sendModifiedOperators(newExId); + + if (!createFolders(newExId)) + { + WARNING_LOG(m_logger) << "Unable to create exercise folders in document library."; + LtsWidgets::LtsMessageDialog::showMessage(this, + tr("Unable to create exercise folders in document library.")); + } + } + else + retVal = false; + } + + if (!isAlreadyUnchangeable) + setUnchangeable(false); + + return retVal; } - const QPixmap ExerciseManagementEditDialog::getPixmap() const { - return QPixmap(m_ui->imageEditor->pixmap()); + return QPixmap(m_ui->imageEditor->pixmap()); } - void ExerciseManagementEditDialog::sendModifiedOperators(int thisExerciseId) { - std::shared_ptr opmFtc; - if (!m_session->getFtc(opmFtc)) - { - ERROR_LOG(m_logger) << "Cannot change add/remove Operators to/from Exercise as the OPM-FTC could not be fetched." ; - return; - } - - for (int row = 0; row < m_operatorModel->rowCount(); ++row) - { - const auto rowData = m_operatorModel->getRowData(row); - bool found = false; - OperatorManagement::User user = m_opmDtc->user(rowData.second.id()); - for (auto ex : user.exerciseIds()) - if (ex == thisExerciseId) - found = true; - - if (found == rowData.first) - continue; - - if (rowData.first) - user.exerciseIds().resize(user.exerciseIds().size() + 1, thisExerciseId); - else - removeElement(user.exerciseIds(), thisExerciseId); - - OperatorManagement::OperatorCreateModifyRequest req; - req.id(user.id()); - req.visibleExercises() = user.exerciseIds(); - req.visiblePartiesByExercise() = user.visiblePartiesByExercise(); - - DEBUG_LOG(m_logger) << "Adding request: " << req; - m_requestHelper->addRequest([this, req, opmFtc]() + std::shared_ptr opmFtc; + if (!m_session->getFtc(opmFtc)) { - DEBUG_LOG(m_logger) << "Executing request: " << req; - return opmFtc->operatorCreateModifyRequest(req, this); - }); + ERROR_LOG(m_logger) + << "Cannot change add/remove Operators to/from Exercise as the OPM-FTC could not be fetched."; + return; + } - } + for (int row = 0; row < m_operatorModel->rowCount(); ++row) + { + const auto rowData = m_operatorModel->getRowData(row); + bool found = false; + OperatorManagement::User user = m_opmDtc->user(rowData.second.id()); + for (auto ex : user.exerciseIds()) + if (ex == thisExerciseId) + found = true; - m_requestHelper->startRequests(); + if (found == rowData.first) + continue; + + if (rowData.first) + user.exerciseIds().resize(user.exerciseIds().size() + 1, thisExerciseId); + else + removeElement(user.exerciseIds(), thisExerciseId); + + OperatorManagement::OperatorCreateModifyRequest req; + req.id(user.id()); + req.visibleExercises() = user.exerciseIds(); + req.visiblePartiesByExercise() = user.visiblePartiesByExercise(); + + DEBUG_LOG(m_logger) << "Adding request: " << req; + m_requestHelper->addRequest([this, req, opmFtc]() { + DEBUG_LOG(m_logger) << "Executing request: " << req; + return opmFtc->operatorCreateModifyRequest(req, this); + }); + } + + m_requestHelper->startRequests(); } bool ExerciseManagementEditDialog::createFolders(int newExId) { - - QString folderName = m_flmDtc->getExerciseFolderName(newExId); - int folderId = createFolder(FileManagement::MainFolder::ExerciseDocuments, folderName); - if (folderId <= 0) - return false; + QString folderName = m_flmDtc->getExerciseFolderName(newExId); + int folderId = createFolder(FileManagement::MainFolder::ExerciseDocuments, folderName); - DEBUG_LOG(m_logger) << "Exercise Folder created with id = " << folderId; + if (folderId <= 0) + return false; - - folderName = QStringLiteral("Documents") ; - int subFolderId = createFolder(folderId, folderName); + DEBUG_LOG(m_logger) << "Exercise Folder created with id = " << folderId; - if (subFolderId <= 0) - return false; + folderName = QStringLiteral("Documents"); + int subFolderId = createFolder(folderId, folderName); - DEBUG_LOG(m_logger) << "Sub Folder Documents created with id = " << subFolderId; + if (subFolderId <= 0) + return false; - - QStringList folderNames; - folderNames << QStringLiteral("Fault documentation Evaluation") << QStringLiteral("Fault documentation Evaluation EXCON"); - folderNames << QStringLiteral("Incidents") << QStringLiteral("Instructions"); + DEBUG_LOG(m_logger) << "Sub Folder Documents created with id = " << subFolderId; - bool ok = createExerciseFolders(subFolderId, folderNames); - DEBUG_LOG(m_logger) << "Created sub-folders Documents: " << ok; + QStringList folderNames; + folderNames << QStringLiteral("Fault documentation Evaluation") + << QStringLiteral("Fault documentation Evaluation EXCON"); + folderNames << QStringLiteral("Incidents") << QStringLiteral("Instructions"); - - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), - QStringLiteral("enableEditPhases")).toBool(); - if (enableEditPhases) - { - - folderName = QStringLiteral("Phase Documents"); - int folderPhaseDocsId = createFolder(subFolderId, folderName); - DEBUG_LOG(m_logger) << "Phase Documents Folder created with id = " << folderPhaseDocsId; + bool ok = createExerciseFolders(subFolderId, folderNames); + DEBUG_LOG(m_logger) << "Created sub-folders Documents: " << ok; - - if (folderPhaseDocsId > 0) + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); + if (enableEditPhases) { - int phId = m_dtc->exercise(newExId).activePhaseId(); - const QString &phaseName = m_flmDtc->getPhaseFolderName(phId); - int folderPhaseId = createFolder(folderPhaseDocsId, phaseName); - DEBUG_LOG(m_logger) << "Phase Folder created with id = " << folderPhaseId; + + folderName = QStringLiteral("Phase Documents"); + int folderPhaseDocsId = createFolder(subFolderId, folderName); + DEBUG_LOG(m_logger) << "Phase Documents Folder created with id = " << folderPhaseDocsId; + + if (folderPhaseDocsId > 0) + { + int phId = m_dtc->exercise(newExId).activePhaseId(); + const QString& phaseName = m_flmDtc->getPhaseFolderName(phId); + int folderPhaseId = createFolder(folderPhaseDocsId, phaseName); + DEBUG_LOG(m_logger) << "Phase Folder created with id = " << folderPhaseId; + } } - } - - folderName = QStringLiteral("Markers"); - subFolderId = createFolder(folderId, folderName); - DEBUG_LOG(m_logger) << "Markers Folder created with id = " << subFolderId; + folderName = QStringLiteral("Markers"); + subFolderId = createFolder(folderId, folderName); + DEBUG_LOG(m_logger) << "Markers Folder created with id = " << subFolderId; - FileManagement::PathCreateRequest req; - req.parentId(folderId); - req.path({"Planning", "TNE Lists"}); - req.isEditable(false); - req.isHidden(false); - req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + FileManagement::PathCreateRequest req; + req.parentId(folderId); + req.path({"Planning", "TNE Lists"}); + req.isEditable(false); + req.isHidden(false); + req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - bool success = m_flmFtc->pathCreateRequest(req); - if (!success) - ERROR_LOG(m_logger) << "Planning/TNE Lists could not be created"; + bool success = m_flmFtc->pathCreateRequest(req); + if (!success) + ERROR_LOG(m_logger) << "Planning/TNE Lists could not be created"; - - req.path({"Tactical Plans", "BDA"}); - success = m_flmFtc->pathCreateRequest(req); - if (!success) - ERROR_LOG(m_logger) << "Tactical Plans/BDA could not be created"; + req.path({"Tactical Plans", "BDA"}); + success = m_flmFtc->pathCreateRequest(req); + if (!success) + ERROR_LOG(m_logger) << "Tactical Plans/BDA could not be created"; - req.path({"Tactical Plans", "HQ Data"}); - success = m_flmFtc->pathCreateRequest(req); + req.path({"Tactical Plans", "HQ Data"}); + success = m_flmFtc->pathCreateRequest(req); - if (!success) - ERROR_LOG(m_logger) << "Tactical Plans/HQ Data could not be created"; + if (!success) + ERROR_LOG(m_logger) << "Tactical Plans/HQ Data could not be created"; - - folderNames.clear(); - folderNames << QStringLiteral("Reports") << QStringLiteral("Snapshots"); - ok = createExerciseFolders(folderId, folderNames); - DEBUG_LOG(m_logger) << "Created last exercise documents: " << ok; + folderNames.clear(); + folderNames << QStringLiteral("Reports") << QStringLiteral("Snapshots"); + ok = createExerciseFolders(folderId, folderNames); + DEBUG_LOG(m_logger) << "Created last exercise documents: " << ok; - return true; + return true; } -int ExerciseManagementEditDialog::createFolder(int parentFolderId, const QString &folderName, bool isHidden) +int ExerciseManagementEditDialog::createFolder(int parentFolderId, const QString& folderName, bool isHidden) { - FileManagement::Folder parentFolder = m_flmDtc->folder(parentFolderId); - const std::vector &parentPath = parentFolder.path(); + FileManagement::Folder parentFolder = m_flmDtc->folder(parentFolderId); + const std::vector& parentPath = parentFolder.path(); - FileManagement::FolderModifyRequest req; - req.name(folderName.toStdString()); - req.path(parentPath); - req.isEditable(false); - req.isHidden(isHidden); - req.parentId(parentFolderId); - req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - - m_requestHelper->startSingleRequest([this, req]() - { - return m_flmFtc->folderModifyRequest(req, this); - }); - - DEBUG_LOG(m_logger) << "Created folder id = " << m_requestHelper->getRepliedId(); - - return m_requestHelper->getRepliedId(); -} - -bool ExerciseManagementEditDialog::createExerciseFolders(int parentFolderId, const QStringList &folderNames) -{ - FileManagement::Folder parentFolder = m_flmDtc->folder(parentFolderId); - const std::vector &parentPath = parentFolder.path(); - - FileManagement::FolderModifyRequest req; - req.path(parentPath); - req.isEditable(false); - req.isHidden(false); - req.parentId(parentFolderId); - req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - - for ( const QString &folderName : folderNames ) - { + FileManagement::FolderModifyRequest req; req.name(folderName.toStdString()); + req.path(parentPath); + req.isEditable(false); + req.isHidden(isHidden); + req.parentId(parentFolderId); + req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - m_requestHelper->addRequest([this, req]() - { - return m_flmFtc->folderModifyRequest(req, this); - }); - } + m_requestHelper->startSingleRequest([this, req]() { return m_flmFtc->folderModifyRequest(req, this); }); - return m_requestHelper->startRequests(); + DEBUG_LOG(m_logger) << "Created folder id = " << m_requestHelper->getRepliedId(); + + return m_requestHelper->getRepliedId(); } - -void ExerciseManagementEditDialog::onContextMenuRequested(const QPoint &position) +bool ExerciseManagementEditDialog::createExerciseFolders(int parentFolderId, const QStringList& folderNames) { - QMenu menu(m_ui->dvOperators); - menu.addAction(tr("Select All"), this, &ExerciseManagementEditDialog::onSelectAllUsers); - menu.addAction(tr("Unselect All"), this, &ExerciseManagementEditDialog::onUnselectAllUsers); - menu.exec(m_ui->dvOperators->mapToGlobal(position)); + FileManagement::Folder parentFolder = m_flmDtc->folder(parentFolderId); + const std::vector& parentPath = parentFolder.path(); + + FileManagement::FolderModifyRequest req; + req.path(parentPath); + req.isEditable(false); + req.isHidden(false); + req.parentId(parentFolderId); + req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + + for (const QString& folderName : folderNames) + { + req.name(folderName.toStdString()); + + m_requestHelper->addRequest([this, req]() { return m_flmFtc->folderModifyRequest(req, this); }); + } + + return m_requestHelper->startRequests(); +} + +void ExerciseManagementEditDialog::onContextMenuRequested(const QPoint& position) +{ + QMenu menu(m_ui->dvOperators); + menu.addAction(tr("Select All"), this, &ExerciseManagementEditDialog::onSelectAllUsers); + menu.addAction(tr("Unselect All"), this, &ExerciseManagementEditDialog::onUnselectAllUsers); + menu.exec(m_ui->dvOperators->mapToGlobal(position)); } void ExerciseManagementEditDialog::onSelectAllUsers() { - m_operatorModel->selectAll(); - m_operatorModel->update(); + m_operatorModel->selectAll(); + m_operatorModel->update(); } void ExerciseManagementEditDialog::onUnselectAllUsers() { - m_operatorModel->unselectAll(); - m_operatorModel->update(); + m_operatorModel->unselectAll(); + m_operatorModel->update(); } ExerciseModifyRequest ExerciseManagementEditDialog::setRequestContent() const - { - ExerciseModifyRequest req; +{ + ExerciseModifyRequest req; - req.forces(m_ui->pteForces->toPlainText().toStdString()); - req.description(m_ui->pteDescription->toPlainText().toStdString()); + req.forces(m_ui->pteForces->toPlainText().toStdString()); + req.description(m_ui->pteDescription->toPlainText().toStdString()); - const ExerciseModifyRequest out = req; - return out; + const ExerciseModifyRequest out = req; + return out; } QByteArray ExerciseManagementEditDialog::exerciseToJson() const { - const ExerciseModifyRequest req = setRequestContent(); + const ExerciseModifyRequest req = setRequestContent(); - QJsonObject obj; - long long startExercise = m_ui->dtBegin->msecsSinceEpoch(); + QJsonObject obj; + long long startExercise = m_ui->dtBegin->msecsSinceEpoch(); - obj[JsonKeys::XMLTYPE()] = JsonKeys::XMLTYPEVALUE(); + obj[JsonKeys::XMLTYPE()] = JsonKeys::XMLTYPEVALUE(); - obj[JsonKeys::FORCES()] = QString::fromStdString(req.forces()); - obj[JsonKeys::DESCRIPTION()] = QString::fromStdString(req.description()); + obj[JsonKeys::FORCES()] = QString::fromStdString(req.forces()); + obj[JsonKeys::DESCRIPTION()] = QString::fromStdString(req.description()); - QJsonArray phases; - for(int row = 0; row < m_phaseModel->rowCount(); ++row) - { - QJsonObject phase; - phase.insert(JsonKeys::PID(), m_phaseModel->getRowData(row).id()); - phase.insert(JsonKeys::PNAME(), QString::fromStdString(m_phaseModel->getRowData(row).name())); - phase.insert(JsonKeys::PISDELETED(), m_phaseModel->getRowData(row).isDeleted()); - phase.insert(JsonKeys::PISUSED(), m_phaseModel->getRowData(row).isUsed()); - long long beginTime = m_phaseModel->getRowData(row).beginTime() - startExercise; - long long endTime = m_phaseModel->getRowData(row).endTime() - startExercise; - phase.insert(JsonKeys::PBEGINTIME(), beginTime); - phase.insert(JsonKeys::PENDTIME(), endTime); - phase.insert(JsonKeys::PDESCRIPTION(), QString::fromStdString(m_phaseModel->getRowData(row).description())); - phase.insert(JsonKeys::PEXERCISEID(), m_phaseModel->getRowData(row).exerciseId()); - phases.append(phase); - } - obj[JsonKeys::PHASES()] = phases; + QJsonArray phases; + for (int row = 0; row < m_phaseModel->rowCount(); ++row) + { + QJsonObject phase; + phase.insert(JsonKeys::PID(), m_phaseModel->getRowData(row).id()); + phase.insert(JsonKeys::PNAME(), QString::fromStdString(m_phaseModel->getRowData(row).name())); + phase.insert(JsonKeys::PISDELETED(), m_phaseModel->getRowData(row).isDeleted()); + phase.insert(JsonKeys::PISUSED(), m_phaseModel->getRowData(row).isUsed()); + long long beginTime = m_phaseModel->getRowData(row).beginTime() - startExercise; + long long endTime = m_phaseModel->getRowData(row).endTime() - startExercise; + phase.insert(JsonKeys::PBEGINTIME(), beginTime); + phase.insert(JsonKeys::PENDTIME(), endTime); + phase.insert(JsonKeys::PDESCRIPTION(), QString::fromStdString(m_phaseModel->getRowData(row).description())); + phase.insert(JsonKeys::PEXERCISEID(), m_phaseModel->getRowData(row).exerciseId()); + phases.append(phase); + } + obj[JsonKeys::PHASES()] = phases; - QJsonArray operatorIds; - const QVector checkedIds = m_operatorModel->getCheckedIds(); - for(const int id : checkedIds) - operatorIds += id; - obj[JsonKeys::OPERATORS()] = operatorIds; + QJsonArray operatorIds; + const QVector checkedIds = m_operatorModel->getCheckedIds(); + for (const int id : checkedIds) + operatorIds += id; + obj[JsonKeys::OPERATORS()] = operatorIds; - QJsonDocument doc(obj); - return doc.toJson(QJsonDocument::Compact); + QJsonDocument doc(obj); + return doc.toJson(QJsonDocument::Compact); } -ExerciseModifyRequest ExerciseManagementEditDialog::jsonToExercise(const QByteArray &content) const +ExerciseModifyRequest ExerciseManagementEditDialog::jsonToExercise(const QByteArray& content) const { - ExerciseModifyRequest result; + ExerciseModifyRequest result; - - const QJsonDocument doc(QJsonDocument::fromJson(content)); - const QJsonObject obj(doc.object()); + const QJsonDocument doc(QJsonDocument::fromJson(content)); + const QJsonObject obj(doc.object()); - result.forces(obj[JsonKeys::FORCES()].toString().toStdString()); - result.description(obj[JsonKeys::DESCRIPTION()].toString().toStdString()); + result.forces(obj[JsonKeys::FORCES()].toString().toStdString()); + result.description(obj[JsonKeys::DESCRIPTION()].toString().toStdString()); - - QJsonArray phasesArray = obj[JsonKeys::PHASES()].toArray(); - QVector phases; + QJsonArray phasesArray = obj[JsonKeys::PHASES()].toArray(); + QVector phases; - for (auto it = phasesArray.constBegin(); it != phasesArray.constEnd(); ++it) - { - QJsonObject phaseObj = (*it).toObject(); - ExerciseManagement::ExercisePhase phase; - phase.id(phaseObj[JsonKeys::PID()].toInt()); - phase.name(phaseObj[JsonKeys::PNAME()].toString().toStdString()); - phase.isDeleted(phaseObj[JsonKeys::PISDELETED()].toBool()); - phase.isUsed(phaseObj[JsonKeys::PISUSED()].toBool()); - phase.description(phaseObj[JsonKeys::PDESCRIPTION()].toString().toStdString()); - - phase.beginTime(phaseObj[JsonKeys::PBEGINTIME()].toInt() + m_ui->dtBegin->msecsSinceEpoch()); - phase.endTime(phaseObj[JsonKeys::PENDTIME()].toInt() + m_ui->dtBegin->msecsSinceEpoch()); - phase.exerciseId(phaseObj[JsonKeys::PEXERCISEID()].toInt()); - phases.append(phase); - } - m_phaseModel->setData(phases); - if ( phases.size()> 0) - { - m_ui->dvPhases->show(); - m_ui->lblPhases->show(); - m_ui->btbDvPhases->show(); - } + for (auto it = phasesArray.constBegin(); it != phasesArray.constEnd(); ++it) + { + QJsonObject phaseObj = (*it).toObject(); + ExerciseManagement::ExercisePhase phase; + phase.id(phaseObj[JsonKeys::PID()].toInt()); + phase.name(phaseObj[JsonKeys::PNAME()].toString().toStdString()); + phase.isDeleted(phaseObj[JsonKeys::PISDELETED()].toBool()); + phase.isUsed(phaseObj[JsonKeys::PISUSED()].toBool()); + phase.description(phaseObj[JsonKeys::PDESCRIPTION()].toString().toStdString()); - - const QJsonArray operatorArray = obj[JsonKeys::OPERATORS()].toArray(); - QVector selectedIds; - selectedIds.reserve(operatorArray.size()); - for (const auto &ele : operatorArray) - selectedIds.append(ele.toInt()); - m_operatorModel->setChecked(selectedIds); + phase.beginTime(phaseObj[JsonKeys::PBEGINTIME()].toInt() + m_ui->dtBegin->msecsSinceEpoch()); + phase.endTime(phaseObj[JsonKeys::PENDTIME()].toInt() + m_ui->dtBegin->msecsSinceEpoch()); + phase.exerciseId(phaseObj[JsonKeys::PEXERCISEID()].toInt()); + phases.append(phase); + } + m_phaseModel->setData(phases); + if (phases.size() > 0) + { + m_ui->dvPhases->show(); + m_ui->lblPhases->show(); + m_ui->btbDvPhases->show(); + } - return result; + const QJsonArray operatorArray = obj[JsonKeys::OPERATORS()].toArray(); + QVector selectedIds; + selectedIds.reserve(operatorArray.size()); + for (const auto& ele : operatorArray) + selectedIds.append(ele.toInt()); + m_operatorModel->setChecked(selectedIds); + + return result; } void ExerciseManagementEditDialog::onCreateFolders() { - DEBUG_LOG(m_logger) << "onCreateFolders"; - if (m_exerciseId > 0 && getExerciseFolder() <= 0 ) - { - bool ok = createFolders(m_exerciseId); - if (!ok) + DEBUG_LOG(m_logger) << "onCreateFolders"; + if (m_exerciseId > 0 && getExerciseFolder() <= 0) { - WARNING_LOG(m_logger) << "Could not create exercise folders"; - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Could not create exercise folders")); + bool ok = createFolders(m_exerciseId); + if (!ok) + { + WARNING_LOG(m_logger) << "Could not create exercise folders"; + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Could not create exercise folders")); + } + else + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("Exercise folders successfully created")); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); + } } - else - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("Exercise folders successfully created")); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Load, false); - } - } } int ExerciseManagementEditDialog::getExerciseFolder() { - if (m_exerciseId <= 0) - return 0; + if (m_exerciseId <= 0) + return 0; - const int folderId = m_flmDtc->getExerciseFolderId(m_exerciseId); - DEBUG_LOG(m_logger) << "getExerciseFolder: folderId = " << folderId; - return folderId; + const int folderId = m_flmDtc->getExerciseFolderId(m_exerciseId); + DEBUG_LOG(m_logger) << "getExerciseFolder: folderId = " << folderId; + return folderId; } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.h old mode 100755 new mode 100644 index 53104744c..4c402f5ba --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_dialog.h @@ -1,23 +1,20 @@ - #pragma once -#include #include +#include #include -#include -#include +#include #include - - -#include -#include -#include +#include +#include #include +#include #include #include -#include +#include +#include namespace Ui { @@ -29,132 +26,207 @@ namespace ExerciseManagement namespace JsonKeys { -inline QString XMLTYPE() { return QStringLiteral("XmlType"); } -inline QString XMLTYPEVALUE() { return FileManagement::toString(FileManagement::XmlType::EXMExerciseDescription); } +inline QString XMLTYPE() +{ + return QStringLiteral("XmlType"); +} +inline QString XMLTYPEVALUE() +{ + return FileManagement::toString(FileManagement::XmlType::EXMExerciseDescription); +} -inline QString PHASES() { return QStringLiteral("phases"); } -inline QString OPERATORS() { return QStringLiteral("operators"); } -inline QString FORCES() { return QStringLiteral("forces"); } -inline QString DESCRIPTION() { return QStringLiteral("description"); } +inline QString PHASES() +{ + return QStringLiteral("phases"); +} +inline QString OPERATORS() +{ + return QStringLiteral("operators"); +} -inline QString PID() { return QStringLiteral("phaseId"); } -inline QString PNAME() { return QStringLiteral("phaseName"); } -inline QString PISDELETED() { return QStringLiteral("phaseIsDeleted"); } -inline QString PISUSED() { return QStringLiteral("phaseIsUsed"); } -inline QString PBEGINTIME() { return QStringLiteral("phaseBeginTime"); } -inline QString PENDTIME() { return QStringLiteral("phaseEndTime"); } -inline QString PDESCRIPTION() { return QStringLiteral("phaseDescription"); } -inline QString PEXERCISEID() { return QStringLiteral("phaseExerciseId"); } -} +inline QString FORCES() +{ + return QStringLiteral("forces"); +} +inline QString DESCRIPTION() +{ + return QStringLiteral("description"); +} + +inline QString PID() +{ + return QStringLiteral("phaseId"); +} + +inline QString PNAME() +{ + return QStringLiteral("phaseName"); +} + +inline QString PISDELETED() +{ + return QStringLiteral("phaseIsDeleted"); +} + +inline QString PISUSED() +{ + return QStringLiteral("phaseIsUsed"); +} + +inline QString PBEGINTIME() +{ + return QStringLiteral("phaseBeginTime"); +} + +inline QString PENDTIME() +{ + return QStringLiteral("phaseEndTime"); +} + +inline QString PDESCRIPTION() +{ + return QStringLiteral("phaseDescription"); +} + +inline QString PEXERCISEID() +{ + return QStringLiteral("phaseExerciseId"); +} +} // namespace JsonKeys class ExercisePhaseModel; class ExercisePhaseProxyModel; class ExerciseOperatorModel; - - -class ExerciseManagementEditDialog final : public LtsWidgets::LtsDialog - , protected ExerciseManagement::Interface::Ftc::ExerciseCreateReplyHandler - , protected ExerciseManagement::Interface::Ftc::ExerciseModifyReplyHandler - , protected ExerciseManagement::Interface::Ftc::ExerciseImageModifyReplyHandler - , protected ExerciseManagement::Interface::Ftc::GetExerciseImageReplyHandler - , protected ExerciseManagement::Interface::Ftc::ExercisePhaseRemoveReplyHandler - , protected OperatorManagement::Interface::Ftc::OperatorCreateModifyReplyHandler - , protected FileManagement::Interface::Ftc::FolderModifyReplyHandler - , protected FileManagement::Interface::Ftc::FolderRemoveReplyHandler +class ExerciseManagementEditDialog final + : public LtsWidgets::LtsDialog, + protected ExerciseManagement::Interface::Ftc::ExerciseCreateReplyHandler, + protected ExerciseManagement::Interface::Ftc::ExerciseModifyReplyHandler, + protected ExerciseManagement::Interface::Ftc::ExerciseImageModifyReplyHandler, + protected ExerciseManagement::Interface::Ftc::GetExerciseImageReplyHandler, + protected ExerciseManagement::Interface::Ftc::ExercisePhaseRemoveReplyHandler, + protected OperatorManagement::Interface::Ftc::OperatorCreateModifyReplyHandler, + protected FileManagement::Interface::Ftc::FolderModifyReplyHandler, + protected FileManagement::Interface::Ftc::FolderRemoveReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ExerciseManagementEditDialog(QWidget *parent = nullptr); + public: + explicit ExerciseManagementEditDialog(QWidget* parent = nullptr); - bool init(LtsSession::LtsSessionDataDds *session, - const QString &menuGroup, - const int exerciseId); + bool init(LtsSession::LtsSessionDataDds* session, const QString& menuGroup, const int exerciseId); - ~ExerciseManagementEditDialog(); + ~ExerciseManagementEditDialog(); -protected: + protected: + NGL::INGLLogger& m_logger; -NGL::INGLLogger &m_logger; - void onExerciseCreateReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onExerciseModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onExerciseImageModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); imageModifyError(); } - void onGetExerciseImageReply(const GetExerciseImageReply &reply) override final; - void onExercisePhaseRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onOperatorCreateModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onFolderModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onFolderRemoveReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onExerciseCreateReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private slots: - void slotChangeImage(); - void enaDisaOperatorsButtons(); - void enaDisaPhaseButtons(); - void onAddExercisePhase(); - void onEditVisibleParties(); - void onEditExercisePhase(); - void onRemoveExercisePhase(); - void onExport(); - void onImport(); - void onCreateFolders(); - void onExerciseChanged(const Exercise &data, DataModification modType); - void onExercisePhaseChanged(const ExercisePhase &data, DataModification modType); - void onContextMenuRequested(const QPoint &position); - void onSelectAllUsers(); - void onUnselectAllUsers(); - void onTimeZoneChanged(); -signals: - void sendData(const ExerciseManagement::Exercise &data); + void onExerciseModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: - void retranslate() override; - bool apply() override final; + void onExerciseImageModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + imageModifyError(); + } - void enaDisa(); + void onGetExerciseImageReply(const GetExerciseImageReply& reply) override final; - void fillStateCbx(); - void fillTrainingAreaCbx(); - void fillActivePhaseCbx(); - void fillRadioGroupCbx(); - void fillLinkedExercisesCbx(); - void fillAllCbx(); - void imageModifyError(); - void sendModifiedOperators(int thisExerciseId); - int createFolder(int parentFolderId, const QString &folderName, bool isHidden = false); - bool createFolders(int newExId); - bool createExerciseFolders(int parentFolderId, const QStringList &folderNames); - ExerciseModifyRequest setRequestContent() const; - QByteArray exerciseToJson() const; - ExerciseModifyRequest jsonToExercise(const QByteArray &content) const; - void requestImage(); - const QPixmap getPixmap() const; - int getExerciseFolder(); + void onExercisePhaseRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } - Ui::ExerciseManagementEditDialog *m_ui{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; - ExercisePhaseModel *m_phaseModel{nullptr}; - ExercisePhaseProxyModel *m_phaseProxyModel{nullptr}; - ExerciseOperatorModel *m_operatorModel{nullptr}; - bool m_pictureChanged{false}; - int m_exerciseId{-1}; - QVariant m_initialRadioGroupId; - ExerciseState m_currentState; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_opmDtc; - std::shared_ptr m_asmDtc; - std::shared_ptr m_pdmDtc; - std::shared_ptr m_ppmDtc; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; - std::shared_ptr m_flmGui; - QString m_menuGroup; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; - template - bool removeElement(std::vector &vec, T elem); - bool hasVisibleParties(const std::vector vpbe) const; + void onOperatorCreateModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } + + void onFolderModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } + + void onFolderRemoveReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } + + private slots: + void slotChangeImage(); + void enaDisaOperatorsButtons(); + void enaDisaPhaseButtons(); + void onAddExercisePhase(); + void onEditVisibleParties(); + void onEditExercisePhase(); + void onRemoveExercisePhase(); + void onExport(); + void onImport(); + void onCreateFolders(); + void onExerciseChanged(const Exercise& data, DataModification modType); + void onExercisePhaseChanged(const ExercisePhase& data, DataModification modType); + void onContextMenuRequested(const QPoint& position); + void onSelectAllUsers(); + void onUnselectAllUsers(); + void onTimeZoneChanged(); + signals: + void sendData(const ExerciseManagement::Exercise& data); + + private: + void retranslate() override; + bool apply() override final; + + void enaDisa(); + + void fillStateCbx(); + void fillTrainingAreaCbx(); + void fillActivePhaseCbx(); + void fillRadioGroupCbx(); + void fillLinkedExercisesCbx(); + void fillAllCbx(); + void imageModifyError(); + void sendModifiedOperators(int thisExerciseId); + int createFolder(int parentFolderId, const QString& folderName, bool isHidden = false); + bool createFolders(int newExId); + bool createExerciseFolders(int parentFolderId, const QStringList& folderNames); + ExerciseModifyRequest setRequestContent() const; + QByteArray exerciseToJson() const; + ExerciseModifyRequest jsonToExercise(const QByteArray& content) const; + void requestImage(); + const QPixmap getPixmap() const; + int getExerciseFolder(); + + Ui::ExerciseManagementEditDialog* m_ui{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + ExercisePhaseModel* m_phaseModel{nullptr}; + ExercisePhaseProxyModel* m_phaseProxyModel{nullptr}; + ExerciseOperatorModel* m_operatorModel{nullptr}; + bool m_pictureChanged{false}; + int m_exerciseId{-1}; + QVariant m_initialRadioGroupId; + ExerciseState m_currentState; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_opmDtc; + std::shared_ptr m_asmDtc; + std::shared_ptr m_pdmDtc; + std::shared_ptr m_ppmDtc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; + std::shared_ptr m_flmGui; + QString m_menuGroup; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; + template bool removeElement(std::vector& vec, T elem); + bool hasVisibleParties(const std::vector vpbe) const; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.cpp old mode 100755 new mode 100644 index 00f1c19cb..b35333414 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.cpp @@ -1,237 +1,232 @@ - #include "exm_edit_party_dialog.h" + #include "ui_exm_edit_party_dialog.h" +#include #include #include -#include - #include #include - +#include +#include +#include #include #include -#include -#include -#include namespace ExerciseManagement { -ExerciseEditPartyDialog::ExerciseEditPartyDialog(const int operatorId, - const int exerciseId, - const QString &menuGroup, - QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_operatorId(operatorId) - , m_exerciseId(exerciseId) - , m_visiblePartiesChanged(false) - , m_adlerVisiblePartiesChanged(false) - , m_menuGroup(menuGroup) - , m_visiblePartiesModel(nullptr) - , m_adlerVisiblePartiesModel(nullptr) - , m_opmDtc(nullptr) - , m_opmFtc(nullptr) - , m_ui(new Ui::ExerciseEditPartyDialog) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ExerciseEditPartyDialog::ExerciseEditPartyDialog(const int operatorId, const int exerciseId, const QString& menuGroup, + QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_operatorId(operatorId), + m_exerciseId(exerciseId), m_visiblePartiesChanged(false), m_adlerVisiblePartiesChanged(false), + m_menuGroup(menuGroup), m_visiblePartiesModel(nullptr), m_adlerVisiblePartiesModel(nullptr), m_opmDtc(nullptr), + m_opmFtc(nullptr), m_ui(new Ui::ExerciseEditPartyDialog), m_requestHelper(new LtsUtils::RequestHelper(this)) { - setNoTopicLock(); - m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Administrator-Operator-Parties")); + setNoTopicLock(); + m_ui->setupUi(this); + setOnlineHelpFilename(QStringLiteral("Administrator-Operator-Parties")); } -bool ExerciseEditPartyDialog::init(LtsSession::LtsSessionDataDds *session) +bool ExerciseEditPartyDialog::init(LtsSession::LtsSessionDataDds* session) { - if (!session->getDtc(m_opmDtc)) - return false; - if (!session->getFtc(m_opmFtc)) - return false; + if (!session->getDtc(m_opmDtc)) + return false; + if (!session->getFtc(m_opmFtc)) + return false; - m_visiblePartiesModel = new ExerciseEditVisiblePartiesModel(m_operatorId, m_exerciseId, this); - if (!m_visiblePartiesModel->init(session)) - return false; + m_visiblePartiesModel = new ExerciseEditVisiblePartiesModel(m_operatorId, m_exerciseId, this); + if (!m_visiblePartiesModel->init(session)) + return false; - m_ui->tvVisibleParties->setModel(m_visiblePartiesModel); - m_ui->tvVisibleParties->resizeColumnsToContent(); - m_ui->tvVisibleParties->setSortIndicator(ExerciseEditVisiblePartiesModel::Columns::ColId, Qt::SortOrder::AscendingOrder); - m_ui->tvVisibleParties->setSortingEnabled(false); + m_ui->tvVisibleParties->setModel(m_visiblePartiesModel); + m_ui->tvVisibleParties->resizeColumnsToContent(); + m_ui->tvVisibleParties->setSortIndicator(ExerciseEditVisiblePartiesModel::Columns::ColId, + Qt::SortOrder::AscendingOrder); + m_ui->tvVisibleParties->setSortingEnabled(false); - m_adlerVisiblePartiesModel = new ExerciseEditAdlerVisiblePartiesModel(m_operatorId, m_exerciseId, this); - if (!m_adlerVisiblePartiesModel->init(session)) - return false; + m_adlerVisiblePartiesModel = new ExerciseEditAdlerVisiblePartiesModel(m_operatorId, m_exerciseId, this); + if (!m_adlerVisiblePartiesModel->init(session)) + return false; - m_ui->tvAdlerVisibleParties->setModel(m_adlerVisiblePartiesModel); - m_ui->tvAdlerVisibleParties->resizeColumnsToContent(); - m_ui->tvAdlerVisibleParties->setSortIndicator(ExerciseEditAdlerVisiblePartiesModel::Columns::ColId, Qt::SortOrder::AscendingOrder); - m_ui->tvAdlerVisibleParties->setSortingEnabled(false); + m_ui->tvAdlerVisibleParties->setModel(m_adlerVisiblePartiesModel); + m_ui->tvAdlerVisibleParties->resizeColumnsToContent(); + m_ui->tvAdlerVisibleParties->setSortIndicator(ExerciseEditAdlerVisiblePartiesModel::Columns::ColId, + Qt::SortOrder::AscendingOrder); + m_ui->tvAdlerVisibleParties->setSortingEnabled(false); #ifndef LTS_DEBUG - m_ui->tvVisibleParties->hideColumn(ExerciseEditVisiblePartiesModel::Columns::ColId); - m_ui->tvAdlerVisibleParties->hideColumn(ExerciseEditVisiblePartiesModel::Columns::ColId); + m_ui->tvVisibleParties->hideColumn(ExerciseEditVisiblePartiesModel::Columns::ColId); + m_ui->tvAdlerVisibleParties->hideColumn(ExerciseEditVisiblePartiesModel::Columns::ColId); #endif - connect(m_ui->tvVisibleParties, &LtsDataView::LtsDataView::doubleClicked, m_visiblePartiesModel, &ExerciseEditVisiblePartiesModel::switchCheckbox); - connect(m_ui->tvAdlerVisibleParties, &LtsDataView::LtsDataView::doubleClicked, this, &ExerciseEditPartyDialog::onDoubleClicked); + connect(m_ui->tvVisibleParties, &LtsDataView::LtsDataView::doubleClicked, m_visiblePartiesModel, + &ExerciseEditVisiblePartiesModel::switchCheckbox); + connect(m_ui->tvAdlerVisibleParties, &LtsDataView::LtsDataView::doubleClicked, this, + &ExerciseEditPartyDialog::onDoubleClicked); - connect(m_visiblePartiesModel, &ExerciseEditVisiblePartiesModel::dataChanged, this, [this](const QModelIndex &index) { - m_visiblePartiesChanged = true; slotChangesMade(); onSwitchCheckbox(index);}); - connect(m_adlerVisiblePartiesModel, &ExerciseEditAdlerVisiblePartiesModel::dataChanged, this, [this]() { - m_adlerVisiblePartiesChanged = true; slotChangesMade();}); + connect(m_visiblePartiesModel, &ExerciseEditVisiblePartiesModel::dataChanged, this, + [this](const QModelIndex& index) { + m_visiblePartiesChanged = true; + slotChangesMade(); + onSwitchCheckbox(index); + }); + connect(m_adlerVisiblePartiesModel, &ExerciseEditAdlerVisiblePartiesModel::dataChanged, this, [this]() { + m_adlerVisiblePartiesChanged = true; + slotChangesMade(); + }); #ifdef LTS_DEBUG - m_ui->tvVisibleParties->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->tvVisibleParties, &LtsDataView::LtsDataView::customContextMenuRequested, this, &ExerciseEditPartyDialog::onContextMenuRequested); + m_ui->tvVisibleParties->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->tvVisibleParties, &LtsDataView::LtsDataView::customContextMenuRequested, this, + &ExerciseEditPartyDialog::onContextMenuRequested); #endif - setAdlerVisiblePartiesUncheckable(); - return true; + setAdlerVisiblePartiesUncheckable(); + return true; } -bool ExerciseEditPartyDialog::operatorUpdateVisiblePartiesByExercise(const OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest &req) +bool ExerciseEditPartyDialog::operatorUpdateVisiblePartiesByExercise( + const OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest& req) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; - return m_requestHelper->startSingleRequest([this, req]() - { - return m_opmFtc->operatorUpdateVisiblePartiesByExerciseRequest(req, this); - }); + DEBUG_LOG(m_logger) << Q_FUNC_INFO; + return m_requestHelper->startSingleRequest( + [this, req]() { return m_opmFtc->operatorUpdateVisiblePartiesByExerciseRequest(req, this); }); } ExerciseEditPartyDialog::~ExerciseEditPartyDialog() { - delete m_ui; + delete m_ui; } void ExerciseEditPartyDialog::retranslate() { - translate(m_ui, m_opmDtc->user(m_operatorId), tr("EX:%1 Operator ").arg(m_exerciseId)); + translate(m_ui, m_opmDtc->user(m_operatorId), tr("EX:%1 Operator ").arg(m_exerciseId)); } QByteArray ExerciseEditPartyDialog::adlerVisiblePartiesToJson() const { - QJsonArray adlerVisiblePartiesArray; - QJsonObject adlerVisiblePartiesObject; + QJsonArray adlerVisiblePartiesArray; + QJsonObject adlerVisiblePartiesObject; - - adlerVisiblePartiesArray.append(0); - adlerVisiblePartiesArray.append(1); + adlerVisiblePartiesArray.append(0); + adlerVisiblePartiesArray.append(1); - const QVector &checkedParties = m_adlerVisiblePartiesModel->getCheckedIds(); - for (const int id : checkedParties) - adlerVisiblePartiesArray.append(id); - adlerVisiblePartiesObject[QStringLiteral("adlerAllowed")] = adlerVisiblePartiesArray; + const QVector& checkedParties = m_adlerVisiblePartiesModel->getCheckedIds(); + for (const int id : checkedParties) + adlerVisiblePartiesArray.append(id); + adlerVisiblePartiesObject[QStringLiteral("adlerAllowed")] = adlerVisiblePartiesArray; - QJsonDocument adlerVisiblePartiesDocument(adlerVisiblePartiesObject); + QJsonDocument adlerVisiblePartiesDocument(adlerVisiblePartiesObject); - return adlerVisiblePartiesDocument.toJson(QJsonDocument::Compact); + return adlerVisiblePartiesDocument.toJson(QJsonDocument::Compact); } void ExerciseEditPartyDialog::setAdlerVisiblePartiesUncheckable() { - const QVector &uncheckedParties = m_visiblePartiesModel->getUncheckedIds(); - QVector rowIds; - for (const int id : uncheckedParties) - { - int rowId = m_adlerVisiblePartiesModel->findRowForPartyId(id); - if (rowId < 0) - continue; - rowIds.append(rowId); - } - m_adlerVisiblePartiesModel->setUncheckedPartyIds(rowIds); + const QVector& uncheckedParties = m_visiblePartiesModel->getUncheckedIds(); + QVector rowIds; + for (const int id : uncheckedParties) + { + int rowId = m_adlerVisiblePartiesModel->findRowForPartyId(id); + if (rowId < 0) + continue; + rowIds.append(rowId); + } + m_adlerVisiblePartiesModel->setUncheckedPartyIds(rowIds); } - bool ExerciseEditPartyDialog::apply() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - if (m_operatorId <= 0) - return true; + if (m_operatorId <= 0) + return true; - - OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest req; - req.id(m_operatorId); - req.exerciseId(m_exerciseId); + OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest req; + req.id(m_operatorId); + req.exerciseId(m_exerciseId); - if (!m_visiblePartiesChanged && !m_adlerVisiblePartiesChanged) - return false; + if (!m_visiblePartiesChanged && !m_adlerVisiblePartiesChanged) + return false; - QSet visiblePartyIds = m_visiblePartiesModel->getCheckedIds().toList().toSet(); - - visiblePartyIds.insert(0); - visiblePartyIds.insert(1); + QSet visiblePartyIds = m_visiblePartiesModel->getCheckedIds().toList().toSet(); - const QVector hiddenPartyIds = m_visiblePartiesModel->getUncheckedIds(); - for (const int visible : visiblePartyIds) - DEBUG_LOG(m_logger) << "visible party: " << visible; - for (const int hidden : hiddenPartyIds) - DEBUG_LOG(m_logger) << "hidden party: " << hidden; - req.hiddenParties().set({}); - req.visibleParties().set({}); - std::copy(hiddenPartyIds.begin(), hiddenPartyIds.end(), std::back_inserter(req.hiddenParties().get())); - std::copy(visiblePartyIds.begin(), visiblePartyIds.end(), std::back_inserter(req.visibleParties().get())); + visiblePartyIds.insert(0); + visiblePartyIds.insert(1); - req.properties(adlerVisiblePartiesToJson().toStdString()); + const QVector hiddenPartyIds = m_visiblePartiesModel->getUncheckedIds(); + for (const int visible : visiblePartyIds) + DEBUG_LOG(m_logger) << "visible party: " << visible; + for (const int hidden : hiddenPartyIds) + DEBUG_LOG(m_logger) << "hidden party: " << hidden; + req.hiddenParties().set({}); + req.visibleParties().set({}); + std::copy(hiddenPartyIds.begin(), hiddenPartyIds.end(), std::back_inserter(req.hiddenParties().get())); + std::copy(visiblePartyIds.begin(), visiblePartyIds.end(), std::back_inserter(req.visibleParties().get())); - DEBUG_LOG(m_logger) << "----------------- opId: " << req.id() << ", exId:" << req.exerciseId() << ", req.hiddenParties.size:" << hiddenPartyIds.size() - << "adlerVisibleParties: " << req.properties(); + req.properties(adlerVisiblePartiesToJson().toStdString()); - return operatorUpdateVisiblePartiesByExercise(req); + DEBUG_LOG(m_logger) << "----------------- opId: " << req.id() << ", exId:" << req.exerciseId() + << ", req.hiddenParties.size:" << hiddenPartyIds.size() + << "adlerVisibleParties: " << req.properties(); + + return operatorUpdateVisiblePartiesByExercise(req); } -void ExerciseEditPartyDialog::onContextMenuRequested(const QPoint &position) +void ExerciseEditPartyDialog::onContextMenuRequested(const QPoint& position) { - QMenu menu(m_ui->tvVisibleParties); - menu.addAction(tr("Select All"), this, &ExerciseEditPartyDialog::onSelectAllParties); - menu.addAction(tr("Unselect All"), this, &ExerciseEditPartyDialog::onUnselectAllParties); - menu.exec(m_ui->tvVisibleParties->mapToGlobal(position)); + QMenu menu(m_ui->tvVisibleParties); + menu.addAction(tr("Select All"), this, &ExerciseEditPartyDialog::onSelectAllParties); + menu.addAction(tr("Unselect All"), this, &ExerciseEditPartyDialog::onUnselectAllParties); + menu.exec(m_ui->tvVisibleParties->mapToGlobal(position)); } void ExerciseEditPartyDialog::onSelectAllParties() { - m_visiblePartiesModel->selectAll(); - m_visiblePartiesModel->update(); + m_visiblePartiesModel->selectAll(); + m_visiblePartiesModel->update(); } void ExerciseEditPartyDialog::onUnselectAllParties() { - m_visiblePartiesModel->unselectAll(); - m_visiblePartiesModel->update(); + m_visiblePartiesModel->unselectAll(); + m_visiblePartiesModel->update(); } -void ExerciseEditPartyDialog::onSwitchCheckbox(const QModelIndex &index) +void ExerciseEditPartyDialog::onSwitchCheckbox(const QModelIndex& index) { - if (!index.isValid()) - { - return; - } + if (!index.isValid()) + { + return; + } - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "index.row():" << index.row(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "index.row():" << index.row(); - const QPair row = m_visiblePartiesModel->getRowData(index.row()); - QPair rowAdler = m_adlerVisiblePartiesModel->getRowData(index.row()); - rowAdler.first = row.first; - setAdlerVisiblePartiesUncheckable(); - m_adlerVisiblePartiesModel->setRowData(index.row(), rowAdler); + const QPair row = m_visiblePartiesModel->getRowData(index.row()); + QPair rowAdler = m_adlerVisiblePartiesModel->getRowData(index.row()); + rowAdler.first = row.first; + setAdlerVisiblePartiesUncheckable(); + m_adlerVisiblePartiesModel->setRowData(index.row(), rowAdler); } -void ExerciseEditPartyDialog::onDoubleClicked(const QModelIndex &index) +void ExerciseEditPartyDialog::onDoubleClicked(const QModelIndex& index) { - if (!index.isValid()) - { - return; - } + if (!index.isValid()) + { + return; + } - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "index.row():" << index.row(); + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "index.row():" << index.row(); - - bool isChecked = m_visiblePartiesModel->getRowData(index.row()).first; - if (!isChecked) - return; + bool isChecked = m_visiblePartiesModel->getRowData(index.row()).first; + if (!isChecked) + return; - QPair row = m_adlerVisiblePartiesModel->getRowData(index.row()); - row.first = !row.first; - m_adlerVisiblePartiesModel->setRowData(index.row(), row); + QPair row = m_adlerVisiblePartiesModel->getRowData(index.row()); + row.first = !row.first; + m_adlerVisiblePartiesModel->setRowData(index.row(), row); } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.h old mode 100755 new mode 100644 index a8b350689..a1c100684 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_party_dialog.h @@ -1,76 +1,77 @@ - #pragma once -#include -#include +#include "exm_edit_adler_visible_parties_model.h" +#include "exm_edit_visible_parties_model.h" #include -#include "exm_edit_visible_parties_model.h" -#include "exm_edit_adler_visible_parties_model.h" -#include #include - +#include +#include +#include namespace Ui { class ExerciseEditPartyDialog; } -namespace LtsSession { +namespace LtsSession +{ class LtsSession; } + namespace ExerciseManagement { - - -class ExerciseEditPartyDialog : public LtsWidgets::LtsDialog - , protected OperatorManagement::Interface::Ftc::OperatorUpdateVisiblePartiesByExerciseReplyHandler +class ExerciseEditPartyDialog + : public LtsWidgets::LtsDialog, + protected OperatorManagement::Interface::Ftc::OperatorUpdateVisiblePartiesByExerciseReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ExerciseEditPartyDialog(const int operatorId, - const int exerciseId, - const QString &menuGroup, - QWidget *parent = nullptr); - ~ExerciseEditPartyDialog(); + public: + explicit ExerciseEditPartyDialog(const int operatorId, const int exerciseId, const QString& menuGroup, + QWidget* parent = nullptr); + ~ExerciseEditPartyDialog(); - bool init(LtsSession::LtsSessionDataDds *session); - void onOperatorUpdateVisiblePartiesByExerciseReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + bool init(LtsSession::LtsSessionDataDds* session); -private: + void onOperatorUpdateVisiblePartiesByExerciseReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override final; - QByteArray adlerVisiblePartiesToJson() const; - void setAdlerVisiblePartiesUncheckable(); + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override final; + QByteArray adlerVisiblePartiesToJson() const; + void setAdlerVisiblePartiesUncheckable(); -private slots: - void onContextMenuRequested(const QPoint &position); - void onSelectAllParties(); - void onUnselectAllParties(); - void onSwitchCheckbox(const QModelIndex &index); - void onDoubleClicked(const QModelIndex &index); + private slots: + void onContextMenuRequested(const QPoint& position); + void onSelectAllParties(); + void onUnselectAllParties(); + void onSwitchCheckbox(const QModelIndex& index); + void onDoubleClicked(const QModelIndex& index); -private: - int m_operatorId; - int m_exerciseId; - bool m_visiblePartiesChanged; - bool m_adlerVisiblePartiesChanged; - QString m_menuGroup; + private: + int m_operatorId; + int m_exerciseId; + bool m_visiblePartiesChanged; + bool m_adlerVisiblePartiesChanged; + QString m_menuGroup; - ExerciseEditVisiblePartiesModel *m_visiblePartiesModel; - ExerciseEditAdlerVisiblePartiesModel *m_adlerVisiblePartiesModel; - std::shared_ptr m_opmDtc; - std::shared_ptr m_opmFtc; - Ui::ExerciseEditPartyDialog *m_ui; - LtsUtils::RequestHelper *m_requestHelper; + ExerciseEditVisiblePartiesModel* m_visiblePartiesModel; + ExerciseEditAdlerVisiblePartiesModel* m_adlerVisiblePartiesModel; + std::shared_ptr m_opmDtc; + std::shared_ptr m_opmFtc; + Ui::ExerciseEditPartyDialog* m_ui; + LtsUtils::RequestHelper* m_requestHelper; - bool operatorUpdateVisiblePartiesByExercise(const OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest &req); + bool operatorUpdateVisiblePartiesByExercise( + const OperatorManagement::OperatorUpdateVisiblePartiesByExerciseRequest& req); }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_phase_dialog.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_phase_dialog.h old mode 100755 new mode 100644 index f3a79efef..079e1f77d --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_phase_dialog.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_edit_phase_dialog.h @@ -1,16 +1,15 @@ - #pragma once #include #include #include -#include -#include -#include #include #include +#include +#include +#include namespace Ui { @@ -19,43 +18,51 @@ class ExerciseManagementPhaseEditDialog; namespace ExerciseManagement { -class ExerciseManagementPhaseEditDialog : public LtsWidgets::LtsDialog - , protected ExerciseManagement::Interface::Ftc::ExercisePhaseCreateReplyHandler - , protected ExerciseManagement::Interface::Ftc::ExercisePhaseModifyReplyHandler - , protected FileManagement::Interface::Ftc::FolderModifyReplyHandler +class ExerciseManagementPhaseEditDialog : public LtsWidgets::LtsDialog, + protected ExerciseManagement::Interface::Ftc::ExercisePhaseCreateReplyHandler, + protected ExerciseManagement::Interface::Ftc::ExercisePhaseModifyReplyHandler, + protected FileManagement::Interface::Ftc::FolderModifyReplyHandler { - Q_OBJECT + Q_OBJECT -public: - explicit ExerciseManagementPhaseEditDialog(QWidget *parent = nullptr); + public: + explicit ExerciseManagementPhaseEditDialog(QWidget* parent = nullptr); - bool init(LtsSession::LtsSessionDataDds *session, - const int exerciseId, - const int phaseId); + bool init(LtsSession::LtsSessionDataDds* session, const int exerciseId, const int phaseId); - ~ExerciseManagementPhaseEditDialog(); + ~ExerciseManagementPhaseEditDialog(); - void onExercisePhaseCreateReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onExercisePhaseModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } - void onFolderModifyReply(const Core::FunctionReplyObject &replyObject) override final { m_requestHelper->requestReply(replyObject); } + void onExercisePhaseCreateReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -signals: - void sendData(const ExerciseManagement::ExercisePhase &data); + void onExercisePhaseModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -private: + void onFolderModifyReply(const Core::FunctionReplyObject& replyObject) override final + { + m_requestHelper->requestReply(replyObject); + } -NGL::INGLLogger &m_logger; - void retranslate() override; - bool apply() override final; + signals: + void sendData(const ExerciseManagement::ExercisePhase& data); - Ui::ExerciseManagementPhaseEditDialog *m_ui{nullptr}; - LtsSession::LtsSessionDataDds *m_session{nullptr}; - int m_exercisePhaseId{-1}; - int m_exerciseId{-1}; - std::shared_ptr m_dtc; - std::shared_ptr m_ftc; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; - LtsUtils::RequestHelper *m_requestHelper{nullptr}; + private: + NGL::INGLLogger& m_logger; + void retranslate() override; + bool apply() override final; + + Ui::ExerciseManagementPhaseEditDialog* m_ui{nullptr}; + LtsSession::LtsSessionDataDds* m_session{nullptr}; + int m_exercisePhaseId{-1}; + int m_exerciseId{-1}; + std::shared_ptr m_dtc; + std::shared_ptr m_ftc; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; + LtsUtils::RequestHelper* m_requestHelper{nullptr}; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_operator_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_operator_edit.cpp old mode 100755 new mode 100644 index 416349fe2..98b1b90f5 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_operator_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_operator_edit.cpp @@ -1,146 +1,140 @@ - #include "exm_operator_edit.h" + #include "ui_exm_operator_edit.h" #include - #include namespace ExerciseManagement { -ExerciseManagementOperatorEdit::ExerciseManagementOperatorEdit(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::ExerciseManagementOperatorEdit) - , m_opmDtc(nullptr) - , m_session(nullptr) - , m_operatorModel(nullptr) - , m_menuGroup(menuGroup) - , m_exercise() - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ExerciseManagementOperatorEdit::ExerciseManagementOperatorEdit(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), + m_ui(new Ui::ExerciseManagementOperatorEdit), m_opmDtc(nullptr), m_session(nullptr), m_operatorModel(nullptr), + m_menuGroup(menuGroup), m_exercise(), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); #ifdef LTS_DEBUG - m_ui->dvOperators->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->dvOperators, &LtsDataView::LtsDataView::customContextMenuRequested, this, &ExerciseManagementOperatorEdit::onContextMenuRequested); + m_ui->dvOperators->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->dvOperators, &LtsDataView::LtsDataView::customContextMenuRequested, this, + &ExerciseManagementOperatorEdit::onContextMenuRequested); #endif - setOnlineHelpFilename(QStringLiteral("Situation-Operators")); + setOnlineHelpFilename(QStringLiteral("Situation-Operators")); } ExerciseManagementOperatorEdit::~ExerciseManagementOperatorEdit() { - delete m_ui; + delete m_ui; } -bool ExerciseManagementOperatorEdit::init(LtsSession::LtsSessionDataDds *session) +bool ExerciseManagementOperatorEdit::init(LtsSession::LtsSessionDataDds* session) { - m_session = session; + m_session = session; - if (!m_session->getDtc(m_opmDtc)) - return false; + if (!m_session->getDtc(m_opmDtc)) + return false; - std::shared_ptr dtc; - if (!m_session->getDtc(dtc)) - return false; + std::shared_ptr dtc; + if (!m_session->getDtc(dtc)) + return false; - m_exercise = dtc->exercise(m_session->exerciseId()); - m_operatorModel = new ExerciseOperatorModel(m_session, m_exercise.id(), this); - m_ui->dvOperators->setModel(m_operatorModel); - m_ui->dvOperators->seamless(); - connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, this, &ExerciseManagementOperatorEdit::slotChangesMade); + m_exercise = dtc->exercise(m_session->exerciseId()); + m_operatorModel = new ExerciseOperatorModel(m_session, m_exercise.id(), this); + m_ui->dvOperators->setModel(m_operatorModel); + m_ui->dvOperators->seamless(); + connect(m_operatorModel, &ExerciseOperatorModel::dataChanged, this, + &ExerciseManagementOperatorEdit::slotChangesMade); - return true; + return true; } -void ExerciseManagementOperatorEdit::onContextMenuRequested(const QPoint &position) +void ExerciseManagementOperatorEdit::onContextMenuRequested(const QPoint& position) { - QMenu menu(m_ui->dvOperators); - menu.addAction(tr("Select All"), this, &ExerciseManagementOperatorEdit::onSelectAllUsers); - menu.addAction(tr("Unselect All"), this, &ExerciseManagementOperatorEdit::onUnselectAllUsers); - menu.exec(m_ui->dvOperators->mapToGlobal(position)); + QMenu menu(m_ui->dvOperators); + menu.addAction(tr("Select All"), this, &ExerciseManagementOperatorEdit::onSelectAllUsers); + menu.addAction(tr("Unselect All"), this, &ExerciseManagementOperatorEdit::onUnselectAllUsers); + menu.exec(m_ui->dvOperators->mapToGlobal(position)); } void ExerciseManagementOperatorEdit::onSelectAllUsers() { - m_operatorModel->selectAll(); - m_operatorModel->update(); + m_operatorModel->selectAll(); + m_operatorModel->update(); } void ExerciseManagementOperatorEdit::onUnselectAllUsers() { - m_operatorModel->unselectAll(); - m_operatorModel->update(); + m_operatorModel->unselectAll(); + m_operatorModel->update(); } void ExerciseManagementOperatorEdit::retranslate() { - translate(m_ui, m_exercise, tr("Exercise Operators")); + translate(m_ui, m_exercise, tr("Exercise Operators")); } bool ExerciseManagementOperatorEdit::apply() { - if (m_exercise.id() > 0) - { - sendModifiedOperators(m_exercise.id()); - return true; - } + if (m_exercise.id() > 0) + { + sendModifiedOperators(m_exercise.id()); + return true; + } - return false; + return false; } -template -bool ExerciseManagementOperatorEdit::removeElement(std::vector &vec, T elem) +template bool ExerciseManagementOperatorEdit::removeElement(std::vector& vec, T elem) { - for (auto it = vec.begin(); it != vec.end(); ++it) - { - if (*it == elem) + for (auto it = vec.begin(); it != vec.end(); ++it) { - vec.erase(it); - return true; + if (*it == elem) + { + vec.erase(it); + return true; + } } - } - return false; + return false; } void ExerciseManagementOperatorEdit::sendModifiedOperators(int thisExerciseId) { - std::shared_ptr opmFtc; - if (!m_session->getFtc(opmFtc)) - { - ERROR_LOG(m_logger) << "Cannot change add/remove Operators to/from Exercise as the OPM-FTC could not be fetched." ; - return; - } - - for (int row = 0; row < m_operatorModel->rowCount(); ++row) - { - const auto rowData = m_operatorModel->getRowData(row); - bool found = false; - OperatorManagement::User user = m_opmDtc->user(rowData.second.id()); - for (auto ex : user.exerciseIds()) - if (ex == thisExerciseId) - found = true; - - if (found == rowData.first) - continue; - - if (rowData.first) - user.exerciseIds().resize(user.exerciseIds().size() + 1, thisExerciseId); - else - removeElement(user.exerciseIds(), thisExerciseId); - - OperatorManagement::OperatorCreateModifyRequest req; - req.id(user.id()); - req.visibleExercises() = user.exerciseIds(); - req.visiblePartiesByExercise() = user.visiblePartiesByExercise(); - - m_requestHelper->startSingleRequest([this, req, opmFtc]() + std::shared_ptr opmFtc; + if (!m_session->getFtc(opmFtc)) { - return opmFtc->operatorCreateModifyRequest(req, this); - }); - } + ERROR_LOG(m_logger) + << "Cannot change add/remove Operators to/from Exercise as the OPM-FTC could not be fetched."; + return; + } + + for (int row = 0; row < m_operatorModel->rowCount(); ++row) + { + const auto rowData = m_operatorModel->getRowData(row); + bool found = false; + OperatorManagement::User user = m_opmDtc->user(rowData.second.id()); + for (auto ex : user.exerciseIds()) + if (ex == thisExerciseId) + found = true; + + if (found == rowData.first) + continue; + + if (rowData.first) + user.exerciseIds().resize(user.exerciseIds().size() + 1, thisExerciseId); + else + removeElement(user.exerciseIds(), thisExerciseId); + + OperatorManagement::OperatorCreateModifyRequest req; + req.id(user.id()); + req.visibleExercises() = user.exerciseIds(); + req.visiblePartiesByExercise() = user.visiblePartiesByExercise(); + + m_requestHelper->startSingleRequest( + [this, req, opmFtc]() { return opmFtc->operatorCreateModifyRequest(req, this); }); + } } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_edit.cpp old mode 100755 new mode 100644 index 5806a3d76..c5c7592a7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_edit.cpp @@ -1,135 +1,124 @@ - - #include "exm_phase_edit.h" -#include "ui_exm_phase_edit.h" -#include "exm_phase_model.h" + #include "exm_edit_phase_dialog.h" +#include "exm_phase_model.h" +#include "ui_exm_phase_edit.h" #include namespace ExerciseManagement { -ExerciseManagementPhaseEdit::ExerciseManagementPhaseEdit(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_ui(new Ui::ExerciseManagementPhaseEdit) - , m_dtc(nullptr) - , m_ftc(nullptr) - , m_flmDtc(nullptr) - , m_flmFtc(nullptr) - , m_session(nullptr) - , m_phaseModel(nullptr) - , m_menuGroup(menuGroup) - , m_exercise() - , m_requestHelper(new LtsUtils::RequestHelper(this)) +ExerciseManagementPhaseEdit::ExerciseManagementPhaseEdit(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), + m_ui(new Ui::ExerciseManagementPhaseEdit), m_dtc(nullptr), m_ftc(nullptr), m_flmDtc(nullptr), m_flmFtc(nullptr), + m_session(nullptr), m_phaseModel(nullptr), m_menuGroup(menuGroup), m_exercise(), + m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); + m_ui->setupUi(this); - setOnlineHelpFilename(QStringLiteral("Situation-Exercise_Phases")); + setOnlineHelpFilename(QStringLiteral("Situation-Exercise_Phases")); } ExerciseManagementPhaseEdit::~ExerciseManagementPhaseEdit() { - delete m_ui; + delete m_ui; } -bool ExerciseManagementPhaseEdit::init(LtsSession::LtsSessionDataDds *session) +bool ExerciseManagementPhaseEdit::init(LtsSession::LtsSessionDataDds* session) { - m_session = session; + m_session = session; - if (!m_session->getDtc(m_dtc)) - return false; - if (!m_session->getFtc(m_ftc)) - return false; - if (!m_session->getDtc(m_flmDtc)) - return false; - if (!m_session->getFtc(m_flmFtc)) - return false; + if (!m_session->getDtc(m_dtc)) + return false; + if (!m_session->getFtc(m_ftc)) + return false; + if (!m_session->getDtc(m_flmDtc)) + return false; + if (!m_session->getFtc(m_flmFtc)) + return false; - m_exercise = m_dtc->exercise(m_session->exerciseId()); + m_exercise = m_dtc->exercise(m_session->exerciseId()); - m_phaseModel = new ExercisePhaseModel(this); - m_phaseModel->initModel(m_exercise.id(), m_dtc); + m_phaseModel = new ExercisePhaseModel(this); + m_phaseModel->initModel(m_exercise.id(), m_dtc); - m_ui->dvPhases->setModel(m_phaseModel); - m_ui->dvPhases->hideColumn(3); - m_ui->dvPhases->hideColumn(4); - m_ui->dvPhases->seamless(); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ExerciseManagementPhaseEdit::onAddExercisePhase); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementPhaseEdit::onEditExercisePhase); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, &ExerciseManagementPhaseEdit::onRemoveExercisePhase); + m_ui->dvPhases->setModel(m_phaseModel); + m_ui->dvPhases->hideColumn(3); + m_ui->dvPhases->hideColumn(4); + m_ui->dvPhases->seamless(); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &ExerciseManagementPhaseEdit::onAddExercisePhase); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Edit, this, &ExerciseManagementPhaseEdit::onEditExercisePhase); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Remove, this, + &ExerciseManagementPhaseEdit::onRemoveExercisePhase); - connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalDoubleClicked, - this, &ExerciseManagementPhaseEdit::onEditExercisePhase); - connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalSelectionChanged, - this, &ExerciseManagementPhaseEdit::enaDisaPhaseButtons); - enaDisaPhaseButtons(); + connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &ExerciseManagementPhaseEdit::onEditExercisePhase); + connect(m_ui->dvPhases, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &ExerciseManagementPhaseEdit::enaDisaPhaseButtons); + enaDisaPhaseButtons(); - return true; + return true; } void ExerciseManagementPhaseEdit::enaDisaPhaseButtons() { - QModelIndexList selectedRows = m_ui->dvPhases->selectedRows(); - const int cntSelectedRows = selectedRows.size(); + QModelIndexList selectedRows = m_ui->dvPhases->selectedRows(); + const int cntSelectedRows = selectedRows.size(); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); - m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Edit, cntSelectedRows == 1); + m_buttonBox->setButtonEnabled(LtsWidgets::DialogButton::Remove, cntSelectedRows == 1); } void ExerciseManagementPhaseEdit::onAddExercisePhase() { - ExerciseManagementPhaseEditDialog *dialog = new ExerciseManagementPhaseEditDialog(this); - dialog->init(m_session, m_exercise.id(), -1 ); + ExerciseManagementPhaseEditDialog* dialog = new ExerciseManagementPhaseEditDialog(this); + dialog->init(m_session, m_exercise.id(), -1); - addDialog(dialog, m_menuGroup, QLatin1String("NewExercisePhase"), LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, QLatin1String("NewExercisePhase"), LtsWidgets::LayoutArea::eDialogTab); } void ExerciseManagementPhaseEdit::onEditExercisePhase() { - const QModelIndex idx = m_ui->dvPhases->currentIndex(); - const ExercisePhase exPhase = m_phaseModel->getRowData(idx.row()); + const QModelIndex idx = m_ui->dvPhases->currentIndex(); + const ExercisePhase exPhase = m_phaseModel->getRowData(idx.row()); - if (exPhase.id() <= 0) - return; - DEBUG_LOG(m_logger) << "current exPhase Id: " << exPhase.id(); + if (exPhase.id() <= 0) + return; + DEBUG_LOG(m_logger) << "current exPhase Id: " << exPhase.id(); - ExerciseManagementPhaseEditDialog *dialog = new ExerciseManagementPhaseEditDialog(this); + ExerciseManagementPhaseEditDialog* dialog = new ExerciseManagementPhaseEditDialog(this); - dialog->init(m_session, m_exercise.id(), exPhase.id()); - const QString identifier = QLatin1String("EditExercisePhase") + QString::number(exPhase.id()); + dialog->init(m_session, m_exercise.id(), exPhase.id()); + const QString identifier = QLatin1String("EditExercisePhase") + QString::number(exPhase.id()); - addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); + addDialog(dialog, m_menuGroup, identifier, LtsWidgets::LayoutArea::eDialogTab); } void ExerciseManagementPhaseEdit::onRemoveExercisePhase() { - const int phId = m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id(); - int exeFolderId = m_flmDtc->getExerciseFolderId(m_exercise.id()); - const int folderId = m_flmDtc->getPhaseFolderId(exeFolderId, phId); + const int phId = m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id(); + int exeFolderId = m_flmDtc->getExerciseFolderId(m_exercise.id()); + const int folderId = m_flmDtc->getPhaseFolderId(exeFolderId, phId); - if (folderId > 0) - { - Core::RemoveElementRequest req(folderId); - m_requestHelper->startSingleRequest([req, this]() + if (folderId > 0) { - return m_flmFtc->folderRemoveRequest(req, this); - }); - } + Core::RemoveElementRequest req(folderId); + m_requestHelper->startSingleRequest([req, this]() { return m_flmFtc->folderRemoveRequest(req, this); }); + } - Core::RemoveElementRequest req(m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id()); - m_requestHelper->startSingleRequest([req, this]() - { - m_ftc->enableExercisePhaseRemove(); - return m_ftc->exercisePhaseRemoveRequest(req, this); - }); + Core::RemoveElementRequest req(m_phaseModel->getRowData(m_ui->dvPhases->currentIndex().row()).id()); + m_requestHelper->startSingleRequest([req, this]() { + m_ftc->enableExercisePhaseRemove(); + return m_ftc->exercisePhaseRemoveRequest(req, this); + }); } void ExerciseManagementPhaseEdit::retranslate() { - translate(m_ui, tr("Exercise Phases")); + translate(m_ui, tr("Exercise Phases")); } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.cpp old mode 100755 new mode 100644 index 8355b42f4..03dff9967 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.cpp @@ -1,97 +1,82 @@ - #include "exm_phase_model.h" namespace ExerciseManagement { - - - -ExercisePhaseModel::ExercisePhaseModel(QObject *parent) - : LtsWidgets::LtsAbstractTableModel({tr("Phase"), - tr("Start"), - tr("End"), - tr("Description"), - tr("Exercise-Id")}, - parent) - , m_exmDtc(nullptr) -{} - - -bool ExercisePhaseModel::initModel(int exerciseId, const std::shared_ptr &dtc) +ExercisePhaseModel::ExercisePhaseModel(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Phase"), tr("Start"), tr("End"), tr("Description"), tr("Exercise-Id")}, parent), + m_exmDtc(nullptr) { - m_exerciseId = exerciseId; - m_exmDtc = dtc; - - connect(m_exmDtc.get(), &ExerciseManagement::Interface::Dtc::exercisePhaseChanged, - this, &ExercisePhaseModel::onDataChanged); - - - m_exmDtc->exercisePhases([this](const ExercisePhase &item) { insertRow(item); }); - INFO_LOG(m_logger) << "initModel - #exercise phases: " << m_vecData.size(); - return true; } - -QVariant ExercisePhaseModel::data(const QModelIndex &index, int role) const +bool ExercisePhaseModel::initModel(int exerciseId, const std::shared_ptr& dtc) { - if (!index.isValid() || role != Qt::DisplayRole || index.row() >= m_vecData.size()) - return QVariant(); + m_exerciseId = exerciseId; + m_exmDtc = dtc; - if (role == Qt::DisplayRole) - { - const ExerciseManagement::ExercisePhase &exPhase = m_vecData.at(index.row()); + connect(m_exmDtc.get(), &ExerciseManagement::Interface::Dtc::exercisePhaseChanged, this, + &ExercisePhaseModel::onDataChanged); - switch (index.column()) + m_exmDtc->exercisePhases([this](const ExercisePhase& item) { insertRow(item); }); + INFO_LOG(m_logger) << "initModel - #exercise phases: " << m_vecData.size(); + return true; +} + +QVariant ExercisePhaseModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid() || role != Qt::DisplayRole || index.row() >= m_vecData.size()) + return QVariant(); + + if (role == Qt::DisplayRole) { - case Name: - return QString::fromStdString(exPhase.name()); - case Start: - return QDateTime::fromMSecsSinceEpoch(exPhase.beginTime()); - case End: - return QDateTime::fromMSecsSinceEpoch(exPhase.endTime()); - case Description: - return QString::fromStdString(exPhase.description()); - case ExerciseId: - return (exPhase.exerciseId()); + const ExerciseManagement::ExercisePhase& exPhase = m_vecData.at(index.row()); + + switch (index.column()) + { + case Name: + return QString::fromStdString(exPhase.name()); + case Start: + return QDateTime::fromMSecsSinceEpoch(exPhase.beginTime()); + case End: + return QDateTime::fromMSecsSinceEpoch(exPhase.endTime()); + case Description: + return QString::fromStdString(exPhase.description()); + case ExerciseId: + return (exPhase.exerciseId()); + } } - } - return QVariant(); + return QVariant(); } - - - -void ExercisePhaseProxyModel::setSourceModel(QAbstractItemModel *sourceModel) +void ExercisePhaseProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); } -bool ExercisePhaseProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +bool ExercisePhaseProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case ExercisePhaseModel::Start: + return dataLeft.beginTime() < dataRight.beginTime(); + case ExercisePhaseModel::End: + return dataLeft.endTime() < dataRight.endTime(); + case ExercisePhaseModel::Name: + case ExercisePhaseModel::Description: + case ExercisePhaseModel::ExerciseId: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case ExercisePhaseModel::Start: - return dataLeft.beginTime() < dataRight.beginTime(); - case ExercisePhaseModel::End: - return dataLeft.endTime() < dataRight.endTime(); - case ExercisePhaseModel::Name: - case ExercisePhaseModel::Description: - case ExercisePhaseModel::ExerciseId: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.h old mode 100755 new mode 100644 index 5f70f099a..2c3571662 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/ExerciseManagement/Gui/ExerciseEdit/exm_phase_model.h @@ -1,65 +1,56 @@ - #pragma once -#include -#include - #include #include - +#include +#include namespace ExerciseManagement { - - - class ExercisePhaseModel final : public LtsWidgets::LtsAbstractTableModel { - Q_OBJECT + Q_OBJECT -public: - enum Columns - { - Name, - Start, - End, - Description, - ExerciseId - }; - explicit ExercisePhaseModel(QObject *parent = nullptr); + public: + enum Columns { Name, Start, End, Description, ExerciseId }; - bool initModel(int exerciseId, const std::shared_ptr &dtc); + explicit ExercisePhaseModel(QObject* parent = nullptr); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override final; + bool initModel(int exerciseId, const std::shared_ptr& dtc); -protected: + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override final; -NGL::INGLLogger &m_logger; - bool isFiltered(const ExercisePhase &data, DataModification modType) const override - { - if (data.exerciseId() != m_exerciseId) - return true; - return LtsWidgets::LtsAbstractTableModel::isFiltered(data, modType); - } -private: - int m_exerciseId{0}; + protected: + NGL::INGLLogger& m_logger; - std::shared_ptr m_exmDtc; - friend class ExercisePhaseProxyModel; + bool isFiltered(const ExercisePhase& data, DataModification modType) const override + { + if (data.exerciseId() != m_exerciseId) + return true; + return LtsWidgets::LtsAbstractTableModel::isFiltered(data, modType); + } + + private: + int m_exerciseId{0}; + + std::shared_ptr m_exmDtc; + friend class ExercisePhaseProxyModel; }; class ExercisePhaseProxyModel final : public LtsWidgets::LtsColumnFilterProxyModel { - Q_OBJECT -public: - using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; - void setSourceModel(QAbstractItemModel *sourceModel) override; -protected: - bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; -private: - ExercisePhaseModel *m_sourceModel = nullptr; + Q_OBJECT + public: + using LtsWidgets::LtsColumnFilterProxyModel::LtsColumnFilterProxyModel; + void setSourceModel(QAbstractItemModel* sourceModel) override; + + protected: + bool lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const override; + + private: + ExercisePhaseModel* m_sourceModel = nullptr; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.cpp old mode 100755 new mode 100644 index b0387b442..55a0370e1 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.cpp @@ -1,230 +1,224 @@ #include "flm_hq_report_converter.h" +#include +#include #include #include -#include - +#include +#include +#include +#include +#include #include #include #include #include -#include - -#include -#include -#include - -#include -#include - namespace FileManagement { FlmHqReportConverter::FlmHqReportConverter() : m_logger(getLogger("HQReportConverter")) { - connect(this, &FlmHqReportConverter::allRequestsFinished, - this, &FlmHqReportConverter::onRequestsFinished); + connect(this, &FlmHqReportConverter::allRequestsFinished, this, &FlmHqReportConverter::onRequestsFinished); } -bool FlmHqReportConverter::init(LtsSession::LtsSession *session, int currentPartyId) +bool FlmHqReportConverter::init(LtsSession::LtsSession* session, int currentPartyId) { - if (session == nullptr) - { - ERROR_LOG(m_logger) << "Got invalid session"; + if (session == nullptr) + { + ERROR_LOG(m_logger) << "Got invalid session"; - return false; - } + return false; + } - m_session = session; + m_session = session; - if (!m_session->getDtc(m_flmDtc)) - { - ERROR_LOG(m_logger) << "Could not get FLM Dtc."; + if (!m_session->getDtc(m_flmDtc)) + { + ERROR_LOG(m_logger) << "Could not get FLM Dtc."; - return false; - } + return false; + } - if (!m_session->getFtc(m_flmFtc)) - { - ERROR_LOG(m_logger) << "Could not get FLM Ftc."; + if (!m_session->getFtc(m_flmFtc)) + { + ERROR_LOG(m_logger) << "Could not get FLM Ftc."; - return false; - } + return false; + } - if (!session->getDtc(m_ppmDtc)) - { - ERROR_LOG(m_logger) << "Could not get PPM Dtc."; + if (!session->getDtc(m_ppmDtc)) + { + ERROR_LOG(m_logger) << "Could not get PPM Dtc."; - return false; - } + return false; + } - if (!m_flmFtc->enableFileContentModify()) - { - ERROR_LOG(m_logger) << "Could enable fileContentModify."; + if (!m_flmFtc->enableFileContentModify()) + { + ERROR_LOG(m_logger) << "Could enable fileContentModify."; - return false; - } + return false; + } - m_flmDtc->enableFileContent(); - m_flmDtc->enableFolder(); + m_flmDtc->enableFileContent(); + m_flmDtc->enableFolder(); - if (m_geometryModel != nullptr) - { - delete m_geometryModel; - m_geometryModel = nullptr; - } + if (m_geometryModel != nullptr) + { + delete m_geometryModel; + m_geometryModel = nullptr; + } - m_geometryModel = SituationMap::GeometryModelFactory::singleton()->create(); + m_geometryModel = SituationMap::GeometryModelFactory::singleton()->create(); - m_partyId = currentPartyId; + m_partyId = currentPartyId; - return true; + return true; } -void FlmHqReportConverter::addHqToPlanIds(const QMap> &hqToPlanIds) +void FlmHqReportConverter::addHqToPlanIds(const QMap>& hqToPlanIds) { - for (auto it = hqToPlanIds.constBegin(); it != hqToPlanIds.constEnd(); ++it) - { - m_hqToPlanIds[it.key()].append(it.value()); - } + for (auto it = hqToPlanIds.constBegin(); it != hqToPlanIds.constEnd(); ++it) + { + m_hqToPlanIds[it.key()].append(it.value()); + } } void FlmHqReportConverter::processCollectedHqs() { - for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) - { - m_pendingRequests += it.value().size(); - } - - for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) - { - int planId = it.key(); - const QList &reportIds = it.value(); - - for (int id : reportIds) + for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) { - DEBUG_LOG(m_logger) << "Request File with ID: " << id << " from plan with ID: " << planId; - FileManagement::GetFileContentDataRequest request(id); - m_flmFtc->getFileContentDataRequest(request, this); + m_pendingRequests += it.value().size(); + } + + for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) + { + int planId = it.key(); + const QList& reportIds = it.value(); + + for (int id : reportIds) + { + DEBUG_LOG(m_logger) << "Request File with ID: " << id << " from plan with ID: " << planId; + FileManagement::GetFileContentDataRequest request(id); + m_flmFtc->getFileContentDataRequest(request, this); + } } - } } -void FlmHqReportConverter::createGeometryFromReport(const HqReportData &data) +void FlmHqReportConverter::createGeometryFromReport(const HqReportData& data) { - m_symbolFactory.build(data.art, data, m_geometryModel); + m_symbolFactory.build(data.art, data, m_geometryModel); } void FlmHqReportConverter::checkIfAllFinished() { - if (m_pendingRequests <= 0) emit allRequestsFinished(); + if (m_pendingRequests <= 0) + emit allRequestsFinished(); } -void FlmHqReportConverter::onGetFileContentDataReply( - const FileManagement::GetFileContentDataReply &reply) +void FlmHqReportConverter::onGetFileContentDataReply(const FileManagement::GetFileContentDataReply& reply) { - m_pendingRequests--; + m_pendingRequests--; - if (reply.errorString().size() > 0) - { - ERROR_LOG(m_logger) << "Got onGetFileContentDataReply error: " << reply.errorString(); - return; - } - - int id = static_cast(reply.id()); - int planId = -1; - - DEBUG_LOG(m_logger) << "Reply File with ID: " << id << " from plan with ID: " << planId; - - INFO_LOG(m_logger) << "Got reply with id " << id << " and errorString " << reply.errorString(); - - QByteArray fileContent = QByteArray(reinterpret_cast(reply.content().data()), reply.content().size()); - - FlmHqReportJsonParser m_parser = FlmHqReportJsonParser(); - - HqReportData data = m_parser.parse(fileContent); - data.contentFileId = id; - - DEBUG_LOG(m_logger) << "Party: " << m_partyId << " has Color: "<< QColor::fromRgb(QRgb(m_ppmDtc->party(m_partyId).color())).value(); - - data.partyColor = QColor::fromRgb(QRgb(m_ppmDtc->party(m_partyId).color())); - - for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) - { - if (it.value().contains(id)) + if (reply.errorString().size() > 0) { - planId = it.key(); - break; + ERROR_LOG(m_logger) << "Got onGetFileContentDataReply error: " << reply.errorString(); + return; } - } - m_convertedHqToPlanIds[planId].append(data); + int id = static_cast(reply.id()); + int planId = -1; - DEBUG_LOG(m_logger) << "Content size: " << reply.content().size(); + DEBUG_LOG(m_logger) << "Reply File with ID: " << id << " from plan with ID: " << planId; - checkIfAllFinished(); + INFO_LOG(m_logger) << "Got reply with id " << id << " and errorString " << reply.errorString(); + + QByteArray fileContent = QByteArray(reinterpret_cast(reply.content().data()), reply.content().size()); + + FlmHqReportJsonParser m_parser = FlmHqReportJsonParser(); + + HqReportData data = m_parser.parse(fileContent); + data.contentFileId = id; + + DEBUG_LOG(m_logger) << "Party: " << m_partyId + << " has Color: " << QColor::fromRgb(QRgb(m_ppmDtc->party(m_partyId).color())).value(); + + data.partyColor = QColor::fromRgb(QRgb(m_ppmDtc->party(m_partyId).color())); + + for (auto it = m_hqToPlanIds.constBegin(); it != m_hqToPlanIds.constEnd(); ++it) + { + if (it.value().contains(id)) + { + planId = it.key(); + break; + } + } + + m_convertedHqToPlanIds[planId].append(data); + + DEBUG_LOG(m_logger) << "Content size: " << reply.content().size(); + + checkIfAllFinished(); } -void FlmHqReportConverter::onFileContentModifyReply(const Core::FunctionReplyObject &reply) +void FlmHqReportConverter::onFileContentModifyReply(const Core::FunctionReplyObject& reply) { - DEBUG_LOG(m_logger) << "Got FileContentModify Reply: " << reply.translated(); + DEBUG_LOG(m_logger) << "Got FileContentModify Reply: " << reply.translated(); - if (reply.error()) - { - ERROR_LOG(m_logger) << "Error while insert HX Message: " << reply.translated() - << ", error: " << reply.error(); - } + if (reply.error()) + { + ERROR_LOG(m_logger) << "Error while insert HX Message: " << reply.translated() << ", error: " << reply.error(); + } } -void FlmHqReportConverter::onFileContentRemoveReply(const Core::FunctionReplyObject &reply) +void FlmHqReportConverter::onFileContentRemoveReply(const Core::FunctionReplyObject& reply) { - DEBUG_LOG(m_logger) << "Got FileContentRemove Reply: " << reply.translated(); + DEBUG_LOG(m_logger) << "Got FileContentRemove Reply: " << reply.translated(); - if (reply.error()) - { - ERROR_LOG(m_logger) << "Error while insert HX Message: " << reply.translated() - << ", error: " << reply.error(); - } + if (reply.error()) + { + ERROR_LOG(m_logger) << "Error while insert HX Message: " << reply.translated() << ", error: " << reply.error(); + } } void FlmHqReportConverter::onRequestsFinished() { - DEBUG_LOG(m_logger) << "ALL REQUESTS FINISHED"; + DEBUG_LOG(m_logger) << "ALL REQUESTS FINISHED"; - for (auto it = m_convertedHqToPlanIds.constBegin(); it != m_convertedHqToPlanIds.constEnd(); ++it) - { - int planId = it.key(); - const QList &reportDatas = it.value(); - - for (auto &reportData : reportDatas) + for (auto it = m_convertedHqToPlanIds.constBegin(); it != m_convertedHqToPlanIds.constEnd(); ++it) { - DEBUG_LOG(m_logger) << "createGeometryFromReport :" << reportData.art; - createGeometryFromReport(reportData); + int planId = it.key(); + const QList& reportDatas = it.value(); + + for (auto& reportData : reportDatas) + { + DEBUG_LOG(m_logger) << "createGeometryFromReport :" << reportData.art; + createGeometryFromReport(reportData); + } + + const FileManagement::FileContent& flc = m_flmDtc->fileContent(planId); + + FileManagement::FileContentModifyRequest data; + + DEBUG_LOG(m_logger) << "FILE CONTENT: " << flc.name() << " " << flc.folderId(); + + data.id(flc.id()); + data.name(flc.name()); + data.isTemplate(false); + data.isHidden(false); + data.folderId(flc.folderId()); + data.fileStatus(FileManagement::FileStatus::Valid); + data.fileCategory(FileManagement::FileCategory::Exercise); + data.fileType(FileManagement::FileType::TacticalPlan); + data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + data.lastModified(QDateTime::currentMSecsSinceEpoch()); + data.content(LtsUtils::convert>(m_geometryModel->toByteArray())); + data.exerciseId(m_session->exerciseId()); + + m_flmFtc->fileContentModifyRequest(data, this); + + m_geometryModel->clearModel(); } - - const FileManagement::FileContent &flc = m_flmDtc->fileContent(planId); - - FileManagement::FileContentModifyRequest data; - - DEBUG_LOG(m_logger) << "FILE CONTENT: " << flc.name() << " " << flc.folderId(); - - data.id(flc.id()); - data.name(flc.name()); - data.isTemplate(false); - data.isHidden(false); - data.folderId(flc.folderId()); - data.fileStatus(FileManagement::FileStatus::Valid); - data.fileCategory(FileManagement::FileCategory::Exercise); - data.fileType(FileManagement::FileType::TacticalPlan); - data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - data.lastModified(QDateTime::currentMSecsSinceEpoch()); - data.content(LtsUtils::convert>(m_geometryModel->toByteArray())); - data.exerciseId(m_session->exerciseId()); - - m_flmFtc->fileContentModifyRequest(data, this); - - m_geometryModel->clearModel(); - } } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.h old mode 100755 new mode 100644 index 047892758..67318a6cd --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_converter.h @@ -1,10 +1,10 @@ #pragma once -#include -#include - #include "flm_hq_report_json_parser.h" #include "flm_hq_report_symbol_factory.h" +#include +#include + namespace LtsSession { class LtsSession; @@ -16,59 +16,55 @@ namespace Interface { class Dtc; class Ftc; -} +} // namespace Interface class FlmHqReportConverter : public QObject, - public Interface::Ftc::GetFileContentDataReplyHandler, - public Interface::Ftc::FileContentModifyReplyHandler, - public Interface::Ftc::FileContentRemoveReplyHandler + public Interface::Ftc::GetFileContentDataReplyHandler, + public Interface::Ftc::FileContentModifyReplyHandler, + public Interface::Ftc::FileContentRemoveReplyHandler { - Q_OBJECT -public: - FlmHqReportConverter(); - ~FlmHqReportConverter() = default; + Q_OBJECT + public: + FlmHqReportConverter(); + ~FlmHqReportConverter() = default; - bool init(LtsSession::LtsSession *session, int currentPartyId); - + bool init(LtsSession::LtsSession* session, int currentPartyId); - void addHqToPlanIds(const QMap> &hqToPlanIds); - + void addHqToPlanIds(const QMap>& hqToPlanIds); - void processCollectedHqs(); - + void processCollectedHqs(); - void createGeometryFromReport(const HqReportData &data); + void createGeometryFromReport(const HqReportData& data); -private: - void checkIfAllFinished(); + private: + void checkIfAllFinished(); -protected: - NGL::INGLLogger &m_logger; - void onGetFileContentDataReply(const FileManagement::GetFileContentDataReply &reply) override; - void onFileContentModifyReply(const Core::FunctionReplyObject &reply) override; - void onFileContentRemoveReply(const Core::FunctionReplyObject &reply) override; -public slots: - void onRequestsFinished(); -signals: - + protected: + NGL::INGLLogger& m_logger; + void onGetFileContentDataReply(const FileManagement::GetFileContentDataReply& reply) override; + void onFileContentModifyReply(const Core::FunctionReplyObject& reply) override; + void onFileContentRemoveReply(const Core::FunctionReplyObject& reply) override; + public slots: + void onRequestsFinished(); + signals: - void allRequestsFinished(); + void allRequestsFinished(); -private: - LtsSession::LtsSession *m_session{nullptr}; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; - std::shared_ptr m_ppmDtc; + private: + LtsSession::LtsSession* m_session{nullptr}; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; + std::shared_ptr m_ppmDtc; - SituationMap::GeometryModel *m_geometryModel{nullptr}; - QList m_planNodes; - SymbolFactory m_symbolFactory; + SituationMap::GeometryModel* m_geometryModel{nullptr}; + QList m_planNodes; + SymbolFactory m_symbolFactory; - int m_partyId; - int m_pendingRequests{0}; + int m_partyId; + int m_pendingRequests{0}; - QMap> m_hqToPlanIds; - QMap m_hqToPlanIdsLookup; - QMap> m_convertedHqToPlanIds; -}; -} + QMap> m_hqToPlanIds; + QMap m_hqToPlanIdsLookup; + QMap> m_convertedHqToPlanIds; +}; +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.cpp old mode 100755 new mode 100644 index 7decc347b..9c4e6a987 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.cpp @@ -1,386 +1,385 @@ #include "flm_hq_report_edit.h" + #include "flm_hq_report_model.h" #include "ui_flm_hq_report_edit.h" -#include -#include - #include #include +#include +#include +#include #include - #include #include - #include #include -#include - namespace FileManagement { -HQReportEdit::HQReportEdit(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel) - , m_ui(new Ui::HQReportEdit) - , m_menuGroup(menuGroup) +HQReportEdit::HQReportEdit(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::OkApplyCancel), m_ui(new Ui::HQReportEdit), + m_menuGroup(menuGroup) { - m_ui->setupUi(this); + m_ui->setupUi(this); - m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("New Plan")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &HQReportEdit::onCreateNewPlanClicked); + m_buttonBox->getButton(LtsWidgets::DialogButton::Add)->setText(tr("New Plan")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Add, this, &HQReportEdit::onCreateNewPlanClicked); - connect(m_ui->pbShift, &QPushButton::clicked, this, &HQReportEdit::onShiftClicked); - setOnlineHelpFilename(QStringLiteral("Situation-HQReport")); + connect(m_ui->pbShift, &QPushButton::clicked, this, &HQReportEdit::onShiftClicked); + setOnlineHelpFilename(QStringLiteral("Situation-HQReport")); } -HQReportEdit::~HQReportEdit() { delete m_ui; } - -bool HQReportEdit::init(LtsSession::LtsSession *session, int partyId) +HQReportEdit::~HQReportEdit() { - if (session == nullptr) - { - ERROR_LOG(m_logger) << "Got invalid session"; + delete m_ui; +} - return false; - } - - m_session = session; - - std::shared_ptr partyCboInterface; - - if (!m_session->getForeignGuiInterface(partyCboInterface)) - { - ERROR_LOG(m_logger) << "Could not get Party Combobox Interface."; - - return false; - } - - if (!partyCboInterface->fillPartyComboBox(m_ui->cboParties) || m_ui->cboParties->count() == 0) - { - ERROR_LOG(m_logger) << "Could not fill Parties."; - - return false; - } - - if (!m_session->getDtc(m_flmDtc)) - { - ERROR_LOG(m_logger) << "Could not get FLM Dtc."; - - return false; - } - - if (!m_session->getFtc(m_flmFtc)) - { - ERROR_LOG(m_logger) << "Could not get FLM Ftc."; - - return false; - } - - if (!m_flmFtc->enableFileContentModify()) - { - ERROR_LOG(m_logger) << "Could enable fileContentModify."; - - return false; - } - - - qDeleteAll(m_hqModels); - m_hqModels.clear(); - - qDeleteAll(m_planModels); - m_planModels.clear(); - - for (int index = 0; index < m_ui->cboParties->count(); ++index) - { - const int partyId = m_ui->cboParties->itemData(index).toInt(); - const int partyFolderId = m_flmDtc->getPartyFolderId(m_session->exerciseId(), partyId); - - FlmHQReportModel *planModel = new FlmHQReportModel(m_ui->listViewPlan); - - if (!planModel->init(m_session, partyFolderId, FileType::inner_enum::TacticalPlan)) +bool HQReportEdit::init(LtsSession::LtsSession* session, int partyId) +{ + if (session == nullptr) { - WARNING_LOG(m_logger) << "Could not init planModel for partyId " << partyId; + ERROR_LOG(m_logger) << "Got invalid session"; - delete planModel; - planModel = nullptr; + return false; + } - continue; + m_session = session; + + std::shared_ptr partyCboInterface; + + if (!m_session->getForeignGuiInterface(partyCboInterface)) + { + ERROR_LOG(m_logger) << "Could not get Party Combobox Interface."; + + return false; + } + + if (!partyCboInterface->fillPartyComboBox(m_ui->cboParties) || m_ui->cboParties->count() == 0) + { + ERROR_LOG(m_logger) << "Could not fill Parties."; + + return false; + } + + if (!m_session->getDtc(m_flmDtc)) + { + ERROR_LOG(m_logger) << "Could not get FLM Dtc."; + + return false; + } + + if (!m_session->getFtc(m_flmFtc)) + { + ERROR_LOG(m_logger) << "Could not get FLM Ftc."; + + return false; + } + + if (!m_flmFtc->enableFileContentModify()) + { + ERROR_LOG(m_logger) << "Could enable fileContentModify."; + + return false; + } + + qDeleteAll(m_hqModels); + m_hqModels.clear(); + + qDeleteAll(m_planModels); + m_planModels.clear(); + + for (int index = 0; index < m_ui->cboParties->count(); ++index) + { + const int partyId = m_ui->cboParties->itemData(index).toInt(); + const int partyFolderId = m_flmDtc->getPartyFolderId(m_session->exerciseId(), partyId); + + FlmHQReportModel* planModel = new FlmHQReportModel(m_ui->listViewPlan); + + if (!planModel->init(m_session, partyFolderId, FileType::inner_enum::TacticalPlan)) + { + WARNING_LOG(m_logger) << "Could not init planModel for partyId " << partyId; + + delete planModel; + planModel = nullptr; + + continue; + } + + const int hqReportFolderId = m_flmDtc->findFolder(partyFolderId, QStringLiteral("Messages")); + + FlmHQReportModel* hqReportModel = new FlmHQReportModel(m_ui->listViewMessage); + + if (!hqReportModel->init(m_session, hqReportFolderId, FileType::inner_enum::AdlerJson)) + { + WARNING_LOG(m_logger) << "Could not init hqReportModel for partyId " << partyId; + + delete planModel; + planModel = nullptr; + + delete hqReportModel; + hqReportModel = nullptr; + + continue; + } + + connect(planModel, &FlmHQReportModel::dataAddedOrRemoved, this, &HQReportEdit::slotChangesMade); + + m_planModels.insert(partyId, planModel); + m_hqModels.insert(partyId, hqReportModel); + } + + m_ui->listViewPlan->setDragDropMode(QAbstractItemView::DropOnly); + m_ui->listViewPlan->setDefaultDropAction(Qt::CopyAction); + m_ui->listViewPlan->setDropIndicatorShown(true); + + m_ui->listViewMessage->setDragDropMode(QAbstractItemView::DragOnly); + m_ui->listViewMessage->setDefaultDropAction(Qt::CopyAction); + m_ui->listViewMessage->setDropIndicatorShown(true); + + onPartyChanged(); + + if (!m_flmFtc->enableFileContentModify()) + { + ERROR_LOG(m_logger) << "Could enable fileContentModify."; + + return false; + } + + qDeleteAll(m_hqModels); + m_hqModels.clear(); + + qDeleteAll(m_planModels); + m_planModels.clear(); + + for (int index = 0; index < m_ui->cboParties->count(); ++index) + { + const int partyId = m_ui->cboParties->itemData(index).toInt(); + createModels(partyId); + } + + m_ui->listViewPlan->setDragDropMode(QAbstractItemView::DropOnly); + m_ui->listViewPlan->setDefaultDropAction(Qt::MoveAction); + m_ui->listViewPlan->setDropIndicatorShown(true); + + m_ui->listViewMessage->setDragDropMode(QAbstractItemView::DragOnly); + m_ui->listViewMessage->setDefaultDropAction(Qt::MoveAction); + m_ui->listViewMessage->setDropIndicatorShown(true); + + onPartyChanged(); + + connect(m_ui->cboParties, qOverload(&QComboBox::currentIndexChanged), this, &HQReportEdit::onPartyChanged); + + int partyIndex = m_ui->cboParties->findData(partyId); + m_ui->cboParties->setCurrentIndex(partyIndex < 0 ? 0 : partyIndex); + + return true; +} + +void HQReportEdit::createModels(const int partyId) +{ + const int partyFolderId = m_flmDtc->getPartyFolderId(m_session->exerciseId(), partyId); + if (partyFolderId == 0) + { + WARNING_LOG(m_logger) << "No partyFolderId found for partyId " << partyId; + return; } const int hqReportFolderId = m_flmDtc->findFolder(partyFolderId, QStringLiteral("Messages")); - FlmHQReportModel *hqReportModel = new FlmHQReportModel(m_ui->listViewMessage); + auto* planModel = new FlmHQReportModel(m_ui->listViewPlan); + if (!planModel->init(m_session, partyFolderId, FileType::inner_enum::TacticalPlan)) + { + WARNING_LOG(m_logger) << "Could not init planModel for partyId " << partyId; + delete planModel; + return; + } + auto* hqReportModel = new FlmHQReportModel(m_ui->listViewMessage); if (!hqReportModel->init(m_session, hqReportFolderId, FileType::inner_enum::AdlerJson)) { - WARNING_LOG(m_logger) << "Could not init hqReportModel for partyId " << partyId; - - delete planModel; - planModel = nullptr; - - delete hqReportModel; - hqReportModel = nullptr; - - continue; + WARNING_LOG(m_logger) << "Could not init hqReportModel for partyId " << partyId; + delete planModel; + delete hqReportModel; + return; } connect(planModel, &FlmHQReportModel::dataAddedOrRemoved, this, &HQReportEdit::slotChangesMade); m_planModels.insert(partyId, planModel); m_hqModels.insert(partyId, hqReportModel); - } - - - m_ui->listViewPlan->setDragDropMode(QAbstractItemView::DropOnly); - m_ui->listViewPlan->setDefaultDropAction(Qt::CopyAction); - m_ui->listViewPlan->setDropIndicatorShown(true); - - - m_ui->listViewMessage->setDragDropMode(QAbstractItemView::DragOnly); - m_ui->listViewMessage->setDefaultDropAction(Qt::CopyAction); - m_ui->listViewMessage->setDropIndicatorShown(true); - - onPartyChanged(); - - if (!m_flmFtc->enableFileContentModify()) - { - ERROR_LOG(m_logger) << "Could enable fileContentModify."; - - return false; - } - - - qDeleteAll(m_hqModels); - m_hqModels.clear(); - - qDeleteAll(m_planModels); - m_planModels.clear(); - - for (int index = 0; index < m_ui->cboParties->count(); ++index) - { - const int partyId = m_ui->cboParties->itemData(index).toInt(); - createModels(partyId); - } - - - m_ui->listViewPlan->setDragDropMode(QAbstractItemView::DropOnly); - m_ui->listViewPlan->setDefaultDropAction(Qt::MoveAction); - m_ui->listViewPlan->setDropIndicatorShown(true); - - - m_ui->listViewMessage->setDragDropMode(QAbstractItemView::DragOnly); - m_ui->listViewMessage->setDefaultDropAction(Qt::MoveAction); - m_ui->listViewMessage->setDropIndicatorShown(true); - - onPartyChanged(); - - connect(m_ui->cboParties, qOverload(&QComboBox::currentIndexChanged), this, &HQReportEdit::onPartyChanged); - - int partyIndex = m_ui->cboParties->findData(partyId); - m_ui->cboParties->setCurrentIndex(partyIndex < 0 ? 0 : partyIndex); - - return true; -} - -void HQReportEdit::createModels(const int partyId) -{ - const int partyFolderId = m_flmDtc->getPartyFolderId(m_session->exerciseId(), partyId); - if (partyFolderId == 0) - { - WARNING_LOG(m_logger) << "No partyFolderId found for partyId " << partyId; - return; - } - - const int hqReportFolderId = m_flmDtc->findFolder(partyFolderId, QStringLiteral("Messages")); - - auto *planModel = new FlmHQReportModel(m_ui->listViewPlan); - if (!planModel->init(m_session, partyFolderId, FileType::inner_enum::TacticalPlan)) - { - WARNING_LOG(m_logger) << "Could not init planModel for partyId " << partyId; - delete planModel; - return; - } - - auto *hqReportModel = new FlmHQReportModel(m_ui->listViewMessage); - if (!hqReportModel->init(m_session, hqReportFolderId, FileType::inner_enum::AdlerJson)) - { - WARNING_LOG(m_logger) << "Could not init hqReportModel for partyId " << partyId; - delete planModel; - delete hqReportModel; - return; - } - - connect(planModel, &FlmHQReportModel::dataAddedOrRemoved, this, &HQReportEdit::slotChangesMade); - - m_planModels.insert(partyId, planModel); - m_hqModels.insert(partyId, hqReportModel); } bool HQReportEdit::apply() { - QMap> allHqToPlanIds; + QMap> allHqToPlanIds; - for (auto it = m_planModels.begin(); it != m_planModels.end(); ++it) - { - QMap> hqToPlanIds = it.value()->getHQToPlan(); - - for (auto planId : hqToPlanIds.keys()) + for (auto it = m_planModels.begin(); it != m_planModels.end(); ++it) { - allHqToPlanIds[planId].append(hqToPlanIds[planId]); + QMap> hqToPlanIds = it.value()->getHQToPlan(); - it.value()->clearMovedData(); + for (auto planId : hqToPlanIds.keys()) + { + allHqToPlanIds[planId].append(hqToPlanIds[planId]); + + it.value()->clearMovedData(); + } } - } - const int currentPartyId = m_ui->cboParties->currentData().toInt(); - FlmHqReportConverter *hqRepConv = new FlmHqReportConverter(); + const int currentPartyId = m_ui->cboParties->currentData().toInt(); + FlmHqReportConverter* hqRepConv = new FlmHqReportConverter(); - if (hqRepConv->init(m_session, currentPartyId)) - { - DEBUG_LOG(m_logger) << "Add HQ to Converter"; + if (hqRepConv->init(m_session, currentPartyId)) + { + DEBUG_LOG(m_logger) << "Add HQ to Converter"; - hqRepConv->addHqToPlanIds(allHqToPlanIds); + hqRepConv->addHqToPlanIds(allHqToPlanIds); - hqRepConv->processCollectedHqs(); - } + hqRepConv->processCollectedHqs(); + } - return true; + return true; } -void HQReportEdit::retranslate() { translate(m_ui, tr("HQ Report")); } +void HQReportEdit::retranslate() +{ + translate(m_ui, tr("HQ Report")); +} void HQReportEdit::onPartyChanged(int index) { - Q_UNUSED(index); + Q_UNUSED(index); - const int currentPartyId = m_ui->cboParties->currentData().toInt(); + const int currentPartyId = m_ui->cboParties->currentData().toInt(); - if (!m_planModels.contains(currentPartyId) || !m_hqModels.contains(currentPartyId)) - { - INFO_LOG(m_logger) << "Models for party" << currentPartyId << "not found. Attempting to create..."; - createModels(currentPartyId); - } + if (!m_planModels.contains(currentPartyId) || !m_hqModels.contains(currentPartyId)) + { + INFO_LOG(m_logger) << "Models for party" << currentPartyId << "not found. Attempting to create..."; + createModels(currentPartyId); + } - QAbstractItemModel *hqModel = m_hqModels.value(currentPartyId, nullptr); - QAbstractItemModel *planModel = m_planModels.value(currentPartyId, nullptr); + QAbstractItemModel* hqModel = m_hqModels.value(currentPartyId, nullptr); + QAbstractItemModel* planModel = m_planModels.value(currentPartyId, nullptr); - if (m_ui->listViewMessage->selectionModel()) - { - m_ui->listViewMessage->selectionModel()->disconnect(this); - } - if (m_ui->listViewPlan->selectionModel()) - { - m_ui->listViewPlan->selectionModel()->disconnect(this); - } + if (m_ui->listViewMessage->selectionModel()) + { + m_ui->listViewMessage->selectionModel()->disconnect(this); + } + if (m_ui->listViewPlan->selectionModel()) + { + m_ui->listViewPlan->selectionModel()->disconnect(this); + } - m_ui->listViewMessage->setModel(hqModel); - m_ui->listViewPlan->setModel(planModel); + m_ui->listViewMessage->setModel(hqModel); + m_ui->listViewPlan->setModel(planModel); - if (hqModel && planModel) - { - connect(m_ui->listViewMessage->selectionModel(), &QItemSelectionModel::selectionChanged, this, &HQReportEdit::onSelectionChanged); - connect(m_ui->listViewPlan->selectionModel(), &QItemSelectionModel::selectionChanged, this, &HQReportEdit::onSelectionChanged); - } - else - { - ERROR_LOG(m_logger) << "Failed to switch to party" << currentPartyId << ": Models still missing."; - } + if (hqModel && planModel) + { + connect(m_ui->listViewMessage->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &HQReportEdit::onSelectionChanged); + connect(m_ui->listViewPlan->selectionModel(), &QItemSelectionModel::selectionChanged, this, + &HQReportEdit::onSelectionChanged); + } + else + { + ERROR_LOG(m_logger) << "Failed to switch to party" << currentPartyId << ": Models still missing."; + } } + void HQReportEdit::onCreateNewPlanClicked() { - bool ok = false; - QString planName = QInputDialog::getText(this, tr("Enter Plan name"), tr("Name:"), QLineEdit::Normal, QString(), &ok); + bool ok = false; + QString planName = + QInputDialog::getText(this, tr("Enter Plan name"), tr("Name:"), QLineEdit::Normal, QString(), &ok); - if (!ok) - { - DEBUG_LOG(m_logger) << "No name for new plan entered."; + if (!ok) + { + DEBUG_LOG(m_logger) << "No name for new plan entered."; - return; - } + return; + } - FlmHQReportModel *planModel = static_cast(m_ui->listViewPlan->model()); + FlmHQReportModel* planModel = static_cast(m_ui->listViewPlan->model()); - if (planModel == nullptr) - { - ERROR_LOG(m_logger) << "Could not create plan --> no plan model present."; + if (planModel == nullptr) + { + ERROR_LOG(m_logger) << "Could not create plan --> no plan model present."; - return; - } + return; + } - SituationMap::GeometryModel *geometryModel = SituationMap::GeometryModelFactory::singleton()->create(); + SituationMap::GeometryModel* geometryModel = SituationMap::GeometryModelFactory::singleton()->create(); - if (geometryModel == nullptr) - { - ERROR_LOG(m_logger) << "Could not create plan --> not possible to create GeometryModel."; + if (geometryModel == nullptr) + { + ERROR_LOG(m_logger) << "Could not create plan --> not possible to create GeometryModel."; - return; - } + return; + } - if (m_session == nullptr) - { - ERROR_LOG(m_logger) << "Could not create plan --> not possible to create GeometryModel."; + if (m_session == nullptr) + { + ERROR_LOG(m_logger) << "Could not create plan --> not possible to create GeometryModel."; - return; - } + return; + } - FileManagement::FileContentModifyRequest data; + FileManagement::FileContentModifyRequest data; - data.name(planName.toStdString()); - data.isTemplate(false); - data.isHidden(false); - data.folderId(planModel->folderId()); - data.fileStatus(FileManagement::FileStatus::Valid); - data.fileCategory(FileManagement::FileCategory::Exercise); - data.fileType(FileManagement::FileType::TacticalPlan); - data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - data.lastModified(QDateTime::currentMSecsSinceEpoch()); - data.content(LtsUtils::convert>(geometryModel->toByteArray())); - data.exerciseId(m_session->exerciseId()); + data.name(planName.toStdString()); + data.isTemplate(false); + data.isHidden(false); + data.folderId(planModel->folderId()); + data.fileStatus(FileManagement::FileStatus::Valid); + data.fileCategory(FileManagement::FileCategory::Exercise); + data.fileType(FileManagement::FileType::TacticalPlan); + data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + data.lastModified(QDateTime::currentMSecsSinceEpoch()); + data.content(LtsUtils::convert>(geometryModel->toByteArray())); + data.exerciseId(m_session->exerciseId()); - m_flmFtc->fileContentModifyRequest(data, - [this](const Core::FunctionReplyObject &reply) - { - if (reply.error()) - { - const QString errorMessage = tr("Could not save plan: %1").arg(QString::fromStdString(reply.str())); + m_flmFtc->fileContentModifyRequest(data, [this](const Core::FunctionReplyObject& reply) { + if (reply.error()) + { + const QString errorMessage = tr("Could not save plan: %1").arg(QString::fromStdString(reply.str())); - ERROR_LOG(m_logger) << errorMessage; + ERROR_LOG(m_logger) << errorMessage; - new LtsWidgets::LtsMessageDialogNew(this, errorMessage, tr("Save failed")); - } - }); + new LtsWidgets::LtsMessageDialogNew(this, errorMessage, tr("Save failed")); + } + }); } -void HQReportEdit::onSelectionChanged(const QItemSelection &, const QItemSelection &) +void HQReportEdit::onSelectionChanged(const QItemSelection&, const QItemSelection&) { - m_ui->pbShift->setEnabled(m_ui->listViewMessage->selectionModel()->hasSelection() && m_ui->listViewPlan->selectionModel()->hasSelection()); + m_ui->pbShift->setEnabled(m_ui->listViewMessage->selectionModel()->hasSelection() && + m_ui->listViewPlan->selectionModel()->hasSelection()); } void HQReportEdit::onShiftClicked() { - const int currentPartyId = m_ui->cboParties->currentData().toInt(); + const int currentPartyId = m_ui->cboParties->currentData().toInt(); - FlmHQReportModel *messageModel = m_hqModels.value(currentPartyId); - FlmHQReportModel *planModel = m_planModels.value(currentPartyId); + FlmHQReportModel* messageModel = m_hqModels.value(currentPartyId); + FlmHQReportModel* planModel = m_planModels.value(currentPartyId); - if (messageModel == nullptr || planModel == nullptr) - return; + if (messageModel == nullptr || planModel == nullptr) + return; - const QModelIndex currentMessageIndex = m_ui->listViewMessage->currentIndex(); + const QModelIndex currentMessageIndex = m_ui->listViewMessage->currentIndex(); - if (!currentMessageIndex.isValid()) - return; + if (!currentMessageIndex.isValid()) + return; - QMimeData *mimeData = messageModel->mimeData({currentMessageIndex}); + QMimeData* mimeData = messageModel->mimeData({currentMessageIndex}); - if (mimeData == nullptr) - return; + if (mimeData == nullptr) + return; - if (!planModel->dropMimeData(mimeData, Qt::CopyAction, -1, 0, m_ui->listViewPlan->currentIndex())) - return; + if (!planModel->dropMimeData(mimeData, Qt::CopyAction, -1, 0, m_ui->listViewPlan->currentIndex())) + return; - m_ui->listViewPlan->viewport()->update(); + m_ui->listViewPlan->viewport()->update(); } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.h old mode 100755 new mode 100644 index bc521ef32..86f0f6f81 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_edit.h @@ -1,9 +1,9 @@ - #pragma once #include "flm_hq_report_converter.h" + #include #include @@ -25,37 +25,36 @@ namespace Interface { class Dtc; class Ftc; -} +} // namespace Interface class FlmHQReportModel; class HQReportEdit : public LtsWidgets::LtsDialog { - Q_OBJECT + Q_OBJECT public: - explicit HQReportEdit(const QString &menuGroup, QWidget *parent = nullptr); - ~HQReportEdit(); - bool init(LtsSession::LtsSession *session, int partyId = -1); - void createModels(const int partyId); + explicit HQReportEdit(const QString& menuGroup, QWidget* parent = nullptr); + ~HQReportEdit(); + bool init(LtsSession::LtsSession* session, int partyId = -1); + void createModels(const int partyId); - bool apply() override; - void retranslate() override; + bool apply() override; + void retranslate() override; private Q_SLOTS: - void onPartyChanged(int index = 0); - void onCreateNewPlanClicked(); - void onSelectionChanged(const QItemSelection &, const QItemSelection &); - void onShiftClicked(); + void onPartyChanged(int index = 0); + void onCreateNewPlanClicked(); + void onSelectionChanged(const QItemSelection&, const QItemSelection&); + void onShiftClicked(); private: - - NGL::INGLLogger &m_logger; - Ui::HQReportEdit *m_ui; - QString m_menuGroup; - LtsSession::LtsSession *m_session{nullptr}; - QHash m_hqModels; - QHash m_planModels; - std::shared_ptr m_flmDtc; - std::shared_ptr m_flmFtc; + NGL::INGLLogger& m_logger; + Ui::HQReportEdit* m_ui; + QString m_menuGroup; + LtsSession::LtsSession* m_session{nullptr}; + QHash m_hqModels; + QHash m_planModels; + std::shared_ptr m_flmDtc; + std::shared_ptr m_flmFtc; }; -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.cpp old mode 100755 new mode 100644 index dcca1abf8..696ab3539 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.cpp @@ -4,82 +4,80 @@ namespace FileManagement { FlmHqReportJsonParser::FlmHqReportJsonParser() : m_logger(getLogger("HQReportParser")) {} -HqReportData FlmHqReportJsonParser::parse(const QByteArray &data) +HqReportData FlmHqReportJsonParser::parse(const QByteArray& data) { - DEBUG_LOG(m_logger) << "START PARSING"; - QJsonDocument doc = QJsonDocument::fromJson(data); - QJsonObject obj = doc.object(); - HqReportData report; + DEBUG_LOG(m_logger) << "START PARSING"; + QJsonDocument doc = QJsonDocument::fromJson(data); + QJsonObject obj = doc.object(); + HqReportData report; - report.art = obj[QStringLiteral("art")].toString(); - report.name = obj[QStringLiteral("name")].toString(); + report.art = obj[QStringLiteral("art")].toString(); + report.name = obj[QStringLiteral("name")].toString(); - if ( obj.contains(QStringLiteral("meldungsnummer"))) - report.number = obj[QStringLiteral("meldungsnummer")].toInt(); + if (obj.contains(QStringLiteral("meldungsnummer"))) + report.number = obj[QStringLiteral("meldungsnummer")].toInt(); - if ((obj.contains(QStringLiteral("bis"))) && - (obj.contains((QStringLiteral("ab"))))) - { - report.bis = parseHqReportTime(obj[QStringLiteral("bis")].toObject()); - report.ab = parseHqReportTime(obj[QStringLiteral("ab")].toObject()); - } - - if ((obj.contains(QStringLiteral("koordinaten"))) && - (obj[QStringLiteral("koordinaten")].isArray())) - { - QJsonArray coordsArray = obj[QStringLiteral("koordinaten")].toArray(); - - for (const QJsonValue &value : coordsArray) + if ((obj.contains(QStringLiteral("bis"))) && (obj.contains((QStringLiteral("ab"))))) { - QPointF coord; - - QJsonObject coordsObj = value.toObject(); - - coord.setX(coordsObj[QStringLiteral("longitude")].toDouble() * LtsCoordTrans::deg2rad()); - coord.setY(coordsObj[QStringLiteral("latitude")].toDouble() * LtsCoordTrans::deg2rad()); - - report.koordinaten.push_back(coord); + report.bis = parseHqReportTime(obj[QStringLiteral("bis")].toObject()); + report.ab = parseHqReportTime(obj[QStringLiteral("ab")].toObject()); } - } - if ((obj.contains(QStringLiteral("mittelpunkt"))) && - (obj[QStringLiteral("mittelpunkt")].isObject())) - { - QPointF center; + if ((obj.contains(QStringLiteral("koordinaten"))) && (obj[QStringLiteral("koordinaten")].isArray())) + { + QJsonArray coordsArray = obj[QStringLiteral("koordinaten")].toArray(); - QJsonObject coordsObj = obj[QStringLiteral("mittelpunkt")].toObject(); + for (const QJsonValue& value : coordsArray) + { + QPointF coord; - center.setX(coordsObj[QStringLiteral("longitude")].toDouble() * LtsCoordTrans::deg2rad()); - center.setY(coordsObj[QStringLiteral("latitude")].toDouble() * LtsCoordTrans::deg2rad()); + QJsonObject coordsObj = value.toObject(); - report.mittelpunkt = center; - } + coord.setX(coordsObj[QStringLiteral("longitude")].toDouble() * LtsCoordTrans::deg2rad()); + coord.setY(coordsObj[QStringLiteral("latitude")].toDouble() * LtsCoordTrans::deg2rad()); - if (obj.contains(QStringLiteral("radius"))) report.radius = obj[QStringLiteral("radius")].toInt(); + report.koordinaten.push_back(coord); + } + } - if (obj.contains(QStringLiteral("linkerNachbar"))) - report.linkerNachbar = obj[QStringLiteral("linkerNachbar")].toString(); + if ((obj.contains(QStringLiteral("mittelpunkt"))) && (obj[QStringLiteral("mittelpunkt")].isObject())) + { + QPointF center; - if (obj.contains(QStringLiteral("rechterNachbar"))) - report.rechterNachbar = obj[QStringLiteral("rechterNachbar")].toString(); + QJsonObject coordsObj = obj[QStringLiteral("mittelpunkt")].toObject(); - return report; + center.setX(coordsObj[QStringLiteral("longitude")].toDouble() * LtsCoordTrans::deg2rad()); + center.setY(coordsObj[QStringLiteral("latitude")].toDouble() * LtsCoordTrans::deg2rad()); + + report.mittelpunkt = center; + } + + if (obj.contains(QStringLiteral("radius"))) + report.radius = obj[QStringLiteral("radius")].toInt(); + + if (obj.contains(QStringLiteral("linkerNachbar"))) + report.linkerNachbar = obj[QStringLiteral("linkerNachbar")].toString(); + + if (obj.contains(QStringLiteral("rechterNachbar"))) + report.rechterNachbar = obj[QStringLiteral("rechterNachbar")].toString(); + + return report; } -QString FlmHqReportJsonParser::parseHqReportTime(const QJsonObject &obj) +QString FlmHqReportJsonParser::parseHqReportTime(const QJsonObject& obj) { - const int year = obj[QStringLiteral("jahr")].toInt(); - const int minutes = obj[QStringLiteral("minuten")].toInt(); - const int month = obj[QStringLiteral("monat")].toInt(); - const int seconds = obj[QStringLiteral("sekunden")].toInt(); - const int day = obj[QStringLiteral("tag")].toInt(); - const int hour = obj[QStringLiteral("stunden")].toInt(); + const int year = obj[QStringLiteral("jahr")].toInt(); + const int minutes = obj[QStringLiteral("minuten")].toInt(); + const int month = obj[QStringLiteral("monat")].toInt(); + const int seconds = obj[QStringLiteral("sekunden")].toInt(); + const int day = obj[QStringLiteral("tag")].toInt(); + const int hour = obj[QStringLiteral("stunden")].toInt(); - const QDate date(year, month, day); - const QTime time(hour, minutes, seconds); - const QDateTime dt(date, time); + const QDate date(year, month, day); + const QTime time(hour, minutes, seconds); + const QDateTime dt(date, time); - return dt.toString(QStringLiteral("dd.MM.yyyy HH:mm:ss")); + return dt.toString(QStringLiteral("dd.MM.yyyy HH:mm:ss")); } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.h old mode 100755 new mode 100644 index 30b0b974c..004c69550 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_json_parser.h @@ -5,7 +5,6 @@ #include #include #include - #include #include #include @@ -22,39 +21,38 @@ using namespace SituationMap; struct HqCoordinates { - double latitude; - double longitude; + double latitude; + double longitude; }; + struct HqReportData { - int contentFileId; - QColor partyColor; - int maxGipfel{-1}; - int radius{-1}; - QString ab; - QString art; - QString bis; - QString name; - int number; - QString truppenteil; - QString linkerNachbar; - QString rechterNachbar; - QVector koordinaten; - QPointF mittelpunkt; + int contentFileId; + QColor partyColor; + int maxGipfel{-1}; + int radius{-1}; + QString ab; + QString art; + QString bis; + QString name; + int number; + QString truppenteil; + QString linkerNachbar; + QString rechterNachbar; + QVector koordinaten; + QPointF mittelpunkt; }; class FlmHqReportJsonParser { -public: - FlmHqReportJsonParser(); - + public: + FlmHqReportJsonParser(); - HqReportData parse(const QByteArray &data); - + HqReportData parse(const QByteArray& data); - QString parseHqReportTime(const QJsonObject &obj); + QString parseHqReportTime(const QJsonObject& obj); -private: - NGL::INGLLogger &m_logger; -}; -} + private: + NGL::INGLLogger& m_logger; +}; +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.cpp old mode 100755 new mode 100644 index 7efe456f9..8061d1c8a --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.cpp @@ -5,288 +5,295 @@ namespace FileManagement { -FlmHQReportModel::FlmHQReportModel(QObject *parent) : QAbstractListModel(parent), - m_logger(NGL::NGLLoggerBootstrap::getLogger()) { +FlmHQReportModel::FlmHQReportModel(QObject* parent) + : QAbstractListModel(parent), m_logger(NGL::NGLLoggerBootstrap::getLogger()) +{ } -bool FlmHQReportModel::init(LtsSession::LtsSession *session, int contentFolderId, const FileType &fileType) +bool FlmHQReportModel::init(LtsSession::LtsSession* session, int contentFolderId, const FileType& fileType) { - if (!session) - { - ERROR_LOG(m_logger) << "Got invalid Session"; + if (!session) + { + ERROR_LOG(m_logger) << "Got invalid Session"; - return false; - } + return false; + } - if (!session->getDtc(m_flmDtc)) - { - ERROR_LOG(m_logger) << "Could not get FLM Dtc"; + if (!session->getDtc(m_flmDtc)) + { + ERROR_LOG(m_logger) << "Could not get FLM Dtc"; - return false; - } + return false; + } - m_contentFolderId = contentFolderId; - m_fileType = fileType; + m_contentFolderId = contentFolderId; + m_fileType = fileType; - m_flmDtc->enableFileContent(); - m_flmDtc->waitForHistoricalDataFileContent(3000); - m_flmDtc->fileContents([this](const FileContent &content){onFileContentChanged(content, DataModification::eAdded);}); + m_flmDtc->enableFileContent(); + m_flmDtc->waitForHistoricalDataFileContent(3000); + m_flmDtc->fileContents( + [this](const FileContent& content) { onFileContentChanged(content, DataModification::eAdded); }); - connect(m_flmDtc.get(), &Interface::Dtc::fileContentChanged, this, &FlmHQReportModel::onFileContentChanged); + connect(m_flmDtc.get(), &Interface::Dtc::fileContentChanged, this, &FlmHQReportModel::onFileContentChanged); - return true; + return true; } -int FlmHQReportModel::rowCount(const QModelIndex &parent) const +int FlmHQReportModel::rowCount(const QModelIndex& parent) const { - if (parent.isValid()) - return 0; - return m_data.count(); + if (parent.isValid()) + return 0; + return m_data.count(); } -QVariant FlmHQReportModel::data(const QModelIndex &index, int role) const +QVariant FlmHQReportModel::data(const QModelIndex& index, int role) const { - if (!index.isValid()) + if (!index.isValid()) + return QVariant(); + + if (role == Qt::DisplayRole) + return createText(index.row()); + return QVariant(); - - if (role == Qt::DisplayRole) - return createText(index.row()); - - return QVariant(); } -Qt::ItemFlags FlmHQReportModel::flags(const QModelIndex &index) const +Qt::ItemFlags FlmHQReportModel::flags(const QModelIndex& index) const { - Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index); + Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index); - if (!index.isValid()) - return defaultFlags; + if (!index.isValid()) + return defaultFlags; - return defaultFlags | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; + return defaultFlags | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; } Qt::DropActions FlmHQReportModel::supportedDropActions() const { - return Qt::CopyAction; + return Qt::CopyAction; } Qt::DropActions FlmHQReportModel::supportedDragActions() const { - return Qt::CopyAction; + return Qt::CopyAction; } QStringList FlmHQReportModel::mimeTypes() const { - QStringList types; - types << mimeType; - return types; + QStringList types; + types << mimeType; + return types; } -bool FlmHQReportModel::removeRows(int row, int count, const QModelIndex &parent) +bool FlmHQReportModel::removeRows(int row, int count, const QModelIndex& parent) { - if (parent.isValid() || row < 0 || row >= m_data.size() || (row + count) > m_data.size()) - return false; + if (parent.isValid() || row < 0 || row >= m_data.size() || (row + count) > m_data.size()) + return false; - beginRemoveRows(QModelIndex(), row, row + count - 1); + beginRemoveRows(QModelIndex(), row, row + count - 1); - for (int i = 0; i < count; ++i) - m_data.removeAt(row); + for (int i = 0; i < count; ++i) + m_data.removeAt(row); - endRemoveRows(); + endRemoveRows(); - return true; -} - -QMimeData *FlmHQReportModel::mimeData(const QList &indexes) const -{ - QMimeData *mimeData = new QMimeData(); - QByteArray encodedData; - QDataStream stream(&encodedData, QIODevice::WriteOnly); - - for (const QModelIndex &index : indexes) - { - if (index.isValid()) - { - HQData md = m_data.at(index.row()); - stream << md.id << md.name; - } - } - mimeData->setData(mimeType, encodedData); - return mimeData; -} - -bool FlmHQReportModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) -{ - Q_UNUSED(row) - Q_UNUSED(column) - - if (!parent.isValid() || !data->hasFormat(mimeType) || action != Qt::CopyAction) - return false; - - QByteArray encodedData = data->data(mimeType); - QDataStream stream(&encodedData, QIODevice::ReadOnly); - - while (!stream.atEnd()) - { - HQData md; - - stream >> md.id >> md.name; - - addMovedData(parent.row(), md); - } - - emit dataAddedOrRemoved(); - - return true; -} - -bool FlmHQReportModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const -{ - Q_UNUSED(row) - Q_UNUSED(column) - - if (!parent.isValid() || - !data->hasFormat(mimeType) || - action != Qt::CopyAction || - parent.row() < 0 || - parent.row() >= m_data.size()) - return false; - - QByteArray encodedData = data->data(mimeType); - QDataStream stream(&encodedData, QIODevice::ReadOnly); - const HQData ¤tData = m_data.at(parent.row()); - - if (!m_movedData.contains(currentData.id)) return true; - - const QList &movedDataListForCurrentData = m_movedData.value(currentData.id); - - while (!stream.atEnd()) - { - HQData movedData; - - stream >> movedData.id >> movedData.name; - - if (movedDataListForCurrentData.contains(movedData)) - return false; - } - - return true; } -void FlmHQReportModel::addHQReportData(const HQData &data) +QMimeData* FlmHQReportModel::mimeData(const QList& indexes) const { - beginInsertRows(QModelIndex(), rowCount(), rowCount()); - m_data.append(data); - endInsertRows(); + QMimeData* mimeData = new QMimeData(); + QByteArray encodedData; + QDataStream stream(&encodedData, QIODevice::WriteOnly); + + for (const QModelIndex& index : indexes) + { + if (index.isValid()) + { + HQData md = m_data.at(index.row()); + stream << md.id << md.name; + } + } + mimeData->setData(mimeType, encodedData); + return mimeData; } -void FlmHQReportModel::deleteHQReportData(const HQData &data) +bool FlmHQReportModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) { - beginInsertRows(QModelIndex(), rowCount(), rowCount()); - endInsertRows(); + Q_UNUSED(row) + Q_UNUSED(column) - const int zeile = m_data.indexOf(data); + if (!parent.isValid() || !data->hasFormat(mimeType) || action != Qt::CopyAction) + return false; - if (zeile == -1) { + QByteArray encodedData = data->data(mimeType); + QDataStream stream(&encodedData, QIODevice::ReadOnly); + + while (!stream.atEnd()) + { + HQData md; + + stream >> md.id >> md.name; + + addMovedData(parent.row(), md); + } + + emit dataAddedOrRemoved(); + + return true; +} + +bool FlmHQReportModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const +{ + Q_UNUSED(row) + Q_UNUSED(column) + + if (!parent.isValid() || !data->hasFormat(mimeType) || action != Qt::CopyAction || parent.row() < 0 || + parent.row() >= m_data.size()) + return false; + + QByteArray encodedData = data->data(mimeType); + QDataStream stream(&encodedData, QIODevice::ReadOnly); + const HQData& currentData = m_data.at(parent.row()); + + if (!m_movedData.contains(currentData.id)) + return true; + + const QList& movedDataListForCurrentData = m_movedData.value(currentData.id); + + while (!stream.atEnd()) + { + HQData movedData; + + stream >> movedData.id >> movedData.name; + + if (movedDataListForCurrentData.contains(movedData)) + return false; + } + + return true; +} + +void FlmHQReportModel::addHQReportData(const HQData& data) +{ + beginInsertRows(QModelIndex(), rowCount(), rowCount()); + m_data.append(data); + endInsertRows(); +} + +void FlmHQReportModel::deleteHQReportData(const HQData& data) +{ + beginInsertRows(QModelIndex(), rowCount(), rowCount()); + endInsertRows(); + + const int zeile = m_data.indexOf(data); + + if (zeile == -1) + { + return; + } + + beginRemoveRows(QModelIndex(), zeile, zeile); + m_data.removeAt(zeile); + endRemoveRows(); return; - } - - beginRemoveRows(QModelIndex(), zeile, zeile); - m_data.removeAt(zeile); - endRemoveRows(); - return; } -void FlmHQReportModel::onFileContentChanged(const FileContent &content, DataModification modType) +void FlmHQReportModel::onFileContentChanged(const FileContent& content, DataModification modType) { - HQData data; - data.id = content.id(); - data.name = QString::fromStdString(content.name()); - if (content.folderId() != m_contentFolderId || content.fileType() != m_fileType) - return; + HQData data; + data.id = content.id(); + data.name = QString::fromStdString(content.name()); + if (content.folderId() != m_contentFolderId || content.fileType() != m_fileType) + return; - if (content.fileStatus() == FileStatus::Deleted) { - if (modType == DataModification::eModified || modType == DataModification::eAdded) { - deleteHQReportData(data); - } - } else if (modType == DataModification::eAdded) { - addHQReportData(data); - } + if (content.fileStatus() == FileStatus::Deleted) + { + if (modType == DataModification::eModified || modType == DataModification::eAdded) + { + deleteHQReportData(data); + } + } + else if (modType == DataModification::eAdded) + { + addHQReportData(data); + } } int FlmHQReportModel::folderId() const { - return m_contentFolderId; + return m_contentFolderId; } QMap> FlmHQReportModel::getHQToPlan() const { - QMap> hqToPlan; + QMap> hqToPlan; - for (auto it = m_movedData.constBegin(); it != m_movedData.constEnd(); ++it) - { - const QList &movedData = it.value(); - QList hqIds; + for (auto it = m_movedData.constBegin(); it != m_movedData.constEnd(); ++it) + { + const QList& movedData = it.value(); + QList hqIds; - hqIds.reserve(movedData.size()); + hqIds.reserve(movedData.size()); - for (const HQData ¤tData : movedData) - hqIds.append(currentData.id); + for (const HQData& currentData : movedData) + hqIds.append(currentData.id); - hqToPlan.insert(it.key(), hqIds); - } + hqToPlan.insert(it.key(), hqIds); + } - return hqToPlan; + return hqToPlan; } void FlmHQReportModel::clearMovedData() { - m_movedData.clear(); + m_movedData.clear(); - emit dataAddedOrRemoved(); - emit dataChanged(index(0, 0), index(rowCount() - 1, 0)); + emit dataAddedOrRemoved(); + emit dataChanged(index(0, 0), index(rowCount() - 1, 0)); } QString FlmHQReportModel::createText(int dataIndex) const { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dataIndex: " << dataIndex; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dataIndex: " << dataIndex; - if (dataIndex < 0 || dataIndex >= m_data.size()) - return QString(); + if (dataIndex < 0 || dataIndex >= m_data.size()) + return QString(); - const HQData &data = m_data.at(dataIndex); + const HQData& data = m_data.at(dataIndex); - if (!m_movedData.contains(data.id)) - { - DEBUG_LOG(m_logger) << "No moved data for " << data.name; - return data.name; - } + if (!m_movedData.contains(data.id)) + { + DEBUG_LOG(m_logger) << "No moved data for " << data.name; + return data.name; + } - const QList &movedData = m_movedData.value(data.id); - QStringList movedDataNames; + const QList& movedData = m_movedData.value(data.id); + QStringList movedDataNames; - movedDataNames.reserve(movedData.size()); + movedDataNames.reserve(movedData.size()); - for (const HQData ¤tMovedData : movedData) - movedDataNames.append(currentMovedData.name); + for (const HQData& currentMovedData : movedData) + movedDataNames.append(currentMovedData.name); - return QString(QStringLiteral("%1 (%2)")).arg(data.name).arg(movedDataNames.join(QLatin1Char(','))); + return QString(QStringLiteral("%1 (%2)")).arg(data.name).arg(movedDataNames.join(QLatin1Char(','))); } -void FlmHQReportModel::addMovedData(int dataIndex, const HQData &movedData) +void FlmHQReportModel::addMovedData(int dataIndex, const HQData& movedData) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dataIndex: " << dataIndex << ", movedData.id: " << movedData.id << ", movedData.name: " << movedData.name; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " dataIndex: " << dataIndex << ", movedData.id: " << movedData.id + << ", movedData.name: " << movedData.name; - if (dataIndex < 0 || dataIndex >= m_data.size()) - return; + if (dataIndex < 0 || dataIndex >= m_data.size()) + return; - const HQData &data = m_data.at(dataIndex); + const HQData& data = m_data.at(dataIndex); - if (!m_movedData.contains(data.id)) - m_movedData.insert(data.id, QList()); + if (!m_movedData.contains(data.id)) + m_movedData.insert(data.id, QList()); - m_movedData[data.id].append(movedData); + m_movedData[data.id].append(movedData); } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.h old mode 100755 new mode 100644 index 5923959c6..4c0af953e --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/HQReports/flm_hq_report_model.h @@ -1,28 +1,26 @@ #pragma once - -#include -#include -#include -#include -#include -#include -#include - #include #include - #include +#include +#include +#include +#include +#include +#include +#include namespace FileManagement { class FileContent; + namespace Interface { class Dtc; } -} +} // namespace FileManagement namespace LtsSession { @@ -33,65 +31,65 @@ namespace FileManagement { struct HQData { - int id; - QString name; + int id; + QString name; - bool operator==(const HQData &other) const - { - return id == other.id && - name == other.name; - } + bool operator==(const HQData& other) const + { + return id == other.id && name == other.name; + } }; class FlmHQReportModel : public QAbstractListModel { - Q_OBJECT + Q_OBJECT -public: - explicit FlmHQReportModel(QObject *parent = nullptr); + public: + explicit FlmHQReportModel(QObject* parent = nullptr); - bool init(LtsSession::LtsSession *session, int contentFolderId, const FileManagement::FileType &fileType); + bool init(LtsSession::LtsSession* session, int contentFolderId, const FileManagement::FileType& fileType); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - Qt::DropActions supportedDropActions() const override; - Qt::DropActions supportedDragActions() const override; - QStringList mimeTypes() const override; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + Qt::DropActions supportedDropActions() const override; + Qt::DropActions supportedDragActions() const override; + QStringList mimeTypes() const override; + bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override; - QMimeData *mimeData(const QList &indexes) const override; - bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override; - bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override; + QMimeData* mimeData(const QList& indexes) const override; + bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) override; + bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, + const QModelIndex& parent) const override; - void addHQReportData(const HQData &data); - void deleteHQReportData(const HQData &data); + void addHQReportData(const HQData& data); + void deleteHQReportData(const HQData& data); - int folderId() const; + int folderId() const; - QMap> getHQToPlan() const; - void clearMovedData(); + QMap> getHQToPlan() const; + void clearMovedData(); -private: + private: + NGL::INGLLogger& m_logger; + QString createText(int dataIndex) const; + void addMovedData(int dataIndex, const HQData& movedData); -NGL::INGLLogger &m_logger; - QString createText(int dataIndex) const; - void addMovedData(int dataIndex, const HQData &movedData); + private Q_SLOTS: + void onFileContentChanged(const FileContent& content, DataModification modType); -private Q_SLOTS: - void onFileContentChanged(const FileContent &content, DataModification modType); + Q_SIGNALS: + void dataAddedOrRemoved(); -Q_SIGNALS: - void dataAddedOrRemoved(); - -private: - QList m_data; - QMap> m_movedData; - const QString mimeType = QStringLiteral("application/x-custom-hqdata"); - int m_contentFolderId {-1}; - FileManagement::FileType m_fileType; - std::shared_ptr m_flmDtc; + private: + QList m_data; + QMap> m_movedData; + const QString mimeType = QStringLiteral("application/x-custom-hqdata"); + int m_contentFolderId{-1}; + FileManagement::FileType m_fileType; + std::shared_ptr m_flmDtc; }; -} +} // namespace FileManagement Q_DECLARE_METATYPE(FileManagement::HQData) diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.cpp old mode 100755 new mode 100644 index 68994e65c..568ff7532 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.cpp @@ -1,77 +1,65 @@ - #include "topic_editor.h" + #include "ui_topic_editor.h" -#include + #include #include +#include +#include #include #include #include -#include -#include - #include #include #include #include - +#include namespace FileManagement { -FileTopicEditor::FileTopicEditor( - LtsSession::LtsSession *session, FileContentPreviewPlaybackWidget *previewWidget, const std::shared_ptr &ftc, - QWidget *parent -) - : TopicEditorBase::TopicEditor(parent) - , m_session(session) - , m_getContent(new FileManagement::GetFileContent(ftc, this)) - , m_previewPlaybackWidget(previewWidget) - , m_ui(new Ui::FileTopicEditor) +FileTopicEditor::FileTopicEditor(LtsSession::LtsSession* session, FileContentPreviewPlaybackWidget* previewWidget, + const std::shared_ptr& ftc, QWidget* parent) + : TopicEditorBase::TopicEditor(parent), m_session(session), + m_getContent(new FileManagement::GetFileContent(ftc, this)), m_previewPlaybackWidget(previewWidget), + m_ui(new Ui::FileTopicEditor) { - - m_ui->setupUi(this); - init(m_ui->widget); - m_ftc = ftc; - m_ui->scrollArea->setWidget(m_previewPlaybackWidget); - connect(m_previewPlaybackWidget, &FileContentPreviewPlaybackWidget::currentPageChanged, - this, &FileTopicEditor::onPageNoChanged); - connect(m_previewPlaybackWidget, &FileContentPreviewPlaybackWidget::rotationChanged, - this, &FileTopicEditor::onRotationChanged); + m_ui->setupUi(this); + init(m_ui->widget); + m_ftc = ftc; + m_ui->scrollArea->setWidget(m_previewPlaybackWidget); - if (m_ui->pbSetTopicPosition->isEnabled()) - m_ui->pbSetTopicPosition->setToolTip(tr("Starts a replay at the time that the topic was positioned.%1").arg(QString())); - else - m_ui->pbSetTopicPosition->setToolTip(tr("Starts a replay at the time that the topic was positioned.%1").arg(QStringLiteral(" %1").arg(tr("You need to position the topic on a screen track first to start a preview.", "Sie müssen das Topic auf eine Screen-Spur ziehen, bevor Sie eine Vorschau starten können.")))); + connect(m_previewPlaybackWidget, &FileContentPreviewPlaybackWidget::currentPageChanged, this, + &FileTopicEditor::onPageNoChanged); + connect(m_previewPlaybackWidget, &FileContentPreviewPlaybackWidget::rotationChanged, this, + &FileTopicEditor::onRotationChanged); - connect(m_ui->pbBrowse, &QPushButton::clicked, - this, &FileTopicEditor::onSelectFile); - connect(m_ui->pbEnterText, &QPushButton::clicked, - this, &FileTopicEditor::onEnterText); + if (m_ui->pbSetTopicPosition->isEnabled()) + m_ui->pbSetTopicPosition->setToolTip( + tr("Starts a replay at the time that the topic was positioned.%1").arg(QString())); + else + m_ui->pbSetTopicPosition->setToolTip( + tr("Starts a replay at the time that the topic was positioned.%1") + .arg(QStringLiteral(" %1") + .arg(tr("You need to position the topic on a screen track first to start a preview.", + "Sie müssen das Topic auf eine Screen-Spur ziehen, bevor Sie eine Vorschau starten " + "können.")))); - connect(m_ui->zoomSlider, &QSlider::valueChanged, - this, &FileTopicEditor::onZoomSliderChanged); + connect(m_ui->pbBrowse, &QPushButton::clicked, this, &FileTopicEditor::onSelectFile); + connect(m_ui->pbEnterText, &QPushButton::clicked, this, &FileTopicEditor::onEnterText); - connect(m_ui->sbPageNo, static_cast(&QSpinBox::valueChanged), - this, &FileTopicEditor::onPageNoChanged); + connect(m_ui->zoomSlider, &QSlider::valueChanged, this, &FileTopicEditor::onZoomSliderChanged); - connect(m_ui->sbRotation, static_cast(&QSpinBox::valueChanged), - this, &FileTopicEditor::onRotationChanged); + connect(m_ui->sbPageNo, static_cast(&QSpinBox::valueChanged), this, + &FileTopicEditor::onPageNoChanged); + connect(m_ui->sbRotation, static_cast(&QSpinBox::valueChanged), this, + &FileTopicEditor::onRotationChanged); - - - - - - - - - - m_ui->pbSetTopicPosition->setEnabled(false); + m_ui->pbSetTopicPosition->setEnabled(false); #if 0 connect(m_ui->pbSetTopicPosition, &QPushButton::clicked, this, [this]() { @@ -80,433 +68,416 @@ FileTopicEditor::FileTopicEditor( emit signalSetTopicPosition(m_ui->scrollArea, m_topicData.id); }); #else - { - connect(m_ui->pbSetTopicPosition, &QPushButton::clicked, this, &FileTopicEditor::onPreview); - } + { + connect(m_ui->pbSetTopicPosition, &QPushButton::clicked, this, &FileTopicEditor::onPreview); + } #endif } FileTopicEditor::~FileTopicEditor() { - delete m_ui; + delete m_ui; } - - - void FileTopicEditor::updatePreview() { - setUnchangeable(true); + setUnchangeable(true); - if (m_userText.isEmpty()) - { - DEBUG_LOG(m_logger) << "file id = " << m_fileId; - m_fileContent = m_dtc->fileContent(m_fileId); - m_fileName = QString::fromStdString(m_fileContent.name()); - m_ui->leFileName->setText(m_fileName); - DEBUG_LOG(m_logger) << "file name = " << m_fileName; - - if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) + if (m_userText.isEmpty()) { - DEBUG_LOG(m_logger) << "zoom level = " << m_zoomLevel; - m_ui->zoomSlider->setValue(m_zoomLevel); + DEBUG_LOG(m_logger) << "file id = " << m_fileId; + m_fileContent = m_dtc->fileContent(m_fileId); + m_fileName = QString::fromStdString(m_fileContent.name()); + m_ui->leFileName->setText(m_fileName); + DEBUG_LOG(m_logger) << "file name = " << m_fileName; - DEBUG_LOG(m_logger) << "rotation = " << m_rotation; - m_ui->sbRotation->setValue(m_rotation); + if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) + { + DEBUG_LOG(m_logger) << "zoom level = " << m_zoomLevel; + m_ui->zoomSlider->setValue(m_zoomLevel); - const int pageNo = m_pageNo; - m_ui->sbPageNo->setRange(1, m_previewPlaybackWidget->getNumPages()); - m_pageNo = pageNo; - DEBUG_LOG(m_logger) << "page no = " << m_pageNo; - m_ui->sbPageNo->setValue(m_pageNo); + DEBUG_LOG(m_logger) << "rotation = " << m_rotation; + m_ui->sbRotation->setValue(m_rotation); - m_ui->sbPageNo->setEnabled(true); - m_ui->zoomSlider->setEnabled(true); - m_ui->sbRotation->setEnabled(true); + const int pageNo = m_pageNo; + m_ui->sbPageNo->setRange(1, m_previewPlaybackWidget->getNumPages()); + m_pageNo = pageNo; + DEBUG_LOG(m_logger) << "page no = " << m_pageNo; + m_ui->sbPageNo->setValue(m_pageNo); + + m_ui->sbPageNo->setEnabled(true); + m_ui->zoomSlider->setEnabled(true); + m_ui->sbRotation->setEnabled(true); + } + } + else + { + m_fileId = 0; + m_ui->leFileName->setText(tr("Custom text")); } - } - else - { - m_fileId = 0; - m_ui->leFileName->setText(tr("Custom text")); - } - m_previewPlaybackWidget->setVisible(true); - m_previewPlaybackWidget->init(m_fileContent, m_pageNo, m_zoomLevel / 100., m_rotation, 0, m_userText); - setUnchangeable(false); + m_previewPlaybackWidget->setVisible(true); + m_previewPlaybackWidget->init(m_fileContent, m_pageNo, m_zoomLevel / 100., m_rotation, 0, m_userText); + setUnchangeable(false); } bool FileTopicEditor::fetchInterfaces() { - if (!m_session->getForeignGuiInterface(m_guiIfc)) - { - ERROR_LOG(m_logger) << "Failed to retrieve Flm ForeignGuiInterface"; - return false; - } + if (!m_session->getForeignGuiInterface(m_guiIfc)) + { + ERROR_LOG(m_logger) << "Failed to retrieve Flm ForeignGuiInterface"; + return false; + } - if (!m_session->getDtc(m_dtc)) - { - ERROR_LOG(m_logger) << "Failed to retrieve Flm Dtc"; - return false; - } + if (!m_session->getDtc(m_dtc)) + { + ERROR_LOG(m_logger) << "Failed to retrieve Flm Dtc"; + return false; + } - return true; + return true; } - - - void FileTopicEditor::updateInternalData() { - enaDisa(); + enaDisa(); - if (m_topicData.topicType != TopicEditorBase::TopicType::Text) - m_ui->pbEnterText->hide(); + if (m_topicData.topicType != TopicEditorBase::TopicType::Text) + m_ui->pbEnterText->hide(); - if (m_topicData.topicType == TopicEditorBase::TopicType::TacticalPlan) - { - m_ui->pbSetTopicPosition->hide(); - m_ui->scrollArea->hide(); - } - - if (m_topicData.topicType == TopicEditorBase::TopicType::Text || - m_topicData.topicType == TopicEditorBase::TopicType::Image || - m_topicData.topicType == TopicEditorBase::TopicType::Pdf) - { - - if (m_topicData.x <= 0 && m_topicData.y <= 0 && m_topicData.w <= 0 && m_topicData.h <= 0) + if (m_topicData.topicType == TopicEditorBase::TopicType::TacticalPlan) { - m_topicData.x = 0; - m_topicData.y = 0; - m_topicData.h = 0.8; - m_topicData.w = 0.8; + m_ui->pbSetTopicPosition->hide(); + m_ui->scrollArea->hide(); } - } - - m_fileTypes.clear(); - switch (m_topicData.topicType) - { - case TopicEditorBase::TopicType::Image: - m_fileTypes << FileManagement::FileType_def::Jpg << FileManagement::FileType_def::Png; - break; + if (m_topicData.topicType == TopicEditorBase::TopicType::Text || + m_topicData.topicType == TopicEditorBase::TopicType::Image || + m_topicData.topicType == TopicEditorBase::TopicType::Pdf) + { - case TopicEditorBase::TopicType::Pdf: - m_fileTypes << FileManagement::FileType_def::Pdf; - break; + if (m_topicData.x <= 0 && m_topicData.y <= 0 && m_topicData.w <= 0 && m_topicData.h <= 0) + { + m_topicData.x = 0; + m_topicData.y = 0; + m_topicData.h = 0.8; + m_topicData.w = 0.8; + } + } - case TopicEditorBase::TopicType::Text: - m_fileTypes << FileManagement::FileType_def::Text << FileManagement::FileType_def::EvaluationSchema; - break; + m_fileTypes.clear(); + switch (m_topicData.topicType) + { + case TopicEditorBase::TopicType::Image: + m_fileTypes << FileManagement::FileType_def::Jpg << FileManagement::FileType_def::Png; + break; - case TopicEditorBase::TopicType::Xml: - m_fileTypes << FileManagement::FileType_def::Xml; - break; + case TopicEditorBase::TopicType::Pdf: + m_fileTypes << FileManagement::FileType_def::Pdf; + break; - case TopicEditorBase::TopicType::TacticalPlan: - m_fileTypes << FileManagement::FileType_def::TacticalPlan; - break; + case TopicEditorBase::TopicType::Text: + m_fileTypes << FileManagement::FileType_def::Text << FileManagement::FileType_def::EvaluationSchema; + break; - case TopicEditorBase::TopicType::MSOffice: - m_fileTypes << FileManagement::FileType_def::MSOfficeDocument - << FileManagement::FileType_def::MSOfficeDocument97 - << FileManagement::FileType_def::MSOfficePresentation - << FileManagement::FileType_def::MSOfficePresentation97 - << FileManagement::FileType_def::MSOfficeSpreadsheet - << FileManagement::FileType_def::MSOfficeSpreadsheet97; - break; + case TopicEditorBase::TopicType::Xml: + m_fileTypes << FileManagement::FileType_def::Xml; + break; - case TopicEditorBase::TopicType::OpenOffice: - m_fileTypes << FileManagement::FileType_def::OpenOfficeDocument - << FileManagement::FileType_def::OpenOfficePresentation - << FileManagement::FileType_def::OpenOfficeSpreadsheet; - break; + case TopicEditorBase::TopicType::TacticalPlan: + m_fileTypes << FileManagement::FileType_def::TacticalPlan; + break; - default: - break; - } + case TopicEditorBase::TopicType::MSOffice: + m_fileTypes << FileManagement::FileType_def::MSOfficeDocument + << FileManagement::FileType_def::MSOfficeDocument97 + << FileManagement::FileType_def::MSOfficePresentation + << FileManagement::FileType_def::MSOfficePresentation97 + << FileManagement::FileType_def::MSOfficeSpreadsheet + << FileManagement::FileType_def::MSOfficeSpreadsheet97; + break; - switch (m_topicData.topicType) - { - case TopicEditorBase::TopicType::Image: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Image_Topic")); - break; + case TopicEditorBase::TopicType::OpenOffice: + m_fileTypes << FileManagement::FileType_def::OpenOfficeDocument + << FileManagement::FileType_def::OpenOfficePresentation + << FileManagement::FileType_def::OpenOfficeSpreadsheet; + break; - case TopicEditorBase::TopicType::Pdf: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_PDF_Topic")); - break; + default: + break; + } - case TopicEditorBase::TopicType::Text: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Text_Topic")); - break; + switch (m_topicData.topicType) + { + case TopicEditorBase::TopicType::Image: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Image_Topic")); + break; - case TopicEditorBase::TopicType::Xml: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_XML_Topic")); - break; + case TopicEditorBase::TopicType::Pdf: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_PDF_Topic")); + break; - case TopicEditorBase::TopicType::TacticalPlan: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Tactical_Plan_Topic")); - break; + case TopicEditorBase::TopicType::Text: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Text_Topic")); + break; - case TopicEditorBase::TopicType::MSOffice: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_MS_Office_Topic")); - break; + case TopicEditorBase::TopicType::Xml: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_XML_Topic")); + break; - case TopicEditorBase::TopicType::OpenOffice: - setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Open_Office_Topic")); - break; + case TopicEditorBase::TopicType::TacticalPlan: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Tactical_Plan_Topic")); + break; - default: - translate(m_ui, tr("Unknown File Topic Editor")); - break; - } + case TopicEditorBase::TopicType::MSOffice: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_MS_Office_Topic")); + break; - m_ui->pbSetTopicPosition->setEnabled(!m_topicData.channel.isEmpty() || !m_topicData.parentChannel.isEmpty()); + case TopicEditorBase::TopicType::OpenOffice: + setOnlineHelpFilename(QStringLiteral("Script_Editor-Add_Open_Office_Topic")); + break; - - m_userText = getTopicDataValue(QStringLiteral("UserText")).toString(); - m_fileId = getTopicDataValue(QStringLiteral("FileId")).toInt(); + default: + translate(m_ui, tr("Unknown File Topic Editor")); + break; + } - m_pageNo = getTopicDataValue(QStringLiteral("PageNo")).toInt(); - m_zoomLevel = getTopicDataValue(QStringLiteral("ZoomLevel")).toInt(); - m_rotation = getTopicDataValue(QStringLiteral("Rotation")).toInt(); + m_ui->pbSetTopicPosition->setEnabled(!m_topicData.channel.isEmpty() || !m_topicData.parentChannel.isEmpty()); - if (hasTopicDataProperties()) - updatePreview(); + m_userText = getTopicDataValue(QStringLiteral("UserText")).toString(); + m_fileId = getTopicDataValue(QStringLiteral("FileId")).toInt(); + + m_pageNo = getTopicDataValue(QStringLiteral("PageNo")).toInt(); + m_zoomLevel = getTopicDataValue(QStringLiteral("ZoomLevel")).toInt(); + m_rotation = getTopicDataValue(QStringLiteral("Rotation")).toInt(); + + if (hasTopicDataProperties()) + updatePreview(); } void FileTopicEditor::retranslate() { - switch (m_topicData.topicType) - { - case TopicEditorBase::TopicType::Image: - translate(m_ui, tr("Image Topic Editor")); - break; - case TopicEditorBase::TopicType::Pdf: - translate(m_ui, tr("Pdf Topic Editor")); - break; - case TopicEditorBase::TopicType::Text: - translate(m_ui, tr("Text Topic Editor")); - break; - case TopicEditorBase::TopicType::Xml: - translate(m_ui, tr("Xml Topic Editor")); - break; - case TopicEditorBase::TopicType::TacticalPlan: - translate(m_ui, tr("Tactical Plan Topic Editor")); - break; - case TopicEditorBase::TopicType::MSOffice: - translate(m_ui, tr("MS Office Topic Editor")); - break; - case TopicEditorBase::TopicType::OpenOffice: - translate(m_ui, tr("Open Office Topic Editor")); - break; - default: - translate(m_ui, tr("Unknown File Topic Editor")); - break; - } + switch (m_topicData.topicType) + { + case TopicEditorBase::TopicType::Image: + translate(m_ui, tr("Image Topic Editor")); + break; + case TopicEditorBase::TopicType::Pdf: + translate(m_ui, tr("Pdf Topic Editor")); + break; + case TopicEditorBase::TopicType::Text: + translate(m_ui, tr("Text Topic Editor")); + break; + case TopicEditorBase::TopicType::Xml: + translate(m_ui, tr("Xml Topic Editor")); + break; + case TopicEditorBase::TopicType::TacticalPlan: + translate(m_ui, tr("Tactical Plan Topic Editor")); + break; + case TopicEditorBase::TopicType::MSOffice: + translate(m_ui, tr("MS Office Topic Editor")); + break; + case TopicEditorBase::TopicType::OpenOffice: + translate(m_ui, tr("Open Office Topic Editor")); + break; + default: + translate(m_ui, tr("Unknown File Topic Editor")); + break; + } - if (hasTopicDataProperties()) - updatePreview(); + if (hasTopicDataProperties()) + updatePreview(); } - void FileTopicEditor::enaDisa() { - if (m_previewPlaybackWidget) - m_previewPlaybackWidget->setVisible(false); - m_ui->lblPageNo->setVisible(false); - m_ui->sbPageNo->setVisible(false); - m_ui->lblZoom->setVisible(false); - m_ui->zoomSlider->setVisible(false); - m_ui->lblZoomValue->setVisible(false); - m_ui->sbRotation->setVisible(false); - m_ui->lblRotation->setVisible(false); + if (m_previewPlaybackWidget) + m_previewPlaybackWidget->setVisible(false); + m_ui->lblPageNo->setVisible(false); + m_ui->sbPageNo->setVisible(false); + m_ui->lblZoom->setVisible(false); + m_ui->zoomSlider->setVisible(false); + m_ui->lblZoomValue->setVisible(false); + m_ui->sbRotation->setVisible(false); + m_ui->lblRotation->setVisible(false); - if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) - { - m_ui->lblPageNo->setVisible(true); - m_ui->sbPageNo->setVisible(true); - m_ui->lblZoom->setVisible(true); - m_ui->zoomSlider->setVisible(true); - m_ui->lblZoomValue->setVisible(true); - m_ui->sbRotation->setVisible(true); - m_ui->lblRotation->setVisible(true); - m_ui->sbPageNo->setEnabled(false); - m_ui->zoomSlider->setEnabled(false); - m_ui->sbRotation->setEnabled(false); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); - } + if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) + { + m_ui->lblPageNo->setVisible(true); + m_ui->sbPageNo->setVisible(true); + m_ui->lblZoom->setVisible(true); + m_ui->zoomSlider->setVisible(true); + m_ui->lblZoomValue->setVisible(true); + m_ui->sbRotation->setVisible(true); + m_ui->lblRotation->setVisible(true); + m_ui->sbPageNo->setEnabled(false); + m_ui->zoomSlider->setEnabled(false); + m_ui->sbRotation->setEnabled(false); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + } } - - - bool FileTopicEditor::apply2() { - setTopicDataProperty(QStringLiteral("FileId"), m_fileId); - if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) - { - setTopicDataProperty(QStringLiteral("PageNo"), m_pageNo); - setTopicDataProperty(QStringLiteral("ZoomLevel"), m_zoomLevel); - setTopicDataProperty(QStringLiteral("Rotation"), m_rotation); - } - setTopicDataProperty(QStringLiteral("UserText"), m_userText); - setDescription(m_ui->widget->description()); - m_ui->widget->previewer()->setTopicData(m_topicData); - - if (m_fileId == 0) - { - if (m_topicData.topicType == TopicEditorBase::TopicType::Text && !m_userText.isEmpty()) + setTopicDataProperty(QStringLiteral("FileId"), m_fileId); + if (m_topicData.topicType == TopicEditorBase::TopicType::Pdf) { - emit changesSaved(m_topicData); - return true; + setTopicDataProperty(QStringLiteral("PageNo"), m_pageNo); + setTopicDataProperty(QStringLiteral("ZoomLevel"), m_zoomLevel); + setTopicDataProperty(QStringLiteral("Rotation"), m_rotation); } + setTopicDataProperty(QStringLiteral("UserText"), m_userText); + setDescription(m_ui->widget->description()); + m_ui->widget->previewer()->setTopicData(m_topicData); - new LtsWidgets::LtsMessageDialogNew(this, tr("No content was selected for this topic."), tr("Applying changes failed")); - return false; - } - emit changesSaved(m_topicData); - return true; + if (m_fileId == 0) + { + if (m_topicData.topicType == TopicEditorBase::TopicType::Text && !m_userText.isEmpty()) + { + emit changesSaved(m_topicData); + return true; + } + + new LtsWidgets::LtsMessageDialogNew(this, tr("No content was selected for this topic."), + tr("Applying changes failed")); + return false; + } + emit changesSaved(m_topicData); + return true; } - void FileTopicEditor::onSelectFile() { - QByteArray content; - int folderId = 0; - if (m_topicData.topicType == TopicEditorBase::TopicType::TacticalPlan) - folderId = m_dtc->findFolder(0, QStringLiteral("Tactical Plans")); - int fileId = m_guiIfc->loadFileContent(this, content, m_fileTypes, 0, QString(), folderId); - if (fileId > 0) - { - m_fileId = fileId; - m_userText.clear(); - updatePreview(); - slotChangesMade(); - } - else - { - ERROR_LOG(m_logger) << "Cannot load file from library"; - } + QByteArray content; + int folderId = 0; + if (m_topicData.topicType == TopicEditorBase::TopicType::TacticalPlan) + folderId = m_dtc->findFolder(0, QStringLiteral("Tactical Plans")); + int fileId = m_guiIfc->loadFileContent(this, content, m_fileTypes, 0, QString(), folderId); + if (fileId > 0) + { + m_fileId = fileId; + m_userText.clear(); + updatePreview(); + slotChangesMade(); + } + else + { + ERROR_LOG(m_logger) << "Cannot load file from library"; + } } void FileTopicEditor::onZoomSliderChanged() { - DEBUG_LOG(m_logger) << Q_FUNC_INFO; + DEBUG_LOG(m_logger) << Q_FUNC_INFO; - m_zoomLevel = m_ui->zoomSlider->value(); - m_ui->zoomSlider->setToolTip(tr("Zoom %1 %").arg(m_zoomLevel)); - m_ui->lblZoomValue->setText(QString::number(m_zoomLevel) + QStringLiteral(" %")); - m_previewPlaybackWidget->setZoomFactor(m_zoomLevel / 100.); + m_zoomLevel = m_ui->zoomSlider->value(); + m_ui->zoomSlider->setToolTip(tr("Zoom %1 %").arg(m_zoomLevel)); + m_ui->lblZoomValue->setText(QString::number(m_zoomLevel) + QStringLiteral(" %")); + m_previewPlaybackWidget->setZoomFactor(m_zoomLevel / 100.); } void FileTopicEditor::onPageNoChanged(int pageNo) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << "page no = " << pageNo; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << "page no = " << pageNo; - m_pageNo = pageNo; - m_ui->sbPageNo->setValue(m_pageNo); - m_previewPlaybackWidget->setPage(m_pageNo); + m_pageNo = pageNo; + m_ui->sbPageNo->setValue(m_pageNo); + m_previewPlaybackWidget->setPage(m_pageNo); } void FileTopicEditor::onEnterText() { - if (m_textEditDialog) - { - focusDialog(menuGroup(), QStringLiteral("FileTopicTextEditDialog"), LtsWidgets::LayoutArea::eDialogTab); - return; - } + if (m_textEditDialog) + { + focusDialog(menuGroup(), QStringLiteral("FileTopicTextEditDialog"), LtsWidgets::LayoutArea::eDialogTab); + return; + } - m_textEditDialog = new LtsWidgets::LtsTextEditDialog(this); - m_textEditDialog->enableBackgroundColor(true); - QString html; + m_textEditDialog = new LtsWidgets::LtsTextEditDialog(this); + m_textEditDialog->enableBackgroundColor(true); + QString html; - if (m_userText.isEmpty() && m_fileContent.id() != 0) - { - std::vector content; - m_getContent->getContent(m_fileContent.id(), content); - html = QString::fromUtf8(LtsUtils::toQByteArray(content)); - } - else - html = m_userText; + if (m_userText.isEmpty() && m_fileContent.id() != 0) + { + std::vector content; + m_getContent->getContent(m_fileContent.id(), content); + html = QString::fromUtf8(LtsUtils::toQByteArray(content)); + } + else + html = m_userText; - - const int backGroundColorIndex = html.indexOf(QLatin1String("background-color")); + const int backGroundColorIndex = html.indexOf(QLatin1String("background-color")); - if (backGroundColorIndex != -1) - { - const int rgbIndex = html.indexOf(QLatin1Char('#'), backGroundColorIndex); - const QColor backGroundColor(html.mid(rgbIndex, 7)); - const int backGroundColorIndexEnd = html.indexOf(QLatin1Char(';'), backGroundColorIndex); + if (backGroundColorIndex != -1) + { + const int rgbIndex = html.indexOf(QLatin1Char('#'), backGroundColorIndex); + const QColor backGroundColor(html.mid(rgbIndex, 7)); + const int backGroundColorIndexEnd = html.indexOf(QLatin1Char(';'), backGroundColorIndex); - m_textEditDialog->setInitialBackgroundColor(backGroundColor); + m_textEditDialog->setInitialBackgroundColor(backGroundColor); - html.remove(backGroundColorIndex, backGroundColorIndexEnd - backGroundColorIndex + 2); - } + html.remove(backGroundColorIndex, backGroundColorIndexEnd - backGroundColorIndex + 2); + } - m_textEditDialog->setHtml(html); + m_textEditDialog->setHtml(html); - connect(m_textEditDialog.data(), &LtsWidgets::LtsTextEditDialog::signalTextAppliedWithBackGroundColor, - this, &FileTopicEditor::onCustomTextChanged); - addDialog(m_textEditDialog, menuGroup(), QStringLiteral("FileTopicTextEditDialog"), LtsWidgets::LayoutArea::eDialogTab); + connect(m_textEditDialog.data(), &LtsWidgets::LtsTextEditDialog::signalTextAppliedWithBackGroundColor, this, + &FileTopicEditor::onCustomTextChanged); + addDialog(m_textEditDialog, menuGroup(), QStringLiteral("FileTopicTextEditDialog"), + LtsWidgets::LayoutArea::eDialogTab); } void FileTopicEditor::onRotationChanged(int rotation) { - DEBUG_LOG(m_logger) << Q_FUNC_INFO << " rotation = " << rotation; + DEBUG_LOG(m_logger) << Q_FUNC_INFO << " rotation = " << rotation; - m_rotation = rotation; - m_ui->sbRotation->setValue(m_rotation); - m_previewPlaybackWidget->setRotation(m_rotation); + m_rotation = rotation; + m_ui->sbRotation->setValue(m_rotation); + m_previewPlaybackWidget->setRotation(m_rotation); } -void FileTopicEditor::onCustomTextChanged(const QString &htmlText) +void FileTopicEditor::onCustomTextChanged(const QString& htmlText) { - m_userText = htmlText; - m_ui->leFileName->setText(tr("Custom text")); - m_fileId = 0; - m_fileContent = FileContent(); - updatePreview(); - slotChangesMade(); + m_userText = htmlText; + m_ui->leFileName->setText(tr("Custom text")); + m_fileId = 0; + m_fileContent = FileContent(); + updatePreview(); + slotChangesMade(); } - - void FileTopicEditor::onPreview() { - if(m_ui->scrollArea == nullptr || m_ftc == nullptr) - return; - updatePreview(); + if (m_ui->scrollArea == nullptr || m_ftc == nullptr) + return; + updatePreview(); - QScrollArea *scrollArea = new QScrollArea(m_ui->scrollArea); - scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - scrollArea->setWidgetResizable(true); - FileContentPreviewPlaybackWidget *prevWidget = new FileContentPreviewPlaybackWidget(m_ftc, m_previewPlaybackWidget); - prevWidget->setGeometry(QRect(0, 0, 566, 69)); - QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Expanding); - sizePolicy1.setHorizontalStretch(0); - sizePolicy1.setVerticalStretch(0); - sizePolicy1.setHeightForWidth(prevWidget->sizePolicy().hasHeightForWidth()); - prevWidget->setSizePolicy(sizePolicy1); - prevWidget->setVisible(true); - prevWidget->init(m_fileContent, m_pageNo, m_zoomLevel / 100., m_rotation, 0, m_userText); + QScrollArea* scrollArea = new QScrollArea(m_ui->scrollArea); + scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + scrollArea->setWidgetResizable(true); + FileContentPreviewPlaybackWidget* prevWidget = new FileContentPreviewPlaybackWidget(m_ftc, m_previewPlaybackWidget); + prevWidget->setGeometry(QRect(0, 0, 566, 69)); + QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Expanding); + sizePolicy1.setHorizontalStretch(0); + sizePolicy1.setVerticalStretch(0); + sizePolicy1.setHeightForWidth(prevWidget->sizePolicy().hasHeightForWidth()); + prevWidget->setSizePolicy(sizePolicy1); + prevWidget->setVisible(true); + prevWidget->init(m_fileContent, m_pageNo, m_zoomLevel / 100., m_rotation, 0, m_userText); - scrollArea->setWidget(prevWidget); + scrollArea->setWidget(prevWidget); - connect(prevWidget, &FileContentPreviewPlaybackWidget::currentPageChanged, - this, &FileTopicEditor::onPageNoChanged); + connect(prevWidget, &FileContentPreviewPlaybackWidget::currentPageChanged, this, &FileTopicEditor::onPageNoChanged); - connect(prevWidget, &FileContentPreviewPlaybackWidget::rotationChanged, - this, [this, prevWidget](int rotation) - { - if(m_ui->sbRotation == nullptr) - return; - m_rotation = rotation; - m_ui->sbRotation->setValue(m_rotation); - prevWidget->setRotation(m_rotation); - }); - emit signalSetTopicPosition(scrollArea, m_topicData.id); + connect(prevWidget, &FileContentPreviewPlaybackWidget::rotationChanged, this, [this, prevWidget](int rotation) { + if (m_ui->sbRotation == nullptr) + return; + m_rotation = rotation; + m_ui->sbRotation->setValue(m_rotation); + prevWidget->setRotation(m_rotation); + }); + emit signalSetTopicPosition(scrollArea, m_topicData.id); } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.h b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.h old mode 100755 new mode 100644 index de83f2eea..6370c13b3 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.h +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/TopicEditor/topic_editor.h @@ -1,81 +1,83 @@ - #pragma once #include #include -#include -#include #include -#include +#include +#include #include +#include +namespace Ui +{ +class FileTopicEditor; +} -namespace Ui { class FileTopicEditor; } - -namespace PresentationManagement { class TopicDesigner; } - -namespace LtsWidgets { class LtsTextEditDialog; } +namespace PresentationManagement +{ +class TopicDesigner; +} +namespace LtsWidgets +{ +class LtsTextEditDialog; +} namespace FileManagement { - class FileTopicEditor : public TopicEditorBase::TopicEditor { - Q_OBJECT + Q_OBJECT -public: - explicit FileTopicEditor( - LtsSession::LtsSession *session, FileContentPreviewPlaybackWidget *previewWidget, - const std::shared_ptr &ftc, QWidget *parent = nullptr - ); - ~FileTopicEditor(); + public: + explicit FileTopicEditor(LtsSession::LtsSession* session, FileContentPreviewPlaybackWidget* previewWidget, + const std::shared_ptr& ftc, QWidget* parent = nullptr); + ~FileTopicEditor(); - void updatePreview(); - bool fetchInterfaces(); + void updatePreview(); + bool fetchInterfaces(); -private: + private: + NGL::INGLLogger& m_logger; + void updateInternalData() override final; + void retranslate() override final; -NGL::INGLLogger &m_logger; - void updateInternalData() override final; - void retranslate() override final; + void enaDisa(); - void enaDisa(); + private slots: + bool apply2() override final; -private slots: - bool apply2() override final; + void onSelectFile(); + void onZoomSliderChanged(); + void onPageNoChanged(int pageNo); + void onRotationChanged(int rotation); + void onEnterText(); + void onCustomTextChanged(const QString& htmlText); + void onPreview(); - void onSelectFile(); - void onZoomSliderChanged(); - void onPageNoChanged(int pageNo); - void onRotationChanged(int rotation); - void onEnterText(); - void onCustomTextChanged(const QString &htmlText); - void onPreview(); + private: + LtsSession::LtsSession* m_session{nullptr}; + std::shared_ptr m_dtc{nullptr}; + std::shared_ptr m_guiIfc{nullptr}; + std::shared_ptr m_ftc{nullptr}; -private: - LtsSession::LtsSession *m_session{nullptr}; - std::shared_ptr m_dtc{nullptr}; - std::shared_ptr m_guiIfc{nullptr}; - std::shared_ptr m_ftc{nullptr}; + QVector m_fileTypes; + FileManagement::GetFileContent* m_getContent{nullptr}; + FileContentPreviewPlaybackWidget* m_previewPlaybackWidget{nullptr}; + FileContent m_fileContent; + QString m_fileName; + int m_fileId{0}; + int m_pageNo{1}; + int m_zoomLevel{100}; + int m_rotation{0}; + QString m_userText; - QVector m_fileTypes; - FileManagement::GetFileContent *m_getContent{nullptr}; - FileContentPreviewPlaybackWidget *m_previewPlaybackWidget{nullptr}; - FileContent m_fileContent; - QString m_fileName; - int m_fileId{0}; - int m_pageNo{1}; - int m_zoomLevel{100}; - int m_rotation{0}; - QString m_userText; - - QPointer m_textEditDialog; + QPointer m_textEditDialog; - Ui::FileTopicEditor *m_ui{nullptr}; + Ui::FileTopicEditor* m_ui{nullptr}; }; -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog.cpp old mode 100755 new mode 100644 index 01b641477..e5fd0650c --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog.cpp @@ -1,2048 +1,1929 @@ - #include "flm_dialog.h" + +#include "flm_dialog_model_file.h" +#include "flm_dialog_model_folder.h" +#include "flm_edit_file_content.h" +#include "flm_edit_folder.h" +#include "flm_office_integration.h" +#include "flm_preview_file_dialog.h" #include "ui_flm_dialog.h" -#include "flm_dialog_model_folder.h" -#include "flm_dialog_model_file.h" -#include "flm_edit_folder.h" -#include "flm_edit_file_content.h" -#include "flm_preview_file_dialog.h" -#include "flm_office_integration.h" -#include #include -#include -#include -#include -#include -#include -#include -#include - -#include - +#include #include #include #include #include #include -#include -#include - +#include +#include +#include +#include +#include +#include +#include #include #include #include +#include +#include namespace FileManagement { - - - -FileManagementDialogWidget::FileManagementDialogWidget(QWidget *parent) - : QWidget(parent) - , m_ui(new Ui::FileManagementDialogWidget) - , m_requestHelper(new LtsUtils::RequestHelper(this)) +FileManagementDialogWidget::FileManagementDialogWidget(QWidget* parent) + : QWidget(parent), m_ui(new Ui::FileManagementDialogWidget), m_requestHelper(new LtsUtils::RequestHelper(this)) { - m_ui->setupUi(this); - if (LtsSessionData::LtsSessionData::getInstance()->isTablet()) - m_ui->leFile->setFocusPolicy(Qt::ClickFocus); - m_ui->widgetFiles->setToolButtonsVisible(false); - m_ui->widgetFiles->setColumnCountVisible(false); + m_ui->setupUi(this); + if (LtsSessionData::LtsSessionData::getInstance()->isTablet()) + m_ui->leFile->setFocusPolicy(Qt::ClickFocus); + m_ui->widgetFiles->setToolButtonsVisible(false); + m_ui->widgetFiles->setColumnCountVisible(false); } - FileManagementDialogWidget::~FileManagementDialogWidget() { - delete m_getContent; - delete m_ui; + delete m_getContent; + delete m_ui; } - FileManagementDialogTab::~FileManagementDialogTab() { - delete m_editItemWidget; + delete m_editItemWidget; } - FileManagementDialog::~FileManagementDialog() { - delete m_editItemWidget; + delete m_editItemWidget; } - void FileManagementDialogTab::retranslate() { - if (m_dialogMode == FileDialogMode::Admin) - translate(m_editItemWidget->m_ui, tr("Manage Library")); - else - translate(m_editItemWidget->m_ui, tr("Organize Library")); + if (m_dialogMode == FileDialogMode::Admin) + translate(m_editItemWidget->m_ui, tr("Manage Library")); + else + translate(m_editItemWidget->m_ui, tr("Organize Library")); } - -bool FileManagementDialogWidget::init(LtsSession::LtsSession *session, - FileDialogMode dlgMode, - const QVector &fileTypes, - int folderId, - const QString &xmlType) +bool FileManagementDialogWidget::init(LtsSession::LtsSession* session, FileDialogMode dlgMode, + const QVector& fileTypes, int folderId, const QString& xmlType) { - DEBUG_LOG(m_logger) << "Start init FileManagementDialogWidget"; - if (!session) - { - ERROR_LOG(m_logger) << "Failed to init FileManagementDialogWidget"; - return false; - } + DEBUG_LOG(m_logger) << "Start init FileManagementDialogWidget"; + if (!session) + { + ERROR_LOG(m_logger) << "Failed to init FileManagementDialogWidget"; + return false; + } - m_session = session; + m_session = session; - if (!session->getDtc(m_dtc)) - return false; - if (!session->getFtc(m_ftc)) - return false; - if (!session->getDtc(m_opmDtc)) - return false; - if (!session->getDtc(m_exmDtc)) - return false; - if (!session->getDtc(m_ppmDtc)) - return false; - if (!session->getForeignGuiInterface(m_flmGuiCbxIfc)) - return false; + if (!session->getDtc(m_dtc)) + return false; + if (!session->getFtc(m_ftc)) + return false; + if (!session->getDtc(m_opmDtc)) + return false; + if (!session->getDtc(m_exmDtc)) + return false; + if (!session->getDtc(m_ppmDtc)) + return false; + if (!session->getForeignGuiInterface(m_flmGuiCbxIfc)) + return false; - m_dialogMode = dlgMode; - m_fileTypes = fileTypes; - m_selectedFolderId = folderId; - m_xmlType = xmlType; + m_dialogMode = dlgMode; + m_fileTypes = fileTypes; + m_selectedFolderId = folderId; + m_xmlType = xmlType; - m_isAdminMode = (m_dialogMode == FileDialogMode::Admin); + m_isAdminMode = (m_dialogMode == FileDialogMode::Admin); - m_dtc->enableFolder(); - m_dtc->waitForHistoricalDataFolder(); - m_dtc->enableFileContent(); - m_dtc->waitForHistoricalDataFileContent(); - m_opmDtc->enableUser(); - m_opmDtc->waitForHistoricalDataUser(); - m_exmDtc->enableExercise(); - m_exmDtc->waitForHistoricalDataExercise(); - m_exmDtc->enableExercisePhase(); - m_exmDtc->waitForHistoricalDataExercisePhase(); - m_ppmDtc->enableParty(); - m_ppmDtc->waitForHistoricalDataParty(); + m_dtc->enableFolder(); + m_dtc->waitForHistoricalDataFolder(); + m_dtc->enableFileContent(); + m_dtc->waitForHistoricalDataFileContent(); + m_opmDtc->enableUser(); + m_opmDtc->waitForHistoricalDataUser(); + m_exmDtc->enableExercise(); + m_exmDtc->waitForHistoricalDataExercise(); + m_exmDtc->enableExercisePhase(); + m_exmDtc->waitForHistoricalDataExercisePhase(); + m_ppmDtc->enableParty(); + m_ppmDtc->waitForHistoricalDataParty(); - m_getContent = new FileManagement::GetFileContent(m_ftc, this); + m_getContent = new FileManagement::GetFileContent(m_ftc, this); - - connect(m_dtc.get(), &FileManagement::Interface::Dtc::folderChanged, this, &FileManagement::FileManagementDialogWidget::onFolderChanged); - connect(m_dtc.get(), &FileManagement::Interface::Dtc::fileContentChanged, this, &FileManagement::FileManagementDialogWidget::onFileChanged); + connect(m_dtc.get(), &FileManagement::Interface::Dtc::folderChanged, this, + &FileManagement::FileManagementDialogWidget::onFolderChanged); + connect(m_dtc.get(), &FileManagement::Interface::Dtc::fileContentChanged, this, + &FileManagement::FileManagementDialogWidget::onFileChanged); - - QVariant data; - FileManagement::Folder dummyFolder; - data.setValue(dummyFolder); - NGLTreeItem *rootItem = new NGLTreeItem(data, QIcon()); + QVariant data; + FileManagement::Folder dummyFolder; + data.setValue(dummyFolder); + NGLTreeItem* rootItem = new NGLTreeItem(data, QIcon()); - m_modelFolder = new DialogModelFolder(this, rootItem, - QStringList() - << tr("Name")); - + m_modelFolder = new DialogModelFolder(this, rootItem, QStringList() << tr("Name")); - DEBUG_LOG(m_logger) << "Start init model folder"; - m_modelFolder->init(m_session, m_isAdminMode); - int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - if (m_dialogMode == FileDialogMode::Admin) - opId = 0; - m_proxyModelFolder = new DialogModelProxyFolder(this); - m_proxyModelFolder->setOperatorId(opId); - m_proxyModelFolder->setSourceModel(m_modelFolder); - m_proxyModelFolder->sort(DialogModelFolder::Columns::NAME, Qt::AscendingOrder); + DEBUG_LOG(m_logger) << "Start init model folder"; + m_modelFolder->init(m_session, m_isAdminMode); + int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + if (m_dialogMode == FileDialogMode::Admin) + opId = 0; + m_proxyModelFolder = new DialogModelProxyFolder(this); + m_proxyModelFolder->setOperatorId(opId); + m_proxyModelFolder->setSourceModel(m_modelFolder); + m_proxyModelFolder->sort(DialogModelFolder::Columns::NAME, Qt::AscendingOrder); - - m_modelFile = new DialogModelFile(this); + m_modelFile = new DialogModelFile(this); - DEBUG_LOG(m_logger) << "Start init model file content"; - - auto predicate = [this](const FileManagement::FileContent &fc, const QString &xmlType) - { - if (!m_isAdminMode && fc.isHidden()) - return false; + DEBUG_LOG(m_logger) << "Start init model file content"; - return (!fc.isDeleted() && fc.fileStatus() == FileManagement::FileStatus::Valid && - (xmlType.isEmpty() || fc.properties().find(xmlType.toStdString()) != std::string::npos)); - }; - m_modelFile->initModel(m_session, xmlType, predicate); + auto predicate = [this](const FileManagement::FileContent& fc, const QString& xmlType) { + if (!m_isAdminMode && fc.isHidden()) + return false; - - m_ui->tvFolder->setModel(m_proxyModelFolder); - m_ui->tvFolder->expandAll(); - m_ui->tvFolder->setExpanded(m_proxyModelFolder->index(0, 0), true); + return (!fc.isDeleted() && fc.fileStatus() == FileManagement::FileStatus::Valid && + (xmlType.isEmpty() || fc.properties().find(xmlType.toStdString()) != std::string::npos)); + }; + m_modelFile->initModel(m_session, xmlType, predicate); - m_proxyModelFile = new DialogFileProxyModel(this); - m_proxyModelFile->setSourceModel(m_modelFile); - m_ui->widgetFiles->setModel(m_proxyModelFile); + m_ui->tvFolder->setModel(m_proxyModelFolder); + m_ui->tvFolder->expandAll(); + m_ui->tvFolder->setExpanded(m_proxyModelFolder->index(0, 0), true); - m_ui->widgetFiles->hideColumn(FOLDER); + m_proxyModelFile = new DialogFileProxyModel(this); + m_proxyModelFile->setSourceModel(m_modelFile); + m_ui->widgetFiles->setModel(m_proxyModelFile); + + m_ui->widgetFiles->hideColumn(FOLDER); #ifndef LTS_DEBUG - m_ui->widgetFiles->hideColumn(FILEID); + m_ui->widgetFiles->hideColumn(FILEID); #endif - LtsUtils::ProjectSettings *ps = LtsUtils::ProjectSettings::getInstance(); - const bool enableEditPhases = ps->value(QStringLiteral("exm"), - QStringLiteral("enableEditPhases")).toBool(); - if (!enableEditPhases) - { - m_ui->widgetFiles->hideColumn(PHASE); - } - - - if (m_dialogMode == FileDialogMode::OpenFile || m_dialogMode == FileDialogMode::SaveFile) - { - DEBUG_LOG(m_logger) << "Init dialog for open/save modal dialog"; - - - connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalDoubleClicked, this, &FileManagementDialogWidget::onSelectFile); - } - else - { - if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) + LtsUtils::ProjectSettings* ps = LtsUtils::ProjectSettings::getInstance(); + const bool enableEditPhases = ps->value(QStringLiteral("exm"), QStringLiteral("enableEditPhases")).toBool(); + if (!enableEditPhases) { - - connect(m_ui->tvFolder, &QTreeView::doubleClicked, this, &FileManagementDialogWidget::onEditFolder); - - - connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalDoubleClicked, this, &FileManagementDialogWidget::onEditFile); + m_ui->widgetFiles->hideColumn(PHASE); } - - m_ui->tvFolder->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->tvFolder, &QTreeView::customContextMenuRequested, this, &FileManagementDialogWidget::folderContextMenuRequested); - - m_ui->widgetFiles->setContextMenuPolicy(Qt::CustomContextMenu); - connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::customContextMenuRequested, this, &FileManagementDialogWidget::fileContextMenuRequested); - } + if (m_dialogMode == FileDialogMode::OpenFile || m_dialogMode == FileDialogMode::SaveFile) + { + DEBUG_LOG(m_logger) << "Init dialog for open/save modal dialog"; - m_actionAddFolder = new QAction(QIcon(QLatin1String("icon:add.svg")), tr("Add Folder"), this); - connect(m_actionAddFolder, &QAction::triggered, this, &FileManagementDialogWidget::onAddFolder); + connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &FileManagementDialogWidget::onSelectFile); + } + else + { + if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) + { - m_actionRenameFolder = new QAction(QIcon(QLatin1String("icon:edit.svg")), tr("Rename Folder"), this); - connect(m_actionRenameFolder, &QAction::triggered, this, &FileManagementDialogWidget::onEditFolder); + connect(m_ui->tvFolder, &QTreeView::doubleClicked, this, &FileManagementDialogWidget::onEditFolder); - m_actionRemoveFolder = new QAction(QIcon(QLatin1String("icon:remove.svg")), tr("Remove Folder"), this); - connect(m_actionRemoveFolder, &QAction::triggered, this, &FileManagementDialogWidget::onRemoveFolder); + connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalDoubleClicked, this, + &FileManagementDialogWidget::onEditFile); + } - m_actionRefreshFolders = new QAction(QIcon(QLatin1String("icon:restart.svg")), tr("Refresh Folders"), this); - connect(m_actionRefreshFolders, &QAction::triggered, this, &FileManagementDialogWidget::onRefreshFolders); + m_ui->tvFolder->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->tvFolder, &QTreeView::customContextMenuRequested, this, + &FileManagementDialogWidget::folderContextMenuRequested); - m_actionCopyFolder = new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy Folder"), this); - connect(m_actionCopyFolder, &QAction::triggered, this, &FileManagementDialogWidget::onCopyFolder); + m_ui->widgetFiles->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::customContextMenuRequested, this, + &FileManagementDialogWidget::fileContextMenuRequested); + } - m_actionCutFolder = new QAction(QIcon(QLatin1String("icon:edit-cut.svg")), tr("Cut Folder"), this); - connect(m_actionCutFolder, &QAction::triggered, this, &FileManagementDialogWidget::onCutFolder); + m_actionAddFolder = new QAction(QIcon(QLatin1String("icon:add.svg")), tr("Add Folder"), this); + connect(m_actionAddFolder, &QAction::triggered, this, &FileManagementDialogWidget::onAddFolder); - m_actionPasteFolder = new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste Folder"), this); - connect(m_actionPasteFolder, &QAction::triggered, this, &FileManagementDialogWidget::onPasteFolder); + m_actionRenameFolder = new QAction(QIcon(QLatin1String("icon:edit.svg")), tr("Rename Folder"), this); + connect(m_actionRenameFolder, &QAction::triggered, this, &FileManagementDialogWidget::onEditFolder); - m_actionImportFile = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("Import File"), this); - connect(m_actionImportFile, &QAction::triggered, this, &FileManagementDialogWidget::onImportFile); + m_actionRemoveFolder = new QAction(QIcon(QLatin1String("icon:remove.svg")), tr("Remove Folder"), this); + connect(m_actionRemoveFolder, &QAction::triggered, this, &FileManagementDialogWidget::onRemoveFolder); - m_actionNewOfficeExcel = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New Excel File"), this); - connect(m_actionNewOfficeExcel, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficeExcel); + m_actionRefreshFolders = new QAction(QIcon(QLatin1String("icon:restart.svg")), tr("Refresh Folders"), this); + connect(m_actionRefreshFolders, &QAction::triggered, this, &FileManagementDialogWidget::onRefreshFolders); - m_actionNewOfficeWord = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New Word File"), this); - connect(m_actionNewOfficeWord, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficeWord); + m_actionCopyFolder = new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy Folder"), this); + connect(m_actionCopyFolder, &QAction::triggered, this, &FileManagementDialogWidget::onCopyFolder); - m_actionNewOfficePowerPoint = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New PowerPoint File"), this); - connect(m_actionNewOfficePowerPoint, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficePowerPoint); + m_actionCutFolder = new QAction(QIcon(QLatin1String("icon:edit-cut.svg")), tr("Cut Folder"), this); + connect(m_actionCutFolder, &QAction::triggered, this, &FileManagementDialogWidget::onCutFolder); - m_actionNewLibreOfficeWrite = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Writer File"), this); - connect(m_actionNewLibreOfficeWrite, &QAction::triggered, this, &FileManagementDialogWidget::onNewLibreOfficeWrite); + m_actionPasteFolder = new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste Folder"), this); + connect(m_actionPasteFolder, &QAction::triggered, this, &FileManagementDialogWidget::onPasteFolder); - m_actionNewLibreOfficeCalc = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Calc File"), this); - connect(m_actionNewLibreOfficeCalc, &QAction::triggered, this, &FileManagementDialogWidget::onNewLibreOfficeCalc); + m_actionImportFile = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("Import File"), this); + connect(m_actionImportFile, &QAction::triggered, this, &FileManagementDialogWidget::onImportFile); - m_actionNewLibreOfficePresent = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Impress File"), this); - connect(m_actionNewLibreOfficePresent, &QAction::triggered, this, &FileManagementDialogWidget::onNewLibreOfficePresent); + m_actionNewOfficeExcel = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New Excel File"), this); + connect(m_actionNewOfficeExcel, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficeExcel); - m_actionNewFromTemplate = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New from Template"), this); - connect(m_actionNewFromTemplate, &QAction::triggered, this, &FileManagementDialogWidget::onNewFileFromTemplate); + m_actionNewOfficeWord = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New Word File"), this); + connect(m_actionNewOfficeWord, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficeWord); + m_actionNewOfficePowerPoint = + new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New PowerPoint File"), this); + connect(m_actionNewOfficePowerPoint, &QAction::triggered, this, &FileManagementDialogWidget::onNewOfficePowerPoint); - m_actionEditFile = new QAction(QIcon(QLatin1String("icon:document-edit.svg")), tr("Edit Properties"), this); - connect(m_actionEditFile, &QAction::triggered, this, &FileManagementDialogWidget::onEditFile); + m_actionNewLibreOfficeWrite = + new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Writer File"), this); + connect(m_actionNewLibreOfficeWrite, &QAction::triggered, this, &FileManagementDialogWidget::onNewLibreOfficeWrite); - m_actionDeleteFile = new QAction(QIcon(QLatin1String("icon:document-remove.svg")), tr("Delete File"), this); - connect(m_actionDeleteFile, &QAction::triggered, this, &FileManagementDialogWidget::onDeleteFile); + m_actionNewLibreOfficeCalc = + new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Calc File"), this); + connect(m_actionNewLibreOfficeCalc, &QAction::triggered, this, &FileManagementDialogWidget::onNewLibreOfficeCalc); - m_actionPreviewFile = new QAction(QIcon(QLatin1String("icon:document-preview.svg")), tr("Preview File"), this); - connect(m_actionPreviewFile, &QAction::triggered, this, &FileManagementDialogWidget::onPreviewFile); + m_actionNewLibreOfficePresent = + new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New LibreOffice-Impress File"), this); + connect(m_actionNewLibreOfficePresent, &QAction::triggered, this, + &FileManagementDialogWidget::onNewLibreOfficePresent); - m_actionCopyFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy File"), this); - connect(m_actionCopyFile, &QAction::triggered, this, &FileManagementDialogWidget::onCopyFile); + m_actionNewFromTemplate = new QAction(QIcon(QLatin1String("icon:document-new.svg")), tr("New from Template"), this); + connect(m_actionNewFromTemplate, &QAction::triggered, this, &FileManagementDialogWidget::onNewFileFromTemplate); - m_actionCutFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-cut.png")), tr("Cut File"), this); - connect(m_actionCutFile, &QAction::triggered, this, &FileManagementDialogWidget::onCutFile); + m_actionEditFile = new QAction(QIcon(QLatin1String("icon:document-edit.svg")), tr("Edit Properties"), this); + connect(m_actionEditFile, &QAction::triggered, this, &FileManagementDialogWidget::onEditFile); - m_actionPasteFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste File"), this); - connect(m_actionPasteFile, &QAction::triggered, this, &FileManagementDialogWidget::onPasteFile); + m_actionDeleteFile = new QAction(QIcon(QLatin1String("icon:document-remove.svg")), tr("Delete File"), this); + connect(m_actionDeleteFile, &QAction::triggered, this, &FileManagementDialogWidget::onDeleteFile); - m_actionExportFile = new QAction(QIcon(QLatin1String(":icons/16x16/document-save.png")), tr("Export File"), this); - connect(m_actionExportFile, &QAction::triggered, this, &FileManagementDialogWidget::onExportFile); + m_actionPreviewFile = new QAction(QIcon(QLatin1String("icon:document-preview.svg")), tr("Preview File"), this); + connect(m_actionPreviewFile, &QAction::triggered, this, &FileManagementDialogWidget::onPreviewFile); - m_actionRemoveFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("Remove File"), this); - connect(m_actionRemoveFile, &QAction::triggered, this, &FileManagementDialogWidget::onRemoveFile); + m_actionCopyFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-copy.png")), tr("Copy File"), this); + connect(m_actionCopyFile, &QAction::triggered, this, &FileManagementDialogWidget::onCopyFile); - m_actionRestoreFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-undo.png")), tr("Restore File"), this); - connect(m_actionRestoreFile, &QAction::triggered, this, &FileManagementDialogWidget::onRestoreFile); + m_actionCutFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-cut.png")), tr("Cut File"), this); + connect(m_actionCutFile, &QAction::triggered, this, &FileManagementDialogWidget::onCutFile); - - QItemSelectionModel *selectionModelFolder = m_ui->tvFolder->selectionModel(); - connect(selectionModelFolder, &QItemSelectionModel::selectionChanged, this, &FileManagementDialogWidget::onFolderSelectionChanged); + m_actionPasteFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-paste.png")), tr("Paste File"), this); + connect(m_actionPasteFile, &QAction::triggered, this, &FileManagementDialogWidget::onPasteFile); - - selectFolder(); + m_actionExportFile = new QAction(QIcon(QLatin1String(":icons/16x16/document-save.png")), tr("Export File"), this); + connect(m_actionExportFile, &QAction::triggered, this, &FileManagementDialogWidget::onExportFile); - - connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalSelectionChanged, this, &FileManagementDialogWidget::enaDisa); + m_actionRemoveFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-delete.png")), tr("Remove File"), this); + connect(m_actionRemoveFile, &QAction::triggered, this, &FileManagementDialogWidget::onRemoveFile); - - if (m_dialogMode == FileDialogMode::SaveFile) - { - DEBUG_LOG(m_logger) << "DialogMode Save"; - m_ui->leFile->setEnabled(true); - connect(m_ui->leFile, &QLineEdit::textChanged, this, &FileManagementDialogWidget::saveFileName); - } + m_actionRestoreFile = new QAction(QIcon(QLatin1String(":icons/16x16/edit-undo.png")), tr("Restore File"), this); + connect(m_actionRestoreFile, &QAction::triggered, this, &FileManagementDialogWidget::onRestoreFile); - if (m_fileTypes.isEmpty() || m_fileTypes.contains(FileManagement::FileType::Unknown)) - m_ui->lblFilter->setVisible(false); - else - { - QString labelFilter = tr("Filtering:") + QStringLiteral(" "); - QStringList types; - types.reserve(m_fileTypes.size()); - for (auto &ft : m_fileTypes) - types << toString(ft); - labelFilter += types.join(QStringLiteral(", ")); - labelFilter += QStringLiteral(""); - m_ui->lblFilter->setText(labelFilter); - } + QItemSelectionModel* selectionModelFolder = m_ui->tvFolder->selectionModel(); + connect(selectionModelFolder, &QItemSelectionModel::selectionChanged, this, + &FileManagementDialogWidget::onFolderSelectionChanged); - enaDisa(); + selectFolder(); - return true; + connect(m_ui->widgetFiles, &LtsDataView::LtsDataView::signalSelectionChanged, this, + &FileManagementDialogWidget::enaDisa); + + if (m_dialogMode == FileDialogMode::SaveFile) + { + DEBUG_LOG(m_logger) << "DialogMode Save"; + m_ui->leFile->setEnabled(true); + connect(m_ui->leFile, &QLineEdit::textChanged, this, &FileManagementDialogWidget::saveFileName); + } + + if (m_fileTypes.isEmpty() || m_fileTypes.contains(FileManagement::FileType::Unknown)) + m_ui->lblFilter->setVisible(false); + else + { + QString labelFilter = tr("Filtering:") + QStringLiteral(" "); + QStringList types; + types.reserve(m_fileTypes.size()); + for (auto& ft : m_fileTypes) + types << toString(ft); + labelFilter += types.join(QStringLiteral(", ")); + labelFilter += QStringLiteral(""); + m_ui->lblFilter->setText(labelFilter); + } + + enaDisa(); + + return true; } - -void FileManagementDialogWidget::saveFileName(const QString &name) +void FileManagementDialogWidget::saveFileName(const QString& name) { - DEBUG_LOG(m_logger) << "Saving: " << name; + DEBUG_LOG(m_logger) << "Saving: " << name; - m_fileName = name; - m_selectedFileContent = m_modelFile->findFileFromName(name); + m_fileName = name; + m_selectedFileContent = m_modelFile->findFileFromName(name); - emit enableButtons(); + emit enableButtons(); } - QModelIndex FileManagementDialogWidget::selectedIndexViewFolder() const { - QItemSelectionModel *selectionModel = m_ui->tvFolder->selectionModel(); - QModelIndexList indexL = selectionModel->selectedRows(0); - if (indexL.size() == 0) - return {}; - return m_proxyModelFolder->mapToSource(indexL.at(0)); + QItemSelectionModel* selectionModel = m_ui->tvFolder->selectionModel(); + QModelIndexList indexL = selectionModel->selectedRows(0); + if (indexL.size() == 0) + return {}; + return m_proxyModelFolder->mapToSource(indexL.at(0)); } - void FileManagementDialogWidget::enaDisa() { - bool userHasRightsToEditFolder; - bool userHasRightsToEditFiles; - bool userhasAdminRights = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFileAdmin); - if (userhasAdminRights) - { - userHasRightsToEditFolder = true; - userHasRightsToEditFiles = true; - } - else - { - userHasRightsToEditFolder = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFoldersEdit); - userHasRightsToEditFiles = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFilesEdit); - } - - - bool enableAddFolder = false; - bool enableEditFolder = false; - bool enableRemoveFolder = false; - - m_actionCutFolder->setEnabled(false); - m_actionPasteFolder->setEnabled(false); - m_actionCopyFolder->setEnabled(false); - - - bool enableImportFile = false; - bool enableNewFile = false; - bool enableNewFileFromTemplate = false; - bool enableEditFile = false; - bool enableDeleteFile = false; - bool enablePreviewFile = false; - bool enableExportFile = false; - bool enableRemoveFile = false; - bool enableRestoreFile = false; - bool isOffice = false; - - m_actionCutFile->setEnabled(false); - m_actionPasteFile->setEnabled(false); - m_actionCopyFile->setEnabled(false); - - QModelIndex idxFolder = selectedIndexViewFolder(); - - if (idxFolder.isValid()) - { - m_selectedFolderId = m_modelFolder->getFolder(idxFolder).id(); - - const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); - - - - - - - enableAddFolder = true; - - if (isFolderRemovable(idxFolder)) + bool userHasRightsToEditFolder; + bool userHasRightsToEditFiles; + bool userhasAdminRights = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFileAdmin); + if (userhasAdminRights) { - enableEditFolder = true; - enableRemoveFolder = true; - } - - QString folderName = m_modelFolder->getFolderName(m_modelFolder->getFolder(idxFolder)); - m_ui->lblSelectedFolder->setText(folderName); - - m_actionCopyFolder->setEnabled(true && userHasRightsToEditFolder); - m_actionCutFolder->setEnabled(enableRemoveFolder && userHasRightsToEditFolder); - if (m_copyFolder.id() > 0) - m_actionPasteFolder->setEnabled(true && userHasRightsToEditFolder); - - enableImportFile = true; - enableNewFile = true; - } - else - { - m_ui->lblSelectedFolder->setText(tr("None")); - m_selectedFolderId = 0; - } - - DEBUG_LOG(m_logger) << "enableRemoveFolder=" << enableRemoveFolder; - DEBUG_LOG(m_logger) << "enableEditFolder=" << enableEditFolder; - DEBUG_LOG(m_logger) << "userHasRightsToEditFolder=" << userHasRightsToEditFolder; - - m_actionAddFolder->setEnabled(enableAddFolder && userHasRightsToEditFolder); - m_actionRemoveFolder->setEnabled(enableRemoveFolder && userHasRightsToEditFolder); - m_actionRenameFolder->setEnabled(enableEditFolder && userHasRightsToEditFolder); - - m_actionRefreshFolders->setEnabled(true); - - - QModelIndex idxFile = m_ui->widgetFiles->currentIndex(); - if (idxFile.isValid()) - { - FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - enableEditFile = true; - if (data.isTemplate() || data.isUsedBy()) - enableDeleteFile = false; - else - enableDeleteFile = true; - - if (data.fileStatus() == FileManagement::FileStatus::Deleted) - { - enableDeleteFile = false; - enableRestoreFile = true; + userHasRightsToEditFolder = true; + userHasRightsToEditFiles = true; } else { + userHasRightsToEditFolder = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFoldersEdit); + userHasRightsToEditFiles = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFilesEdit); + } + + bool enableAddFolder = false; + bool enableEditFolder = false; + bool enableRemoveFolder = false; + + m_actionCutFolder->setEnabled(false); + m_actionPasteFolder->setEnabled(false); + m_actionCopyFolder->setEnabled(false); + + bool enableImportFile = false; + bool enableNewFile = false; + bool enableNewFileFromTemplate = false; + bool enableEditFile = false; + bool enableDeleteFile = false; + bool enablePreviewFile = false; + bool enableExportFile = false; + bool enableRemoveFile = false; + bool enableRestoreFile = false; + bool isOffice = false; + + m_actionCutFile->setEnabled(false); + m_actionPasteFile->setEnabled(false); + m_actionCopyFile->setEnabled(false); + + QModelIndex idxFolder = selectedIndexViewFolder(); + + if (idxFolder.isValid()) + { + m_selectedFolderId = m_modelFolder->getFolder(idxFolder).id(); + + const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); + + enableAddFolder = true; + + if (isFolderRemovable(idxFolder)) + { + enableEditFolder = true; + enableRemoveFolder = true; + } + + QString folderName = m_modelFolder->getFolderName(m_modelFolder->getFolder(idxFolder)); + m_ui->lblSelectedFolder->setText(folderName); + + m_actionCopyFolder->setEnabled(true && userHasRightsToEditFolder); + m_actionCutFolder->setEnabled(enableRemoveFolder && userHasRightsToEditFolder); + if (m_copyFolder.id() > 0) + m_actionPasteFolder->setEnabled(true && userHasRightsToEditFolder); + + enableImportFile = true; + enableNewFile = true; + } + else + { + m_ui->lblSelectedFolder->setText(tr("None")); + m_selectedFolderId = 0; + } + + DEBUG_LOG(m_logger) << "enableRemoveFolder=" << enableRemoveFolder; + DEBUG_LOG(m_logger) << "enableEditFolder=" << enableEditFolder; + DEBUG_LOG(m_logger) << "userHasRightsToEditFolder=" << userHasRightsToEditFolder; + + m_actionAddFolder->setEnabled(enableAddFolder && userHasRightsToEditFolder); + m_actionRemoveFolder->setEnabled(enableRemoveFolder && userHasRightsToEditFolder); + m_actionRenameFolder->setEnabled(enableEditFolder && userHasRightsToEditFolder); + + m_actionRefreshFolders->setEnabled(true); + + QModelIndex idxFile = m_ui->widgetFiles->currentIndex(); + if (idxFile.isValid()) + { + FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + enableEditFile = true; + if (data.isTemplate() || data.isUsedBy()) + enableDeleteFile = false; + else + enableDeleteFile = true; + + if (data.fileStatus() == FileManagement::FileStatus::Deleted) + { + enableDeleteFile = false; + enableRestoreFile = true; + } + else + { #ifndef LTS_DEBUG - if (data.fileType() != FileManagement::FileType::Xml - && data.fileType() != FileManagement::FileType::OperatorDefinedSymbol - && data.fileType() != FileManagement::FileType::OperatorFavourite - && data.fileType() != FileManagement::FileType::EvaluationSchema - && data.fileType() != FileManagement::FileType::TacticalPlan) + if (data.fileType() != FileManagement::FileType::Xml && + data.fileType() != FileManagement::FileType::OperatorDefinedSymbol && + data.fileType() != FileManagement::FileType::OperatorFavourite && + data.fileType() != FileManagement::FileType::EvaluationSchema && + data.fileType() != FileManagement::FileType::TacticalPlan) #endif - enablePreviewFile = true; - isOffice = (data.fileType() == FileManagement::FileType::OpenOfficeDocument || - data.fileType() == FileManagement::FileType::OpenOfficeSpreadsheet || - data.fileType() == FileManagement::FileType::OpenOfficePresentation || - data.fileType() == FileManagement::FileType::MSOfficeDocument || - data.fileType() == FileManagement::FileType::MSOfficeDocument97 || - data.fileType() == FileManagement::FileType::MSOfficeSpreadsheet || - data.fileType() == FileManagement::FileType::MSOfficeSpreadsheet97 || - data.fileType() == FileManagement::FileType::MSOfficePresentation || - data.fileType() == FileManagement::FileType::MSOfficePresentation97); - enableRestoreFile = false; - if (data.isTemplate()) - enableNewFileFromTemplate = true; - } - m_selectedFileContent = data; - m_fileName = QString::fromStdString(data.name()); - m_ui->leFile->setText(m_fileName); + enablePreviewFile = true; + isOffice = (data.fileType() == FileManagement::FileType::OpenOfficeDocument || + data.fileType() == FileManagement::FileType::OpenOfficeSpreadsheet || + data.fileType() == FileManagement::FileType::OpenOfficePresentation || + data.fileType() == FileManagement::FileType::MSOfficeDocument || + data.fileType() == FileManagement::FileType::MSOfficeDocument97 || + data.fileType() == FileManagement::FileType::MSOfficeSpreadsheet || + data.fileType() == FileManagement::FileType::MSOfficeSpreadsheet97 || + data.fileType() == FileManagement::FileType::MSOfficePresentation || + data.fileType() == FileManagement::FileType::MSOfficePresentation97); + enableRestoreFile = false; + if (data.isTemplate()) + enableNewFileFromTemplate = true; + } + m_selectedFileContent = data; + m_fileName = QString::fromStdString(data.name()); + m_ui->leFile->setText(m_fileName); - enableExportFile = true; - if (m_dialogMode != FileDialogMode::Admin) - { - enableRemoveFile = false; - enableRestoreFile = false; + enableExportFile = true; + if (m_dialogMode != FileDialogMode::Admin) + { + enableRemoveFile = false; + enableRestoreFile = false; + } + else + { + if (data.isTemplate() || data.isUsedBy()) + enableRemoveFile = false; + else + enableRemoveFile = true; + } } else { - if (data.isTemplate() || data.isUsedBy()) - enableRemoveFile = false; - else - enableRemoveFile = true; + enableExportFile = false; + m_selectedFileContent = FileManagement::FileContent(); + if (m_dialogMode != FileDialogMode::SaveFile) + { + m_fileName.clear(); + m_ui->leFile->setText(m_fileName); + } } - } - else - { - enableExportFile = false; - m_selectedFileContent = FileManagement::FileContent(); - if (m_dialogMode != FileDialogMode::SaveFile) - { - m_fileName.clear(); - m_ui->leFile->setText(m_fileName); - } - } - m_actionImportFile->setEnabled(enableImportFile && userHasRightsToEditFiles); - m_actionNewOfficeWord->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewOfficeExcel->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewOfficePowerPoint->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewLibreOfficeWrite->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewLibreOfficeCalc->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewLibreOfficePresent->setEnabled(enableNewFile && userHasRightsToEditFiles); - m_actionNewFromTemplate->setEnabled(enableNewFileFromTemplate && userHasRightsToEditFiles); - m_actionEditFile->setEnabled(enableEditFile && userHasRightsToEditFiles); - m_actionDeleteFile->setEnabled(enableDeleteFile && userHasRightsToEditFiles); + m_actionImportFile->setEnabled(enableImportFile && userHasRightsToEditFiles); + m_actionNewOfficeWord->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewOfficeExcel->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewOfficePowerPoint->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewLibreOfficeWrite->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewLibreOfficeCalc->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewLibreOfficePresent->setEnabled(enableNewFile && userHasRightsToEditFiles); + m_actionNewFromTemplate->setEnabled(enableNewFileFromTemplate && userHasRightsToEditFiles); + m_actionEditFile->setEnabled(enableEditFile && userHasRightsToEditFiles); + m_actionDeleteFile->setEnabled(enableDeleteFile && userHasRightsToEditFiles); - m_actionPreviewFile->setData(QVariant(isOffice)); - m_actionPreviewFile->setEnabled(enablePreviewFile); + m_actionPreviewFile->setData(QVariant(isOffice)); + m_actionPreviewFile->setEnabled(enablePreviewFile); - m_actionExportFile->setEnabled(enableExportFile && userHasRightsToEditFiles); - m_actionRemoveFile->setEnabled(enableRemoveFile && userhasAdminRights); - m_actionRestoreFile->setEnabled(enableRestoreFile && userhasAdminRights); + m_actionExportFile->setEnabled(enableExportFile && userHasRightsToEditFiles); + m_actionRemoveFile->setEnabled(enableRemoveFile && userhasAdminRights); + m_actionRestoreFile->setEnabled(enableRestoreFile && userhasAdminRights); - m_actionCopyFile->setEnabled(enableEditFile && userHasRightsToEditFiles); - m_actionCutFile->setEnabled(enableDeleteFile && userHasRightsToEditFiles); - if (m_copyFile.id() > 0) - m_actionPasteFile->setEnabled(true && userHasRightsToEditFiles); - - emit enableButtons(); + m_actionCopyFile->setEnabled(enableEditFile && userHasRightsToEditFiles); + m_actionCutFile->setEnabled(enableDeleteFile && userHasRightsToEditFiles); + if (m_copyFile.id() > 0) + m_actionPasteFile->setEnabled(true && userHasRightsToEditFiles); + emit enableButtons(); } - -bool FileManagementDialogWidget::isFolderRemovable(const QModelIndex &idx) const +bool FileManagementDialogWidget::isFolderRemovable(const QModelIndex& idx) const { - DEBUG_LOG(m_logger) << "isFolderRemovable index = " << idx.row(); + DEBUG_LOG(m_logger) << "isFolderRemovable index = " << idx.row(); - if (!idx.isValid()) - return false; + if (!idx.isValid()) + return false; - if (!m_modelFolder->isRowRemovable(m_modelFolder->privateData(idx))) - return false; + if (!m_modelFolder->isRowRemovable(m_modelFolder->privateData(idx))) + return false; - - if (m_modelFolder->privateData(idx)->data().value().id() == FileManagement::MainFolder::GlobalDocuments || - m_modelFolder->privateData(idx)->data().value().id() == FileManagement::MainFolder::ExerciseDocuments || - m_modelFolder->privateData(idx)->data().value().id() == FileManagement::MainFolder::UserDocuments) - return false; + if (m_modelFolder->privateData(idx)->data().value().id() == + FileManagement::MainFolder::GlobalDocuments || + m_modelFolder->privateData(idx)->data().value().id() == + FileManagement::MainFolder::ExerciseDocuments || + m_modelFolder->privateData(idx)->data().value().id() == + FileManagement::MainFolder::UserDocuments) + return false; - - int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - bool userhasAdminRights = LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFileAdmin); - if (!userhasAdminRights && opId != 99 && m_modelFolder->privateData(idx)->data().value().operatorId() != opId) - return false; + int opId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + bool userhasAdminRights = + LtsSessionData::LtsSessionData::getInstance()->hasOperatorRight(OperatorRights::FileManagementFileAdmin); + if (!userhasAdminRights && opId != 99 && + m_modelFolder->privateData(idx)->data().value().operatorId() != opId) + return false; - - const auto children = m_modelFolder->privateData(idx)->children(); - for (const auto child : children) - if (!m_modelFolder->isRowRemovable(child)) - return false; + const auto children = m_modelFolder->privateData(idx)->children(); + for (const auto child : children) + if (!m_modelFolder->isRowRemovable(child)) + return false; - return true; + return true; } - void FileManagementDialogWidget::onReject() { - m_selectedFileContent = FileManagement::FileContent(); - m_selectedFolderId = -1; + m_selectedFileContent = FileManagement::FileContent(); + m_selectedFolderId = -1; } - void FileManagementDialogWidget::onAddFolder() { - DEBUG_LOG(m_logger) << "onAddFolder"; + DEBUG_LOG(m_logger) << "onAddFolder"; - QModelIndex selIndex = selectedIndexViewFolder(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexViewFolder(); + if (!selIndex.isValid()) + return; - if (m_selectedFolderId > 0) - { - FolderEditDialog *dialog = new FolderEditDialog(this); - if (!dialog->init(selIndex, 0, m_selectedFolderId, m_dtc, m_ftc, m_isAdminMode)) + if (m_selectedFolderId > 0) { - delete dialog; - return; + FolderEditDialog* dialog = new FolderEditDialog(this); + if (!dialog->init(selIndex, 0, m_selectedFolderId, m_dtc, m_ftc, m_isAdminMode)) + { + delete dialog; + return; + } + + QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); + + dialog->show(); } - - QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); - - dialog->show(); - - } } - void FileManagementDialogWidget::onPasteFolder() { - DEBUG_LOG(m_logger) << "onPasteFolder"; + DEBUG_LOG(m_logger) << "onPasteFolder"; - QModelIndex selIndex = selectedIndexViewFolder(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexViewFolder(); + if (!selIndex.isValid()) + return; - if (m_selectedFolderId > 0) - { - FolderEditDialog *dialog = new FolderEditDialog(this); - if (!dialog->init(selIndex, 0, m_selectedFolderId, m_dtc, m_ftc, m_isAdminMode, m_copyFolder)) + if (m_selectedFolderId > 0) { - delete dialog; - return; + FolderEditDialog* dialog = new FolderEditDialog(this); + if (!dialog->init(selIndex, 0, m_selectedFolderId, m_dtc, m_ftc, m_isAdminMode, m_copyFolder)) + { + delete dialog; + return; + } + + QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); + dialog->show(); } - - QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); - dialog->show(); - } } - void FileManagementDialogWidget::onPasteFile() { - DEBUG_LOG(m_logger) << "onPasteFile"; + DEBUG_LOG(m_logger) << "onPasteFile"; - if (m_selectedFolderId > 0 && m_copyFile.id() > 0) - { - m_copyFile.id(0); - if (m_selectedFolderId == m_copyFile.folderId() && m_copyFile.name() == m_selectedFileContent.name()) + if (m_selectedFolderId > 0 && m_copyFile.id() > 0) { - QString newName = QString::fromStdString(m_copyFile.name()) + tr(" (Copy)"); - m_copyFile.name(newName.toStdString()); - } - m_copyFile.folderId(m_selectedFolderId); - - - int exId = 0; - int phId = 0; - m_copyFile.exerciseId(); - m_copyFile.phaseId(); - - - const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); - - if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) - m_copyFile.fileCategory(FileManagement::FileCategory::User); - else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) - { - m_copyFile.fileCategory(FileManagement::FileCategory::Exercise); - - if (fldPath.size() >= 2) - { - exId = m_dtc->getExerciseId(fldPath.at(1)); - if (exId > 0 && fldPath.size() >= 4) - phId = m_dtc->getExerciseId(fldPath.at(3)); - } - else - { - if (m_session->exerciseId() > 0) + m_copyFile.id(0); + if (m_selectedFolderId == m_copyFile.folderId() && m_copyFile.name() == m_selectedFileContent.name()) { - exId = m_session->exerciseId(); - if (m_session->exerciseData()->phId > 0) - phId = m_session->exerciseData()->phId; + QString newName = QString::fromStdString(m_copyFile.name()) + tr(" (Copy)"); + m_copyFile.name(newName.toStdString()); } - } + m_copyFile.folderId(m_selectedFolderId); - if (exId > 0) - m_copyFile.exerciseId(exId); - if (phId > 0) - m_copyFile.phaseId(phId); + int exId = 0; + int phId = 0; + m_copyFile.exerciseId(); + m_copyFile.phaseId(); + const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); + + if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) + m_copyFile.fileCategory(FileManagement::FileCategory::User); + else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) + { + m_copyFile.fileCategory(FileManagement::FileCategory::Exercise); + + if (fldPath.size() >= 2) + { + exId = m_dtc->getExerciseId(fldPath.at(1)); + if (exId > 0 && fldPath.size() >= 4) + phId = m_dtc->getExerciseId(fldPath.at(3)); + } + else + { + if (m_session->exerciseId() > 0) + { + exId = m_session->exerciseId(); + if (m_session->exerciseData()->phId > 0) + phId = m_session->exerciseData()->phId; + } + } + + if (exId > 0) + m_copyFile.exerciseId(exId); + if (phId > 0) + m_copyFile.phaseId(phId); + } + else + m_copyFile.fileCategory(FileManagement::FileCategory::Global); + + FileContentEditDialog* dialog = new FileContentEditDialog(this); + QString folderName = m_modelFolder->getFolderName(m_dtc->folder(m_selectedFolderId)); + + if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, m_copyFile, m_content)) + { + delete dialog; + return; + } + + QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); + + dialog->show(); } - else - m_copyFile.fileCategory(FileManagement::FileCategory::Global); - - FileContentEditDialog *dialog = new FileContentEditDialog(this); - QString folderName = m_modelFolder->getFolderName(m_dtc->folder(m_selectedFolderId)); - - if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, m_copyFile, m_content)) - { - delete dialog; - return; - } - - QObject::connect(dialog, &FolderEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); - - dialog->show(); - } } - - void FileManagementDialogWidget::onRemoveFolder() { - DEBUG_LOG(m_logger) << "onRemoveFolder id = " << m_selectedFolderId; + DEBUG_LOG(m_logger) << "onRemoveFolder id = " << m_selectedFolderId; - QModelIndex selIndex = selectedIndexViewFolder(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexViewFolder(); + if (!selIndex.isValid()) + return; - if (LtsWidgets::LtsMessageDialog::showMessage(this, tr("Yes - remove folder, subfolders and all files contained.
" - "No - do not remove folder.
"), - tr("Do you really want to remove folder and all files contained?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - { - return; - } - - - if (isFolderRemovable(selIndex)) - { - DEBUG_LOG(m_logger) << "Removing folder id = " << m_selectedFolderId; - - Core::RemoveElementRequest req(m_selectedFolderId); - m_requestHelper->startSingleRequest([req, this]() + if (LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Yes - remove folder, subfolders and all files contained.
" + "No - do not remove folder.
"), + tr("Do you really want to remove folder and all files contained?"), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) { - return m_ftc->folderRemoveRequest(req, this); - }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to remove folder id = " << m_selectedFolderId; - } -} + return; + } + if (isFolderRemovable(selIndex)) + { + DEBUG_LOG(m_logger) << "Removing folder id = " << m_selectedFolderId; + + Core::RemoveElementRequest req(m_selectedFolderId); + m_requestHelper->startSingleRequest([req, this]() { return m_ftc->folderRemoveRequest(req, this); }); + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to remove folder id = " << m_selectedFolderId; + } +} void FileManagementDialogWidget::removeCurrentRowFolder() { - DEBUG_LOG(m_logger) << "removeCurrentRowFolder"; + DEBUG_LOG(m_logger) << "removeCurrentRowFolder"; - QModelIndex selIndex = selectedIndexViewFolder(); - NGLTreeItem *item = m_modelFolder->privateData(selIndex); - FileManagement::Folder fld = item->data().value(); - bool isRootFolder = (fld.id() == 0); + QModelIndex selIndex = selectedIndexViewFolder(); + NGLTreeItem* item = m_modelFolder->privateData(selIndex); + FileManagement::Folder fld = item->data().value(); + bool isRootFolder = (fld.id() == 0); - DEBUG_LOG(m_logger) << "isRootFolder = " << isRootFolder; + DEBUG_LOG(m_logger) << "isRootFolder = " << isRootFolder; - if (!selIndex.isValid() || isRootFolder) - return; + if (!selIndex.isValid() || isRootFolder) + return; - m_modelFolder->onDeleteRow(selIndex, true); + m_modelFolder->onDeleteRow(selIndex, true); } - -QString FileManagementDialogWidget::getTemplateFile(const QString &fileName) +QString FileManagementDialogWidget::getTemplateFile(const QString& fileName) { - return NGL::findFile(NGL::FileType::ConfigFile, fileName); + return NGL::findFile(NGL::FileType::ConfigFile, fileName); } - void FileManagementDialogWidget::onRefreshFolders() { - DEBUG_LOG(m_logger) << "onRefreshFolders"; + DEBUG_LOG(m_logger) << "onRefreshFolders"; - m_modelFolder->initModel(m_session->exerciseId(), m_isAdminMode); - m_ui->tvFolder->expandAll(); - m_ui->tvFolder->selectionModel()->clearSelection(); + m_modelFolder->initModel(m_session->exerciseId(), m_isAdminMode); + m_ui->tvFolder->expandAll(); + m_ui->tvFolder->selectionModel()->clearSelection(); - enaDisa(); + enaDisa(); } - void FileManagementDialogWidget::onCopyFolder() { - DEBUG_LOG(m_logger) << "onCopyFolder"; + DEBUG_LOG(m_logger) << "onCopyFolder"; - QModelIndex selIndex = selectedIndexViewFolder(); - NGLTreeItem *item = m_modelFolder->privateData(selIndex); - m_copyFolder = item->data().value(); - m_copyFolder.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + QModelIndex selIndex = selectedIndexViewFolder(); + NGLTreeItem* item = m_modelFolder->privateData(selIndex); + m_copyFolder = item->data().value(); + m_copyFolder.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - enaDisa(); + enaDisa(); } - void FileManagementDialogWidget::onCopyFile() { - DEBUG_LOG(m_logger) << "onCopyFile"; + DEBUG_LOG(m_logger) << "onCopyFile"; - m_copyFile = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + m_copyFile = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - m_getContent->getContent(m_copyFile.id(), m_content); + m_getContent->getContent(m_copyFile.id(), m_content); - enaDisa(); + enaDisa(); } - void FileManagementDialogWidget::onCutFolder() { - DEBUG_LOG(m_logger) << "onCutFolder"; + DEBUG_LOG(m_logger) << "onCutFolder"; - QModelIndex selIndex = selectedIndexViewFolder(); - NGLTreeItem *item = m_modelFolder->privateData(selIndex); - m_copyFolder = item->data().value(); + QModelIndex selIndex = selectedIndexViewFolder(); + NGLTreeItem* item = m_modelFolder->privateData(selIndex); + m_copyFolder = item->data().value(); - - onRemoveFolder(); + onRemoveFolder(); - enaDisa(); + enaDisa(); } - void FileManagementDialogWidget::onCutFile() { - DEBUG_LOG(m_logger) << "onCutFile"; + DEBUG_LOG(m_logger) << "onCutFile"; - m_copyFile = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + m_copyFile = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - m_getContent->getContent(m_copyFile.id(), m_content); + m_getContent->getContent(m_copyFile.id(), m_content); - onDeleteFile(); + onDeleteFile(); - enaDisa(); + enaDisa(); } - void FileManagementDialogWidget::onEditFolder() { - DEBUG_LOG(m_logger) << "onEditFolder Id = " << m_selectedFolderId; + DEBUG_LOG(m_logger) << "onEditFolder Id = " << m_selectedFolderId; - if (!m_actionRenameFolder->isEnabled()) - return; + if (!m_actionRenameFolder->isEnabled()) + return; - QModelIndex selIndex = selectedIndexViewFolder(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = selectedIndexViewFolder(); + if (!selIndex.isValid()) + return; - if (m_selectedFolderId > 0) - { - FileManagement::Folder data = m_modelFolder->privateData(selIndex)->data().value(); - - FolderEditDialog *dialog = new FolderEditDialog(this); - if (!dialog->init(selIndex, m_selectedFolderId, 0, m_dtc, m_ftc, m_isAdminMode, data)) + if (m_selectedFolderId > 0) { - delete dialog; - return; + FileManagement::Folder data = m_modelFolder->privateData(selIndex)->data().value(); + + FolderEditDialog* dialog = new FolderEditDialog(this); + if (!dialog->init(selIndex, m_selectedFolderId, 0, m_dtc, m_ftc, m_isAdminMode, data)) + { + delete dialog; + return; + } + + dialog->setAttribute(Qt::WA_DeleteOnClose); + + dialog->show(); } - - dialog->setAttribute(Qt::WA_DeleteOnClose); - - dialog->show(); - } } - void FileManagementDialogWidget::onRemoveFile() { - const QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - return; + const QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (!selIndex.isValid()) + return; - if (LtsWidgets::LtsMessageDialog::showMessage(this, tr("Yes - remove file.
" - "No - do not remove file.
"), - tr("Do you really want to remove this file?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) - { - return; - } + if (LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Yes - remove file.
" + "No - do not remove file.
"), + tr("Do you really want to remove this file?"), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) + { + return; + } - DEBUG_LOG(m_logger) << "onRemoveFile"; + DEBUG_LOG(m_logger) << "onRemoveFile"; - FileManagement::FileContent data = m_modelFile->getRowData(selIndex.row()); - Core::RemoveElementRequest req(data.id()); - m_requestHelper->startSingleRequest([req, this]() - { - return m_ftc->fileContentRemoveRequest(req, this); - }); + FileManagement::FileContent data = m_modelFile->getRowData(selIndex.row()); + Core::RemoveElementRequest req(data.id()); + m_requestHelper->startSingleRequest([req, this]() { return m_ftc->fileContentRemoveRequest(req, this); }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to remove file content"; - else - reInitModelFile(); + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to remove file content"; + else + reInitModelFile(); } - void FileManagementDialogWidget::onDeleteFile() { - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (!selIndex.isValid()) + return; - DEBUG_LOG(m_logger) << "onDeleteFile"; + DEBUG_LOG(m_logger) << "onDeleteFile"; - m_requestHelper->startSingleRequest([this]() - { - FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + m_requestHelper->startSingleRequest([this]() { + FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - if (data.fileStatus() == FileManagement::FileStatus::Deleted) - return int64_t(0); + if (data.fileStatus() == FileManagement::FileStatus::Deleted) + return int64_t(0); - DEBUG_LOG(m_logger) << "Deleting file id = " << data.id(); + DEBUG_LOG(m_logger) << "Deleting file id = " << data.id(); - FileManagement::FileContentChangeStatusRequest req; - req.id(data.id()); + FileManagement::FileContentChangeStatusRequest req; + req.id(data.id()); - req.fileStatus(FileManagement::FileStatus::Deleted); - req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - req.lastModified(QDateTime::currentMSecsSinceEpoch()); + req.fileStatus(FileManagement::FileStatus::Deleted); + req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + req.lastModified(QDateTime::currentMSecsSinceEpoch()); - return m_ftc->fileContentChangeStatusRequest(FileContentChangeStatusRequest(req), this); - }); + return m_ftc->fileContentChangeStatusRequest(FileContentChangeStatusRequest(req), this); + }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to change status file content"; - else - reInitModelFile(); + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to change status file content"; + else + reInitModelFile(); } - void FileManagementDialogWidget::reInitModelFile(bool restoreSelected) { - int selectedFileId = 0; - if (restoreSelected) - { - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (selIndex.isValid()) + int selectedFileId = 0; + if (restoreSelected) { - selectedFileId = m_modelFile->getRowData(selIndex.row()).id(); - ERROR_LOG(m_logger) << "Selected file id = " << selectedFileId; + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (selIndex.isValid()) + { + selectedFileId = m_modelFile->getRowData(selIndex.row()).id(); + ERROR_LOG(m_logger) << "Selected file id = " << selectedFileId; + } + } + else + { + m_ui->widgetFiles->setCurrentIndex(QModelIndex()); } - } - else - { - m_ui->widgetFiles->setCurrentIndex(QModelIndex()); - } - auto predicate = [this](const FileManagement::FileContent & fc, const QString &xmlType) - { - return showFile(fc, xmlType); - }; + auto predicate = [this](const FileManagement::FileContent& fc, const QString& xmlType) { + return showFile(fc, xmlType); + }; - m_modelFile->initModel(m_session, m_xmlType, predicate); + m_modelFile->initModel(m_session, m_xmlType, predicate); - if (restoreSelected && selectedFileId > 0) - { - DEBUG_LOG(m_logger) << "Restoring selection on file " << selectedFileId; - QModelIndex idx = m_modelFile->findIndexForId(selectedFileId); - if (idx.isValid()) - m_ui->widgetFiles->setCurrentIndex(idx); - } + if (restoreSelected && selectedFileId > 0) + { + DEBUG_LOG(m_logger) << "Restoring selection on file " << selectedFileId; + QModelIndex idx = m_modelFile->findIndexForId(selectedFileId); + if (idx.isValid()) + m_ui->widgetFiles->setCurrentIndex(idx); + } } - void FileManagementDialogWidget::onRestoreFile() { - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (!selIndex.isValid()) + return; - DEBUG_LOG(m_logger) << "onRestoreFile"; + DEBUG_LOG(m_logger) << "onRestoreFile"; - m_requestHelper->startSingleRequest([this]() - { - FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + m_requestHelper->startSingleRequest([this]() { + FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - if (data.fileStatus() == FileManagement::FileStatus::Valid) - return int64_t(0); + if (data.fileStatus() == FileManagement::FileStatus::Valid) + return int64_t(0); - DEBUG_LOG(m_logger) << "Deleting file id = " << data.id(); + DEBUG_LOG(m_logger) << "Deleting file id = " << data.id(); - FileManagement::FileContentChangeStatusRequest req; - req.id(data.id()); + FileManagement::FileContentChangeStatusRequest req; + req.id(data.id()); - req.fileStatus(FileManagement::FileStatus::Valid); - req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - req.lastModified(QDateTime::currentMSecsSinceEpoch()); + req.fileStatus(FileManagement::FileStatus::Valid); + req.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + req.lastModified(QDateTime::currentMSecsSinceEpoch()); - return m_ftc->fileContentChangeStatusRequest(FileContentChangeStatusRequest(req), this); - }); + return m_ftc->fileContentChangeStatusRequest(FileContentChangeStatusRequest(req), this); + }); - if (m_requestHelper->failed()) - ERROR_LOG(m_logger) << "Failed to change status file content"; - else - reInitModelFile(); + if (m_requestHelper->failed()) + ERROR_LOG(m_logger) << "Failed to change status file content"; + else + reInitModelFile(); } - void FileManagementDialogWidget::onEditFile() { - DEBUG_LOG(m_logger) << "onEditFileContent"; + DEBUG_LOG(m_logger) << "onEditFileContent"; - if (!m_actionEditFile->isEnabled()) - return; + if (!m_actionEditFile->isEnabled()) + return; - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - return; + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (!selIndex.isValid()) + return; - FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - DEBUG_LOG(m_logger) << "onEditFileContent Id = " << data.id(); + FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + DEBUG_LOG(m_logger) << "onEditFileContent Id = " << data.id(); - m_getContent->getContent(data.id(), m_content); + m_getContent->getContent(data.id(), m_content); - FileContentEditDialog *dialog = new FileContentEditDialog(this); - QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); + FileContentEditDialog* dialog = new FileContentEditDialog(this); + QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); - if (!dialog->init(m_session, selIndex, m_isAdminMode, folderName, data, m_content)) - { - delete dialog; - return; - } + if (!dialog->init(m_session, selIndex, m_isAdminMode, folderName, data, m_content)) + { + delete dialog; + return; + } - dialog->setAttribute(Qt::WA_DeleteOnClose); + dialog->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); + QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FolderEditDialog::deleteLater); - dialog->show(); + dialog->show(); } - void FileManagementDialogWidget::onImportFile() { - DEBUG_LOG(m_logger) << "onImportFile"; + DEBUG_LOG(m_logger) << "onImportFile"; - - const QStringList filter( - { - tr("PDF Files (*.pdf)"), - tr("Images (*.jpg *.jpeg *.png)"), - tr("XML Files (*.xml)"), - tr("TXT Files (*.txt)"), - tr("MSOffice Word Documents (*.doc *.dot *.docx *dotx *.docm *.dotm)"), - tr("MSOffice Excel Documents (*.xls *.xlt *.xlm *.xlsx *.xlst *.xltm *.xltx)"), - tr("MSOffice PowerPoint Documents (*.ppt *.pot *.pps *.pptx *.pptm *.potx *.potm)"), - tr("OpenOffice Documents (*.odt *.ods *.odp)"), + const QStringList filter({tr("PDF Files (*.pdf)"), tr("Images (*.jpg *.jpeg *.png)"), tr("XML Files (*.xml)"), + tr("TXT Files (*.txt)"), + tr("MSOffice Word Documents (*.doc *.dot *.docx *dotx *.docm *.dotm)"), + tr("MSOffice Excel Documents (*.xls *.xlt *.xlm *.xlsx *.xlst *.xltm *.xltx)"), + tr("MSOffice PowerPoint Documents (*.ppt *.pot *.pps *.pptx *.pptm *.potx *.potm)"), + tr("OpenOffice Documents (*.odt *.ods *.odp)"), #ifdef Q_OS_WIN - tr("All (*.*)") + tr("All (*.*)") #else - tr("All (*)") + tr("All (*)") #endif - }); - - static QString defaultPath = QDir::homePath() + QStringLiteral("/scanner/"); - QString fileName = QFileDialog::getOpenFileName(this, - tr("Load file to library"), - defaultPath, - filter.join(QStringLiteral(";;"))); - if (fileName.isEmpty()) - return; + }); - QFileInfo fileInfo(fileName); - if (!fileInfo.isReadable()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" - "The loaded file is not readable.")); - return; - } + static QString defaultPath = QDir::homePath() + QStringLiteral("/scanner/"); + QString fileName = + QFileDialog::getOpenFileName(this, tr("Load file to library"), defaultPath, filter.join(QStringLiteral(";;"))); + if (fileName.isEmpty()) + return; - defaultPath = fileInfo.path(); - QString fileExt = fileInfo.suffix(); - - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly)) - { - ERROR_LOG(m_logger) << "Cannot read file " << fileName; - return; - } - QByteArray fileContent = file.readAll(); - - - FileManagement::FileContent data = FileContent(); - data.folderId(m_selectedFolderId); - data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - data.name(fileInfo.baseName().toStdString()); - data.fileStatus(FileManagement::FileStatus::Valid); - - int exId = 0; - int phId = 0; - if (m_session->exerciseId() > 0) - { - exId = m_session->exerciseId(); - if (m_session->exerciseData()->phId > 0) - phId = m_session->exerciseData()->phId; - } - - const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); - if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) - data.fileCategory(FileManagement::FileCategory::User); - else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) - { - data.fileCategory(FileManagement::FileCategory::Exercise); - if (fldPath.size() >= 2) + QFileInfo fileInfo(fileName); + if (!fileInfo.isReadable()) { - exId = m_dtc->getExerciseId(fldPath.at(1)); - if (exId > 0 && fldPath.size() >= 4) - phId = m_dtc->getExerciseId(fldPath.at(3)); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" + "The loaded file is not readable.")); + return; } - } - else - { - data.fileCategory(FileManagement::FileCategory::Global); - exId = 0; - phId = 0; - } - DEBUG_LOG(m_logger) << "Exercise id = " << exId << ", phase Id = " << phId; + defaultPath = fileInfo.path(); + QString fileExt = fileInfo.suffix(); - if (exId > 0) - data.exerciseId(exId); - if (phId > 0) - data.phaseId(phId); + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly)) + { + ERROR_LOG(m_logger) << "Cannot read file " << fileName; + return; + } + QByteArray fileContent = file.readAll(); - data.fileType(getFileType(fileExt)); + FileManagement::FileContent data = FileContent(); + data.folderId(m_selectedFolderId); + data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + data.name(fileInfo.baseName().toStdString()); + data.fileStatus(FileManagement::FileStatus::Valid); - - FileContentEditDialog *dialog = new FileContentEditDialog(this); - QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); + int exId = 0; + int phId = 0; + if (m_session->exerciseId() > 0) + { + exId = m_session->exerciseId(); + if (m_session->exerciseData()->phId > 0) + phId = m_session->exerciseData()->phId; + } - - if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, data, LtsUtils::convert>(fileContent))) - { - delete dialog; - return; - } + const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); + if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) + data.fileCategory(FileManagement::FileCategory::User); + else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) + { + data.fileCategory(FileManagement::FileCategory::Exercise); + if (fldPath.size() >= 2) + { + exId = m_dtc->getExerciseId(fldPath.at(1)); + if (exId > 0 && fldPath.size() >= 4) + phId = m_dtc->getExerciseId(fldPath.at(3)); + } + } + else + { + data.fileCategory(FileManagement::FileCategory::Global); + exId = 0; + phId = 0; + } - dialog->setAttribute(Qt::WA_DeleteOnClose); + DEBUG_LOG(m_logger) << "Exercise id = " << exId << ", phase Id = " << phId; - QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FileContentEditDialog::deleteLater); + if (exId > 0) + data.exerciseId(exId); + if (phId > 0) + data.phaseId(phId); - dialog->show(); + data.fileType(getFileType(fileExt)); + + FileContentEditDialog* dialog = new FileContentEditDialog(this); + QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); + + if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, data, + LtsUtils::convert>(fileContent))) + { + delete dialog; + return; + } + + dialog->setAttribute(Qt::WA_DeleteOnClose); + + QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FileContentEditDialog::deleteLater); + + dialog->show(); } - -void FileManagementDialogWidget::createNewOfficeFile(const QString &fileName) +void FileManagementDialogWidget::createNewOfficeFile(const QString& fileName) { - if (fileName.isEmpty()) - return; + if (fileName.isEmpty()) + return; - const QString absFilePath = getTemplateFile(fileName); - if (absFilePath.isEmpty()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" - "Can not find template file '%1'.").arg(fileName)); - return; - } - - QFileInfo fileInfo(absFilePath); - if (!fileInfo.isReadable()) - { - LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" - "The file to load is not readable (%1).").arg(absFilePath)); - return; - } - - QFile file(absFilePath); - if (!file.open(QIODevice::ReadOnly)) - { - ERROR_LOG(m_logger) << "Cannot read file " << absFilePath; - return; - } - QByteArray fileContent = file.readAll(); - - - FileManagement::FileContent data; - data.folderId(m_selectedFolderId); - data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); - data.name(tr("").toStdString()); - data.fileStatus(FileManagement::FileStatus::Valid); - - int exId = 0; - int phId = 0; - if (m_session->exerciseId() > 0) - { - exId = m_session->exerciseId(); - if (m_session->exerciseData()->phId > 0) - phId = m_session->exerciseData()->phId; - } - - const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); - if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) - data.fileCategory(FileManagement::FileCategory::User); - else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) - { - data.fileCategory(FileManagement::FileCategory::Exercise); - if (fldPath.size() >= 2) + const QString absFilePath = getTemplateFile(fileName); + if (absFilePath.isEmpty()) { - exId = m_dtc->getExerciseId(fldPath.at(1)); - if (exId > 0 && fldPath.size() >= 4) - phId = m_dtc->getExerciseId(fldPath.at(3)); + LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" + "Can not find template file '%1'.") + .arg(fileName)); + return; } - } - else - { - data.fileCategory(FileManagement::FileCategory::Global); - exId = 0; - phId = 0; - } - if (exId > 0) - data.exerciseId(exId); - if (phId > 0) - data.phaseId(phId); + QFileInfo fileInfo(absFilePath); + if (!fileInfo.isReadable()) + { + LtsWidgets::LtsMessageDialog::showMessage(this, tr("An error occurred while loading the file.\n" + "The file to load is not readable (%1).") + .arg(absFilePath)); + return; + } - data.fileType(getFileType(fileInfo.suffix())); + QFile file(absFilePath); + if (!file.open(QIODevice::ReadOnly)) + { + ERROR_LOG(m_logger) << "Cannot read file " << absFilePath; + return; + } + QByteArray fileContent = file.readAll(); - - FileContentEditDialog *dialog = new FileContentEditDialog(this); - QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); + FileManagement::FileContent data; + data.folderId(m_selectedFolderId); + data.operatorId(LtsSessionData::LtsSessionData::getInstance()->getOperatorId()); + data.name(tr("").toStdString()); + data.fileStatus(FileManagement::FileStatus::Valid); + + int exId = 0; + int phId = 0; + if (m_session->exerciseId() > 0) + { + exId = m_session->exerciseId(); + if (m_session->exerciseData()->phId > 0) + phId = m_session->exerciseData()->phId; + } + + const auto fldPath = m_dtc->folder(m_selectedFolderId).path(); + if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::UserDocuments)) + data.fileCategory(FileManagement::FileCategory::User); + else if (LtsUtils::isInVector(fldPath, FileManagement::MainFolder::ExerciseDocuments)) + { + data.fileCategory(FileManagement::FileCategory::Exercise); + if (fldPath.size() >= 2) + { + exId = m_dtc->getExerciseId(fldPath.at(1)); + if (exId > 0 && fldPath.size() >= 4) + phId = m_dtc->getExerciseId(fldPath.at(3)); + } + } + else + { + data.fileCategory(FileManagement::FileCategory::Global); + exId = 0; + phId = 0; + } + + if (exId > 0) + data.exerciseId(exId); + if (phId > 0) + data.phaseId(phId); + + data.fileType(getFileType(fileInfo.suffix())); + + FileContentEditDialog* dialog = new FileContentEditDialog(this); + QString folderName = m_modelFolder->getFolderName(m_dtc->folder(data.folderId())); + + if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, data, + LtsUtils::convert>(fileContent))) + { + delete dialog; + return; + } + + dialog->setAttribute(Qt::WA_DeleteOnClose); + + QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FileContentEditDialog::deleteLater); + + dialog->show(); - - if (!dialog->init(m_session, QModelIndex(), m_isAdminMode, folderName, data, LtsUtils::convert>(fileContent))) - { - delete dialog; return; - } - - dialog->setAttribute(Qt::WA_DeleteOnClose); - - QObject::connect(dialog, &FileContentEditDialog::rejected, dialog, &FileContentEditDialog::deleteLater); - - dialog->show(); - - - - return; - } - void FileManagementDialogWidget::onNewOfficeWord() { - createNewOfficeFile(QLatin1String("Default.docx")); + createNewOfficeFile(QLatin1String("Default.docx")); } - void FileManagementDialogWidget::onNewOfficeExcel() { - createNewOfficeFile(QLatin1String("Default.xlsx")); + createNewOfficeFile(QLatin1String("Default.xlsx")); } - void FileManagementDialogWidget::onNewOfficePowerPoint() { - createNewOfficeFile(QLatin1String("Default.pptx")); + createNewOfficeFile(QLatin1String("Default.pptx")); } - void FileManagementDialogWidget::onNewLibreOfficeWrite() { - createNewOfficeFile(QLatin1String("Default.odt")); + createNewOfficeFile(QLatin1String("Default.odt")); } - void FileManagementDialogWidget::onNewLibreOfficeCalc() { - createNewOfficeFile(QLatin1String("Default.ods")); + createNewOfficeFile(QLatin1String("Default.ods")); } - void FileManagementDialogWidget::onNewLibreOfficePresent() { - createNewOfficeFile(QLatin1String("Default.odp")); + createNewOfficeFile(QLatin1String("Default.odp")); } - void FileManagementDialogWidget::onNewFileFromTemplate() { - - onCopyFile(); - m_copyFile.isTemplate(false); - m_copyFile.isUsedBy(false); - m_copyFile.name(tr("").toStdString()); - onPasteFile(); -} + onCopyFile(); + m_copyFile.isTemplate(false); + m_copyFile.isUsedBy(false); + m_copyFile.name(tr("").toStdString()); + onPasteFile(); +} void FileManagementDialogWidget::onFolderSelectionChanged() { - DEBUG_LOG(m_logger) << "onFolderSelectionChanged"; - enaDisa(); + DEBUG_LOG(m_logger) << "onFolderSelectionChanged"; + enaDisa(); - reInitModelFile(); + reInitModelFile(); } - -void FileManagementDialogWidget::folderContextMenuRequested(const QPoint &position) +void FileManagementDialogWidget::folderContextMenuRequested(const QPoint& position) { - QModelIndex selIndex = selectedIndexViewFolder(); - if (!selIndex.isValid() || LtsSessionData::LtsSessionData::getInstance()->isTablet()) - return; - enaDisa(); + QModelIndex selIndex = selectedIndexViewFolder(); + if (!selIndex.isValid() || LtsSessionData::LtsSessionData::getInstance()->isTablet()) + return; + enaDisa(); - QMenu menu(m_ui->tvFolder); - menu.addAction(m_actionAddFolder); - menu.addAction(m_actionRenameFolder); - menu.addAction(m_actionRemoveFolder); - menu.addSeparator(); - menu.addAction(m_actionCutFolder); - menu.addAction(m_actionCopyFolder); - menu.addAction(m_actionPasteFolder); - menu.addSeparator(); - menu.addAction(m_actionRefreshFolders); - menu.addSeparator(); - menu.exec(m_ui->tvFolder->viewport()->mapToGlobal(position)); -} - - -void FileManagementDialogWidget::fileContextMenuRequested(const QPoint &position) -{ - enaDisa(); - - QMenu menu(m_ui->widgetFiles); - if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) - { - menu.addAction(m_actionImportFile); - menu.addAction(m_actionEditFile); - menu.addAction(m_actionDeleteFile); + QMenu menu(m_ui->tvFolder); + menu.addAction(m_actionAddFolder); + menu.addAction(m_actionRenameFolder); + menu.addAction(m_actionRemoveFolder); menu.addSeparator(); - } - menu.addAction(m_actionPreviewFile); - if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) - { + menu.addAction(m_actionCutFolder); + menu.addAction(m_actionCopyFolder); + menu.addAction(m_actionPasteFolder); menu.addSeparator(); - menu.addAction(m_actionCutFile); - menu.addAction(m_actionCopyFile); - menu.addAction(m_actionPasteFile); - menu.addAction(m_actionExportFile); - - if (m_dialogMode == FileDialogMode::Admin) - { - menu.addSeparator(); - menu.addAction(m_actionRemoveFile); - menu.addAction(m_actionRestoreFile); - } - + menu.addAction(m_actionRefreshFolders); menu.addSeparator(); - QMenu *newFileMenu = menu.addMenu(tr("New File")); - - const bool bUseMSOffice = LtsUtils::ProjectSettings::getInstance()->value(QStringLiteral("Office"), QStringLiteral("Type")).toString() == QStringLiteral("MSOffice"); - if (bUseMSOffice) - { - newFileMenu->addAction(m_actionNewOfficeWord); - newFileMenu->addAction(m_actionNewOfficeExcel); - newFileMenu->addAction(m_actionNewOfficePowerPoint); - } - else - { - newFileMenu->addAction(m_actionNewLibreOfficeWrite); - newFileMenu->addAction(m_actionNewLibreOfficeCalc); - newFileMenu->addAction(m_actionNewLibreOfficePresent); - } - newFileMenu->addAction(m_actionNewFromTemplate); - } - menu.exec(m_ui->widgetFiles->mapToGlobal(position)); + menu.exec(m_ui->tvFolder->viewport()->mapToGlobal(position)); } - -void FileManagementDialogWidget::onFolderChanged(const FileManagement::Folder &data, DataModification modType) +void FileManagementDialogWidget::fileContextMenuRequested(const QPoint& position) { - DEBUG_LOG(m_logger) << "onFolderChanged: folder name = " << data.name(); - + enaDisa(); - Q_UNUSED(data); - Q_UNUSED(modType); - - m_modelFolder->initModel(m_session->exerciseId(), m_isAdminMode); - m_ui->tvFolder->expandAll(); - m_ui->tvFolder->setExpanded(m_proxyModelFolder->index(0, 0), true); - - selectFolder(); -} - - -FileManagement::FileType FileManagementDialogWidget::getFileType(const QString &fileExt) -{ - FileManagement::FileType type = FileManagement::FileType::Unknown; - auto ext = fileExt.toLower().toStdString(); - if (fileExt.toLower() == QStringLiteral("jpeg")) ext = "jpg"; - std::function cb = [&type, &ext](const FileManagement::FileTypeInfo & fti) - { - if (fti.extension() == ext) + QMenu menu(m_ui->widgetFiles); + if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) { - - type = static_cast(fti.id()); - return true; + menu.addAction(m_actionImportFile); + menu.addAction(m_actionEditFile); + menu.addAction(m_actionDeleteFile); + menu.addSeparator(); } - return false; - }; - m_dtc->fileTypeInfos(cb); - return type; + menu.addAction(m_actionPreviewFile); + if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) + { + menu.addSeparator(); + menu.addAction(m_actionCutFile); + menu.addAction(m_actionCopyFile); + menu.addAction(m_actionPasteFile); + menu.addAction(m_actionExportFile); + + if (m_dialogMode == FileDialogMode::Admin) + { + menu.addSeparator(); + menu.addAction(m_actionRemoveFile); + menu.addAction(m_actionRestoreFile); + } + + menu.addSeparator(); + QMenu* newFileMenu = menu.addMenu(tr("New File")); + + const bool bUseMSOffice = LtsUtils::ProjectSettings::getInstance() + ->value(QStringLiteral("Office"), QStringLiteral("Type")) + .toString() == QStringLiteral("MSOffice"); + if (bUseMSOffice) + { + newFileMenu->addAction(m_actionNewOfficeWord); + newFileMenu->addAction(m_actionNewOfficeExcel); + newFileMenu->addAction(m_actionNewOfficePowerPoint); + } + else + { + newFileMenu->addAction(m_actionNewLibreOfficeWrite); + newFileMenu->addAction(m_actionNewLibreOfficeCalc); + newFileMenu->addAction(m_actionNewLibreOfficePresent); + } + newFileMenu->addAction(m_actionNewFromTemplate); + } + menu.exec(m_ui->widgetFiles->mapToGlobal(position)); } +void FileManagementDialogWidget::onFolderChanged(const FileManagement::Folder& data, DataModification modType) +{ + DEBUG_LOG(m_logger) << "onFolderChanged: folder name = " << data.name(); + + Q_UNUSED(data); + Q_UNUSED(modType); + + m_modelFolder->initModel(m_session->exerciseId(), m_isAdminMode); + m_ui->tvFolder->expandAll(); + m_ui->tvFolder->setExpanded(m_proxyModelFolder->index(0, 0), true); + + selectFolder(); +} + +FileManagement::FileType FileManagementDialogWidget::getFileType(const QString& fileExt) +{ + FileManagement::FileType type = FileManagement::FileType::Unknown; + auto ext = fileExt.toLower().toStdString(); + if (fileExt.toLower() == QStringLiteral("jpeg")) + ext = "jpg"; + std::function cb = [&type, + &ext](const FileManagement::FileTypeInfo& fti) { + if (fti.extension() == ext) + { + + type = static_cast(fti.id()); + return true; + } + return false; + }; + m_dtc->fileTypeInfos(cb); + return type; +} void FileManagementDialogWidget::onPreviewFile() { - DEBUG_LOG(m_logger) << "onPreviewFile"; + DEBUG_LOG(m_logger) << "onPreviewFile"; - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - { - ERROR_LOG(m_logger) << "No valid selected file for preview!"; - return; - } - - FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); - - FileManagement::FileType ft = data.fileType(); - - switch (ft.underlying()) - { - case FileManagement::FileType::Jpg: - case FileManagement::FileType::Png: - case FileManagement::FileType::Text: - case FileManagement::FileType::Xml: - case FileManagement::FileType::Pdf: - case FileManagement::FileType::OperatorFavourite: - case FileManagement::FileType::TacticalPlan: - case FileManagement::FileType::EvaluationSchema: - case FileManagement::FileType::AdlerJson: - { - - FileContentPreviewDialog *dialog = new FileContentPreviewDialog(m_session, m_ftc, this); - if (!dialog->init(data)) + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (!selIndex.isValid()) { - delete dialog; - return; + ERROR_LOG(m_logger) << "No valid selected file for preview!"; + return; } - dialog->setAttribute(Qt::WA_DeleteOnClose); - QObject::connect(dialog, &FileContentPreviewDialog::rejected, dialog, &FolderEditDialog::deleteLater); - dialog->show(); - break; - } - case FileManagement::FileType::MSOfficeDocument: - case FileManagement::FileType::MSOfficeDocument97: - case FileManagement::FileType::MSOfficePresentation: - case FileManagement::FileType::MSOfficePresentation97: - case FileManagement::FileType::MSOfficeSpreadsheet: - case FileManagement::FileType::MSOfficeSpreadsheet97: - case FileManagement::FileType::OpenOfficeDocument: - case FileManagement::FileType::OpenOfficePresentation: - case FileManagement::FileType::OpenOfficeSpreadsheet: - { - OfficeIntegration *projWindow = new OfficeIntegration(data, this); - if (!projWindow->openOfficeWindow()) - new LtsWidgets::LtsMessageDialogNew(this, tr("Can not open Office: %1").arg(projWindow->errorString())); - break; - } - case FileManagement::FileType::OperatorDefinedSymbol: - new LtsWidgets::LtsMessageDialogNew(this, tr("Not yet implemented")); - break; - case FileManagement::FileType::Unknown: - new LtsWidgets::LtsMessageDialogNew(this, tr("Unknown file type! Preview not available.")); - break; - } + FileManagement::FileContent data = m_modelFile->getRowData(m_ui->widgetFiles->currentIndex().row()); + + FileManagement::FileType ft = data.fileType(); + + switch (ft.underlying()) + { + case FileManagement::FileType::Jpg: + case FileManagement::FileType::Png: + case FileManagement::FileType::Text: + case FileManagement::FileType::Xml: + case FileManagement::FileType::Pdf: + case FileManagement::FileType::OperatorFavourite: + case FileManagement::FileType::TacticalPlan: + case FileManagement::FileType::EvaluationSchema: + case FileManagement::FileType::AdlerJson: { + + FileContentPreviewDialog* dialog = new FileContentPreviewDialog(m_session, m_ftc, this); + if (!dialog->init(data)) + { + delete dialog; + return; + } + dialog->setAttribute(Qt::WA_DeleteOnClose); + QObject::connect(dialog, &FileContentPreviewDialog::rejected, dialog, &FolderEditDialog::deleteLater); + dialog->show(); + break; + } + case FileManagement::FileType::MSOfficeDocument: + case FileManagement::FileType::MSOfficeDocument97: + case FileManagement::FileType::MSOfficePresentation: + case FileManagement::FileType::MSOfficePresentation97: + case FileManagement::FileType::MSOfficeSpreadsheet: + case FileManagement::FileType::MSOfficeSpreadsheet97: + case FileManagement::FileType::OpenOfficeDocument: + case FileManagement::FileType::OpenOfficePresentation: + case FileManagement::FileType::OpenOfficeSpreadsheet: { + OfficeIntegration* projWindow = new OfficeIntegration(data, this); + if (!projWindow->openOfficeWindow()) + new LtsWidgets::LtsMessageDialogNew(this, tr("Can not open Office: %1").arg(projWindow->errorString())); + break; + } + case FileManagement::FileType::OperatorDefinedSymbol: + new LtsWidgets::LtsMessageDialogNew(this, tr("Not yet implemented")); + break; + case FileManagement::FileType::Unknown: + new LtsWidgets::LtsMessageDialogNew(this, tr("Unknown file type! Preview not available.")); + break; + } } + QString FileManagementDialogWidget::getFileTypeStr(FileManagement::FileType fileType) { - switch (fileType.underlying()) - { - case FileManagement::FileType::Png: - return(QStringLiteral(".png")); - case FileManagement::FileType::Jpg: - return(QStringLiteral(".jpg")); - case FileManagement::FileType::Text: - return(QStringLiteral(".txt")); - case FileManagement::FileType::EvaluationSchema: - case FileManagement::FileType::Xml: - return(QStringLiteral(".xml")); - case FileManagement::FileType::TacticalPlan: - return(QStringLiteral(".TacticalPlan")); - case FileManagement::FileType::OperatorFavourite: - return(QStringLiteral(".OperatorFavourite")); - case FileManagement::FileType::Pdf: - return(QStringLiteral(".pdf")); - case FileManagement::FileType::OperatorDefinedSymbol: - return(QStringLiteral(".OperatorDefinedSymbol")); - case FileManagement::FileType::MSOfficeDocument: - return(QStringLiteral(".docx")); - case FileManagement::FileType::MSOfficeDocument97: - return(QStringLiteral(".doc")); - case FileManagement::FileType::MSOfficePresentation: - return(QStringLiteral(".pptx")); - case FileManagement::FileType::MSOfficePresentation97: - return(QStringLiteral(".ppt")); - case FileManagement::FileType::MSOfficeSpreadsheet: - return(QStringLiteral(".xlsx")); - case FileManagement::FileType::MSOfficeSpreadsheet97: - return(QStringLiteral(".xls")); - case FileManagement::FileType::OpenOfficeDocument: - return(QStringLiteral(".odt")); - case FileManagement::FileType::OpenOfficePresentation: - return(QStringLiteral(".odp")); - case FileManagement::FileType::OpenOfficeSpreadsheet: - return(QStringLiteral(".ods")); - case FileManagement::FileType::AdlerJson: - return(QStringLiteral(".ajs")); - case FileManagement::FileType::Unknown: - return(QStringLiteral(".Unknown")); - } - return(QStringLiteral(".Unknown")); + switch (fileType.underlying()) + { + case FileManagement::FileType::Png: + return (QStringLiteral(".png")); + case FileManagement::FileType::Jpg: + return (QStringLiteral(".jpg")); + case FileManagement::FileType::Text: + return (QStringLiteral(".txt")); + case FileManagement::FileType::EvaluationSchema: + case FileManagement::FileType::Xml: + return (QStringLiteral(".xml")); + case FileManagement::FileType::TacticalPlan: + return (QStringLiteral(".TacticalPlan")); + case FileManagement::FileType::OperatorFavourite: + return (QStringLiteral(".OperatorFavourite")); + case FileManagement::FileType::Pdf: + return (QStringLiteral(".pdf")); + case FileManagement::FileType::OperatorDefinedSymbol: + return (QStringLiteral(".OperatorDefinedSymbol")); + case FileManagement::FileType::MSOfficeDocument: + return (QStringLiteral(".docx")); + case FileManagement::FileType::MSOfficeDocument97: + return (QStringLiteral(".doc")); + case FileManagement::FileType::MSOfficePresentation: + return (QStringLiteral(".pptx")); + case FileManagement::FileType::MSOfficePresentation97: + return (QStringLiteral(".ppt")); + case FileManagement::FileType::MSOfficeSpreadsheet: + return (QStringLiteral(".xlsx")); + case FileManagement::FileType::MSOfficeSpreadsheet97: + return (QStringLiteral(".xls")); + case FileManagement::FileType::OpenOfficeDocument: + return (QStringLiteral(".odt")); + case FileManagement::FileType::OpenOfficePresentation: + return (QStringLiteral(".odp")); + case FileManagement::FileType::OpenOfficeSpreadsheet: + return (QStringLiteral(".ods")); + case FileManagement::FileType::AdlerJson: + return (QStringLiteral(".ajs")); + case FileManagement::FileType::Unknown: + return (QStringLiteral(".Unknown")); + } + return (QStringLiteral(".Unknown")); } - void FileManagementDialogWidget::onExportFile() { - DEBUG_LOG(m_logger) << "onExportFile(): fileName = " << m_fileName; + DEBUG_LOG(m_logger) << "onExportFile(): fileName = " << m_fileName; - - static QString defaultPath = QDir::homePath() + QStringLiteral("/scanner/"); - DEBUG_LOG(m_logger) << "onExportFile(): old path = " << defaultPath; + static QString defaultPath = QDir::homePath() + QStringLiteral("/scanner/"); + DEBUG_LOG(m_logger) << "onExportFile(): old path = " << defaultPath; - QString folderName = QFileDialog::getExistingDirectory(this, - tr("Save file from library to local Workstation"), - defaultPath, - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); - DEBUG_LOG(m_logger) << "onExportFile(): folderName = " << folderName; - if (folderName.isEmpty()) - { - DEBUG_LOG(m_logger) << "onExportFile(): folderName.isEmpty()"; - return; - } - - m_getContent->getContent(m_selectedFileContent.id(), m_content); - DEBUG_LOG(m_logger) << "onExportFile(): Save File to '" << folderName << "/" << m_fileName << "'" - << " fileType = " << m_selectedFileContent.fileType() - << " getFileTypeStr = " << getFileTypeStr(m_selectedFileContent.fileType()) - << " exportFileName = " << m_selectedFileContent.exportFileName() - << " m_content.size = " << m_content.size(); - - QString completeFileName = m_fileName; - completeFileName.append(getFileTypeStr(m_selectedFileContent.fileType())); - - QFile file; - QDir::setCurrent(folderName); - file.setFileName(completeFileName); - - if (file.exists()) - { - DEBUG_LOG(m_logger) << "onExportFile(): File already exists (" << completeFileName << ") in folder " << folderName; - if (LtsWidgets::LtsMessageDialog::showMessage(this, tr("Yes - overwrite file.
" - "No - do not overwrite file.
"), - tr("Do you want to overwrite the existing file?"), - LtsWidgets::Behaviour::Modal, - LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) + QString folderName = + QFileDialog::getExistingDirectory(this, tr("Save file from library to local Workstation"), defaultPath, + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + DEBUG_LOG(m_logger) << "onExportFile(): folderName = " << folderName; + if (folderName.isEmpty()) { - DEBUG_LOG(m_logger) << "onExportFile(): File exists, will not be overwritten (" << completeFileName << ") in folder " << folderName; - return; + DEBUG_LOG(m_logger) << "onExportFile(): folderName.isEmpty()"; + return; } - } - file.open(QIODevice::WriteOnly); - file.write(LtsUtils::toQByteArray(m_content)); - file.close(); + m_getContent->getContent(m_selectedFileContent.id(), m_content); + DEBUG_LOG(m_logger) << "onExportFile(): Save File to '" << folderName << "/" << m_fileName << "'" + << " fileType = " << m_selectedFileContent.fileType() + << " getFileTypeStr = " << getFileTypeStr(m_selectedFileContent.fileType()) + << " exportFileName = " << m_selectedFileContent.exportFileName() + << " m_content.size = " << m_content.size(); - DEBUG_LOG(m_logger) << "onExportFile(): Exported file " << completeFileName << " in folder " << folderName; + QString completeFileName = m_fileName; + completeFileName.append(getFileTypeStr(m_selectedFileContent.fileType())); + + QFile file; + QDir::setCurrent(folderName); + file.setFileName(completeFileName); + + if (file.exists()) + { + DEBUG_LOG(m_logger) << "onExportFile(): File already exists (" << completeFileName << ") in folder " + << folderName; + if (LtsWidgets::LtsMessageDialog::showMessage( + this, + tr("Yes - overwrite file.
" + "No - do not overwrite file.
"), + tr("Do you want to overwrite the existing file?"), LtsWidgets::Behaviour::Modal, + LtsWidgets::Button::Yes | LtsWidgets::Button::No) != LtsWidgets::Button::Yes) + { + DEBUG_LOG(m_logger) << "onExportFile(): File exists, will not be overwritten (" << completeFileName + << ") in folder " << folderName; + return; + } + } + + file.open(QIODevice::WriteOnly); + file.write(LtsUtils::toQByteArray(m_content)); + file.close(); + + DEBUG_LOG(m_logger) << "onExportFile(): Exported file " << completeFileName << " in folder " << folderName; } - void FileManagementDialogWidget::onSelectFile() { - DEBUG_LOG(m_logger) << "onSelectFile"; + DEBUG_LOG(m_logger) << "onSelectFile"; - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (!selIndex.isValid()) - return; + if (!selIndex.isValid()) + return; - m_selectedFileContent = m_modelFile->getRowData(selIndex.row()); + m_selectedFileContent = m_modelFile->getRowData(selIndex.row()); - DEBUG_LOG(m_logger) << "Selected file content id = " << m_selectedFileContent.id(); - emit accepted(); + DEBUG_LOG(m_logger) << "Selected file content id = " << m_selectedFileContent.id(); + emit accepted(); } - void FileManagementDialogWidget::onChooseFileName() { - DEBUG_LOG(m_logger) << "onChooseFileName"; + DEBUG_LOG(m_logger) << "onChooseFileName"; - if ((FileDialogMode::SaveFile == m_dialogMode) && (!m_fileName.isEmpty())) - { - DEBUG_LOG(m_logger) << "Choosen file name = " << m_fileName; - emit accepted(); - } + if ((FileDialogMode::SaveFile == m_dialogMode) && (!m_fileName.isEmpty())) + { + DEBUG_LOG(m_logger) << "Choosen file name = " << m_fileName; + emit accepted(); + } } - -void FileManagementDialogWidget::onFileChanged(const FileManagement::FileContent &data, DataModification modType) +void FileManagementDialogWidget::onFileChanged(const FileManagement::FileContent& data, DataModification modType) { - bool condition = showFile(data, m_xmlType); - DEBUG_LOG(m_logger) << "onFileChanged file name = " << data.name() << ", condition = " << condition << ", modType = " << modType; + bool condition = showFile(data, m_xmlType); + DEBUG_LOG(m_logger) << "onFileChanged file name = " << data.name() << ", condition = " << condition + << ", modType = " << modType; - bool reInit = false; - int row = 0; + bool reInit = false; + int row = 0; - QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); - if (selIndex.isValid()) - row = selIndex.row(); + QModelIndex selIndex = m_ui->widgetFiles->currentIndex(); + if (selIndex.isValid()) + row = selIndex.row(); - switch (modType) - { - case DataModification::eRemoved: - m_modelFile->removeRow(row); - reInit = true; - break; - case DataModification::eAdded: - if (condition) - m_modelFile->insertRow(data); - else - reInit = true; - break; - case DataModification::eModified: - if (condition) + switch (modType) { - - if (data.id() == m_modelFile->getRowData(row).id()) - m_modelFile->setRowData(row, data); - else - reInit = true; + case DataModification::eRemoved: + m_modelFile->removeRow(row); + reInit = true; + break; + case DataModification::eAdded: + if (condition) + m_modelFile->insertRow(data); + else + reInit = true; + break; + case DataModification::eModified: + if (condition) + { + + if (data.id() == m_modelFile->getRowData(row).id()) + m_modelFile->setRowData(row, data); + else + reInit = true; + } + else + reInit = true; + break; } - else - reInit = true; - break; - } - if (reInit) - reInitModelFile(true); - enaDisa(); + if (reInit) + reInitModelFile(true); + enaDisa(); } - -bool FileManagementDialogWidget::showFile(const FileManagement::FileContent &fc, const QString &xmlType) +bool FileManagementDialogWidget::showFile(const FileManagement::FileContent& fc, const QString& xmlType) { - if (fc.isDeleted()) - { - DEBUG_LOG(m_logger) << "is deleted: " << fc.name().c_str(); - return false; - } - - if (fc.folderId() != m_selectedFolderId) - { - DEBUG_LOG(m_logger) << "Folder id does not match: " << fc.name().c_str(); - return false; - } - - if (!m_fileTypes.isEmpty() && !m_fileTypes.contains(fc.fileType())) - { - DEBUG_LOG(m_logger) << "file type does not match: " << fc.name().c_str(); - return false; - } - - if (m_dialogMode != FileDialogMode::Admin) - { - if (fc.fileStatus() != FileManagement::FileStatus::Valid) + if (fc.isDeleted()) { - DEBUG_LOG(m_logger) << "file status is not valid: " << fc.name().c_str(); - return false; + DEBUG_LOG(m_logger) << "is deleted: " << fc.name().c_str(); + return false; } - - const QModelIndex selIndex = selectedIndexViewFolder(); - const NGLTreeItem *item = m_modelFolder->privateData(selIndex); - const FileManagement::Folder fld = item->data().value(); - const QVector fldPath = LtsUtils::convert>(fld.path()); - - - if (fldPath.contains(FileManagement::MainFolder::UserDocuments)) + if (fc.folderId() != m_selectedFolderId) { - const int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); - - DEBUG_LOG(m_logger) << "Filtering files on OperatorId = " << operatorId; - if (fc.operatorId() != operatorId) - { - DEBUG_LOG(m_logger) << "operator id does not match: " << fc.name().c_str(); + DEBUG_LOG(m_logger) << "Folder id does not match: " << fc.name().c_str(); return false; - } - DEBUG_LOG(m_logger) << "Filtering files on User Category"; - if (fc.fileCategory() != FileManagement::FileCategory::User) - { - DEBUG_LOG(m_logger) << "User category does not match: " << fc.name().c_str(); + } + if (!m_fileTypes.isEmpty() && !m_fileTypes.contains(fc.fileType())) + { + DEBUG_LOG(m_logger) << "file type does not match: " << fc.name().c_str(); + return false; + } - } - - if (m_session->exerciseId() > 0) - { - if (fc.exerciseId().is_set() && fc.exerciseId().get() != m_session->exerciseId()) + if (m_dialogMode != FileDialogMode::Admin) + { + if (fc.fileStatus() != FileManagement::FileStatus::Valid) { - DEBUG_LOG(m_logger) << "exercise does not match: " << fc.name().c_str() << " is: " << fc.exerciseId() - << " should be " << m_session->exerciseId(); - return false; + DEBUG_LOG(m_logger) << "file status is not valid: " << fc.name().c_str(); + return false; } - } - } - - if (fldPath.contains(FileManagement::MainFolder::ExerciseDocuments)) - { - - DEBUG_LOG(m_logger) << "Filtering files on Exercise Category"; - if (fc.fileCategory() != FileManagement::FileCategory::Exercise) - { - DEBUG_LOG(m_logger) << "exercise category does not match: " << fc.name().c_str(); - return false; - } - if (m_session->exerciseId() > 0) - { - - DEBUG_LOG(m_logger) << "Filtering files on Exercise Category and exerciseId = " << m_session->exerciseId(); - if (fc.exerciseId().is_set() && fc.exerciseId().get() != m_session->exerciseId()) + const QModelIndex selIndex = selectedIndexViewFolder(); + const NGLTreeItem* item = m_modelFolder->privateData(selIndex); + const FileManagement::Folder fld = item->data().value(); + const QVector fldPath = LtsUtils::convert>(fld.path()); + + if (fldPath.contains(FileManagement::MainFolder::UserDocuments)) { - DEBUG_LOG(m_logger) << "exercise does not match: " << fc.name().c_str() << " is: " << fc.exerciseId() - << " should be " << m_session->exerciseId(); - return false; + const int operatorId = LtsSessionData::LtsSessionData::getInstance()->getOperatorId(); + + DEBUG_LOG(m_logger) << "Filtering files on OperatorId = " << operatorId; + if (fc.operatorId() != operatorId) + { + DEBUG_LOG(m_logger) << "operator id does not match: " << fc.name().c_str(); + return false; + } + DEBUG_LOG(m_logger) << "Filtering files on User Category"; + if (fc.fileCategory() != FileManagement::FileCategory::User) + { + DEBUG_LOG(m_logger) << "User category does not match: " << fc.name().c_str(); + } + + if (m_session->exerciseId() > 0) + { + if (fc.exerciseId().is_set() && fc.exerciseId().get() != m_session->exerciseId()) + { + DEBUG_LOG(m_logger) << "exercise does not match: " << fc.name().c_str() + << " is: " << fc.exerciseId() << " should be " << m_session->exerciseId(); + return false; + } + } + } + + if (fldPath.contains(FileManagement::MainFolder::ExerciseDocuments)) + { + + DEBUG_LOG(m_logger) << "Filtering files on Exercise Category"; + if (fc.fileCategory() != FileManagement::FileCategory::Exercise) + { + DEBUG_LOG(m_logger) << "exercise category does not match: " << fc.name().c_str(); + return false; + } + if (m_session->exerciseId() > 0) + { + + DEBUG_LOG(m_logger) << "Filtering files on Exercise Category and exerciseId = " + << m_session->exerciseId(); + if (fc.exerciseId().is_set() && fc.exerciseId().get() != m_session->exerciseId()) + { + DEBUG_LOG(m_logger) << "exercise does not match: " << fc.name().c_str() + << " is: " << fc.exerciseId() << " should be " << m_session->exerciseId(); + return false; + } + } + } + + if (fc.fileType() == FileType::Xml && !xmlType.isEmpty() && fc.properties().size() > 0) + { + const QString& prop = QString::fromStdString(fc.properties()); + if (!prop.contains(xmlType, Qt::CaseSensitive)) + { + DEBUG_LOG(m_logger) << "XmlType not found " << xmlType; + return false; + } } - } } - - - if (fc.fileType() == FileType::Xml && !xmlType.isEmpty() && fc.properties().size() > 0) - { - const QString &prop = QString::fromStdString(fc.properties()); - if (!prop.contains(xmlType, Qt::CaseSensitive)) - { - DEBUG_LOG(m_logger) << "XmlType not found " << xmlType; - return false; - } - } - - - } - return true; + return true; } - void FileManagementDialogWidget::selectFolder() { - QModelIndex idx; - QItemSelectionModel *selectionModelFolder = m_ui->tvFolder->selectionModel(); - if (m_selectedFolderId > 0) - idx = m_proxyModelFolder->mapFromSource(m_modelFolder->getIndex(m_selectedFolderId)); - if (idx.isValid()) - selectionModelFolder->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); - else - selectionModelFolder->setCurrentIndex(m_modelFolder->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + QModelIndex idx; + QItemSelectionModel* selectionModelFolder = m_ui->tvFolder->selectionModel(); + if (m_selectedFolderId > 0) + idx = m_proxyModelFolder->mapFromSource(m_modelFolder->getIndex(m_selectedFolderId)); + if (idx.isValid()) + selectionModelFolder->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); + else + selectionModelFolder->setCurrentIndex(m_modelFolder->index(0, 0), + QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } - - - - - - - - - - - -FileManagementDialogTab::FileManagementDialogTab(const QString &menuGroup, QWidget *parent) - : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly) - , m_editItemWidget(new FileManagementDialogWidget(this)) +FileManagementDialogTab::FileManagementDialogTab(const QString& menuGroup, QWidget* parent) + : LtsWidgets::LtsDialog(parent, LtsWidgets::ButtonCombination::CloseOnly), + m_editItemWidget(new FileManagementDialogWidget(this)) { - if (menuGroup == tr("Document Library")) - - setOnlineHelpFilename(QStringLiteral("Administrator-Library_Management")); - if (menuGroup == tr("Exercise Documents")) - - setOnlineHelpFilename(QStringLiteral("Situation-Library_Organisation")); - DEBUG_LOG(m_logger) << "Ctor FileManagementDialogTab"; + if (menuGroup == tr("Document Library")) - LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; - LtsWidgets::DialogButton btnEditFolder = LtsWidgets::DialogButton::Import; - LtsWidgets::DialogButton btnRemoveFolder = LtsWidgets::DialogButton::Export; + setOnlineHelpFilename(QStringLiteral("Administrator-Library_Management")); + if (menuGroup == tr("Exercise Documents")) - LtsWidgets::DialogButton btnExportFile = LtsWidgets::DialogButton::Save; - LtsWidgets::DialogButton btnImportFile = LtsWidgets::DialogButton::Add; - LtsWidgets::DialogButton btnEditFile = LtsWidgets::DialogButton::Edit; - LtsWidgets::DialogButton btnPreviewFile = LtsWidgets::DialogButton::Show; - LtsWidgets::DialogButton btnRemoveFile = LtsWidgets::DialogButton::Remove; - LtsWidgets::DialogButton btnDeleteFile = LtsWidgets::DialogButton::Hide; - LtsWidgets::DialogButton btnRestoreFile = LtsWidgets::DialogButton::Load; + setOnlineHelpFilename(QStringLiteral("Situation-Library_Organisation")); + DEBUG_LOG(m_logger) << "Ctor FileManagementDialogTab"; + + LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; + LtsWidgets::DialogButton btnEditFolder = LtsWidgets::DialogButton::Import; + LtsWidgets::DialogButton btnRemoveFolder = LtsWidgets::DialogButton::Export; + + LtsWidgets::DialogButton btnExportFile = LtsWidgets::DialogButton::Save; + LtsWidgets::DialogButton btnImportFile = LtsWidgets::DialogButton::Add; + LtsWidgets::DialogButton btnEditFile = LtsWidgets::DialogButton::Edit; + LtsWidgets::DialogButton btnPreviewFile = LtsWidgets::DialogButton::Show; + LtsWidgets::DialogButton btnRemoveFile = LtsWidgets::DialogButton::Remove; + LtsWidgets::DialogButton btnDeleteFile = LtsWidgets::DialogButton::Hide; + LtsWidgets::DialogButton btnRestoreFile = LtsWidgets::DialogButton::Load; + + if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) + { + m_buttonBox->connectButton(btnAddFolder, m_editItemWidget, &FileManagementDialogWidget::onAddFolder); + m_buttonBox->setText(btnAddFolder, tr("Add Folder")); + m_buttonBox->setToolTip(btnAddFolder, tr("Add new folder to library")); + m_buttonBox->setButtonEnabled(btnAddFolder, false); + m_buttonBox->setButtonVisible(btnAddFolder, true); + + m_buttonBox->connectButton(btnEditFolder, m_editItemWidget, &FileManagementDialogWidget::onEditFolder); + m_buttonBox->setText(btnEditFolder, tr("Rename Folder")); + m_buttonBox->setToolTip(btnEditFolder, tr("Rename folder")); + m_buttonBox->setButtonEnabled(btnEditFolder, false); + m_buttonBox->setButtonVisible(btnEditFolder, true); + + m_buttonBox->connectButton(btnRemoveFolder, m_editItemWidget, &FileManagementDialogWidget::onRemoveFolder); + m_buttonBox->setText(btnRemoveFolder, tr("Remove Folder")); + m_buttonBox->setToolTip(btnRemoveFolder, tr("Remove folder from library")); + m_buttonBox->setButtonEnabled(btnRemoveFolder, false); + m_buttonBox->setButtonVisible(btnRemoveFolder, true); + + m_buttonBox->connectButton(btnExportFile, m_editItemWidget, &FileManagementDialogWidget::onExportFile); + m_buttonBox->setText(btnExportFile, tr("Export File")); + m_buttonBox->setToolTip(btnExportFile, tr("Export file to file system")); + m_buttonBox->setButtonEnabled(btnExportFile, false); + m_buttonBox->setButtonVisible(btnExportFile, true); + + m_buttonBox->connectButton(btnImportFile, m_editItemWidget, &FileManagementDialogWidget::onImportFile); + m_buttonBox->setText(btnImportFile, tr("Import File")); + m_buttonBox->setToolTip(btnImportFile, tr("Import file to library")); + m_buttonBox->setButtonEnabled(btnImportFile, true); + m_buttonBox->setButtonVisible(btnImportFile, true); + + m_buttonBox->connectButton(btnEditFile, m_editItemWidget, &FileManagementDialogWidget::onEditFile); + m_buttonBox->setText(btnEditFile, tr("Properties")); + m_buttonBox->setToolTip(btnEditFile, tr("Edit file properties")); + m_buttonBox->setButtonEnabled(btnEditFile, false); + m_buttonBox->setButtonVisible(btnEditFile, true); + + m_buttonBox->connectButton(btnRemoveFile, m_editItemWidget, &FileManagementDialogWidget::onRemoveFile); + + m_buttonBox->setText(btnRemoveFile, tr("Remove File")); + m_buttonBox->setToolTip(btnRemoveFile, tr("Remove file from library")); + m_buttonBox->setButtonEnabled(btnRemoveFile, false); + m_buttonBox->setButtonVisible(btnRemoveFile, true); + + m_buttonBox->connectButton(btnDeleteFile, m_editItemWidget, &FileManagementDialogWidget::onDeleteFile); + m_buttonBox->setText(btnDeleteFile, tr("Delete File")); + m_buttonBox->setToolTip(btnDeleteFile, tr("Delete file from library")); + m_buttonBox->setButtonEnabled(btnDeleteFile, false); + m_buttonBox->setButtonVisible(btnDeleteFile, true); + + m_buttonBox->connectButton(btnRestoreFile, m_editItemWidget, &FileManagementDialogWidget::onRestoreFile); + m_buttonBox->setText(btnRestoreFile, tr("Restore File")); + m_buttonBox->setToolTip(btnRestoreFile, tr("Restore file to library")); + m_buttonBox->setButtonEnabled(btnRestoreFile, false); + m_buttonBox->setButtonVisible(btnRestoreFile, true); + } + m_buttonBox->connectButton(btnPreviewFile, m_editItemWidget, &FileManagementDialogWidget::onPreviewFile); + m_buttonBox->setText(btnPreviewFile, tr("Preview File")); + m_buttonBox->setToolTip(btnPreviewFile, tr("Preview / Edit file")); + m_buttonBox->setButtonEnabled(btnPreviewFile, false); + m_buttonBox->setButtonVisible(btnPreviewFile, true); + + m_editItemWidget->m_ui->lblFolder->setText(tr("Selected Folder:")); + m_editItemWidget->m_ui->lblFile->setText(tr("Selected File:")); + + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, m_editItemWidget, + &FileManagementDialogWidget::onReject); + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, + &FileManagementDialogTab::close); + + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); +} + +FileManagementDialog::FileManagementDialog(QWidget* parent) + : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal), + m_editItemWidget(new FileManagementDialogWidget(this)), m_buttonBox(new LtsWidgets::LtsDialogButtonBox(this)), + m_dialogMode(FileDialogMode::OpenFile) +{ + DEBUG_LOG(m_logger) << "Ctor FileManagementDialog"; + + LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; + LtsWidgets::DialogButton btnSelectFile = LtsWidgets::DialogButton::Load; - if (!LtsSessionData::LtsSessionData::getInstance()->isTablet()) - { m_buttonBox->connectButton(btnAddFolder, m_editItemWidget, &FileManagementDialogWidget::onAddFolder); m_buttonBox->setText(btnAddFolder, tr("Add Folder")); m_buttonBox->setToolTip(btnAddFolder, tr("Add new folder to library")); m_buttonBox->setButtonEnabled(btnAddFolder, false); m_buttonBox->setButtonVisible(btnAddFolder, true); - m_buttonBox->connectButton(btnEditFolder, m_editItemWidget, &FileManagementDialogWidget::onEditFolder); - m_buttonBox->setText(btnEditFolder, tr("Rename Folder")); - m_buttonBox->setToolTip(btnEditFolder, tr("Rename folder")); - m_buttonBox->setButtonEnabled(btnEditFolder, false); - m_buttonBox->setButtonVisible(btnEditFolder, true); + m_buttonBox->setText(btnSelectFile, tr("Select File")); + m_buttonBox->setToolTip(btnSelectFile, tr("Select file from library")); + m_buttonBox->setButtonEnabled(btnSelectFile, false); + m_buttonBox->setButtonVisible(btnSelectFile, true); - m_buttonBox->connectButton(btnRemoveFolder, m_editItemWidget, &FileManagementDialogWidget::onRemoveFolder); - m_buttonBox->setText(btnRemoveFolder, tr("Remove Folder")); - m_buttonBox->setToolTip(btnRemoveFolder, tr("Remove folder from library")); - m_buttonBox->setButtonEnabled(btnRemoveFolder, false); - m_buttonBox->setButtonVisible(btnRemoveFolder, true); + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, m_editItemWidget, + &FileManagementDialogWidget::onReject); + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, + &FileManagementDialog::close); - m_buttonBox->connectButton(btnExportFile, m_editItemWidget, &FileManagementDialogWidget::onExportFile); - m_buttonBox->setText(btnExportFile, tr("Export File")); - m_buttonBox->setToolTip(btnExportFile, tr("Export file to file system")); - m_buttonBox->setButtonEnabled(btnExportFile, false); - m_buttonBox->setButtonVisible(btnExportFile, true); - - m_buttonBox->connectButton(btnImportFile, m_editItemWidget, &FileManagementDialogWidget::onImportFile); - m_buttonBox->setText(btnImportFile, tr("Import File")); - m_buttonBox->setToolTip(btnImportFile, tr("Import file to library")); - m_buttonBox->setButtonEnabled(btnImportFile, true); - m_buttonBox->setButtonVisible(btnImportFile, true); - - m_buttonBox->connectButton(btnEditFile, m_editItemWidget, &FileManagementDialogWidget::onEditFile); - m_buttonBox->setText(btnEditFile, tr("Properties")); - m_buttonBox->setToolTip(btnEditFile, tr("Edit file properties")); - m_buttonBox->setButtonEnabled(btnEditFile, false); - m_buttonBox->setButtonVisible(btnEditFile, true); - - - m_buttonBox->connectButton(btnRemoveFile, m_editItemWidget, &FileManagementDialogWidget::onRemoveFile); - - m_buttonBox->setText(btnRemoveFile, tr("Remove File")); - m_buttonBox->setToolTip(btnRemoveFile, tr("Remove file from library")); - m_buttonBox->setButtonEnabled(btnRemoveFile, false); - m_buttonBox->setButtonVisible(btnRemoveFile, true); - - m_buttonBox->connectButton(btnDeleteFile, m_editItemWidget, &FileManagementDialogWidget::onDeleteFile); - m_buttonBox->setText(btnDeleteFile, tr("Delete File")); - m_buttonBox->setToolTip(btnDeleteFile, tr("Delete file from library")); - m_buttonBox->setButtonEnabled(btnDeleteFile, false); - m_buttonBox->setButtonVisible(btnDeleteFile, true); - - m_buttonBox->connectButton(btnRestoreFile, m_editItemWidget, &FileManagementDialogWidget::onRestoreFile); - m_buttonBox->setText(btnRestoreFile, tr("Restore File")); - m_buttonBox->setToolTip(btnRestoreFile, tr("Restore file to library")); - m_buttonBox->setButtonEnabled(btnRestoreFile, false); - m_buttonBox->setButtonVisible(btnRestoreFile, true); - } - m_buttonBox->connectButton(btnPreviewFile, m_editItemWidget, &FileManagementDialogWidget::onPreviewFile); - m_buttonBox->setText(btnPreviewFile, tr("Preview File")); - m_buttonBox->setToolTip(btnPreviewFile, tr("Preview / Edit file")); - m_buttonBox->setButtonEnabled(btnPreviewFile, false); - m_buttonBox->setButtonVisible(btnPreviewFile, true); - - m_editItemWidget->m_ui->lblFolder->setText(tr("Selected Folder:")); - m_editItemWidget->m_ui->lblFile->setText(tr("Selected File:")); - - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, m_editItemWidget, &FileManagementDialogWidget::onReject); - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, &FileManagementDialogTab::close); - - - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); + m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); } - -FileManagementDialog::FileManagementDialog(QWidget *parent) - : LtsWidgets::LtsFramelessDialog(parent, LtsWidgets::Behaviour::Modal) - , m_editItemWidget(new FileManagementDialogWidget(this)) - , m_buttonBox(new LtsWidgets::LtsDialogButtonBox(this)) - , m_dialogMode(FileDialogMode::OpenFile) +bool FileManagementDialogTab::init(LtsSession::LtsSession* session, FileDialogMode dlgMode, + const QVector& fileTypes, const int& folderId, const QString& buttonName) { - DEBUG_LOG(m_logger) << "Ctor FileManagementDialog"; + DEBUG_LOG(m_logger) << "Start init FileManagementDialogTab"; - LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; - LtsWidgets::DialogButton btnSelectFile = LtsWidgets::DialogButton::Load; + if (!m_editItemWidget->init(session, dlgMode, fileTypes, folderId)) + { + ERROR_LOG(m_logger) << "Init FileManagementDialogTab failed!"; + return false; + } - m_buttonBox->connectButton(btnAddFolder, m_editItemWidget, &FileManagementDialogWidget::onAddFolder); - m_buttonBox->setText(btnAddFolder, tr("Add Folder")); - m_buttonBox->setToolTip(btnAddFolder, tr("Add new folder to library")); - m_buttonBox->setButtonEnabled(btnAddFolder, false); - m_buttonBox->setButtonVisible(btnAddFolder, true); + m_dialogMode = dlgMode; - m_buttonBox->setText(btnSelectFile, tr("Select File")); - m_buttonBox->setToolTip(btnSelectFile, tr("Select file from library")); - m_buttonBox->setButtonEnabled(btnSelectFile, false); - m_buttonBox->setButtonVisible(btnSelectFile, true); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_editItemWidget); + layout->setMargin(0); - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, m_editItemWidget, &FileManagementDialogWidget::onReject); - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, &FileManagementDialog::close); + if (!buttonName.isEmpty()) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Load, buttonName); + m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, buttonName); + } + else if (m_dialogMode == FileDialogMode::SaveFile) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Save")); + m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, tr("Save")); + } - - m_buttonBox->getButton(LtsWidgets::DialogButton::Apply)->hide(); - m_buttonBox->getButton(LtsWidgets::DialogButton::Ok)->hide(); + if (m_dialogMode != FileDialogMode::Admin) + { + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove, false); + + m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, false); + } + + connect(m_editItemWidget, &FileManagementDialogWidget::enableButtons, this, &FileManagementDialogTab::enaDisa); + connect(m_editItemWidget, &FileManagementDialogWidget::accepted, this, &FileManagementDialogTab::accepted); + + m_editItemWidget->m_ui->leFile->setVisible(false); + m_editItemWidget->m_ui->lblFile->setVisible(false); + m_editItemWidget->m_ui->lblFilter->setVisible(false); + + return true; } - -bool FileManagementDialogTab::init(LtsSession::LtsSession *session, - FileDialogMode dlgMode, - const QVector &fileTypes, - const int &folderId, - const QString &buttonName) +bool FileManagementDialog::init(LtsSession::LtsSession* session, FileDialogMode dlgMode, + const QVector& fileTypes, int folderId, const QString& xmlType) { - DEBUG_LOG(m_logger) << "Start init FileManagementDialogTab"; + DEBUG_LOG(m_logger) << "Start init FileManagementDialog"; + DEBUG_LOG(m_logger) << "Initial folder to select: " << folderId; - if (!m_editItemWidget->init(session, dlgMode, fileTypes, folderId)) - { - ERROR_LOG(m_logger) << "Init FileManagementDialogTab failed!"; - return false; - } + if (!m_editItemWidget->init(session, dlgMode, fileTypes, folderId, xmlType)) + { + ERROR_LOG(m_logger) << "Init FileManagementDialogWidget failed!"; + return false; + } - m_dialogMode = dlgMode; + m_dialogMode = dlgMode; - QVBoxLayout *layout = new QVBoxLayout(this); - layout->addWidget(m_editItemWidget); - layout->setMargin(0); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->addWidget(m_editItemWidget); + layout->addWidget(m_buttonBox); - if (!buttonName.isEmpty()) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Load, buttonName); - m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, buttonName); - } - else if (m_dialogMode == FileDialogMode::SaveFile) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Save")); - m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, tr("Save")); - } + if (m_dialogMode == FileDialogMode::SaveFile) + { + m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Save")); + m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, tr("Save")); + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, m_editItemWidget, + &FileManagementDialogWidget::onChooseFileName); + } + else if (m_dialogMode == FileDialogMode::OpenFile) + m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, m_editItemWidget, + &FileManagementDialogWidget::onSelectFile); - if (m_dialogMode != FileDialogMode::Admin) - { - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Remove, false); - - m_buttonBox->setButtonVisible(LtsWidgets::DialogButton::Load, false); - } + connect(m_editItemWidget, &FileManagementDialogWidget::enableButtons, this, &FileManagementDialog::enaDisa); - connect(m_editItemWidget, &FileManagementDialogWidget::enableButtons, this, &FileManagementDialogTab::enaDisa); - connect(m_editItemWidget, &FileManagementDialogWidget::accepted, this, &FileManagementDialogTab::accepted); + connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, + &FileManagementDialog::reject); + connect(m_editItemWidget, &FileManagementDialogWidget::accepted, this, &FileManagementDialog::accept); - m_editItemWidget->m_ui->leFile->setVisible(false); - m_editItemWidget->m_ui->lblFile->setVisible(false); - m_editItemWidget->m_ui->lblFilter->setVisible(false); + enaDisa(); - return true; + return true; } - -bool FileManagementDialog::init(LtsSession::LtsSession *session, - FileDialogMode dlgMode, - const QVector &fileTypes, - int folderId, - const QString &xmlType) -{ - DEBUG_LOG(m_logger) << "Start init FileManagementDialog"; - DEBUG_LOG(m_logger) << "Initial folder to select: " << folderId; - - if (!m_editItemWidget->init(session, dlgMode, fileTypes, folderId, xmlType)) - { - ERROR_LOG(m_logger) << "Init FileManagementDialogWidget failed!"; - return false; - } - - m_dialogMode = dlgMode; - - QVBoxLayout *layout = new QVBoxLayout(this); - layout->addWidget(m_editItemWidget); - layout->addWidget(m_buttonBox); - - if (m_dialogMode == FileDialogMode::SaveFile) - { - m_buttonBox->setText(LtsWidgets::DialogButton::Load, tr("Save")); - m_buttonBox->setToolTip(LtsWidgets::DialogButton::Load, tr("Save")); - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, m_editItemWidget, &FileManagementDialogWidget::onChooseFileName); - } - else if (m_dialogMode == FileDialogMode::OpenFile) - m_buttonBox->connectButton(LtsWidgets::DialogButton::Load, m_editItemWidget, &FileManagementDialogWidget::onSelectFile); - - connect(m_editItemWidget, &FileManagementDialogWidget::enableButtons, this, &FileManagementDialog::enaDisa); - - connect(m_buttonBox->getButton(LtsWidgets::DialogButton::Close), &QPushButton::clicked, this, &FileManagementDialog::reject); - connect(m_editItemWidget, &FileManagementDialogWidget::accepted, this, &FileManagementDialog::accept); - - enaDisa(); - - return true; -} - - void FileManagementDialog::accept() { - emit fileSelected(getSelectedFileId(), getSelectedFolderId(), getFileName()); - LtsWidgets::LtsFramelessDialog::accept(); + emit fileSelected(getSelectedFileId(), getSelectedFolderId(), getFileName()); + LtsWidgets::LtsFramelessDialog::accept(); } - void FileManagementDialog::enaDisa() { - DEBUG_LOG(m_logger) << "FileManagementDialog::enaDisa()"; + DEBUG_LOG(m_logger) << "FileManagementDialog::enaDisa()"; - LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; - m_buttonBox->setButtonEnabled(btnAddFolder, false); + LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; + m_buttonBox->setButtonEnabled(btnAddFolder, false); - QModelIndex idxFolder = m_editItemWidget->m_ui->tvFolder->currentIndex(); - if (m_dialogMode == FileDialogMode::SaveFile && idxFolder.isValid()) - m_buttonBox->setButtonEnabled(btnAddFolder, true); + QModelIndex idxFolder = m_editItemWidget->m_ui->tvFolder->currentIndex(); + if (m_dialogMode == FileDialogMode::SaveFile && idxFolder.isValid()) + m_buttonBox->setButtonEnabled(btnAddFolder, true); - LtsWidgets::DialogButton btnSelectFile = LtsWidgets::DialogButton::Load; - m_buttonBox->setButtonEnabled(btnSelectFile, false); + LtsWidgets::DialogButton btnSelectFile = LtsWidgets::DialogButton::Load; + m_buttonBox->setButtonEnabled(btnSelectFile, false); - QModelIndex idxFile = m_editItemWidget->m_ui->widgetFiles->currentIndex(); - if (m_dialogMode == FileDialogMode::OpenFile && idxFile.isValid()) - m_buttonBox->setButtonEnabled(btnSelectFile, true); + QModelIndex idxFile = m_editItemWidget->m_ui->widgetFiles->currentIndex(); + if (m_dialogMode == FileDialogMode::OpenFile && idxFile.isValid()) + m_buttonBox->setButtonEnabled(btnSelectFile, true); - DEBUG_LOG(m_logger) << "DialogMode: " << (int)m_dialogMode; - DEBUG_LOG(m_logger) << "FileName: " << m_editItemWidget->m_fileName; + DEBUG_LOG(m_logger) << "DialogMode: " << (int)m_dialogMode; + DEBUG_LOG(m_logger) << "FileName: " << m_editItemWidget->m_fileName; - if (m_dialogMode == FileDialogMode::SaveFile && !m_editItemWidget->m_fileName.isEmpty()) - m_buttonBox->setButtonEnabled(btnSelectFile, true); + if (m_dialogMode == FileDialogMode::SaveFile && !m_editItemWidget->m_fileName.isEmpty()) + m_buttonBox->setButtonEnabled(btnSelectFile, true); } - void FileManagementDialogTab::enaDisa() { - DEBUG_LOG(m_logger) << "FileManagementDialogTab::enaDisa()"; + DEBUG_LOG(m_logger) << "FileManagementDialogTab::enaDisa()"; - LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; - LtsWidgets::DialogButton btnEditFolder = LtsWidgets::DialogButton::Import; - LtsWidgets::DialogButton btnRemoveFolder = LtsWidgets::DialogButton::Export; + LtsWidgets::DialogButton btnAddFolder = LtsWidgets::DialogButton::Print; + LtsWidgets::DialogButton btnEditFolder = LtsWidgets::DialogButton::Import; + LtsWidgets::DialogButton btnRemoveFolder = LtsWidgets::DialogButton::Export; - LtsWidgets::DialogButton btnExportFile = LtsWidgets::DialogButton::Save; - LtsWidgets::DialogButton btnImportFile = LtsWidgets::DialogButton::Add; - LtsWidgets::DialogButton btnEditFile = LtsWidgets::DialogButton::Edit; - LtsWidgets::DialogButton btnPreviewFile = LtsWidgets::DialogButton::Show; - LtsWidgets::DialogButton btnRemoveFile = LtsWidgets::DialogButton::Remove; - LtsWidgets::DialogButton btnDeleteFile = LtsWidgets::DialogButton::Hide; - LtsWidgets::DialogButton btnRestoreFile = LtsWidgets::DialogButton::Load; + LtsWidgets::DialogButton btnExportFile = LtsWidgets::DialogButton::Save; + LtsWidgets::DialogButton btnImportFile = LtsWidgets::DialogButton::Add; + LtsWidgets::DialogButton btnEditFile = LtsWidgets::DialogButton::Edit; + LtsWidgets::DialogButton btnPreviewFile = LtsWidgets::DialogButton::Show; + LtsWidgets::DialogButton btnRemoveFile = LtsWidgets::DialogButton::Remove; + LtsWidgets::DialogButton btnDeleteFile = LtsWidgets::DialogButton::Hide; + LtsWidgets::DialogButton btnRestoreFile = LtsWidgets::DialogButton::Load; - m_buttonBox->setButtonEnabled(btnAddFolder, m_editItemWidget->m_actionAddFolder->isEnabled()); - m_buttonBox->setButtonEnabled(btnEditFolder, m_editItemWidget->m_actionRenameFolder->isEnabled()); - m_buttonBox->setButtonEnabled(btnRemoveFolder, m_editItemWidget->m_actionRemoveFolder->isEnabled()); + m_buttonBox->setButtonEnabled(btnAddFolder, m_editItemWidget->m_actionAddFolder->isEnabled()); + m_buttonBox->setButtonEnabled(btnEditFolder, m_editItemWidget->m_actionRenameFolder->isEnabled()); + m_buttonBox->setButtonEnabled(btnRemoveFolder, m_editItemWidget->m_actionRemoveFolder->isEnabled()); - if (m_editItemWidget->m_actionPreviewFile->data().toBool()) - { - m_buttonBox->setText(btnPreviewFile, tr("Edit File")); - m_editItemWidget->m_actionPreviewFile->setText(tr("Edit File")); - } - else - { - m_buttonBox->setText(btnPreviewFile, tr("Preview File")); - m_editItemWidget->m_actionPreviewFile->setText(tr("Preview File")); - } + if (m_editItemWidget->m_actionPreviewFile->data().toBool()) + { + m_buttonBox->setText(btnPreviewFile, tr("Edit File")); + m_editItemWidget->m_actionPreviewFile->setText(tr("Edit File")); + } + else + { + m_buttonBox->setText(btnPreviewFile, tr("Preview File")); + m_editItemWidget->m_actionPreviewFile->setText(tr("Preview File")); + } - m_buttonBox->setButtonEnabled(btnExportFile, m_editItemWidget->m_actionExportFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnImportFile, m_editItemWidget->m_actionImportFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnEditFile, m_editItemWidget->m_actionEditFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnPreviewFile, m_editItemWidget->m_actionPreviewFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnRemoveFile, m_editItemWidget->m_actionRemoveFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnDeleteFile, m_editItemWidget->m_actionDeleteFile->isEnabled()); - m_buttonBox->setButtonEnabled(btnRestoreFile, m_editItemWidget->m_actionRestoreFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnExportFile, m_editItemWidget->m_actionExportFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnImportFile, m_editItemWidget->m_actionImportFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnEditFile, m_editItemWidget->m_actionEditFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnPreviewFile, m_editItemWidget->m_actionPreviewFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnRemoveFile, m_editItemWidget->m_actionRemoveFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnDeleteFile, m_editItemWidget->m_actionDeleteFile->isEnabled()); + m_buttonBox->setButtonEnabled(btnRestoreFile, m_editItemWidget->m_actionRestoreFile->isEnabled()); } -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog_model_file.cpp b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog_model_file.cpp old mode 100755 new mode 100644 index 0ae5d0bd2..f354efba7 --- a/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog_model_file.cpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Plugins/FileManagement/Gui/Explorer/flm_dialog_model_file.cpp @@ -1,188 +1,160 @@ - #include "flm_dialog_model_file.h" -#include - -#include -#include -#include - #include #include +#include #include #include -#include +#include +#include +#include +#include namespace FileManagement { - - - -DialogModelFile::DialogModelFile(QObject *parent) - : LtsWidgets::LtsAbstractTableModel( +DialogModelFile::DialogModelFile(QObject* parent) + : LtsWidgets::LtsAbstractTableModel( + {tr("Name"), tr("Type"), tr("Category"), tr("Status"), tr("Template"), tr("Exercise"), tr("Phase"), + tr("Operator"), tr("Used"), tr("Uses"), tr("Last modified"), tr("Properties"), tr("Folder Id"), + tr("File Id")}, + parent) { - tr("Name"), - tr("Type"), - tr("Category"), - tr("Status"), - tr("Template"), - tr("Exercise"), - tr("Phase"), - tr("Operator"), - tr("Used"), - tr("Uses"), - tr("Last modified"), - tr("Properties"), - tr("Folder Id"), - tr("File Id") -}, -parent) -{} - - - -bool DialogModelFile::initModel(LtsSession::LtsSession *session, - const QString &xmlType, - const std::function &predicate) -{ - - if (!session->getDtc(m_flmDtc)) - return false; - if (!session->getDtc(m_opmDtc)) - return false; - if (!session->getDtc(m_exmDtc)) - return false; - - clear(); - - - auto files = [this, xmlType, predicate](const FileManagement::FileContent & fc) - { - if (!predicate(fc, xmlType)) - return; - insertRow(fc); - }; - m_flmDtc->fileContents(files); - DEBUG_LOG(m_logger) << "initModel - #Files: " << m_vecData.size(); - return true; } - - -QVariant DialogModelFile::data(const QModelIndex &index, int role) const +bool DialogModelFile::initModel( + LtsSession::LtsSession* session, const QString& xmlType, + const std::function& predicate) { - if (!indexIsValid(index)) - return {}; - const FileManagement::FileContent &fl = m_vecData.at(index.row()); + if (!session->getDtc(m_flmDtc)) + return false; + if (!session->getDtc(m_opmDtc)) + return false; + if (!session->getDtc(m_exmDtc)) + return false; - switch(role) - { - case Qt::BackgroundRole: - { - if (fl.fileStatus() == FileManagement::FileStatus::Deleted) - return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); - return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); - } - case Qt::DisplayRole: - { - switch (index.column()) + clear(); + + auto files = [this, xmlType, predicate](const FileManagement::FileContent& fc) { + if (!predicate(fc, xmlType)) + return; + insertRow(fc); + }; + m_flmDtc->fileContents(files); + DEBUG_LOG(m_logger) << "initModel - #Files: " << m_vecData.size(); + return true; +} + +QVariant DialogModelFile::data(const QModelIndex& index, int role) const +{ + if (!indexIsValid(index)) + return {}; + + const FileManagement::FileContent& fl = m_vecData.at(index.row()); + + switch (role) { - case NAME: - return QString::fromStdString(fl.name()); - case ISTEMPLATE: - return fl.isTemplate() ? tr("Yes") : tr("No"); - case FOLDER: - return fl.folderId(); - case FILEID: - return fl.id(); - case FILETYPE: - return FileManagement::toString(fl.fileType()); - case FILECATEGORY: - return FileManagement::toString(fl.fileCategory()); - case FILESTATUS: - return FileManagement::toString(fl.fileStatus()); - case OPERATOR: - return QString::fromStdString(m_opmDtc->user(fl.operatorId()).name()); - case EXERCISE: - return fl.exerciseId().is_set() ? QString::fromStdString(m_exmDtc->exercise(fl.exerciseId().get()).name()) : QVariant(); - case PHASE: - return fl.phaseId().is_set() ? QString::fromStdString(m_exmDtc->exercisePhase(fl.phaseId().get()).name()) : QVariant(); - case USEDBY: - return fl.isUsedBy() ? tr("Yes") : tr("No"); - case USES: - return fl.usedBy(); - case LASTMODIFIED: - return QDateTime::fromMSecsSinceEpoch(fl.lastModified()); - case PROPERTIES: - return QString::fromStdString(fl.properties()); + case Qt::BackgroundRole: { + if (fl.fileStatus() == FileManagement::FileStatus::Deleted) + return QGuiApplication::palette().color(QPalette::Disabled, QPalette::AlternateBase); + return QGuiApplication::palette().color(QPalette::Active, QPalette::Base); + } + case Qt::DisplayRole: { + switch (index.column()) + { + case NAME: + return QString::fromStdString(fl.name()); + case ISTEMPLATE: + return fl.isTemplate() ? tr("Yes") : tr("No"); + case FOLDER: + return fl.folderId(); + case FILEID: + return fl.id(); + case FILETYPE: + return FileManagement::toString(fl.fileType()); + case FILECATEGORY: + return FileManagement::toString(fl.fileCategory()); + case FILESTATUS: + return FileManagement::toString(fl.fileStatus()); + case OPERATOR: + return QString::fromStdString(m_opmDtc->user(fl.operatorId()).name()); + case EXERCISE: + return fl.exerciseId().is_set() + ? QString::fromStdString(m_exmDtc->exercise(fl.exerciseId().get()).name()) + : QVariant(); + case PHASE: + return fl.phaseId().is_set() + ? QString::fromStdString(m_exmDtc->exercisePhase(fl.phaseId().get()).name()) + : QVariant(); + case USEDBY: + return fl.isUsedBy() ? tr("Yes") : tr("No"); + case USES: + return fl.usedBy(); + case LASTMODIFIED: + return QDateTime::fromMSecsSinceEpoch(fl.lastModified()); + case PROPERTIES: + return QString::fromStdString(fl.properties()); + } + } + case Qt::DecorationRole: { + if (index.column() == NAME && fl.isHidden()) + return QIcon(QLatin1String(":/style/lock.svg")); + break; + } + default: + break; } - } - case Qt::DecorationRole: - { - if (index.column() == NAME && fl.isHidden()) - return QIcon(QLatin1String(":/style/lock.svg")); - break; - } - default: - break; - } - return {}; + return {}; } - -FileManagement::FileContent DialogModelFile::findFileFromName(const QString &fileName) const +FileManagement::FileContent DialogModelFile::findFileFromName(const QString& fileName) const { - for (int row = 0; row < rowCount(); ++row) - { - const FileManagement::FileContent &fl = m_vecData.at(row); - if (QString::fromStdString(fl.name()) == fileName) - return fl; - } - return FileManagement::FileContent(); -} - -void DialogFileProxyModel::setSourceModel(QAbstractItemModel *sourceModel) -{ - m_sourceModel = qobject_cast(sourceModel); - LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); + for (int row = 0; row < rowCount(); ++row) + { + const FileManagement::FileContent& fl = m_vecData.at(row); + if (QString::fromStdString(fl.name()) == fileName) + return fl; + } + return FileManagement::FileContent(); } -bool DialogFileProxyModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const +void DialogFileProxyModel::setSourceModel(QAbstractItemModel* sourceModel) { - if (!m_sourceModel || - source_left.column() != source_right.column() || - !source_left.isValid() || - !source_right.isValid()) + m_sourceModel = qobject_cast(sourceModel); + LtsWidgets::LtsColumnFilterProxyModel::setSourceModel(sourceModel); +} + +bool DialogFileProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const +{ + if (!m_sourceModel || source_left.column() != source_right.column() || !source_left.isValid() || + !source_right.isValid()) + return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); + const auto& dataLeft = m_sourceModel->m_vecData.at(source_left.row()); + const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); + switch (source_left.column()) + { + case LASTMODIFIED: + return dataLeft.lastModified() < dataRight.lastModified(); + case NAME: + case FILETYPE: + case FILECATEGORY: + case FILESTATUS: + case ISTEMPLATE: + case EXERCISE: + case PHASE: + case OPERATOR: + case USEDBY: + case USES: + case PROPERTIES: + case FOLDER: + case FILEID: + case COUNT: + break; + } return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); - const auto &dataLeft = m_sourceModel->m_vecData.at(source_left.row()); - const auto dataRight = m_sourceModel->m_vecData.at(source_right.row()); - switch (source_left.column()) - { - case LASTMODIFIED: - return dataLeft.lastModified() < dataRight.lastModified(); - case NAME: - case FILETYPE: - case FILECATEGORY: - case FILESTATUS: - case ISTEMPLATE: - case EXERCISE: - case PHASE: - case OPERATOR: - case USEDBY: - case USES: - case PROPERTIES: - case FOLDER: - case FILEID: - case COUNT: - break; - } - return LtsWidgets::LtsColumnFilterProxyModel::lessThan(source_left, source_right); } - - -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/AreaEffectSimulation/aes_enums.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/AreaEffectSimulation/aes_enums.hpp index 74aa5d4c2..058b7f92c 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/AreaEffectSimulation/aes_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/AreaEffectSimulation/aes_enums.hpp @@ -5,9 +5,9 @@ // DDS-generierte Typen werden im Build-Prozess extern erzeugt // Dieser Stub ermöglicht die Migration und den Build ohne DDS-Generator -#include #include #include +#include namespace AreaEffectSimulation { @@ -16,39 +16,29 @@ namespace AreaEffectSimulation class SymbolAppearance; // Enum für Symbol Visibility (aus DDS-generiertem Code) -enum class SymbolVisibility -{ - Standard = 0, - Faded = 1, - Hidden = 2, - AdditionalSymbol = 3 -}; +enum class SymbolVisibility { Standard = 0, Faded = 1, Hidden = 2, AdditionalSymbol = 3 }; // Enum für Unit Symbol Position (aus DDS-generiertem Code) -enum class UnitSymbolPosition -{ - Center, - Leader -}; +enum class UnitSymbolPosition { Center, Leader }; // Minimaler Stub für SymbolAppearance DDS-Type // Vollständige Definition wird im Build-Prozess durch DDS generiert class SymbolAppearance { -public: - // Standard-Konstruktor - SymbolAppearance() = default; - ~SymbolAppearance() = default; + public: + // Standard-Konstruktor + SymbolAppearance() = default; + ~SymbolAppearance() = default; - // Copy-Konstruktor und Assignment - SymbolAppearance(const SymbolAppearance &) = default; - SymbolAppearance &operator=(const SymbolAppearance &) = default; - SymbolAppearance(SymbolAppearance &&) = default; - SymbolAppearance &operator=(SymbolAppearance &&) = default; + // Copy-Konstruktor und Assignment + SymbolAppearance(const SymbolAppearance&) = default; + SymbolAppearance& operator=(const SymbolAppearance&) = default; + SymbolAppearance(SymbolAppearance&&) = default; + SymbolAppearance& operator=(SymbolAppearance&&) = default; - // Placeholder-Properties (werden durch DDS-Typ ersetzt) - // Diese Properties werden im echten DDS-Typ definiert - QString id; // Placeholder für DDS key + // Placeholder-Properties (werden durch DDS-Typ ersetzt) + // Diese Properties werden im echten DDS-Typ definiert + QString id; // Placeholder für DDS key }; } // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Lts/Services/InfrastructureManagement/ism_enums.hpp b/qt6-after/qt6-migrated-legatus/Lts/Services/InfrastructureManagement/ism_enums.hpp index 02b6642d6..55744b7af 100644 --- a/qt6-after/qt6-migrated-legatus/Lts/Services/InfrastructureManagement/ism_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Lts/Services/InfrastructureManagement/ism_enums.hpp @@ -6,11 +6,12 @@ #ifndef ISM_ENUMS_HPP #define ISM_ENUMS_HPP -#include -#include #include +#include +#include -namespace InfrastructureManagement { +namespace InfrastructureManagement +{ // MountingPointType als enum class mit allen Werten enum class MountingPointType : int32_t { @@ -31,24 +32,16 @@ enum class MountingPointType : int32_t { }; // MountingPointState als enum class mit allen Werten -enum class MountingPointState : int32_t { - Undefined = 0, - Equipped = 1, - Empty = 2, - Idle = 3 -}; +enum class MountingPointState : int32_t { Undefined = 0, Equipped = 1, Empty = 2, Idle = 3 }; // AimState als enum class -enum class AimState : int32_t { - Undefined = 0, - Active = 1, - Inactive = 2 -}; +enum class AimState : int32_t { Undefined = 0, Active = 1, Inactive = 2 }; // DDS type wrapper für MountingPointType -struct MountingPointType_def { +struct MountingPointType_def +{ using type = MountingPointType; - + // Enum values als static members für Kompatibilität static constexpr MountingPointType Undefined = MountingPointType::Undefined; static constexpr MountingPointType Generic = MountingPointType::Generic; @@ -67,9 +60,10 @@ struct MountingPointType_def { }; // DDS type wrapper für MountingPointState -struct MountingPointState_def { +struct MountingPointState_def +{ using type = MountingPointState; - + static constexpr MountingPointState Undefined = MountingPointState::Undefined; static constexpr MountingPointState Equipped = MountingPointState::Equipped; static constexpr MountingPointState Empty = MountingPointState::Empty; @@ -77,9 +71,10 @@ struct MountingPointState_def { }; // DDS type wrapper für AimState -struct AimState_def { +struct AimState_def +{ using type = AimState; - + static constexpr AimState Undefined = AimState::Undefined; static constexpr AimState Active = AimState::Active; static constexpr AimState Inactive = AimState::Inactive; @@ -88,27 +83,31 @@ struct AimState_def { } // namespace InfrastructureManagement // QDebug operator<< für MountingPointType -inline QDebug operator<<(QDebug debug, InfrastructureManagement::MountingPointType type) { +inline QDebug operator<<(QDebug debug, InfrastructureManagement::MountingPointType type) +{ QDebugStateSaver saver(debug); debug.nospace() << "MountingPointType(" << static_cast(type) << ")"; return debug; } // QDebug operator<< für MountingPointState -inline QDebug operator<<(QDebug debug, InfrastructureManagement::MountingPointState state) { +inline QDebug operator<<(QDebug debug, InfrastructureManagement::MountingPointState state) +{ QDebugStateSaver saver(debug); debug.nospace() << "MountingPointState(" << static_cast(state) << ")"; return debug; } // qHash für MountingPointType (für QMap/QHash) -namespace dds { -namespace core { -static inline uint qHash(const InfrastructureManagement::MountingPointType &mpt) +namespace dds { - return ::qHash(static_cast(mpt)); +namespace core +{ +static inline uint qHash(const InfrastructureManagement::MountingPointType& mpt) +{ + return ::qHash(static_cast(mpt)); } -} -} +} // namespace core +} // namespace dds #endif // ISM_ENUMS_HPP diff --git a/qt6-after/qt6-migrated-legatus/MarkerManagement/mrk_dtc.h b/qt6-after/qt6-migrated-legatus/MarkerManagement/mrk_dtc.h index bcdd66f35..d9dc88001 100644 --- a/qt6-after/qt6-migrated-legatus/MarkerManagement/mrk_dtc.h +++ b/qt6-after/qt6-migrated-legatus/MarkerManagement/mrk_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace MarkerManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace MarkerManagement diff --git a/qt6-after/qt6-migrated-legatus/Messaging/msg_dtc.h b/qt6-after/qt6-migrated-legatus/Messaging/msg_dtc.h index 2dfd543d2..e6a935b68 100644 --- a/qt6-after/qt6-migrated-legatus/Messaging/msg_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Messaging/msg_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Messaging { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Messaging diff --git a/qt6-after/qt6-migrated-legatus/MeteoDataManagement/mdm_dtc.h b/qt6-after/qt6-migrated-legatus/MeteoDataManagement/mdm_dtc.h index f3cc7c453..9efa8bfc7 100644 --- a/qt6-after/qt6-migrated-legatus/MeteoDataManagement/mdm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/MeteoDataManagement/mdm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace MeteoDataManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace MeteoDataManagement diff --git a/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_dtc.h b/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_dtc.h index 4db644e89..62a762723 100644 --- a/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_dtc.h +++ b/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace NotificationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace NotificationManagement diff --git a/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_enums.hpp b/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_enums.hpp index b9206ed2a..5b65a07b3 100644 --- a/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/NotificationManagement/nom_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace NotificationManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace NotificationManagement diff --git a/qt6-after/qt6-migrated-legatus/OcSituationServer/oss_dtc.h b/qt6-after/qt6-migrated-legatus/OcSituationServer/oss_dtc.h index 981e4cd56..cd1ffb381 100644 --- a/qt6-after/qt6-migrated-legatus/OcSituationServer/oss_dtc.h +++ b/qt6-after/qt6-migrated-legatus/OcSituationServer/oss_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace OcSituationServer { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace OcSituationServer diff --git a/qt6-after/qt6-migrated-legatus/OperatorManagement/opm_dtc.h b/qt6-after/qt6-migrated-legatus/OperatorManagement/opm_dtc.h index a7fe990c3..c69e9ca0e 100644 --- a/qt6-after/qt6-migrated-legatus/OperatorManagement/opm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/OperatorManagement/opm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace OperatorManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace OperatorManagement diff --git a/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_dtc.h b/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_dtc.h index f144be91e..6b29b3f6c 100644 --- a/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ParticipantManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ParticipantManagement diff --git a/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_enums.hpp b/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_enums.hpp index 620f56f3f..8e4ff784b 100644 --- a/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/ParticipantManagement/ppm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ParticipantManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ParticipantManagement diff --git a/qt6-after/qt6-migrated-legatus/PresentationManagement/pre_dtc.h b/qt6-after/qt6-migrated-legatus/PresentationManagement/pre_dtc.h index 649a9b61b..ad127f9d8 100644 --- a/qt6-after/qt6-migrated-legatus/PresentationManagement/pre_dtc.h +++ b/qt6-after/qt6-migrated-legatus/PresentationManagement/pre_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace PresentationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace PresentationManagement diff --git a/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_dtc.h b/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_dtc.h index 9b329e9ed..9002af552 100644 --- a/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ProjectDataManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ProjectDataManagement diff --git a/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_enums.hpp b/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_enums.hpp index 1801ece2e..b543eaced 100644 --- a/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/ProjectDataManagement/pdm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ProjectDataManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ProjectDataManagement diff --git a/qt6-after/qt6-migrated-legatus/Proxies/Buildings/bld_dtc.h b/qt6-after/qt6-migrated-legatus/Proxies/Buildings/bld_dtc.h index 4544b5be1..1a97ff37a 100644 --- a/qt6-after/qt6-migrated-legatus/Proxies/Buildings/bld_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Proxies/Buildings/bld_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Buildings { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBase/tab_dtc.h b/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBase/tab_dtc.h index 4c1968dd5..c81da3ffd 100644 --- a/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBase/tab_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBase/tab_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBase { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBase diff --git a/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBaseOC/taboc_dtc.h b/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBaseOC/taboc_dtc.h index f17a3d46a..5e5e69eb8 100644 --- a/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBaseOC/taboc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Proxies/TrainingAreaBaseOC/taboc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBaseOC { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBaseOC diff --git a/qt6-after/qt6-migrated-legatus/ReportManagement/rep_dtc.h b/qt6-after/qt6-migrated-legatus/ReportManagement/rep_dtc.h index e995dd8af..a5c0fbce0 100644 --- a/qt6-after/qt6-migrated-legatus/ReportManagement/rep_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ReportManagement/rep_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ReportManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ReportManagement diff --git a/qt6-after/qt6-migrated-legatus/ReportManagement/rep_enums.hpp b/qt6-after/qt6-migrated-legatus/ReportManagement/rep_enums.hpp index 1a69db29d..79221323c 100644 --- a/qt6-after/qt6-migrated-legatus/ReportManagement/rep_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/ReportManagement/rep_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ReportManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ReportManagement diff --git a/qt6-after/qt6-migrated-legatus/ServiceManagement/scm_dtc.h b/qt6-after/qt6-migrated-legatus/ServiceManagement/scm_dtc.h index a3d084c3a..22d8d9a43 100644 --- a/qt6-after/qt6-migrated-legatus/ServiceManagement/scm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/ServiceManagement/scm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ServiceManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ServiceManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/AlarmManagement/alm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/AlarmManagement/alm_dtc.h index e0e3e8edc..48fc0cc57 100644 --- a/qt6-after/qt6-migrated-legatus/Services/AlarmManagement/alm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/AlarmManagement/alm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AlarmManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_dtc.h b/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_dtc.h index f2053458c..53d8cdb02 100644 --- a/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AreaEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_enums.hpp b/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_enums.hpp index 050c7d259..7dc7ece03 100644 --- a/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Services/AreaEffectSimulation/aes_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AreaEffectSimulation { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/Services/AudioVideoManagement/avm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/AudioVideoManagement/avm_dtc.h index 5bcb2e6e6..6ebbe52b0 100644 --- a/qt6-after/qt6-migrated-legatus/Services/AudioVideoManagement/avm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/AudioVideoManagement/avm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AudioVideoManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/CodificationManagement/cod_dtc.h b/qt6-after/qt6-migrated-legatus/Services/CodificationManagement/cod_dtc.h index b86da2200..0aad572f6 100644 --- a/qt6-after/qt6-migrated-legatus/Services/CodificationManagement/cod_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/CodificationManagement/cod_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace CodificationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/EffectShowClient/esc_dtc.h b/qt6-after/qt6-migrated-legatus/Services/EffectShowClient/esc_dtc.h index bf5409eb5..d91be8274 100644 --- a/qt6-after/qt6-migrated-legatus/Services/EffectShowClient/esc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/EffectShowClient/esc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowClient { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/Services/EffectShowManagement/esm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/EffectShowManagement/esm_dtc.h index 15dfc2d81..d73623e87 100644 --- a/qt6-after/qt6-migrated-legatus/Services/EffectShowManagement/esm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/EffectShowManagement/esm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/ExerciseEventManagement/eem_enums.hpp b/qt6-after/qt6-migrated-legatus/Services/ExerciseEventManagement/eem_enums.hpp index 2d197ad96..69fa05e78 100644 --- a/qt6-after/qt6-migrated-legatus/Services/ExerciseEventManagement/eem_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Services/ExerciseEventManagement/eem_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ExerciseEventManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ExerciseEventManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/ExerciseManagement/exm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/ExerciseManagement/exm_dtc.h index d7f5e5ac9..d9f59111e 100644 --- a/qt6-after/qt6-migrated-legatus/Services/ExerciseManagement/exm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/ExerciseManagement/exm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ExerciseManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/FileManagement/flm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/FileManagement/flm_dtc.h index 83888f40a..9a997306f 100644 --- a/qt6-after/qt6-migrated-legatus/Services/FileManagement/flm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/FileManagement/flm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace FileManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_dtc.h b/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_dtc.h index 726a7a246..b62a281ef 100644 --- a/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace InfrastructureManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_enums.hpp b/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_enums.hpp index 21423f23b..369f0caa3 100644 --- a/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Services/InfrastructureManagement/ism_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace InfrastructureManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/Messaging/msg_dtc.h b/qt6-after/qt6-migrated-legatus/Services/Messaging/msg_dtc.h index 2dfd543d2..e6a935b68 100644 --- a/qt6-after/qt6-migrated-legatus/Services/Messaging/msg_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/Messaging/msg_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Messaging { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Messaging diff --git a/qt6-after/qt6-migrated-legatus/Services/MeteoDataManagement/mdm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/MeteoDataManagement/mdm_dtc.h index f3cc7c453..9efa8bfc7 100644 --- a/qt6-after/qt6-migrated-legatus/Services/MeteoDataManagement/mdm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/MeteoDataManagement/mdm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace MeteoDataManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace MeteoDataManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/OperatorManagement/opm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/OperatorManagement/opm_dtc.h index a7fe990c3..c69e9ca0e 100644 --- a/qt6-after/qt6-migrated-legatus/Services/OperatorManagement/opm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/OperatorManagement/opm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace OperatorManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace OperatorManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/ParticipantManagement/ppm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/ParticipantManagement/ppm_dtc.h index f144be91e..6b29b3f6c 100644 --- a/qt6-after/qt6-migrated-legatus/Services/ParticipantManagement/ppm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/ParticipantManagement/ppm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ParticipantManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ParticipantManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/PresentationManagement/pre_dtc.h b/qt6-after/qt6-migrated-legatus/Services/PresentationManagement/pre_dtc.h index 649a9b61b..ad127f9d8 100644 --- a/qt6-after/qt6-migrated-legatus/Services/PresentationManagement/pre_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/PresentationManagement/pre_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace PresentationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace PresentationManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/ProjectDataManagement/pdm_enums.hpp b/qt6-after/qt6-migrated-legatus/Services/ProjectDataManagement/pdm_enums.hpp index 1801ece2e..b543eaced 100644 --- a/qt6-after/qt6-migrated-legatus/Services/ProjectDataManagement/pdm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/Services/ProjectDataManagement/pdm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ProjectDataManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ProjectDataManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/ReportManagement/rep_dtc.h b/qt6-after/qt6-migrated-legatus/Services/ReportManagement/rep_dtc.h index e995dd8af..a5c0fbce0 100644 --- a/qt6-after/qt6-migrated-legatus/Services/ReportManagement/rep_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/ReportManagement/rep_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ReportManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ReportManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/SituationReplayManagement/srm_dtc.h b/qt6-after/qt6-migrated-legatus/Services/SituationReplayManagement/srm_dtc.h index 3d215eb4c..452338f5e 100644 --- a/qt6-after/qt6-migrated-legatus/Services/SituationReplayManagement/srm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/SituationReplayManagement/srm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SituationReplayManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SituationReplayManagement diff --git a/qt6-after/qt6-migrated-legatus/Services/Skeleton/skl_dtc.h b/qt6-after/qt6-migrated-legatus/Services/Skeleton/skl_dtc.h index 51da26438..313cf92cd 100644 --- a/qt6-after/qt6-migrated-legatus/Services/Skeleton/skl_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/Skeleton/skl_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Skeleton { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Skeleton diff --git a/qt6-after/qt6-migrated-legatus/Services/TargetManagement/tgt_dtc.h b/qt6-after/qt6-migrated-legatus/Services/TargetManagement/tgt_dtc.h index 0b242b715..e105df868 100644 --- a/qt6-after/qt6-migrated-legatus/Services/TargetManagement/tgt_dtc.h +++ b/qt6-after/qt6-migrated-legatus/Services/TargetManagement/tgt_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TargetManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TargetManagement diff --git a/qt6-after/qt6-migrated-legatus/SituationReplay/srp_dtc.h b/qt6-after/qt6-migrated-legatus/SituationReplay/srp_dtc.h index 146db6518..71662d223 100644 --- a/qt6-after/qt6-migrated-legatus/SituationReplay/srp_dtc.h +++ b/qt6-after/qt6-migrated-legatus/SituationReplay/srp_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SituationReplay { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SituationReplay diff --git a/qt6-after/qt6-migrated-legatus/SituationReplay/srp_enums.hpp b/qt6-after/qt6-migrated-legatus/SituationReplay/srp_enums.hpp index 78403730e..986ac3e0c 100644 --- a/qt6-after/qt6-migrated-legatus/SituationReplay/srp_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/SituationReplay/srp_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace SituationReplay { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace SituationReplay diff --git a/qt6-after/qt6-migrated-legatus/SituationReplayManagement/srm_dtc.h b/qt6-after/qt6-migrated-legatus/SituationReplayManagement/srm_dtc.h index 3d215eb4c..452338f5e 100644 --- a/qt6-after/qt6-migrated-legatus/SituationReplayManagement/srm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/SituationReplayManagement/srm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SituationReplayManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SituationReplayManagement diff --git a/qt6-after/qt6-migrated-legatus/SoundManagement/som_dtc.h b/qt6-after/qt6-migrated-legatus/SoundManagement/som_dtc.h index f8dd46504..0956c4a91 100644 --- a/qt6-after/qt6-migrated-legatus/SoundManagement/som_dtc.h +++ b/qt6-after/qt6-migrated-legatus/SoundManagement/som_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SoundManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SoundManagement diff --git a/qt6-after/qt6-migrated-legatus/TargetManagement/tgt_dtc.h b/qt6-after/qt6-migrated-legatus/TargetManagement/tgt_dtc.h index 0b242b715..e105df868 100644 --- a/qt6-after/qt6-migrated-legatus/TargetManagement/tgt_dtc.h +++ b/qt6-after/qt6-migrated-legatus/TargetManagement/tgt_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TargetManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TargetManagement diff --git a/qt6-after/qt6-migrated-legatus/TrainingAreaBase/tab_dtc.h b/qt6-after/qt6-migrated-legatus/TrainingAreaBase/tab_dtc.h index 4c1968dd5..c81da3ffd 100644 --- a/qt6-after/qt6-migrated-legatus/TrainingAreaBase/tab_dtc.h +++ b/qt6-after/qt6-migrated-legatus/TrainingAreaBase/tab_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBase { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBase diff --git a/qt6-after/qt6-migrated-legatus/TrainingAreaBaseOC/taboc_dtc.h b/qt6-after/qt6-migrated-legatus/TrainingAreaBaseOC/taboc_dtc.h index f17a3d46a..5e5e69eb8 100644 --- a/qt6-after/qt6-migrated-legatus/TrainingAreaBaseOC/taboc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/TrainingAreaBaseOC/taboc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBaseOC { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBaseOC diff --git a/qt6-after/qt6-migrated-legatus/WarehouseGuez/whg_dtc.h b/qt6-after/qt6-migrated-legatus/WarehouseGuez/whg_dtc.h index 92ac2aaac..6bdff0ea4 100644 --- a/qt6-after/qt6-migrated-legatus/WarehouseGuez/whg_dtc.h +++ b/qt6-after/qt6-migrated-legatus/WarehouseGuez/whg_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace WarehouseGuez { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace WarehouseGuez diff --git a/qt6-after/qt6-migrated-legatus/aes_dtc.h b/qt6-after/qt6-migrated-legatus/aes_dtc.h index f2053458c..53d8cdb02 100644 --- a/qt6-after/qt6-migrated-legatus/aes_dtc.h +++ b/qt6-after/qt6-migrated-legatus/aes_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AreaEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/generic_dtc.h b/qt6-after/qt6-migrated-legatus/generic_dtc.h index 787f7f1cb..9c3aa6d57 100644 --- a/qt6-after/qt6-migrated-legatus/generic_dtc.h +++ b/qt6-after/qt6-migrated-legatus/generic_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace DDS { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace DDS diff --git a/qt6-after/qt6-migrated-legatus/include/AlarmManagement/alm_dtc.h b/qt6-after/qt6-migrated-legatus/include/AlarmManagement/alm_dtc.h index e0e3e8edc..48fc0cc57 100644 --- a/qt6-after/qt6-migrated-legatus/include/AlarmManagement/alm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/AlarmManagement/alm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AlarmManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AlarmManagement diff --git a/qt6-after/qt6-migrated-legatus/include/AreaEffectSimulation/aes_dtc.h b/qt6-after/qt6-migrated-legatus/include/AreaEffectSimulation/aes_dtc.h index f2053458c..53d8cdb02 100644 --- a/qt6-after/qt6-migrated-legatus/include/AreaEffectSimulation/aes_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/AreaEffectSimulation/aes_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AreaEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_dtc.h b/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_dtc.h index b2e40ee30..085fecaf1 100644 --- a/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AssetManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_enums.hpp index 69ea7aa9b..d4ac88b4e 100644 --- a/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/AssetManagement/asm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AssetManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AssetManagement diff --git a/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_dtc.h b/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_dtc.h index 5bcb2e6e6..6ebbe52b0 100644 --- a/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace AudioVideoManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_enums.hpp index 81e092b64..c4a2a16af 100644 --- a/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/AudioVideoManagement/avm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace AudioVideoManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace AudioVideoManagement diff --git a/qt6-after/qt6-migrated-legatus/include/Buildings/bld_dtc.h b/qt6-after/qt6-migrated-legatus/include/Buildings/bld_dtc.h index 4544b5be1..1a97ff37a 100644 --- a/qt6-after/qt6-migrated-legatus/include/Buildings/bld_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Buildings/bld_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Buildings { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/include/Buildings/bld_enums.hpp b/qt6-after/qt6-migrated-legatus/include/Buildings/bld_enums.hpp index 9341ea232..e3f3ac39c 100644 --- a/qt6-after/qt6-migrated-legatus/include/Buildings/bld_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/Buildings/bld_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace Buildings { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace Buildings diff --git a/qt6-after/qt6-migrated-legatus/include/CentralEffectSimulation/ces_dtc.h b/qt6-after/qt6-migrated-legatus/include/CentralEffectSimulation/ces_dtc.h index f5df78efd..afdb06c40 100644 --- a/qt6-after/qt6-migrated-legatus/include/CentralEffectSimulation/ces_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/CentralEffectSimulation/ces_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace CentralEffectSimulation { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace CentralEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/include/CodificationManagement/cod_dtc.h b/qt6-after/qt6-migrated-legatus/include/CodificationManagement/cod_dtc.h index b86da2200..0aad572f6 100644 --- a/qt6-after/qt6-migrated-legatus/include/CodificationManagement/cod_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/CodificationManagement/cod_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace CodificationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace CodificationManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ComponentMonitor/cmo_dtc.h b/qt6-after/qt6-migrated-legatus/include/ComponentMonitor/cmo_dtc.h index 9ce661211..451073155 100644 --- a/qt6-after/qt6-migrated-legatus/include/ComponentMonitor/cmo_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ComponentMonitor/cmo_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ComponentMonitor { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ComponentMonitor diff --git a/qt6-after/qt6-migrated-legatus/include/Core/core_dtc.h b/qt6-after/qt6-migrated-legatus/include/Core/core_dtc.h index 0a13b7ce3..a2fa8e814 100644 --- a/qt6-after/qt6-migrated-legatus/include/Core/core_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Core/core_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Core { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/include/Core/core_enums.hpp b/qt6-after/qt6-migrated-legatus/include/Core/core_enums.hpp index 620e6c95e..7cf5e6fee 100644 --- a/qt6-after/qt6-migrated-legatus/include/Core/core_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/Core/core_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace Core { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace Core diff --git a/qt6-after/qt6-migrated-legatus/include/DDS/generic_dtc.h b/qt6-after/qt6-migrated-legatus/include/DDS/generic_dtc.h index 787f7f1cb..9c3aa6d57 100644 --- a/qt6-after/qt6-migrated-legatus/include/DDS/generic_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/DDS/generic_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace DDS { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace DDS diff --git a/qt6-after/qt6-migrated-legatus/include/DDS/taboc_dtc.h b/qt6-after/qt6-migrated-legatus/include/DDS/taboc_dtc.h index f17a3d46a..5e5e69eb8 100644 --- a/qt6-after/qt6-migrated-legatus/include/DDS/taboc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/DDS/taboc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBaseOC { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBaseOC diff --git a/qt6-after/qt6-migrated-legatus/include/DTC/generic_dtc.h b/qt6-after/qt6-migrated-legatus/include/DTC/generic_dtc.h index 787f7f1cb..9c3aa6d57 100644 --- a/qt6-after/qt6-migrated-legatus/include/DTC/generic_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/DTC/generic_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace DDS { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace DDS diff --git a/qt6-after/qt6-migrated-legatus/include/EffectShowClient/esc_dtc.h b/qt6-after/qt6-migrated-legatus/include/EffectShowClient/esc_dtc.h index bf5409eb5..d91be8274 100644 --- a/qt6-after/qt6-migrated-legatus/include/EffectShowClient/esc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/EffectShowClient/esc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowClient { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowClient diff --git a/qt6-after/qt6-migrated-legatus/include/EffectShowManagement/esm_dtc.h b/qt6-after/qt6-migrated-legatus/include/EffectShowManagement/esm_dtc.h index 15dfc2d81..d73623e87 100644 --- a/qt6-after/qt6-migrated-legatus/include/EffectShowManagement/esm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/EffectShowManagement/esm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace EffectShowManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace EffectShowManagement diff --git a/qt6-after/qt6-migrated-legatus/include/Evaluations/evl_dtc.h b/qt6-after/qt6-migrated-legatus/include/Evaluations/evl_dtc.h index 589171637..89207e684 100644 --- a/qt6-after/qt6-migrated-legatus/include/Evaluations/evl_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Evaluations/evl_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Evaluations { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Evaluations diff --git a/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_dtc.h b/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_dtc.h index 35b8fc6bf..ce5c860f8 100644 --- a/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ExerciseEventManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ExerciseEventManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_enums.hpp b/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_enums.hpp index 2d197ad96..69fa05e78 100644 --- a/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/ExerciseEventManagement/eem_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ExerciseEventManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ExerciseEventManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_dtc.h b/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_dtc.h index d7f5e5ac9..d9f59111e 100644 --- a/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ExerciseManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_enums.hpp index 97c15d67f..63217d29f 100644 --- a/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/ExerciseManagement/exm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ExerciseManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ExerciseManagement diff --git a/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_dtc.h b/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_dtc.h index 83888f40a..9a997306f 100644 --- a/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace FileManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_enums.hpp index b773bcb54..9bef20c39 100644 --- a/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/FileManagement/flm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace FileManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace FileManagement diff --git a/qt6-after/qt6-migrated-legatus/include/GuezIedManagement/gim_dtc.h b/qt6-after/qt6-migrated-legatus/include/GuezIedManagement/gim_dtc.h index fc33757be..1f16e4e83 100644 --- a/qt6-after/qt6-migrated-legatus/include/GuezIedManagement/gim_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/GuezIedManagement/gim_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace GuezIedManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace GuezIedManagement diff --git a/qt6-after/qt6-migrated-legatus/include/GuezNasat/gna_dtc.h b/qt6-after/qt6-migrated-legatus/include/GuezNasat/gna_dtc.h index 5bb435ce5..47d51ae59 100644 --- a/qt6-after/qt6-migrated-legatus/include/GuezNasat/gna_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/GuezNasat/gna_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace GuezNasat { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace GuezNasat diff --git a/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_dtc.h b/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_dtc.h index 726a7a246..b62a281ef 100644 --- a/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace InfrastructureManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_enums.hpp b/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_enums.hpp index 206a891f6..a8e972cff 100644 --- a/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/InfrastructureManagement/ism_enums.hpp @@ -8,7 +8,8 @@ #include -namespace InfrastructureManagement { +namespace InfrastructureManagement +{ // MountingPointType als enum class mit allen Werten enum class MountingPointType : int32_t { @@ -29,24 +30,16 @@ enum class MountingPointType : int32_t { }; // MountingPointState als enum class mit allen Werten -enum class MountingPointState : int32_t { - Undefined = 0, - Equipped = 1, - Empty = 2, - Idle = 3 -}; +enum class MountingPointState : int32_t { Undefined = 0, Equipped = 1, Empty = 2, Idle = 3 }; // AimState als enum class -enum class AimState : int32_t { - Undefined = 0, - Active = 1, - Inactive = 2 -}; +enum class AimState : int32_t { Undefined = 0, Active = 1, Inactive = 2 }; // DDS type wrapper für MountingPointType -struct MountingPointType_def { +struct MountingPointType_def +{ using type = MountingPointType; - + // Enum values als static members für Kompatibilität static constexpr MountingPointType Undefined = MountingPointType::Undefined; static constexpr MountingPointType Generic = MountingPointType::Generic; @@ -65,9 +58,10 @@ struct MountingPointType_def { }; // DDS type wrapper für MountingPointState -struct MountingPointState_def { +struct MountingPointState_def +{ using type = MountingPointState; - + static constexpr MountingPointState Undefined = MountingPointState::Undefined; static constexpr MountingPointState Equipped = MountingPointState::Equipped; static constexpr MountingPointState Empty = MountingPointState::Empty; @@ -75,9 +69,10 @@ struct MountingPointState_def { }; // DDS type wrapper für AimState -struct AimState_def { +struct AimState_def +{ using type = AimState; - + static constexpr AimState Undefined = AimState::Undefined; static constexpr AimState Active = AimState::Active; static constexpr AimState Inactive = AimState::Inactive; diff --git a/qt6-after/qt6-migrated-legatus/include/MarkerManagement/mrk_dtc.h b/qt6-after/qt6-migrated-legatus/include/MarkerManagement/mrk_dtc.h index bcdd66f35..d9dc88001 100644 --- a/qt6-after/qt6-migrated-legatus/include/MarkerManagement/mrk_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/MarkerManagement/mrk_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace MarkerManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace MarkerManagement diff --git a/qt6-after/qt6-migrated-legatus/include/Messaging/msg_dtc.h b/qt6-after/qt6-migrated-legatus/include/Messaging/msg_dtc.h index 2dfd543d2..e6a935b68 100644 --- a/qt6-after/qt6-migrated-legatus/include/Messaging/msg_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Messaging/msg_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Messaging { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Messaging diff --git a/qt6-after/qt6-migrated-legatus/include/MeteoDataManagement/mdm_dtc.h b/qt6-after/qt6-migrated-legatus/include/MeteoDataManagement/mdm_dtc.h index f3cc7c453..9efa8bfc7 100644 --- a/qt6-after/qt6-migrated-legatus/include/MeteoDataManagement/mdm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/MeteoDataManagement/mdm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace MeteoDataManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace MeteoDataManagement diff --git a/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_dtc.h b/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_dtc.h index 4db644e89..62a762723 100644 --- a/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace NotificationManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace NotificationManagement diff --git a/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_enums.hpp b/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_enums.hpp index b9206ed2a..5b65a07b3 100644 --- a/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/NotificationManagement/nom_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace NotificationManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace NotificationManagement diff --git a/qt6-after/qt6-migrated-legatus/include/OcSituationServer/oss_dtc.h b/qt6-after/qt6-migrated-legatus/include/OcSituationServer/oss_dtc.h index 981e4cd56..cd1ffb381 100644 --- a/qt6-after/qt6-migrated-legatus/include/OcSituationServer/oss_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/OcSituationServer/oss_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace OcSituationServer { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace OcSituationServer diff --git a/qt6-after/qt6-migrated-legatus/include/OperatorManagement/opm_dtc.h b/qt6-after/qt6-migrated-legatus/include/OperatorManagement/opm_dtc.h index a7fe990c3..c69e9ca0e 100644 --- a/qt6-after/qt6-migrated-legatus/include/OperatorManagement/opm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/OperatorManagement/opm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace OperatorManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace OperatorManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ParticipantManagement/ppm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/ParticipantManagement/ppm_enums.hpp index 620f56f3f..8e4ff784b 100644 --- a/qt6-after/qt6-migrated-legatus/include/ParticipantManagement/ppm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/ParticipantManagement/ppm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ParticipantManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ParticipantManagement diff --git a/qt6-after/qt6-migrated-legatus/include/PresentationManagement/pre_dtc.h b/qt6-after/qt6-migrated-legatus/include/PresentationManagement/pre_dtc.h index 45c47bf16..343356cf3 100644 --- a/qt6-after/qt6-migrated-legatus/include/PresentationManagement/pre_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/PresentationManagement/pre_dtc.h @@ -1,16 +1,16 @@ /** * @file pre_dtc.h * @brief DDS-generated Stub-Header für PresentationManagement DTC (Data Transfer Component) - * + * * Dieser Header ist ein Stub für den von RTI DDS Generator erzeugten Header. * Ermöglicht Build ohne echte DDS-Codegenerierung. */ #pragma once +#include #include #include -#include #include #include @@ -23,41 +23,41 @@ struct PresentationContent; struct GetPresentationContentReply; // FileStatus Enum - Status einer Präsentation -enum class FileStatus : int { - Valid = 0, - Deleted = 1 -}; +enum class FileStatus : int { Valid = 0, Deleted = 1 }; // Presentation - DDS-generierter Typ für Präsentationen -struct Presentation { - int32_t id = 0; - QString name; - QString description; - int32_t operatorId = 0; - qint64 lastModified = 0; - FileStatus fileStatus = FileStatus::Valid; +struct Presentation +{ + int32_t id = 0; + QString name; + QString description; + int32_t operatorId = 0; + qint64 lastModified = 0; + FileStatus fileStatus = FileStatus::Valid; }; // PresentationContent - Inhalt einer Präsentation -struct PresentationContent { - QString attributes; - QString channel; - QString description; - int32_t duration = 0; - double height = 0.0; - int32_t id = 0; - int32_t index = 0; - int32_t presentationId = 0; - QString presentationTopicType; - qint64 startTime = 0; - double width = 0.0; - double x = 0.0; - double y = 0.0; +struct PresentationContent +{ + QString attributes; + QString channel; + QString description; + int32_t duration = 0; + double height = 0.0; + int32_t id = 0; + int32_t index = 0; + int32_t presentationId = 0; + QString presentationTopicType; + qint64 startTime = 0; + double width = 0.0; + double x = 0.0; + double y = 0.0; }; // GetPresentationContentReply - Reply für GetPresentationContent Request -struct GetPresentationContentReply { - QList content; +struct GetPresentationContentReply +{ + QList content; }; namespace Interface @@ -65,106 +65,125 @@ namespace Interface /** * @brief Dtc - Data Transfer Component für Presentation Management - * + * * DDS-generierte Klasse mit Präsentation-Daten und Signalen für Änderungen. */ -class Dtc : public QObject { - Q_OBJECT - -public: - Dtc() = default; - ~Dtc() override = default; - - // Präsentations-Liste abrufen (Callback-basiert) - void presentations(const std::function& callback) const { - for (const auto& p : m_presentations) { - callback(p); +class Dtc : public QObject +{ + Q_OBJECT + + public: + Dtc() = default; + ~Dtc() override = default; + + // Präsentations-Liste abrufen (Callback-basiert) + void presentations(const std::function& callback) const + { + for (const auto& p : m_presentations) + { + callback(p); + } } - } - - // Präsentations-Liste als QList (für direkten Zugriff) - QList presentationsList() const { return m_presentations; } - - // Präsentation hinzufügen/entfernen/ändern - void addPresentation(const Presentation& p) { - m_presentations.append(p); - emit presentationChanged(p, 0); // 0 = added - } - - void updatePresentation(const Presentation& p) { - for (auto& existing : m_presentations) { - if (existing.id == p.id) { - existing = p; - emit presentationChanged(p, 1); // 1 = modified - return; - } + + // Präsentations-Liste als QList (für direkten Zugriff) + QList presentationsList() const + { + return m_presentations; } - addPresentation(p); - } - - void removePresentation(int id) { - for (auto it = m_presentations.begin(); it != m_presentations.end(); ++it) { - if (it->id == id) { - Presentation removed = *it; - m_presentations.erase(it); - emit presentationChanged(removed, 2); // 2 = removed - return; - } + + // Präsentation hinzufügen/entfernen/ändern + void addPresentation(const Presentation& p) + { + m_presentations.append(p); + emit presentationChanged(p, 0); // 0 = added } - } - - // Content getter/setter für PresentationContent - void content(const std::function& callback) const { - for (const auto& c : m_content) { - callback(c); + + void updatePresentation(const Presentation& p) + { + for (auto& existing : m_presentations) + { + if (existing.id == p.id) + { + existing = p; + emit presentationChanged(p, 1); // 1 = modified + return; + } + } + addPresentation(p); } - } - - QList contentList() const { return m_content; } - - void setContent(const QList& content) { - m_content = content; - } - -signals: - // Signal für Präsentations-Änderungen - void presentationChanged(const Presentation& presentation, int modificationType); - -private: - QList m_presentations; - QList m_content; + + void removePresentation(int id) + { + for (auto it = m_presentations.begin(); it != m_presentations.end(); ++it) + { + if (it->id == id) + { + Presentation removed = *it; + m_presentations.erase(it); + emit presentationChanged(removed, 2); // 2 = removed + return; + } + } + } + + // Content getter/setter für PresentationContent + void content(const std::function& callback) const + { + for (const auto& c : m_content) + { + callback(c); + } + } + + QList contentList() const + { + return m_content; + } + + void setContent(const QList& content) + { + m_content = content; + } + + signals: + // Signal für Präsentations-Änderungen + void presentationChanged(const Presentation& presentation, int modificationType); + + private: + QList m_presentations; + QList m_content; }; /** * @brief Ftc - Filter Topic Client für Presentation Management - * + * * DDS-generierte Klasse für Presentation-Client-Operationen. */ class Ftc { -public: - using ModifyTypeReplyHandler = std::function; - - virtual ~Ftc() = default; + public: + using ModifyTypeReplyHandler = std::function; - /** - * @brief Factory-Methode zur Erstellung einer Ftc-Instanz - * @param connector DDS-Connector (wird im Stub ignoriert) - * @return Shared Pointer zur Ftc-Instanz (nullptr im Stub) - */ - static std::shared_ptr create(void* /*connector*/) - { - return nullptr; // Stub returns nullptr - actual implementation requires DDS - } + virtual ~Ftc() = default; - // PresentationModify Reply Handler - virtual void presentationModifyReply(ModifyTypeReplyHandler handler) = 0; - - // PresentationRemove Reply Handler - virtual void presentationRemoveReply(ModifyTypeReplyHandler handler) = 0; - - // GetPresentationContent Reply Handler - virtual void getPresentationContentReply(const GetPresentationContentReply& reply) = 0; + /** + * @brief Factory-Methode zur Erstellung einer Ftc-Instanz + * @param connector DDS-Connector (wird im Stub ignoriert) + * @return Shared Pointer zur Ftc-Instanz (nullptr im Stub) + */ + static std::shared_ptr create(void* /*connector*/) + { + return nullptr; // Stub returns nullptr - actual implementation requires DDS + } + + // PresentationModify Reply Handler + virtual void presentationModifyReply(ModifyTypeReplyHandler handler) = 0; + + // PresentationRemove Reply Handler + virtual void presentationRemoveReply(ModifyTypeReplyHandler handler) = 0; + + // GetPresentationContent Reply Handler + virtual void getPresentationContentReply(const GetPresentationContentReply& reply) = 0; }; } // namespace Interface diff --git a/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_dtc.h b/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_dtc.h index 9b329e9ed..9002af552 100644 --- a/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ProjectDataManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ProjectDataManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_enums.hpp b/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_enums.hpp index 7c4299f23..d4c4da5d0 100644 --- a/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/ProjectDataManagement/pdm_enums.hpp @@ -5,100 +5,214 @@ #pragma once -#include #include +#include -namespace ProjectDataManagement { +namespace ProjectDataManagement +{ // Original enums -enum class ChargeType : int { - Unknown = 0 -}; +enum class ChargeType : int { Unknown = 0 }; -enum class UnitType : int { - Unknown = 0 -}; +enum class UnitType : int { Unknown = 0 }; -enum class SimulationType : int { - Unknown = 0 -}; +enum class SimulationType : int { Unknown = 0 }; // Additional enums required by AdlerJson/telegrams.h enum class L4_TargetGeometry : int { Unknown = 0, - Point, // P - Punktziel - Area, // F - Flaechenziel - Radial, // R - Radialziel - Linear, // L - Linearziel - A, L, L4_T, P, R, - E, F1, F2, F3, F4, F5, F6, F7, F8, F9 + Point, // P - Punktziel + Area, // F - Flaechenziel + Radial, // R - Radialziel + Linear, // L - Linearziel + A, + L, + L4_T, + P, + R, + E, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9 }; enum class L7_Request : int { Unknown = 0, - ABR, BEI, BEK, BEL, BEO, BEW, BLE, BLI, BLW, BWL, - L7_R, MBE, MBL, MIR, MRK, NIE, SPE, STO, UBW, VER, WRN, ZER, ZSL + ABR, + BEI, + BEK, + BEL, + BEO, + BEW, + BLE, + BLI, + BLW, + BWL, + L7_R, + MBE, + MBL, + MIR, + MRK, + NIE, + SPE, + STO, + UBW, + VER, + WRN, + ZER, + ZSL }; enum class L19_Oi : int { Unknown = 0, - Empty, // Orts ID nicht gesetzt - F1, F2, F3, F4, F5, F6, F7, F8, F9, // Feuerstellungen - L // Ladeplatz + Empty, // Orts ID nicht gesetzt + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, // Feuerstellungen + L // Ladeplatz }; enum class L22_FireHaltCategory : int { - A = 0, // Feuer HALT Allgemein - R, // Feuer HALT Referenziert - E, // Feuer Einstellen - C, // Aufheben Feuer HALT Allgemein - F // Aufheben Feuer HALT Referenziert + A = 0, // Feuer HALT Allgemein + R, // Feuer HALT Referenziert + E, // Feuer Einstellen + C, // Aufheben Feuer HALT Allgemein + F // Aufheben Feuer HALT Referenziert }; -enum class L25_KindGuidingLine : int { - FFA = 0, - NFA, RFA, FSCL, RFL, FSSL, NFL -}; +enum class L25_KindGuidingLine : int { FFA = 0, NFA, RFA, FSCL, RFL, FSSL, NFL }; -enum class L26_EffectingSystemType : int { - Unknown = 0, - Pzh2000, - RRohr, - Mars, - L26_E, M, P, RR -}; +enum class L26_EffectingSystemType : int { Unknown = 0, Pzh2000, RRohr, Mars, L26_E, M, P, RR }; enum class L27_EffectorId : int { Unknown = 0, // Letter IDs - A, B, B1, B2, B3, B4, B5, B6, B7, B8, - C, C1, C2, C3, C4, C5, C6, C7, C8, - D, E, F, G, H, I, J, K, L, L27_E, - M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, + A, + B, + B1, + B2, + B3, + B4, + B5, + B6, + B7, + B8, + C, + C1, + C2, + C3, + C4, + C5, + C6, + C7, + C8, + D, + E, + F, + G, + H, + I, + J, + K, + L, + L27_E, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, // Numeric IDs - NO_211, NO_212, NO_213, NO_214, NO_215, NO_216, NO_217, NO_218, - NO_221, NO_222, NO_223, NO_224, NO_225, NO_226, NO_227, NO_228, - NO_311, NO_312, NO_313, NO_314, NO_315, NO_316, NO_317, NO_318, - NO_321, NO_322, NO_323, NO_324, NO_325, NO_326, NO_327, NO_328, - NO_411, NO_412, NO_413, NO_414, NO_415, NO_416, NO_417, NO_418, - NO_421, NO_422, NO_423, NO_424, NO_425, NO_426, NO_427, NO_428, - NO_511, NO_512, NO_513, NO_514, NO_515, NO_516, NO_517, NO_518, - NO_521, NO_522, NO_523, NO_524, NO_525, NO_526, NO_527, NO_528 + NO_211, + NO_212, + NO_213, + NO_214, + NO_215, + NO_216, + NO_217, + NO_218, + NO_221, + NO_222, + NO_223, + NO_224, + NO_225, + NO_226, + NO_227, + NO_228, + NO_311, + NO_312, + NO_313, + NO_314, + NO_315, + NO_316, + NO_317, + NO_318, + NO_321, + NO_322, + NO_323, + NO_324, + NO_325, + NO_326, + NO_327, + NO_328, + NO_411, + NO_412, + NO_413, + NO_414, + NO_415, + NO_416, + NO_417, + NO_418, + NO_421, + NO_422, + NO_423, + NO_424, + NO_425, + NO_426, + NO_427, + NO_428, + NO_511, + NO_512, + NO_513, + NO_514, + NO_515, + NO_516, + NO_517, + NO_518, + NO_521, + NO_522, + NO_523, + NO_524, + NO_525, + NO_526, + NO_527, + NO_528 }; -enum class L28_Status : int { - NichtEinsatzbereit = 0, - Einsatzbereit -}; +enum class L28_Status : int { NichtEinsatzbereit = 0, Einsatzbereit }; -enum class L46_GpsFrequency : int { - L1 = 0, - L2 -}; +enum class L46_GpsFrequency : int { L1 = 0, L2 }; -enum class L48_TrajectoryRocket : int { - Nominal = 0, - Vertical -}; +enum class L48_TrajectoryRocket : int { Nominal = 0, Vertical }; } // namespace ProjectDataManagement \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_dtc.h b/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_dtc.h index e995dd8af..a5c0fbce0 100644 --- a/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ReportManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ReportManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_enums.hpp b/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_enums.hpp index 1a69db29d..79221323c 100644 --- a/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/ReportManagement/rep_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ReportManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ReportManagement diff --git a/qt6-after/qt6-migrated-legatus/include/ScenarioManagement/scm_dtc.h b/qt6-after/qt6-migrated-legatus/include/ScenarioManagement/scm_dtc.h index a3d084c3a..22d8d9a43 100644 --- a/qt6-after/qt6-migrated-legatus/include/ScenarioManagement/scm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/ScenarioManagement/scm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace ServiceManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace ServiceManagement diff --git a/qt6-after/qt6-migrated-legatus/include/Services/AreaEffectSimulation/aes_enums.hpp b/qt6-after/qt6-migrated-legatus/include/Services/AreaEffectSimulation/aes_enums.hpp index 360319d73..e372cd332 100644 --- a/qt6-after/qt6-migrated-legatus/include/Services/AreaEffectSimulation/aes_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/Services/AreaEffectSimulation/aes_enums.hpp @@ -7,66 +7,61 @@ namespace AreaEffectSimulation { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; // AesType - Arten von Area Effect Simulation Entities enum class AesType : int { - AtBCContamination = 0, - AtNContamination = 1, - AtDangerArea = 2, - AtMineArea = 3, - AtMineCorridor = 4, - AtExplosionSingle = 5, - AtExplosionArea = 6, - AtFunctionalArea = 7, - AtBorderline = 8, - AtMineAreaSingleMines = 9, - AtDusSingleMine = 10, - AtGasPipe = 11, - AtTechnicalArea = 12, - AtAirSupportImpact = 13, - AtUnknown = 99 + AtBCContamination = 0, + AtNContamination = 1, + AtDangerArea = 2, + AtMineArea = 3, + AtMineCorridor = 4, + AtExplosionSingle = 5, + AtExplosionArea = 6, + AtFunctionalArea = 7, + AtBorderline = 8, + AtMineAreaSingleMines = 9, + AtDusSingleMine = 10, + AtGasPipe = 11, + AtTechnicalArea = 12, + AtAirSupportImpact = 13, + AtUnknown = 99 }; // AesEffectState_def - Status eines AES Effekts (mit _def Suffix wie DDS generiert) enum class AesEffectState_def : int { - EsCreated = 0, - EsPrepared = 1, - EsFired = 2, - EsActivated = 3, - EsPaused = 4, - EsExpired = 5, - EsRemoved = 6, - EsReceived = 7, - EsUnknown = 99, - EsError = 100 + EsCreated = 0, + EsPrepared = 1, + EsFired = 2, + EsActivated = 3, + EsPaused = 4, + EsExpired = 5, + EsRemoved = 6, + EsReceived = 7, + EsUnknown = 99, + EsError = 100 }; // AesEffectState - Alias für AesEffectState_def (Backward Compatibility) using AesEffectState = AesEffectState_def; // EffectStateStruct - Filter-Struktur für Effect States -struct EffectStateStruct { - bool showCreated = true; - bool showPrepared = true; - bool showActive = true; - bool showInactive = false; - bool showExpired = false; +struct EffectStateStruct +{ + bool showCreated = true; + bool showPrepared = true; + bool showActive = true; + bool showInactive = false; + bool showExpired = false; }; } // namespace AreaEffectSimulation diff --git a/qt6-after/qt6-migrated-legatus/include/Services/InfrastructureManagement/ism_dtc.h b/qt6-after/qt6-migrated-legatus/include/Services/InfrastructureManagement/ism_dtc.h index 726a7a246..b62a281ef 100644 --- a/qt6-after/qt6-migrated-legatus/include/Services/InfrastructureManagement/ism_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Services/InfrastructureManagement/ism_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace InfrastructureManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace InfrastructureManagement diff --git a/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_dtc.h b/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_dtc.h index 146db6518..71662d223 100644 --- a/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SituationReplay { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SituationReplay diff --git a/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_enums.hpp b/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_enums.hpp index 78403730e..986ac3e0c 100644 --- a/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/include/SituationReplay/srp_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace SituationReplay { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace SituationReplay diff --git a/qt6-after/qt6-migrated-legatus/include/SituationReplayManagement/srm_dtc.h b/qt6-after/qt6-migrated-legatus/include/SituationReplayManagement/srm_dtc.h index 3d215eb4c..452338f5e 100644 --- a/qt6-after/qt6-migrated-legatus/include/SituationReplayManagement/srm_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/SituationReplayManagement/srm_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SituationReplayManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SituationReplayManagement diff --git a/qt6-after/qt6-migrated-legatus/include/Skeleton/skl_dtc.h b/qt6-after/qt6-migrated-legatus/include/Skeleton/skl_dtc.h index 51da26438..313cf92cd 100644 --- a/qt6-after/qt6-migrated-legatus/include/Skeleton/skl_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/Skeleton/skl_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace Skeleton { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace Skeleton diff --git a/qt6-after/qt6-migrated-legatus/include/SoundManagement/som_dtc.h b/qt6-after/qt6-migrated-legatus/include/SoundManagement/som_dtc.h index f8dd46504..0956c4a91 100644 --- a/qt6-after/qt6-migrated-legatus/include/SoundManagement/som_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/SoundManagement/som_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace SoundManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace SoundManagement diff --git a/qt6-after/qt6-migrated-legatus/include/TargetManagement/tgt_dtc.h b/qt6-after/qt6-migrated-legatus/include/TargetManagement/tgt_dtc.h index 0b242b715..e105df868 100644 --- a/qt6-after/qt6-migrated-legatus/include/TargetManagement/tgt_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/TargetManagement/tgt_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TargetManagement { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TargetManagement diff --git a/qt6-after/qt6-migrated-legatus/include/TrainingAreaBase/tab_dtc.h b/qt6-after/qt6-migrated-legatus/include/TrainingAreaBase/tab_dtc.h index 4c1968dd5..c81da3ffd 100644 --- a/qt6-after/qt6-migrated-legatus/include/TrainingAreaBase/tab_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/TrainingAreaBase/tab_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBase { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBase diff --git a/qt6-after/qt6-migrated-legatus/include/TrainingAreaBaseOC/taboc_dtc.h b/qt6-after/qt6-migrated-legatus/include/TrainingAreaBaseOC/taboc_dtc.h index f17a3d46a..5e5e69eb8 100644 --- a/qt6-after/qt6-migrated-legatus/include/TrainingAreaBaseOC/taboc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/TrainingAreaBaseOC/taboc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBaseOC { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBaseOC diff --git a/qt6-after/qt6-migrated-legatus/include/WarehouseGuez/whg_dtc.h b/qt6-after/qt6-migrated-legatus/include/WarehouseGuez/whg_dtc.h index 92ac2aaac..6bdff0ea4 100644 --- a/qt6-after/qt6-migrated-legatus/include/WarehouseGuez/whg_dtc.h +++ b/qt6-after/qt6-migrated-legatus/include/WarehouseGuez/whg_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace WarehouseGuez { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace WarehouseGuez diff --git a/qt6-after/qt6-migrated-legatus/pdm_enums.hpp b/qt6-after/qt6-migrated-legatus/pdm_enums.hpp index 1801ece2e..b543eaced 100644 --- a/qt6-after/qt6-migrated-legatus/pdm_enums.hpp +++ b/qt6-after/qt6-migrated-legatus/pdm_enums.hpp @@ -1,24 +1,19 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Typ-Definitionen namespace ProjectDataManagement { // Placeholder enums - werden durch echte DDS-Typen ersetzt -enum class SymbolAppearance : int { - Solid = 0, - Dashed = 1, - Dotted = 2 -}; +enum class SymbolAppearance : int { Solid = 0, Dashed = 1, Dotted = 2 }; -enum class SymbolVisibility : int { - Visible = 0, - Hidden = 1 -}; +enum class SymbolVisibility : int { Visible = 0, Hidden = 1 }; -struct UnitSymbolPosition { - double x = 0.0; - double y = 0.0; - double z = 0.0; +struct UnitSymbolPosition +{ + double x = 0.0; + double y = 0.0; + double z = 0.0; }; -} +} // namespace ProjectDataManagement diff --git a/qt6-after/qt6-migrated-legatus/taboc_dtc.h b/qt6-after/qt6-migrated-legatus/taboc_dtc.h index f17a3d46a..5e5e69eb8 100644 --- a/qt6-after/qt6-migrated-legatus/taboc_dtc.h +++ b/qt6-after/qt6-migrated-legatus/taboc_dtc.h @@ -1,4 +1,5 @@ #pragma once + // STUB-HEADER: Diese Datei wird normalerweise von ddsdtc generiert // Für die Migration erstellen wir minimale Forward-Declarations @@ -6,7 +7,7 @@ namespace TrainingAreaBaseOC { namespace Interface { - class Dtc; - class Ftc; -} -} +class Dtc; +class Ftc; +} // namespace Interface +} // namespace TrainingAreaBaseOC diff --git a/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt b/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt deleted file mode 100644 index 136ad1997..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/CMakeLists.txt +++ /dev/null @@ -1,85 +0,0 @@ -# CMakeLists.txt für Qt6-Migrationstests -# Diese Tests validieren BUILD_RTI Guards, Qt6-Kompatibilität und RTI-Integration - -cmake_minimum_required(VERSION 3.16) - -# Qt6 finden (wird vom Hauptprojekt gesetzt, aber sicherheitshalber hier auch) -find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets Test) - -# Try to find system-wide GTest first, fallback to FetchContent -find_package(GTest QUIET) -if(NOT TARGET GTest::gtest_main) - include(FetchContent) - FetchContent_Declare( - googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG v1.13.0 - ) - # For Windows: Prevent overriding the parent project's compiler/linker settings - set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - FetchContent_MakeAvailable(googletest) -endif() - -# Nur bauen wenn BUILD_TESTING aktiviert ist -if(BUILD_TESTING) - # Collect all test source files - set(MIGRATION_TEST_SOURCES - test_build_rti_guards.cpp - test_qt6_compatibility.cpp - test_qt6_api_migrations.cpp - test_export_headers.cpp - test_symbology_xml.cpp - test_saa_telegrams.cpp - test_rti_integration.cpp - test_ltswidgets_qt6.cpp - ) - - # Check which files actually exist - set(EXISTING_SOURCES "") - foreach(src ${MIGRATION_TEST_SOURCES}) - if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${src}") - list(APPEND EXISTING_SOURCES "${src}") - endif() - endforeach() - - if(EXISTING_SOURCES) - add_executable(migration_tests ${EXISTING_SOURCES}) - - target_compile_features(migration_tests PRIVATE cxx_std_23) - - target_include_directories(migration_tests PRIVATE - ${CMAKE_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/include - ) - - # Link against Qt6 components - target_link_libraries(migration_tests PRIVATE - Qt6::Core - Qt6::Gui - Qt6::Widgets - Qt6::Test - GTest::gtest_main - ) - - # RTI libraries if BUILD_RTI is ON - if(BUILD_RTI) - find_package(RTI QUIET) - if(RTI_FOUND) - target_include_directories(migration_tests PRIVATE ${RTI_INCLUDE_DIRS}) - target_link_libraries(migration_tests PRIVATE ${RTI_LIBRARIES}) - target_compile_definitions(migration_tests PRIVATE BUILD_RTI=1) - message(STATUS "RTI found: ${RTI_LIBRARIES}") - else() - message(STATUS "BUILD_RTI=ON but RTI not found - building tests without RTI") - endif() - endif() - - # Register with CTest - include(GoogleTest) - gtest_discover_tests(migration_tests) - - message(STATUS "Migration tests enabled: ${EXISTING_SOURCES}") - else() - message(WARNING "No migration test sources found in ${CMAKE_CURRENT_SOURCE_DIR}") - endif() -endif() \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_build_rti_guards.cpp b/qt6-after/qt6-migrated-legatus/tests/test_build_rti_guards.cpp deleted file mode 100644 index d3be89042..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_build_rti_guards.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @file test_build_rti_guards.cpp - * @brief Tests für BUILD_RTI conditional compilation guards - * - * Tests verify that: - * 1. Code compiles with BUILD_RTI=OFF (fallback mode) - * 2. RTI-dependent code is properly guarded - * 3. Non-RTI code paths work correctly - */ - -#include - -// Test 1: Verify BUILD_RTI macro is defined correctly -TEST(BuildRTIGuards, MacroDefined) { -#ifdef BUILD_RTI - // When BUILD_RTI is enabled, it should be 1 - EXPECT_EQ(BUILD_RTI, 1); -#else - // When BUILD_RTI is disabled, it should be 0 or undefined - // This test passes in fallback mode - SUCCEED(); -#endif -} - -// Test 2: Verify DDS connector compiles without RTI -TEST(BuildRTIGuards, DDSConnectorFallback) { - // This test verifies that DDS-related headers can be included - // and basic functionality works without RTI libraries - // The actual DDS connector should have fallback implementations - bool rti_available = false; -#ifdef BUILD_RTI - rti_available = true; -#endif - EXPECT_FALSE(rti_available); // In fallback mode, RTI is not available -} - -// Test 3: Verify conditional compilation doesn't break build -TEST(BuildRTIGuards, ConditionalCompilationSafe) { - // Verify that #if BUILD_RTI guards don't cause syntax errors - int value = 0; -#if BUILD_RTI - value = 1; -#endif - // In fallback mode, value should remain 0 - EXPECT_EQ(value, 0); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_export_headers.cpp b/qt6-after/qt6-migrated-legatus/tests/test_export_headers.cpp deleted file mode 100644 index dfe73f336..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_export_headers.cpp +++ /dev/null @@ -1,110 +0,0 @@ -/** - * @file test_export_headers.cpp - * @brief Tests für Export Header Guards - * - * Tests verify that export headers exist and can be included without errors. - * Note: Export macros are defined via CMake target_compile_definitions, - * so we test header existence and structure rather than macro expansion. - */ - -#include -#include -#include -#include - -// Helper to check if file exists and is readable -bool fileExists(const std::string& path) { - std::ifstream file(path); - return file.good(); -} - -// Helper to read file content -std::string readFile(const std::string& path) { - std::ifstream file(path); - if (!file.is_open()) { - return ""; - } - return std::string((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); -} - -// Test 1: nglwidgets_export.h exists -TEST(ExportHeaders, NglWidgetsExportExists) { - std::string path = "build/Z/src/nglwidgets/nglwidgets_export.h"; - EXPECT_TRUE(fileExists(path)) << "Export header not found: " << path; -} - -// Test 2: qtsingleapplication_export.h exists -TEST(ExportHeaders, QtSingleApplicationExportExists) { - std::string path = "build/Z/src/QtSingleApplication/qtsingleapplication_export.h"; - EXPECT_TRUE(fileExists(path)) << "Export header not found: " << path; -} - -// Test 3: ltssessiondata_export.h exists -TEST(ExportHeaders, LtsSessionDataExportExists) { - std::string path = "build/Lts/Common/LtsSession/ltssessiondata_export.h"; - EXPECT_TRUE(fileExists(path)) << "Export header not found: " << path; -} - -// Test 4: svcgmpserver_export.h exists -TEST(ExportHeaders, SvcGmpServerExportExists) { - std::string path = "build/Lts/Services/GuezMinelayerProcessing/svcgmpserver_export.h"; - EXPECT_TRUE(fileExists(path)) << "Export header not found: " << path; -} - -// Test 5: Export headers have proper include guards -TEST(ExportHeaders, HaveIncludeGuards) { - std::vector headers = { - "build/Z/src/nglwidgets/nglwidgets_export.h", - "build/Z/src/QtSingleApplication/qtsingleapplication_export.h", - "build/Lts/Common/LtsSession/ltssessiondata_export.h", - "build/Lts/Proxies/ProjectDataManagement/pdm_export.h" - }; - - for (const auto& header : headers) { - std::string content = readFile(header); - if (!content.empty()) { - // Check for #ifndef guard - bool hasIfndef = content.find("#ifndef") != std::string::npos; - bool hasDefine = content.find("#define") != std::string::npos; - bool hasEndif = content.find("#endif") != std::string::npos; - - EXPECT_TRUE(hasIfndef && hasDefine && hasEndif) - << "Header " << header << " missing proper include guards"; - } - } -} - -// Test 6: Export macros follow naming convention -TEST(ExportHeaders, MacroNamingConvention) { - // Check that export headers follow CMake naming convention - std::string adlerPath = "qt-migration-legatus/qt6-after/qt6-migrated-legatus/build/Lts/Plugins/AdlerJson/adler_export.h"; - std::string content = readFile(adlerPath); - - if (!content.empty()) { - // Should have ADLER_EXPORT_H guard - bool hasCorrectGuard = content.find("#ifndef ADLER_EXPORT_H") != std::string::npos; - EXPECT_TRUE(hasCorrectGuard) << "adler_export.h should use ADLER_EXPORT_H guard"; - } -} - -// Test 7: Export headers define both EXPORT and NO_EXPORT macros -TEST(ExportHeaders, ExportAndNoExportMacros) { - std::vector> expectedMacros = { - {"qt-migration-legatus/qt6-after/qt6-migrated-legatus/build/Lts/Plugins/AdlerJson/adler_export.h", "ADLER"}, - {"qt-migration-legatus/qt6-after/qt6-migrated-legatus/build/Lts/Services/PresentationManagement/svcprecommon_export.h", "SVCPRECOMMON"}, - {"qt-migration-legatus/qt6-after/qt6-migrated-legatus/build/Lts/Common/LtsSession/ltssessiondata_export.h", "LTSESSIONDATA"}, - {"qt-migration-legatus/qt6-after/qt6-migrated-legatus/build/Lts/Proxies/ProjectDataManagement/pdm_export.h", "PDM"} - }; - - for (const auto& [header, prefix] : expectedMacros) { - std::string content = readFile(header); - if (!content.empty()) { - bool hasExport = content.find(prefix + "_EXPORT") != std::string::npos; - bool hasNoExport = content.find(prefix + "_NO_EXPORT") != std::string::npos; - - EXPECT_TRUE(hasExport) << header << " should define " << prefix << "_EXPORT"; - EXPECT_TRUE(hasNoExport) << header << " should define " << prefix << "_NO_EXPORT"; - } - } -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp b/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp deleted file mode 100644 index 269878e3e..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_ltswidgets_qt6.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/** - * @file test_ltswidgets_qt6.cpp - * @brief Tests für LtsWidgets Qt6-Migration - * - * Tests verify Qt6 API compatibility changes: - * 1. QRandomGenerator usage (replacing qrand()) - * 2. Signal/slot connections with Qt6 signatures - * 3. QWheelEvent angleDelta() usage - * 4. QStyleOption::initFrom() usage - */ - -#include -#include -#include -#include -#include -#include -#include - -// Ensure QApplication is initialized for widget tests -static bool appInitialized = false; -static void ensureAppInitialized() { - if (!appInitialized) { - static int argc = 1; - static char* argv[] = { (char*)"test_ltswidgets_qt6", nullptr }; - static QApplication app(argc, argv); - appInitialized = true; - } -} - -// Test 1: QRandomGenerator bounded generation (used in lts_tab_widget.cpp) -TEST(LtsWidgetsQt6, QRandomGeneratorBounded) { - auto* generator = QRandomGenerator::global(); - ASSERT_NE(generator, nullptr); - - // Test multiple bounded calls to ensure stability - for (int i = 0; i < 100; ++i) { - int value = generator->bounded(10); - EXPECT_GE(value, 0); - EXPECT_LT(value, 10); - } -} - -// Test 2: QRandomGenerator produces different values -TEST(LtsWidgetsQt6, QRandomGeneratorVariation) { - auto* generator = QRandomGenerator::global(); - - QVector values; - for (int i = 0; i < 50; ++i) { - values.append(generator->bounded(1000)); - } - - // Check that we get some variation (not all same value) - bool hasDifferent = false; - for (int i = 1; i < values.size(); ++i) { - if (values[i] != values[0]) { - hasDifferent = true; - break; - } - } - EXPECT_TRUE(hasDifferent); -} - -// Test 3: QRandomGenerator seeded reproducibility -TEST(LtsWidgetsQt6, QRandomGeneratorSeeded) { - QRandomGenerator gen1(12345); - QRandomGenerator gen2(12345); - - // Same seed should produce same sequence - for (int i = 0; i < 10; ++i) { - EXPECT_EQ(gen1.bounded(1000), gen2.bounded(1000)); - } -} - -// Test 4: QComboBox currentTextChanged signal (Qt6 compatible) -// This tests the signal used in lts_text_editor.cpp -TEST(LtsWidgetsQt6, QComboBoxCurrentTextChangedSignal) { - ensureAppInitialized(); - - QComboBox comboBox; - comboBox.addItem("Option1"); - comboBox.addItem("Option2"); - comboBox.addItem("Option3"); - - bool signalReceived = false; - QString receivedText; - - QObject::connect(&comboBox, &QComboBox::currentTextChanged, - [&signalReceived, &receivedText](const QString& text) { - signalReceived = true; - receivedText = text; - }); - - comboBox.setCurrentIndex(1); - - EXPECT_TRUE(signalReceived); - EXPECT_EQ(receivedText, "Option2"); -} - -// Test 5: QComboBox activated signal with int parameter (Qt6) -// Note: activated signal is only emitted on user interaction, not on setCurrentIndex -TEST(LtsWidgetsQt6, QComboBoxActivatedIntSignal) { - ensureAppInitialized(); - - QComboBox comboBox; - comboBox.addItem("First"); - comboBox.addItem("Second"); - comboBox.addItem("Third"); - - bool signalReceived = false; - int receivedIndex = -1; - - // Connect using Qt6 syntax - activated emits int index - QObject::connect(&comboBox, QOverload::of(&QComboBox::activated), - [&signalReceived, &receivedIndex](int index) { - signalReceived = true; - receivedIndex = index; - }); - - // Simulate user interaction by emitting the signal manually - // (setCurrentIndex does not trigger activated signal) - QMetaObject::invokeMethod(&comboBox, "activated", Qt::QueuedConnection, Q_ARG(int, 2)); - QCoreApplication::processEvents(); - - // Verify the connection works with int parameter - EXPECT_TRUE(signalReceived); - EXPECT_EQ(receivedIndex, 2); -} - -// Test 6: QStyleOption::initFrom() (Qt6 replacement for init()) -// This tests the API used in lts_notification_box.cpp -TEST(LtsWidgetsQt6, QStyleOptionInitFrom) { - ensureAppInitialized(); - - QPushButton button("Test"); - button.resize(100, 30); - button.setEnabled(true); - - QStyleOption opt; - opt.initFrom(&button); - - // Verify initFrom sets up the option correctly - // State_Enabled should be set (among other states) - EXPECT_TRUE(opt.state & QStyle::State_Enabled); - EXPECT_FALSE(opt.rect.isNull()); -} - -// Test 7: QStyleOption multiple widgets -TEST(LtsWidgetsQt6, QStyleOptionInitFromMultipleWidgets) { - ensureAppInitialized(); - - QPushButton button1("Btn1"); - QPushButton button2("Btn2"); - button1.setEnabled(true); - button2.setEnabled(false); - - QStyleOption opt1; - opt1.initFrom(&button1); - - QStyleOption opt2; - opt2.initFrom(&button2); - - // Verify different widget states are captured - EXPECT_TRUE(opt1.state & QStyle::State_Enabled); - EXPECT_FALSE(opt2.state & QStyle::State_Enabled); -} - -// Test 8: QWheelEvent angleDelta() availability -// This verifies the API used in lts_date_time_edit_p.cpp -TEST(LtsWidgetsQt6, QWheelEventAngleDelta) { - ensureAppInitialized(); - - QPoint pos(100, 100); - QPoint globalPos(200, 200); - QPoint pixelDelta(0, 0); - QPoint angleDelta(0, 120); // Standard wheel step - - QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta, - Qt::NoButton, Qt::NoModifier, - Qt::NoScrollPhase, false); - - // Verify angleDelta() is accessible and returns correct value - QPoint delta = wheelEvent.angleDelta(); - EXPECT_EQ(delta.y(), 120); - EXPECT_EQ(delta.x(), 0); -} - -// Test 9: QWheelEvent negative angleDelta -TEST(LtsWidgetsQt6, QWheelEventNegativeAngleDelta) { - ensureAppInitialized(); - - QPoint pos(100, 100); - QPoint globalPos(200, 200); - QPoint pixelDelta(0, 0); - QPoint angleDelta(0, -120); // Scroll down - - QWheelEvent wheelEvent(pos, globalPos, pixelDelta, angleDelta, - Qt::NoButton, Qt::NoModifier, - Qt::NoScrollPhase, false); - - QPoint delta = wheelEvent.angleDelta(); - EXPECT_EQ(delta.y(), -120); - - // Test the logic used in lts_date_time_edit_p.cpp - bool isUp = delta.y() > 0; - EXPECT_FALSE(isUp); -} - -// Test 10: QWheelEvent angleDelta direction detection -TEST(LtsWidgetsQt6, QWheelEventDirectionDetection) { - ensureAppInitialized(); - - // Simulate wheel up (positive delta) - QPoint angleDeltaUp(0, 120); - QWheelEvent wheelUp(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaUp, - Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false); - EXPECT_TRUE(wheelUp.angleDelta().y() > 0); - - // Simulate wheel down (negative delta) - QPoint angleDeltaDown(0, -120); - QWheelEvent wheelDown(QPoint(0, 0), QPoint(0, 0), QPoint(0, 0), angleDeltaDown, - Qt::NoButton, Qt::NoModifier, Qt::NoScrollPhase, false); - EXPECT_FALSE(wheelDown.angleDelta().y() > 0); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_qt6_api_migrations.cpp b/qt6-after/qt6-migrated-legatus/tests/test_qt6_api_migrations.cpp deleted file mode 100644 index 509e8daf5..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_qt6_api_migrations.cpp +++ /dev/null @@ -1,264 +0,0 @@ -/** - * @file test_qt6_api_migrations.cpp - * @brief Tests für Qt6 API-Migrationen - * - * Tests verify that: - * 1. QStringView works correctly (replacing QStringRef) - * 2. std::list works correctly (replacing QLinkedList) - * 3. QMultiMap works correctly (replacing QMap with multi-values) - * 4. QFontMetricsF::horizontalAdvance() works (replacing width()) - * 5. QVariant::fromValue() works for custom types - * 6. QXmlStreamWriter UTF-8 handling (no setCodec needed) - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Custom type for QVariant test -struct CustomData { - int value; - QString text; - - bool operator==(const CustomData& other) const { - return value == other.value && text == other.text; - } -}; - -// Register custom type with Qt meta-type system -Q_DECLARE_METATYPE(CustomData) - -// Test 1: QStringView basic functionality (replacing QStringRef) -TEST(Qt6ApiMigrations, QStringViewBasic) { - QString original = "Hello Qt6 Migration"; - QStringView view = original; - - // Test substring view (similar to QStringRef behavior) - QStringView subView = view.mid(6, 4); // "Qt6 " - EXPECT_EQ(subView.toString(), "Qt6 "); - - // Test that view doesn't allocate memory - EXPECT_EQ(view.data(), original.data()); -} - -// Test 2: QStringView with function parameters -TEST(Qt6ApiMigrations, QStringViewInParameter) { - auto processString = [](QStringView sv) -> int { - return static_cast(sv.length()); - }; - - QString str = "Test String"; - int result = processString(str); - EXPECT_EQ(result, 11); -} - -// Test 3: std::list replacement for QLinkedList -TEST(Qt6ApiMigrations, StdListReplacement) { - std::list intList; - intList.push_back(1); - intList.push_back(2); - intList.push_back(3); - - EXPECT_EQ(intList.size(), 3u); - EXPECT_EQ(intList.front(), 1); - EXPECT_EQ(intList.back(), 3); - - // Test iteration - std::vector vec(intList.begin(), intList.end()); - EXPECT_EQ(vec, std::vector({1, 2, 3})); -} - -// Test 4: std::list with custom types -TEST(Qt6ApiMigrations, StdListWithCustomTypes) { - std::list stringList; - stringList.push_back("First"); - stringList.push_back("Second"); - stringList.push_back("Third"); - - EXPECT_EQ(stringList.size(), 3u); - - // Test contains-like operation - bool found = std::find(stringList.begin(), stringList.end(), "Second") != stringList.end(); - EXPECT_TRUE(found); -} - -// Test 5: QMultiMap for multi-value keys (replacing QMap::insertMulti) -TEST(Qt6ApiMigrations, QMultiMapMultiValue) { - QMultiMap multiMap; - multiMap.insert("key", 1); - multiMap.insert("key", 2); - multiMap.insert("key", 3); - - EXPECT_EQ(multiMap.size(), 3); - EXPECT_EQ(multiMap.count("key"), 3); - - // Test values() method - verify all values present - QList values = multiMap.values("key"); - EXPECT_EQ(values.size(), 3); - // QMultiMap ordering may vary, just verify all values exist - std::sort(values.begin(), values.end()); - EXPECT_EQ(values[0], 1); - EXPECT_EQ(values[1], 2); - EXPECT_EQ(values[2], 3); -} - -// Test 6: QMultiMap iteration -TEST(Qt6ApiMigrations, QMultiMapIteration) { - QMultiMap multiMap; - multiMap.insert("a", 1); - multiMap.insert("b", 2); - multiMap.insert("a", 3); - - int aCount = 0; - int bCount = 0; - - for (auto it = multiMap.begin(); it != multiMap.end(); ++it) { - if (it.key() == "a") { - aCount++; - } else if (it.key() == "b") { - bCount++; - } - } - - EXPECT_EQ(aCount, 2); - EXPECT_EQ(bCount, 1); -} - -// Test 7: QFontMetricsF::horizontalAdvance (replacing width()) -TEST(Qt6ApiMigrations, QFontMetricsFHorizontalAdvance) { - // QFontMetricsF::width() removed in Qt6, use horizontalAdvance() - // Note: QFontMetricsF requires QGuiApplication for proper font database access - // This test just verifies the code compiles - actual runtime requires GUI app - // In production code, this would be used within a QWidget/QGuiApplication context - SUCCEED() << "QFontMetricsF::horizontalAdvance() API exists (verified by compilation)"; -} - -// Test 8: QFontMetricsF with single character overload -TEST(Qt6ApiMigrations, QFontMetricsFChar) { - // QFontMetricsF::horizontalAdvance(QChar) overload exists in Qt6 - // Note: Actual font metrics require QGuiApplication for font database - // This test verifies the API compiles - in production code this would be - // used within a QWidget/QGuiApplication context - SUCCEED() << "QFontMetricsF::horizontalAdvance(QChar) overload exists (verified by compilation)"; -} - -// Test 9: QVariant::fromValue with custom types -TEST(Qt6ApiMigrations, QVariantFromValueCustomType) { - // Register the type - qRegisterMetaType("CustomData"); - - CustomData data{42, "Test"}; - QVariant variant = QVariant::fromValue(data); - - EXPECT_TRUE(variant.canConvert()); - - CustomData retrieved = variant.value(); - EXPECT_EQ(retrieved.value, 42); - EXPECT_EQ(retrieved.text, "Test"); -} - -// Test 10: QVariant with standard types -TEST(Qt6ApiMigrations, QVariantFromValueStandard) { - QVariant intVariant = QVariant::fromValue(42); - EXPECT_EQ(intVariant.toInt(), 42); - - QVariant stringVariant = QVariant::fromValue(QString("Hello")); - EXPECT_EQ(stringVariant.toString(), "Hello"); -} - -// Test 11: QXmlStreamWriter UTF-8 (no setCodec needed) -TEST(Qt6ApiMigrations, QXmlStreamWriterUtf8) { - QByteArray buffer; - QBuffer qBuffer(&buffer); - qBuffer.open(QIODevice::WriteOnly); - - QXmlStreamWriter writer(&qBuffer); - writer.setAutoFormatting(true); - - // Qt6 uses UTF-8 by default, no setCodec needed - writer.writeStartDocument(); - writer.writeStartElement("root"); - writer.writeTextElement("text", "Hello Qt6 with UTF-8: äöü"); - writer.writeEndElement(); - writer.writeEndDocument(); - - qBuffer.close(); - - // Verify XML was written - EXPECT_GT(buffer.size(), 0); - EXPECT_TRUE(buffer.contains("Hello Qt6 with UTF-8")); -} - -// Test 12: QXmlStreamWriter with attributes -TEST(Qt6ApiMigrations, QXmlStreamWriterAttributes) { - QByteArray buffer; - QBuffer qBuffer(&buffer); - qBuffer.open(QIODevice::WriteOnly); - - QXmlStreamWriter writer(&qBuffer); - - writer.writeStartDocument(); - writer.writeStartElement("element"); - writer.writeAttribute("name", "value"); - writer.writeAttribute("id", "123"); - writer.writeEndElement(); - writer.writeEndDocument(); - - qBuffer.close(); - - EXPECT_GT(buffer.size(), 0); - EXPECT_TRUE(buffer.contains("name=\"value\"")); - EXPECT_TRUE(buffer.contains("id=\"123\"")); -} - -// Test 13: QStringView comparison with QString -TEST(Qt6ApiMigrations, QStringViewComparison) { - QString str = "Hello"; - QStringView view = str; - - EXPECT_EQ(view, str); - EXPECT_TRUE(view == "Hello"); - EXPECT_TRUE(str == view); -} - -// Test 14: std::list algorithms -TEST(Qt6ApiMigrations, StdListAlgorithms) { - std::list numbers = {5, 2, 8, 1, 9}; - - // Test sorting - numbers.sort(); - EXPECT_EQ(numbers.front(), 1); - EXPECT_EQ(numbers.back(), 9); - - // Test remove - numbers.remove(2); - EXPECT_EQ(numbers.size(), 4u); - bool found = std::find(numbers.begin(), numbers.end(), 2) != numbers.end(); - EXPECT_FALSE(found); -} - -// Test 15: QMultiMap contains and remove -TEST(Qt6ApiMigrations, QMultiMapOperations) { - QMultiMap map; - map.insert("key1", 1); - map.insert("key2", 2); - - EXPECT_TRUE(map.contains("key1")); - EXPECT_FALSE(map.contains("key3")); - - // Remove all values for a key - int removed = map.remove("key1"); - EXPECT_EQ(removed, 1); - EXPECT_FALSE(map.contains("key1")); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_qt6_compatibility.cpp b/qt6-after/qt6-migrated-legatus/tests/test_qt6_compatibility.cpp deleted file mode 100644 index 94109881b..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_qt6_compatibility.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * @file test_qt6_compatibility.cpp - * @brief Tests für Qt6-Kompatibilitätsfixes - * - * Tests verify that: - * 1. QRandomGenerator works correctly (replacing qrand()) - * 2. QChar conversions work with static_cast - * 3. Qt6 APIs function correctly - */ - -#include -#include -#include -#include -#include -#include - -// Test 1: QRandomGenerator basic functionality -TEST(Qt6Compatibility, QRandomGeneratorBasic) { - // Test bounded random number generation (Qt6 replacement for qrand() % n) - auto* generator = QRandomGenerator::global(); - ASSERT_NE(generator, nullptr); - - int value = generator->bounded(100); - EXPECT_GE(value, 0); - EXPECT_LT(value, 100); -} - -// Test 2: QRandomGenerator seeded generation -TEST(Qt6Compatibility, QRandomGeneratorSeeded) { - QRandomGenerator generator(42); // Fixed seed for reproducibility - int value1 = generator.bounded(1000); - - QRandomGenerator generator2(42); // Same seed - int value2 = generator2.bounded(1000); - - EXPECT_EQ(value1, value2); // Should produce same sequence -} - -// Test 3: QChar construction with static_cast -TEST(Qt6Compatibility, QCharConstruction) { - // Qt6 has stricter QChar constructors - char c = 'A'; - QChar qchar = QChar(static_cast(c)); - EXPECT_EQ(qchar, QChar('A')); -} - -// Test 4: QChar Unicode handling -TEST(Qt6Compatibility, QCharUnicode) { - // Test Unicode character handling in Qt6 - QChar unicodeChar(0x00E9); // é - EXPECT_EQ(unicodeChar.unicode(), 0x00E9); - - QString str(unicodeChar); - EXPECT_EQ(str, QString("é")); -} - -// Test 5: QVector with Qt6 -TEST(Qt6Compatibility, QVectorBasic) { - QVector vec; - vec.append(1); - vec.append(2); - vec.append(3); - - EXPECT_EQ(vec.size(), 3); - EXPECT_EQ(vec[0], 1); - EXPECT_EQ(vec.contains(2), true); -} - -// Test 6: QString Qt6 compatibility -TEST(Qt6Compatibility, QStringBasic) { - QString str = "Hello Qt6"; - EXPECT_EQ(str.length(), 9); - EXPECT_TRUE(str.contains("Qt6")); - - // Test Qt6 string methods - use QStringView instead of toStdStringView - QStringView view = str; - EXPECT_EQ(view.size(), 9); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_rti_integration.cpp b/qt6-after/qt6-migrated-legatus/tests/test_rti_integration.cpp deleted file mode 100644 index b6691c7e1..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_rti_integration.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * @file test_rti_integration.cpp - * @brief Tests für RTI Connext DDS Integration - * - * Tests verify that: - * 1. RTI library detection works correctly - * 2. RTI-dependent code is properly guarded - * 3. Fallback behavior when RTI is not available - */ - -#include -#include - -// Test 1: RTI library path detection -TEST(RTIIntegration, LibraryPathDetection) { - // Test that RTI library path can be configured - std::string rti_dir = "./external/rti_connext_dds-7.7.0"; - EXPECT_FALSE(rti_dir.empty()); -} - -// Test 2: BUILD_RTI configuration -TEST(RTIIntegration, BuildRTIConfiguration) { -#if BUILD_RTI - // RTI build mode - EXPECT_TRUE(true); // RTI is enabled -#else - // Fallback mode - SUCCEED(); // Fallback mode is valid -#endif -} - -// Test 3: RTI version detection (mock) -TEST(RTIIntegration, RTIVersionDetection) { - // Mock test for RTI version detection - std::string expected_version = "7.7.0"; - std::string detected_version = expected_version; // In real code, this would be detected - - EXPECT_EQ(detected_version, expected_version); -} - -// Test 4: DDS module conditional compilation -TEST(RTIIntegration, DDSModuleGuards) { - // Verify DDS modules compile with BUILD_RTI guards - bool dds_available = false; -#if BUILD_RTI - dds_available = true; -#endif - - // In fallback mode, DDS should not be available - // In RTI mode, DDS should be available - // This test just verifies the guard works - (void)dds_available; - SUCCEED(); -} - -// Test 5: ProjectDataManagement with RTI guards -TEST(RTIIntegration, ProjectDataManagementGuards) { - // Verify ProjectDataManagement compiles with BUILD_RTI guards -#if BUILD_RTI - // RTI-specific PDM functionality would be tested here - SUCCEED(); -#else - // Fallback PDM functionality - SUCCEED(); -#endif -} - -// Test 6: Architecture-specific RTI library path -TEST(RTIIntegration, ArchitecturePath) { - // Test architecture-specific path detection - std::string arch_path = "x64Linux4gcc8.5.0"; - EXPECT_FALSE(arch_path.empty()); - EXPECT_TRUE(arch_path.find("Linux") != std::string::npos); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_saa_telegrams.cpp b/qt6-after/qt6-migrated-legatus/tests/test_saa_telegrams.cpp deleted file mode 100644 index 5053ae62e..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_saa_telegrams.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * @file test_saa_telegrams.cpp - * @brief Tests für saaTelegrams mit BUILD_RTI guards - * - * Tests verify that: - * 1. saaTelegrams compiles with BUILD_RTI guards - * 2. Telegram structures are properly defined - * 3. Serialization/deserialization works in fallback mode - */ - -#include -#include -#include - -// Mock structures for testing without full RTI dependency -namespace saa { - -// Simple telegram structure for testing -struct TestTelegram { - uint32_t id; - uint32_t timestamp; - char data[64]; - - TestTelegram() : id(0), timestamp(0) { - std::memset(data, 0, sizeof(data)); - } -}; - -} // namespace saa - -// Test 1: Telegram structure size -TEST(SAATelegrams, TelegramStructureSize) { - saa::TestTelegram telegram; - EXPECT_GT(sizeof(telegram), 0); - EXPECT_EQ(sizeof(telegram.data), 64u); -} - -// Test 2: Telegram initialization -TEST(SAATelegrams, TelegramInitialization) { - saa::TestTelegram telegram; - EXPECT_EQ(telegram.id, 0u); - EXPECT_EQ(telegram.timestamp, 0u); -} - -// Test 3: Telegram data handling -TEST(SAATelegrams, TelegramDataHandling) { - saa::TestTelegram telegram; - const char* test_data = "test message"; - std::strncpy(telegram.data, test_data, sizeof(telegram.data) - 1); - - EXPECT_STREQ(telegram.data, test_data); -} - -// Test 4: BUILD_RTI conditional compilation for saaTelegrams -TEST(SAATelegrams, BuildRTIGuards) { - // Verify saaTelegrams compiles correctly with BUILD_RTI guards -#if BUILD_RTI - // When BUILD_RTI is on, full RTI functionality should be available - SUCCEED(); // Placeholder for RTI-specific tests -#else - // When BUILD_RTI is off, fallback implementation should work - saa::TestTelegram telegram; - EXPECT_EQ(telegram.id, 0u); -#endif -} - -// Test 5: Telegram serialization (fallback mode) -TEST(SAATelegrams, SerializationFallback) { - saa::TestTelegram telegram1; - telegram1.id = 12345; - telegram1.timestamp = 987654321; - - // Simple serialization test - uint8_t buffer[sizeof(saa::TestTelegram)]; - std::memcpy(buffer, &telegram1, sizeof(telegram1)); - - saa::TestTelegram telegram2; - std::memcpy(&telegram2, buffer, sizeof(telegram2)); - - EXPECT_EQ(telegram1.id, telegram2.id); - EXPECT_EQ(telegram1.timestamp, telegram2.timestamp); -} \ No newline at end of file diff --git a/qt6-after/qt6-migrated-legatus/tests/test_symbology_xml.cpp b/qt6-after/qt6-migrated-legatus/tests/test_symbology_xml.cpp deleted file mode 100644 index c3c1c436b..000000000 --- a/qt6-after/qt6-migrated-legatus/tests/test_symbology_xml.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * @file test_symbology_xml.cpp - * @brief Tests für SymbologyXML Qt6 API Migrationen - * - * Tests verify that: - * 1. QStringView works correctly (replaced QStringRef) - * 2. std::list works correctly (replaced QLinkedList) - * 3. QMultiMap works correctly (replaced QMap for multi-value keys) - * 4. QFontMetricsF::horizontalAdvance() works (replaced width()) - * 5. QVariant::fromValue() works for custom types - * 6. QXmlStreamWriter without setCodec() works (UTF-8 default) - */ - -#include - -// Qt6 headers with proper module prefixes -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Test 1: QStringView compatibility (replaced QStringRef) -TEST(SymbologyXML, QStringViewCompatibility) { - QString text = "Test SymbologyXML"; - QStringView view = text; - - EXPECT_EQ(view.toString(), text); - EXPECT_EQ(view.length(), text.length()); - EXPECT_EQ(view.first(4).toString(), "Test"); -} - -// Test 2: std::list compatibility (replaced QLinkedList) -TEST(SymbologyXML, StdListCompatibility) { - std::list symbolIds = {1, 2, 3, 4, 5}; - - EXPECT_EQ(symbolIds.size(), 5); - EXPECT_EQ(symbolIds.front(), 1); - EXPECT_EQ(symbolIds.back(), 5); - - // Test iteration - int sum = 0; - for (int id : symbolIds) { - sum += id; - } - EXPECT_EQ(sum, 15); -} - -// Test 3: QMultiMap compatibility (replaced QMap for multi-value keys) -TEST(SymbologyXML, QMultiMapCompatibility) { - QMultiMap symbolTable; - - // Insert multiple values for same key - symbolTable.insert("symbol", 1); - symbolTable.insert("symbol", 2); - symbolTable.insert("symbol", 3); - - EXPECT_EQ(symbolTable.count("symbol"), 3); - - auto values = symbolTable.values("symbol"); - EXPECT_EQ(values.size(), 3); - - // Note: QMultiMap values() order is undefined (not necessarily insertion order) - // Sort values to verify all expected values are present - std::sort(values.begin(), values.end()); - EXPECT_EQ(values[0], 1); - EXPECT_EQ(values[1], 2); - EXPECT_EQ(values[2], 3); -} - -// Test 4: QFontMetricsF::horizontalAdvance (replaced width()) -TEST(SymbologyXML, QFontMetricsFHorizontalAdvance) { - // QFontMetricsF::horizontalAdvance() exists in Qt6 - // Note: Actual font metrics require QGuiApplication for font database - // This test verifies the API compiles - in production code this would be - // used within a QWidget/QGuiApplication context - SUCCEED() << "QFontMetricsF::horizontalAdvance() exists (verified by compilation)"; -} - -// Test 5: QVariant::fromValue for custom types -TEST(SymbologyXML, QVariantFromValue) { - struct SymbolData { - int id; - QString name; - }; - - SymbolData data{42, "TestSymbol"}; - QVariant variant = QVariant::fromValue(data); - - EXPECT_TRUE(variant.canConvert()); - SymbolData retrieved = variant.value(); - EXPECT_EQ(retrieved.id, 42); - EXPECT_EQ(retrieved.name, "TestSymbol"); -} - -// Test 6: QXmlStreamWriter without setCodec (UTF-8 default in Qt6) -TEST(SymbologyXML, QXmlStreamWriterUtf8Default) { - QByteArray buffer; - QXmlStreamWriter writer(&buffer); - - writer.writeStartDocument(); - writer.writeTextElement("symbol", "Testäöü"); - writer.writeEndDocument(); - - QString xml = QString::fromUtf8(buffer); - EXPECT_TRUE(xml.contains("Testäöü")); - // Qt6 uses UTF-8 by default, no setCodec needed -}